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 org.jetbrains.annotations.NotNull;
024    import org.jetbrains.kotlin.diagnostics.Diagnostic;
025    
026    import java.util.Collection;
027    
028    public class DiagnosticsElementsCache {
029        private final Diagnostics diagnostics;
030    
031        private final AtomicNotNullLazyValue<MultiMap<PsiElement, Diagnostic>> elementToDiagnostic = new AtomicNotNullLazyValue<MultiMap<PsiElement, Diagnostic>>() {
032            @NotNull
033            @Override
034            protected MultiMap<PsiElement, Diagnostic> compute() {
035                return buildElementToDiagnosticCache(diagnostics);
036            }
037        };
038    
039        public DiagnosticsElementsCache(Diagnostics diagnostics) {
040            this.diagnostics = diagnostics;
041        }
042    
043        @NotNull
044        public Collection<Diagnostic> getDiagnostics(@NotNull PsiElement psiElement) {
045            return elementToDiagnostic.getValue().get(psiElement);
046        }
047    
048        private static MultiMap<PsiElement, Diagnostic> buildElementToDiagnosticCache(Diagnostics diagnostics) {
049            MultiMap<PsiElement, Diagnostic> elementToDiagnostic = new ConcurrentMultiMap<PsiElement, Diagnostic>();
050            for (Diagnostic diagnostic : diagnostics) {
051                elementToDiagnostic.putValue(diagnostic.getPsiElement(), diagnostic);
052            }
053    
054            return elementToDiagnostic;
055        }
056    }