下面列出了怎么用com.intellij.psi.util.CachedValueProvider的API类实例代码及写法,或者点击链接到github查看源代码。
@NotNull
private static Map<String, Collection<TemplateAnnotationUsage>> getTemplateAnnotationUsagesMap(@NotNull Project project) {
return CachedValuesManager.getManager(project).getCachedValue(project, PHP_GENERICS_TEMPLATES, () -> {
Map<String, Collection<TemplateAnnotationUsage>> map = new HashMap<>();
FileBasedIndex instance = FileBasedIndex.getInstance();
GlobalSearchScope scope = PhpIndex.getInstance(project).getSearchScope();
instance.processAllKeys(TemplateAnnotationIndex.KEY, (key) -> {
map.putIfAbsent(key, new HashSet<>());
map.get(key).addAll(instance.getValues(TemplateAnnotationIndex.KEY, key, scope));
return true;
}, project);
return CachedValueProvider.Result.create(map, getModificationTracker(project));
}, false);
}
@NotNull
private synchronized static Collection<String> getAllResourceKeys(@NotNull Project project) {
CachedValue<Collection<String>> userData = project.getUserData(RESOURCE_KEYS);
if (userData != null && userData.hasUpToDateValue()) {
return RESOURCE_KEYS_LOCAL_CACHE.getOrDefault(project, new ArrayList<>());
}
CachedValue<Collection<String>> cachedValue = CachedValuesManager.getManager(project).createCachedValue(() -> {
Collection<String> allKeys = FileBasedIndex.getInstance().getAllKeys(ResourcePathIndex.KEY, project);
if (RESOURCE_KEYS_LOCAL_CACHE.containsKey(project)) {
RESOURCE_KEYS_LOCAL_CACHE.replace(project, allKeys);
} else {
RESOURCE_KEYS_LOCAL_CACHE.put(project, allKeys);
}
return CachedValueProvider.Result.create(new ArrayList<>(), PsiModificationTracker.MODIFICATION_COUNT);
}, false);
project.putUserData(RESOURCE_KEYS, cachedValue);
return RESOURCE_KEYS_LOCAL_CACHE.getOrDefault(project, cachedValue.getValue());
}
@NotNull
private synchronized static Collection<String> getAllKeys(@NotNull Project project) {
CachedValue<Collection<String>> cachedValue = project.getUserData(TRANSLATION_KEYS);
if (cachedValue != null && cachedValue.hasUpToDateValue()) {
return TRANSLATION_KEYS_LOCAL_CACHE.getOrDefault(project, new ArrayList<>());
}
cachedValue = CachedValuesManager.getManager(project).createCachedValue(() -> {
Collection<String> allKeys = FileBasedIndex.getInstance().getAllKeys(TranslationIndex.KEY, project);
if (TRANSLATION_KEYS_LOCAL_CACHE.containsKey(project)) {
TRANSLATION_KEYS_LOCAL_CACHE.replace(project, allKeys);
} else {
TRANSLATION_KEYS_LOCAL_CACHE.put(project, allKeys);
}
return CachedValueProvider.Result.create(new ArrayList<>(), MODIFICATION_COUNT);
}, false);
project.putUserData(TRANSLATION_KEYS, cachedValue);
return TRANSLATION_KEYS_LOCAL_CACHE.getOrDefault(project, cachedValue.getValue());
}
@Nullable
private RunConfigurationContext findTestContext(ConfigurationContext context) {
if (!SmRunnerUtils.getSelectedSmRunnerTreeElements(context).isEmpty()) {
// handled by a different producer
return null;
}
ContextWrapper wrapper = new ContextWrapper(context);
PsiElement psi = context.getPsiLocation();
return psi == null
? null
: CachedValuesManager.getCachedValue(
psi,
cacheKey,
() ->
CachedValueProvider.Result.create(
doFindTestContext(wrapper.context),
PsiModificationTracker.MODIFICATION_COUNT,
BlazeSyncModificationTracker.getInstance(wrapper.context.getProject())));
}
/**
* Based on {@link JUnitUtil#isTestClass}. We don't use that directly because it returns true for
* all inner classes of a test class, regardless of whether they're also test classes.
*/
public static boolean isTestClass(PsiClass psiClass) {
if (psiClass.getQualifiedName() == null) {
return false;
}
if (JUnitUtil.isJUnit5(psiClass) && JUnitUtil.isJUnit5TestClass(psiClass, true)) {
return true;
}
if (!PsiClassUtil.isRunnableClass(psiClass, true, true)) {
return false;
}
if (isJUnit4Class(psiClass)) {
return true;
}
if (isTestCaseInheritor(psiClass)) {
return true;
}
return CachedValuesManager.getCachedValue(
psiClass,
() ->
CachedValueProvider.Result.create(
hasTestOrSuiteMethods(psiClass),
PsiModificationTracker.JAVA_STRUCTURE_MODIFICATION_COUNT));
}
@Nonnull
public static Unity3dManifest parse(@Nonnull Project project)
{
return CachedValuesManager.getManager(project).getCachedValue(project, () ->
{
Path projectPath = Paths.get(project.getBasePath());
Path manifestJson = projectPath.resolve(Paths.get("Packages", "manifest.json"));
if(Files.exists(manifestJson))
{
Gson gson = new Gson();
try (Reader reader = Files.newBufferedReader(manifestJson))
{
return CachedValueProvider.Result.create(gson.fromJson(reader, Unity3dManifest.class), PsiModificationTracker.MODIFICATION_COUNT);
}
catch(Exception e)
{
LOG.error(e);
}
}
return CachedValueProvider.Result.create(EMPTY, PsiModificationTracker.MODIFICATION_COUNT);
});
}
@Override
@NotNull
public Collection<String> getGlobalNamespaces(@NotNull AnnotationGlobalNamespacesLoaderParameter parameter) {
Project project = parameter.getProject();
CachedValue<Collection<String>> cache = project.getUserData(CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() ->
CachedValueProvider.Result.create(getGlobalNamespacesInner(project), PsiModificationTracker.MODIFICATION_COUNT), false
);
project.putUserData(CACHE, cache);
}
return cache.getValue();
}
@Nonnull
@RequiredReadAction
public static EnumSet<CSharpModifier> getModifiersCached(@Nonnull CSharpModifierList modifierList)
{
if(!modifierList.isValid())
{
return emptySet;
}
return CachedValuesManager.getCachedValue(modifierList, () ->
{
Set<CSharpModifier> modifiers = new THashSet<>();
for(CSharpModifier modifier : CSharpModifier.values())
{
if(hasModifier(modifierList, modifier))
{
modifiers.add(modifier);
}
}
return CachedValueProvider.Result.create(modifiers.isEmpty() ? emptySet : EnumSet.copyOf(modifiers), PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
});
}
@RequiredReadAction
@Nonnull
@Override
public DotNetTypeRef[] getExtendTypeRefs()
{
return CachedValuesManager.getCachedValue(this, new CachedValueProvider<DotNetTypeRef[]>()
{
@Nullable
@Override
@RequiredReadAction
public Result<DotNetTypeRef[]> compute()
{
DotNetTypeRef[] extendTypeRefs = CSharpTypeDeclarationImplUtil.getExtendTypeRefs(CSharpTypeDeclarationImpl.this);
return Result.create(extendTypeRefs, PsiModificationTracker.OUT_OF_CODE_BLOCK_MODIFICATION_COUNT);
}
});
}
@Nonnull
private Data<T> computeData(@Nullable CachedValueProvider.Result<T> result) {
if (result == null) {
return new Data<>(null, ArrayUtilRt.EMPTY_OBJECT_ARRAY, ArrayUtil.EMPTY_LONG_ARRAY);
}
T value = result.getValue();
Object[] inferredDependencies = normalizeDependencies(result);
long[] inferredTimeStamps = new long[inferredDependencies.length];
for (int i = 0; i < inferredDependencies.length; i++) {
inferredTimeStamps[i] = getTimeStamp(inferredDependencies[i]);
}
if (CachedValueProfiler.canProfile()) {
ProfilingInfo profilingInfo = CachedValueProfiler.getInstance().getTemporaryInfo(result);
if (profilingInfo != null) {
return new ProfilingData<>(value, inferredDependencies, inferredTimeStamps, profilingInfo);
}
}
return new Data<>(value, inferredDependencies, inferredTimeStamps);
}
@NotNull
@Override
public List<HaxeModel> getExposedMembers() {
List<HaxeModel> exposed = cacheManager.getCachedValue(getBasePsi(), () -> {
List<HaxeModel> exposedMembers = getExposedMembersInternal();
PsiElement [] dependencies = new PsiElement[exposedMembers.size() + 1];
int i = 0;
dependencies[i++] = getBasePsi();
for (HaxeModel xMember : exposedMembers) {
dependencies[i++] = xMember.getBasePsi();
}
return new CachedValueProvider.Result<>(exposedMembers, (Object[])dependencies);
});
return exposed;
}
/**
* Retrieve the list of classes implemented in the given File.
*
* @param psiRoot - File to search.
* @return A List of found classes, or an empty array if none.
*/
@NotNull
public static List<HaxeClass> getClassList(@NotNull HaxeFile psiRoot) {
CachedValuesManager manager = CachedValuesManager.getManager(psiRoot.getProject());
ArrayList<HaxeClass> classList = manager.getCachedValue(psiRoot, () -> {
ArrayList<HaxeClass> classes = new ArrayList<>();
for (PsiElement child : psiRoot.getChildren()) {
if (child instanceof HaxeClass) {
classes.add((HaxeClass)child);
}
}
return new CachedValueProvider.Result<>(classes, psiRoot);
});
return classList;
}
@Override
protected CachedValue<PsiReference[]> compute(final PsiElement element, Object p) {
return CachedValuesManager.getManager(element.getProject()).createCachedValue(() -> {
IssueNavigationConfiguration navigationConfiguration = IssueNavigationConfiguration.getInstance(element.getProject());
if (navigationConfiguration == null) {
return CachedValueProvider.Result.create(PsiReference.EMPTY_ARRAY, element);
}
List<PsiReference> refs = null;
GlobalPathReferenceProvider provider = myReferenceProvider.get();
CharSequence commentText = StringUtil.newBombedCharSequence(element.getText(), 500);
for (IssueNavigationConfiguration.LinkMatch link : navigationConfiguration.findIssueLinks(commentText)) {
if (refs == null) refs = new SmartList<>();
if (provider == null) {
provider = (GlobalPathReferenceProvider)PathReferenceManager.getInstance().getGlobalWebPathReferenceProvider();
myReferenceProvider.lazySet(provider);
}
provider.createUrlReference(element, link.getTargetUrl(), link.getRange(), refs);
}
PsiReference[] references = refs != null ? refs.toArray(new PsiReference[refs.size()]) : PsiReference.EMPTY_ARRAY;
return new CachedValueProvider.Result<>(references, element, navigationConfiguration);
}, false);
}
@NotNull
@Override
public Collection<TwigPath> getNamespaces(@NotNull TwigNamespaceExtensionParameter parameter) {
Project project = parameter.getProject();
Collection<Pair<String, String>> cachedValue = CachedValuesManager.getManager(project).getCachedValue(
project,
CACHE,
() -> CachedValueProvider.Result.create(getTwigPaths(project), PsiModificationTracker.MODIFICATION_COUNT),
false
);
// TwigPath is not cache able as it right now; we need to build it here
return cachedValue.stream()
.map(p -> new TwigPath(p.getFirst(), p.getSecond(), TwigUtil.NamespaceType.ADD_PATH, true))
.collect(Collectors.toList());
}
/**
* @param dataHolderKey Main data to cache
* @param dataHolderNames Cache extracted name Set
*/
static public synchronized <T> Map<String, List<T>> getSetDataCache(@NotNull final Project project, @NotNull Key<CachedValue<Map<String, List<T>>>> dataHolderKey, final @NotNull Key<CachedValue<Set<String>>> dataHolderNames, @NotNull final ID<String, T> ID, @NotNull final GlobalSearchScope scope) {
return CachedValuesManager.getManager(project).getCachedValue(
project,
dataHolderKey,
() -> {
Map<String, List<T>> items = new HashMap<>();
final FileBasedIndex fileBasedIndex = FileBasedIndex.getInstance();
getIndexKeysCache(project, dataHolderNames, ID).forEach(service ->
items.put(service, fileBasedIndex.getValues(ID, service, scope))
);
return CachedValueProvider.Result.create(items, getModificationTrackerForIndexId(project, ID));
},
false
);
}
@RequiredReadAction
public static boolean isPackageSupported(@Nonnull Project project) {
return CachedValuesManager.getManager(project).getCachedValue(project, () -> {
boolean result = false;
PsiPackageSupportProvider[] extensions = PsiPackageSupportProvider.EP_NAME.getExtensions();
ModuleManager moduleManager = ModuleManager.getInstance(project);
loop:
for (Module module : moduleManager.getModules()) {
ModuleRootManager rootManager = ModuleRootManager.getInstance(module);
for (ModuleExtension moduleExtension : rootManager.getExtensions()) {
for (PsiPackageSupportProvider extension : extensions) {
if (extension.isSupported(moduleExtension)) {
result = true;
break loop;
}
}
}
}
return CachedValueProvider.Result.create(result, ProjectRootManager.getInstance(project));
});
}
public CachedValue<MultiValuesMap<VirtualFile, Artifact>> getFileToArtifactsMap() {
if (myFile2Artifacts == null) {
myFile2Artifacts =
CachedValuesManager.getManager(myProject).createCachedValue(new CachedValueProvider<MultiValuesMap<VirtualFile, Artifact>>() {
public Result<MultiValuesMap<VirtualFile, Artifact>> compute() {
MultiValuesMap<VirtualFile, Artifact> result = computeFileToArtifactsMap();
List<ModificationTracker> trackers = new ArrayList<ModificationTracker>();
trackers.add(myArtifactManager.getModificationTracker());
for (ComplexPackagingElementType<?> type : PackagingElementFactory.getInstance(myProject).getComplexElementTypes()) {
ContainerUtil.addIfNotNull(trackers, type.getAllSubstitutionsModificationTracker(myProject));
}
return Result.create(result, trackers.toArray(new ModificationTracker[trackers.size()]));
}
}, false);
}
return myFile2Artifacts;
}
@Override
public Data getFileData(@Nonnull PsiFile file) {
ApplicationManager.getApplication().assertReadAccessAllowed();
if (shouldUseMemoryStorage(file)) {
return CachedValuesManager.getManager(file.getProject()).getCachedValue(file, myCacheKey, () -> {
Data data = myCalculator.calcData(file.getProject(), file.getViewProvider().getVirtualFile());
return CachedValueProvider.Result.create(data, file, ourReindexTracker);
}, false);
}
file.putUserData(myCacheKey, null);
return myPersistence.getFileData(file.getProject(), file.getVirtualFile());
}
@Nonnull
@Override
protected final CachedValueProvider<AnAction[]> createChildrenProvider(@Nonnull final ActionManager actionManager) {
return new CachedValueProvider<AnAction[]>() {
@Nullable
@Override
public Result<AnAction[]> compute() {
return Result.create(computeChildren(actionManager), ModificationTracker.NEVER_CHANGED);
}
};
}
private static OffsetsInFile insertDummyIdentifierWithCache(PsiFile file, int startOffset, int endOffset, String replacement) {
ProperTextRange editRange = ProperTextRange.create(startOffset, endOffset);
assertRangeWithinDocument(editRange, file.getViewProvider().getDocument());
ConcurrentMap<Pair<ProperTextRange, String>, OffsetsInFile> map = CachedValuesManager.getCachedValue(file, () -> CachedValueProvider.Result
.create(ConcurrentFactoryMap.createMap(key -> copyWithDummyIdentifier(new OffsetsInFile(file), key.first.getStartOffset(), key.first.getEndOffset(), key.second)), file,
file.getViewProvider().getDocument()));
return map.get(Pair.create(editRange, replacement));
}
private static boolean unsyncedFileContainsGtestMacroCalls(OCFile file) {
return CachedValuesManager.getCachedValue(
file,
() ->
CachedValueProvider.Result.create(
computeUnsyncedFileContainsGtestMacroCalls(file),
PsiModificationTracker.MODIFICATION_COUNT));
}
@NotNull
synchronized public static Collection<PhpToolboxProviderInterface> getProviders(final @NotNull Project project) {
CachedValue<Collection<PhpToolboxProviderInterface>> cache = project.getUserData(PROVIDER_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getProvidersInner(project), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(PROVIDER_CACHE, cache);
}
return cache.getValue();
}
@NotNull
synchronized public static Collection<JsonRegistrar> getRegistrar(final @NotNull Project project, final @NotNull PhpToolboxApplicationService phpToolboxApplicationService) {
CachedValue<Collection<JsonRegistrar>> cache = project.getUserData(REGISTRAR_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getRegistrarInner(project, phpToolboxApplicationService), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(REGISTRAR_CACHE, cache);
}
return cache.getValue();
}
@NotNull
synchronized public static Collection<JsonRegistrar> getTypes(final @NotNull Project project) {
CachedValue<Collection<JsonRegistrar>> cache = project.getUserData(TYPE_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getTypesInner(project), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(TYPE_CACHE, cache);
}
return cache.getValue();
}
synchronized public static Collection<JsonConfigFile> getJsonConfigs(final @NotNull Project project, final @NotNull PhpToolboxApplicationService phpToolboxApplicationService) {
CachedValue<Collection<JsonConfigFile>> cache = project.getUserData(CONFIGS_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getJsonConfigsInner(project, phpToolboxApplicationService), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(CONFIGS_CACHE, cache);
}
Collection<JsonConfigFile> jsonConfigFiles = new ArrayList<>(cache.getValue());
// prevent reindex issues
if (!DumbService.getInstance(project).isDumb()) {
CachedValue<Collection<JsonConfigFile>> indexCache = project.getUserData(CONFIGS_CACHE_INDEX);
if (indexCache == null) {
indexCache = CachedValuesManager.getManager(project).createCachedValue(() -> {
Collection<JsonConfigFile> jsonConfigFiles1 = new ArrayList<>();
for (final PsiFile psiFile : FilenameIndex.getFilesByName(project, ".ide-toolbox.metadata.json", GlobalSearchScope.allScope(project))) {
JsonConfigFile cachedValue = CachedValuesManager.getCachedValue(psiFile, () -> new CachedValueProvider.Result<>(
JsonParseUtil.getDeserializeConfig(psiFile.getText()),
psiFile,
psiFile.getVirtualFile()
));
if(cachedValue != null) {
jsonConfigFiles1.add(cachedValue);
}
}
return CachedValueProvider.Result.create(jsonConfigFiles1, PsiModificationTracker.MODIFICATION_COUNT);
}, false);
}
project.putUserData(CONFIGS_CACHE_INDEX, indexCache);
jsonConfigFiles.addAll(indexCache.getValue());
}
return jsonConfigFiles;
}
@NotNull
synchronized public static Collection<JsonRegistrar> getRegistrar(final @NotNull Project project, final @NotNull PhpToolboxApplicationService phpToolboxApplicationService) {
CachedValue<Collection<JsonRegistrar>> cache = project.getUserData(REGISTRAR_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getRegistrarInner(project, phpToolboxApplicationService), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(REGISTRAR_CACHE, cache);
}
return cache.getValue();
}
@NotNull
synchronized public static Collection<JsonRegistrar> getTypes(final @NotNull Project project) {
CachedValue<Collection<JsonRegistrar>> cache = project.getUserData(TYPE_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getTypesInner(project), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(TYPE_CACHE, cache);
}
return cache.getValue();
}
synchronized public static Collection<JsonConfigFile> getJsonConfigs(final @NotNull Project project, final @NotNull PhpToolboxApplicationService phpToolboxApplicationService) {
CachedValue<Collection<JsonConfigFile>> cache = project.getUserData(CONFIGS_CACHE);
if(cache == null) {
cache = CachedValuesManager.getManager(project).createCachedValue(() -> CachedValueProvider.Result.create(getJsonConfigsInner(project, phpToolboxApplicationService), PsiModificationTracker.MODIFICATION_COUNT), false);
project.putUserData(CONFIGS_CACHE, cache);
}
Collection<JsonConfigFile> jsonConfigFiles = new ArrayList<>(cache.getValue());
// prevent reindex issues
if (!DumbService.getInstance(project).isDumb()) {
CachedValue<Collection<JsonConfigFile>> indexCache = project.getUserData(CONFIGS_CACHE_INDEX);
if (indexCache == null) {
indexCache = CachedValuesManager.getManager(project).createCachedValue(() -> {
Collection<JsonConfigFile> jsonConfigFiles1 = new ArrayList<>();
for (final PsiFile psiFile : FilenameIndex.getFilesByName(project, ".ide-toolbox.metadata.json", GlobalSearchScope.allScope(project))) {
JsonConfigFile cachedValue = CachedValuesManager.getCachedValue(psiFile, () -> new CachedValueProvider.Result<>(
JsonParseUtil.getDeserializeConfig(psiFile.getText()),
psiFile,
psiFile.getVirtualFile()
));
if(cachedValue != null) {
jsonConfigFiles1.add(cachedValue);
}
}
return CachedValueProvider.Result.create(jsonConfigFiles1, PsiModificationTracker.MODIFICATION_COUNT);
}, false);
}
project.putUserData(CONFIGS_CACHE_INDEX, indexCache);
jsonConfigFiles.addAll(indexCache.getValue());
}
return jsonConfigFiles;
}
@Nonnull
@RequiredReadAction
private static CSharpResolveContext cacheTypeContextImpl(@Nonnull DotNetGenericExtractor genericExtractor,
@Nonnull final CSharpTypeDeclaration typeDeclaration,
@Nullable final Set<PsiElement> recursiveGuardSet)
{
if(genericExtractor == DotNetGenericExtractor.EMPTY && (recursiveGuardSet == null || recursiveGuardSet.size() == 1 && recursiveGuardSet.contains(typeDeclaration)))
{
CachedValue<CSharpResolveContext> provider = typeDeclaration.getUserData(RESOLVE_CONTEXT);
if(provider != null)
{
return provider.getValue();
}
CachedValue<CSharpResolveContext> cachedValue = CachedValuesManager.getManager(typeDeclaration.getProject()).createCachedValue(new CachedValueProvider<CSharpResolveContext>()
{
@Nullable
@Override
@RequiredReadAction
public Result<CSharpResolveContext> compute()
{
return Result.<CSharpResolveContext>create(new CSharpTypeResolveContext(typeDeclaration, DotNetGenericExtractor.EMPTY, null), PsiModificationTracker.MODIFICATION_COUNT);
}
}, false);
typeDeclaration.putUserData(RESOLVE_CONTEXT, cachedValue);
return cachedValue.getValue();
}
else
{
return new CSharpTypeResolveContext(typeDeclaration, genericExtractor, recursiveGuardSet);
}
}
@Nonnull
private static Set<String> collectVariableFor(@Nonnull PsiElement element)
{
return CachedValuesManager.getCachedValue(element, () -> {
PsiFile psiFile = element.getContainingFile();
Set<String> defines = CSharpFileStubElementType.getStableDefines(psiFile);
CSharpPreprocessorVisitor visitor = new CSharpPreprocessorVisitor(defines, element.getStartOffsetInParent());
psiFile.accept(visitor);
return CachedValueProvider.Result.create(visitor.getVariables(), element);
}) ;
}