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.cli.common.messages;
018    
019    import com.intellij.openapi.util.text.StringUtil;
020    import com.intellij.psi.PsiElement;
021    import com.intellij.psi.PsiErrorElement;
022    import com.intellij.psi.PsiFile;
023    import com.intellij.psi.PsiModifierListOwner;
024    import com.intellij.psi.util.PsiFormatUtil;
025    import kotlin.jvm.functions.Function0;
026    import org.jetbrains.annotations.NotNull;
027    import org.jetbrains.annotations.Nullable;
028    import org.jetbrains.kotlin.analyzer.AnalysisResult;
029    import org.jetbrains.kotlin.descriptors.ClassDescriptor;
030    import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
031    import org.jetbrains.kotlin.diagnostics.*;
032    import org.jetbrains.kotlin.diagnostics.rendering.DefaultErrorMessages;
033    import org.jetbrains.kotlin.load.java.JavaBindingContext;
034    import org.jetbrains.kotlin.load.java.JvmAbi;
035    import org.jetbrains.kotlin.load.java.components.TraceBasedErrorReporter;
036    import org.jetbrains.kotlin.load.java.components.TraceBasedErrorReporter.AbiVersionErrorData;
037    import org.jetbrains.kotlin.psi.JetFile;
038    import org.jetbrains.kotlin.resolve.AnalyzingUtils;
039    import org.jetbrains.kotlin.resolve.BindingContext;
040    import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
041    import org.jetbrains.kotlin.resolve.DescriptorUtils;
042    import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics;
043    import org.jetbrains.kotlin.resolve.jvm.JvmClassName;
044    import org.jetbrains.kotlin.utils.UtilsPackage;
045    
046    import java.util.ArrayList;
047    import java.util.Collection;
048    import java.util.List;
049    
050    import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
051    import static org.jetbrains.kotlin.diagnostics.DiagnosticUtils.sortedDiagnostics;
052    
053    public final class AnalyzerWithCompilerReport {
054    
055        @NotNull
056        private static CompilerMessageSeverity convertSeverity(@NotNull Severity severity) {
057            switch (severity) {
058                case INFO:
059                    return CompilerMessageSeverity.INFO;
060                case ERROR:
061                    return CompilerMessageSeverity.ERROR;
062                case WARNING:
063                    return CompilerMessageSeverity.WARNING;
064            }
065            throw new IllegalStateException("Unknown severity: " + severity);
066        }
067    
068        private static final DiagnosticFactory0<PsiErrorElement> SYNTAX_ERROR_FACTORY = DiagnosticFactory0.create(Severity.ERROR);
069    
070        private final MessageSeverityCollector messageCollector;
071        private AnalysisResult analysisResult = null;
072    
073        public AnalyzerWithCompilerReport(@NotNull MessageCollector collector) {
074            messageCollector = new MessageSeverityCollector(collector);
075        }
076    
077        private static boolean reportDiagnostic(
078                @NotNull Diagnostic diagnostic,
079                @NotNull MessageCollector messageCollector,
080                boolean incompatibleFilesFound
081        ) {
082            if (!diagnostic.isValid()) return false;
083    
084            String render;
085            if (diagnostic instanceof MyDiagnostic) {
086                render = ((MyDiagnostic) diagnostic).message;
087            }
088            else {
089                render = DefaultErrorMessages.render(diagnostic);
090            }
091    
092            if (incompatibleFilesFound && Errors.UNRESOLVED_REFERENCE_DIAGNOSTICS.contains(diagnostic.getFactory())) {
093                render += "\n(note: this may be caused by the fact that some classes compiled with an incompatible version of Kotlin " +
094                          "were found in the classpath. Such classes cannot be loaded properly by this version of Kotlin compiler. " +
095                          "See below for more information)";
096            }
097    
098            PsiFile file = diagnostic.getPsiFile();
099            messageCollector.report(
100                    convertSeverity(diagnostic.getSeverity()),
101                    render,
102                    MessageUtil.psiFileToMessageLocation(file, file.getName(), DiagnosticUtils.getLineAndColumn(diagnostic))
103            );
104    
105            return diagnostic.getSeverity() == Severity.ERROR;
106        }
107    
108        private void reportIncompleteHierarchies() {
109            assert analysisResult != null;
110            BindingContext bindingContext = analysisResult.getBindingContext();
111            Collection<ClassDescriptor> classes = bindingContext.getKeys(TraceBasedErrorReporter.INCOMPLETE_HIERARCHY);
112            if (!classes.isEmpty()) {
113                StringBuilder message = new StringBuilder("Supertypes of the following classes cannot be resolved. " +
114                                                          "Please make sure you have the required dependencies in the classpath:\n");
115                for (ClassDescriptor descriptor : classes) {
116                    String fqName = DescriptorUtils.getFqName(descriptor).asString();
117                    List<String> unresolved = bindingContext.get(TraceBasedErrorReporter.INCOMPLETE_HIERARCHY, descriptor);
118                    assert unresolved != null && !unresolved.isEmpty() :
119                            "Incomplete hierarchy should be reported with names of unresolved superclasses: " + fqName;
120                    message.append("    class ").append(fqName)
121                            .append(", unresolved supertypes: ").append(UtilsPackage.join(unresolved, ", "))
122                            .append("\n");
123                }
124                messageCollector.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION);
125            }
126        }
127    
128        private void reportAlternativeSignatureErrors() {
129            assert analysisResult != null;
130            BindingContext bc = analysisResult.getBindingContext();
131            Collection<DeclarationDescriptor> descriptorsWithErrors = bc.getKeys(JavaBindingContext.LOAD_FROM_JAVA_SIGNATURE_ERRORS);
132            if (!descriptorsWithErrors.isEmpty()) {
133                StringBuilder message = new StringBuilder("The following Java entities have annotations with wrong Kotlin signatures:\n");
134                for (DeclarationDescriptor descriptor : descriptorsWithErrors) {
135                    PsiElement declaration = DescriptorToSourceUtils.descriptorToDeclaration(descriptor);
136                    assert declaration instanceof PsiModifierListOwner;
137    
138                    List<String> errors = bc.get(JavaBindingContext.LOAD_FROM_JAVA_SIGNATURE_ERRORS, descriptor);
139                    assert errors != null && !errors.isEmpty();
140    
141                    String externalName = PsiFormatUtil.getExternalName((PsiModifierListOwner) declaration);
142                    message.append(externalName).append(":\n");
143    
144                    for (String error : errors) {
145                        message.append("    ").append(error).append("\n");
146                    }
147                }
148                messageCollector.report(CompilerMessageSeverity.ERROR, message.toString(), CompilerMessageLocation.NO_LOCATION);
149            }
150        }
151    
152        @NotNull
153        private List<AbiVersionErrorData> getAbiVersionErrors() {
154            assert analysisResult != null;
155            BindingContext bindingContext = analysisResult.getBindingContext();
156    
157            Collection<String> errorClasses = bindingContext.getKeys(TraceBasedErrorReporter.ABI_VERSION_ERRORS);
158            List<AbiVersionErrorData> result = new ArrayList<AbiVersionErrorData>(errorClasses.size());
159            for (String kotlinClass : errorClasses) {
160                result.add(bindingContext.get(TraceBasedErrorReporter.ABI_VERSION_ERRORS, kotlinClass));
161            }
162    
163            return result;
164        }
165    
166        private void reportAbiVersionErrors(@NotNull List<AbiVersionErrorData> errors) {
167            for (AbiVersionErrorData data : errors) {
168                String path = toSystemDependentName(data.getFilePath());
169                messageCollector.report(
170                        CompilerMessageSeverity.ERROR,
171                        "Class '" + JvmClassName.byClassId(data.getClassId()) + "' was compiled with an incompatible version of Kotlin. " +
172                        "Its ABI version is " + data.getActualVersion() + ", expected ABI version is " + JvmAbi.VERSION,
173                        CompilerMessageLocation.create(path, -1, -1, null)
174                );
175            }
176        }
177    
178        private static boolean reportDiagnostics(
179                @NotNull Diagnostics diagnostics,
180                @NotNull MessageCollector messageCollector,
181                boolean incompatibleFilesFound
182        ) {
183            boolean hasErrors = false;
184            for (Diagnostic diagnostic : sortedDiagnostics(diagnostics.all())) {
185                hasErrors |= reportDiagnostic(diagnostic, messageCollector, incompatibleFilesFound);
186            }
187            return hasErrors;
188        }
189    
190        public static boolean reportDiagnostics(@NotNull Diagnostics diagnostics, @NotNull MessageCollector collector) {
191            return reportDiagnostics(diagnostics, collector, false);
192        }
193    
194        private void reportSyntaxErrors(@NotNull Collection<JetFile> files) {
195            for (JetFile file : files) {
196                reportSyntaxErrors(file, messageCollector);
197            }
198        }
199    
200        public static class SyntaxErrorReport {
201            private final boolean hasErrors;
202            private final boolean allErrorsAtEof;
203    
204            public SyntaxErrorReport(boolean hasErrors, boolean allErrorsAtEof) {
205                this.hasErrors = hasErrors;
206                this.allErrorsAtEof = allErrorsAtEof;
207            }
208    
209            public boolean isHasErrors() {
210                return hasErrors;
211            }
212    
213            public boolean isAllErrorsAtEof() {
214                return allErrorsAtEof;
215            }
216        }
217    
218        public static SyntaxErrorReport reportSyntaxErrors(@NotNull final PsiElement file, @NotNull final MessageCollector messageCollector) {
219            class ErrorReportingVisitor extends AnalyzingUtils.PsiErrorElementVisitor {
220                boolean hasErrors = false;
221                boolean allErrorsAtEof = true;
222    
223                private <E extends PsiElement> void reportDiagnostic(E element, DiagnosticFactory0<E> factory, String message) {
224                    MyDiagnostic<?> diagnostic = new MyDiagnostic<E>(element, factory, message);
225                    AnalyzerWithCompilerReport.reportDiagnostic(diagnostic, messageCollector, false);
226                    if (element.getTextRange().getStartOffset() != file.getTextRange().getEndOffset()) {
227                        allErrorsAtEof = false;
228                    }
229                    hasErrors = true;
230                }
231    
232                @Override
233                public void visitErrorElement(PsiErrorElement element) {
234                    String description = element.getErrorDescription();
235                    reportDiagnostic(element, SYNTAX_ERROR_FACTORY, StringUtil.isEmpty(description) ? "Syntax error" : description);
236                }
237            }
238            ErrorReportingVisitor visitor = new ErrorReportingVisitor();
239    
240            file.accept(visitor);
241    
242            return new SyntaxErrorReport(visitor.hasErrors, visitor.allErrorsAtEof);
243        }
244    
245        @Nullable
246        public AnalysisResult getAnalysisResult() {
247            return analysisResult;
248        }
249    
250        public boolean hasErrors() {
251            return messageCollector.anyReported(CompilerMessageSeverity.ERROR);
252        }
253    
254        public void analyzeAndReport(@NotNull Collection<JetFile> files, @NotNull Function0<AnalysisResult> analyzer) {
255            analysisResult = analyzer.invoke();
256            reportSyntaxErrors(files);
257            List<AbiVersionErrorData> abiVersionErrors = getAbiVersionErrors();
258            reportDiagnostics(analysisResult.getBindingContext().getDiagnostics(), messageCollector, !abiVersionErrors.isEmpty());
259            if (hasErrors()) {
260                reportAbiVersionErrors(abiVersionErrors);
261            }
262            reportIncompleteHierarchies();
263            reportAlternativeSignatureErrors();
264        }
265    
266        private static class MyDiagnostic<E extends PsiElement> extends SimpleDiagnostic<E> {
267            private final String message;
268    
269            public MyDiagnostic(@NotNull E psiElement, @NotNull DiagnosticFactory0<E> factory, String message) {
270                super(psiElement, factory, Severity.ERROR);
271                this.message = message;
272            }
273    
274            @Override
275            public boolean isValid() {
276                return true;
277            }
278        }
279    }