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.diagnostics;
018    
019    import org.jetbrains.annotations.NotNull;
020    
021    import java.util.Arrays;
022    import java.util.Collection;
023    
024    public abstract class DiagnosticFactory<D extends Diagnostic> {
025    
026        private String name = null;
027        private final Severity severity;
028    
029        protected DiagnosticFactory(@NotNull Severity severity) {
030            this.severity = severity;
031        }
032    
033        /*package*/ void setName(@NotNull String name) {
034            this.name = name;
035        }
036    
037        @NotNull
038        public String getName() {
039            return name;
040        }
041    
042        @NotNull
043        public Severity getSeverity() {
044            return severity;
045        }
046    
047        @NotNull
048        public D cast(@NotNull Diagnostic diagnostic) {
049            if (diagnostic.getFactory() != this) {
050                throw new IllegalArgumentException("Factory mismatch: expected " + this + " but was " + diagnostic.getFactory());
051            }
052    
053            //noinspection unchecked
054            return (D) diagnostic;
055        }
056    
057        @NotNull
058        public static <D extends Diagnostic> D cast(@NotNull Diagnostic diagnostic, @NotNull DiagnosticFactory<? extends D>... factories) {
059            return cast(diagnostic, Arrays.asList(factories));
060        }
061    
062        @NotNull
063        public static <D extends Diagnostic> D cast(@NotNull Diagnostic diagnostic, @NotNull Collection<? extends DiagnosticFactory<? extends D>> factories) {
064            for (DiagnosticFactory<? extends D> factory : factories) {
065                if (diagnostic.getFactory() == factory) return factory.cast(diagnostic);
066            }
067    
068            throw new IllegalArgumentException("Factory mismatch: expected one of " + factories + " but was " + diagnostic.getFactory());
069        }
070    
071        @Override
072        public String toString() {
073            return getName();
074        }
075    }