aboutsummaryrefslogtreecommitdiffstats
path: root/sd-plugin/src/main/java/org/intellij/sdk/language/hierarchy/SdCallerTreeStructure.java
blob: f6b21fc9ead489ccdf36b0a4964b8d14dbd1ae3c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package org.intellij.sdk.language.hierarchy;

import com.intellij.openapi.progress.ProgressManager;
import com.intellij.openapi.project.Project;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiReference;
import com.intellij.psi.search.SearchScope;
import com.intellij.psi.search.searches.ReferencesSearch;
import com.intellij.psi.util.PsiTreeUtil;
import com.intellij.util.containers.ContainerUtil;
import org.intellij.sdk.language.psi.SdFirstPhaseDefinition;
import org.intellij.sdk.language.psi.SdFunctionDefinition;
import org.jetbrains.annotations.NotNull;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.function.Consumer;

public class SdCallerTreeStructure extends SdCallTreeStructure {
    
    private HashMap<String, HashSet<PsiElement>> macroTreeChildren;
    
    public SdCallerTreeStructure(Project project, PsiElement element, String currentScopeType) {
        super(project, element, currentScopeType);
        macroTreeChildren = new HashMap<>();
    }
    
    @NotNull
    @Override
    protected HashSet<PsiElement> getChildren(@NotNull SdFunctionDefinition element) {
        return getCallers(element, macrosMap);
    }
    
    private HashSet<PsiElement> getCallers(@NotNull SdFunctionDefinition macro, @NotNull HashMap<String, List<PsiElement>> macrosMap) {
        String macroName = macro.getName();

        if (macroTreeChildren.containsKey(macroName)) {
            return macroTreeChildren.get(macroName);
        }
        
        HashSet<PsiElement> results = new HashSet<>();
        
        for (PsiElement macroImpl : macrosMap.get(macroName)) {
            SearchScope searchScope = getSearchScope(myScopeType, macroImpl);
            ReferencesSearch.search(macroImpl, searchScope).forEach((Consumer<? super PsiReference>) r -> {
                ProgressManager.checkCanceled();
                PsiElement psiElement = r.getElement();
                SdFunctionDefinition f = PsiTreeUtil.getParentOfType(psiElement, SdFunctionDefinition.class, false);
                if (f != null && !f.getName().equals(macroName)) { 
                    ContainerUtil.addIfNotNull(results, f); 
                } else {
                    SdFirstPhaseDefinition fp = PsiTreeUtil.getParentOfType(psiElement, SdFirstPhaseDefinition.class, false);
                    ContainerUtil.addIfNotNull(results, fp);
                }
            });
        }
        
        macroTreeChildren.put(macroName, results);
        return results;
    }
    
}