001    /*
002     * Copyright 2010-2015 JetBrains s.r.o.
003     *
004     * Licensed under the Apache License, Version 2.0 (the "License");
005     * you may not use this file except in compliance with the License.
006     * You may obtain a copy of the License at
007     *
008     * http://www.apache.org/licenses/LICENSE-2.0
009     *
010     * Unless required by applicable law or agreed to in writing, software
011     * distributed under the License is distributed on an "AS IS" BASIS,
012     * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013     * See the License for the specific language governing permissions and
014     * limitations under the License.
015     */
016    
017    package org.jetbrains.kotlin.resolve.diagnostics;
018    
019    import com.intellij.openapi.util.AtomicNotNullLazyValue;
020    import com.intellij.psi.PsiElement;
021    import com.intellij.util.containers.ConcurrentMultiMap;
022    import com.intellij.util.containers.MultiMap;
023    import kotlin.jvm.functions.Function1;
024    import org.jetbrains.annotations.NotNull;
025    import org.jetbrains.kotlin.diagnostics.Diagnostic;
026    
027    import java.util.Collection;
028    
029    public class DiagnosticsElementsCache {
030        private final Diagnostics diagnostics;
031        private final Function1<Diagnostic, Boolean> filter;
032    
033        private final AtomicNotNullLazyValue<MultiMap<PsiElement, Diagnostic>> elementToDiagnostic = new AtomicNotNullLazyValue<MultiMap<PsiElement, Diagnostic>>() {
034            @NotNull
035            @Override
036            protected MultiMap<PsiElement, Diagnostic> compute() {
037                return buildElementToDiagnosticCache(diagnostics, filter);
038            }
039        };
040    
041        public DiagnosticsElementsCache(Diagnostics diagnostics, Function1<Diagnostic, Boolean> filter) {
042            this.diagnostics = diagnostics;
043            this.filter = filter;
044        }
045    
046        @NotNull
047        public Collection<Diagnostic> getDiagnostics(@NotNull PsiElement psiElement) {
048            return elementToDiagnostic.getValue().get(psiElement);
049        }
050    
051        private static MultiMap<PsiElement, Diagnostic> buildElementToDiagnosticCache(Diagnostics diagnostics, Function1<Diagnostic, Boolean> filter) {
052            MultiMap<PsiElement, Diagnostic> elementToDiagnostic = new ConcurrentMultiMap<PsiElement, Diagnostic>();
053            for (Diagnostic diagnostic : diagnostics) {
054                if (filter.invoke(diagnostic)) {
055                    elementToDiagnostic.putValue(diagnostic.getPsiElement(), diagnostic);
056                }
057            }
058    
059            return elementToDiagnostic;
060        }
061    }