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 com.google.common.collect.Lists;
020    import com.intellij.lang.ASTNode;
021    import com.intellij.openapi.application.ApplicationManager;
022    import com.intellij.openapi.editor.Document;
023    import com.intellij.openapi.util.TextRange;
024    import com.intellij.openapi.vfs.VirtualFile;
025    import com.intellij.psi.PsiElement;
026    import com.intellij.psi.PsiFile;
027    import org.jetbrains.annotations.NotNull;
028    import org.jetbrains.annotations.Nullable;
029    import org.jetbrains.kotlin.descriptors.DeclarationDescriptor;
030    import org.jetbrains.kotlin.psi.KtExpression;
031    import org.jetbrains.kotlin.resolve.DescriptorToSourceUtils;
032    import org.jetbrains.kotlin.resolve.diagnostics.Diagnostics;
033    
034    import java.util.Collection;
035    import java.util.Collections;
036    import java.util.Comparator;
037    import java.util.List;
038    
039    public class DiagnosticUtils {
040        @NotNull
041        private static final Comparator<TextRange> TEXT_RANGE_COMPARATOR = new Comparator<TextRange>() {
042            @Override
043            public int compare(@NotNull TextRange o1, @NotNull TextRange o2) {
044                if (o1.getStartOffset() != o2.getStartOffset()) {
045                    return o1.getStartOffset() - o2.getStartOffset();
046                }
047                return o1.getEndOffset() - o2.getEndOffset();
048            }
049        };
050    
051        private DiagnosticUtils() {
052        }
053    
054        public static String atLocation(DeclarationDescriptor descriptor) {
055            PsiElement element = DescriptorToSourceUtils.descriptorToDeclaration(descriptor);
056            if (element == null) {
057                element = DescriptorToSourceUtils.descriptorToDeclaration(descriptor.getOriginal());
058            }
059            if (element == null && descriptor instanceof ASTNode) {
060                element = getClosestPsiElement((ASTNode) descriptor);
061            }
062            if (element != null) {
063                return atLocation(element);
064            } else {
065                return "unknown location";
066            }
067        }
068    
069        public static String atLocation(KtExpression expression) {
070            return atLocation(expression.getNode());
071        }
072    
073        public static String atLocation(@NotNull PsiElement element) {
074            return atLocation(element.getNode());
075        }
076    
077        public static String atLocation(@NotNull ASTNode node) {
078            int startOffset = node.getStartOffset();
079            PsiElement element = getClosestPsiElement(node);
080            if (element != null && element.isValid()) {
081                return atLocation(element.getContainingFile(), element.getTextRange());
082            }
083            return "' at offset " + startOffset + " (line and file unknown: no PSI element)";
084        }
085    
086        @Nullable
087        public static PsiElement getClosestPsiElement(@NotNull ASTNode node) {
088            while (node.getPsi() == null) {
089                node = node.getTreeParent();
090            }
091            return node.getPsi();
092        }
093        
094        @NotNull
095        public static PsiFile getContainingFile(@NotNull ASTNode node) {
096            PsiElement closestPsiElement = getClosestPsiElement(node);
097            assert closestPsiElement != null : "This node is not contained by a file";
098            return closestPsiElement.getContainingFile();
099        }
100    
101        @NotNull
102        public static String atLocation(@NotNull PsiFile file, @NotNull TextRange textRange) {
103            Document document = file.getViewProvider().getDocument();
104            return atLocation(file, textRange, document);
105        }
106    
107        @NotNull
108        public static String atLocation(PsiFile file, TextRange textRange, Document document) {
109            int offset = textRange.getStartOffset();
110            VirtualFile virtualFile = file.getVirtualFile();
111            String pathSuffix = " in " + (virtualFile == null ? file.getName() : virtualFile.getPath());
112            return offsetToLineAndColumn(document, offset).toString() + pathSuffix;
113        }
114    
115        @NotNull
116        public static LineAndColumn getLineAndColumn(@NotNull Diagnostic diagnostic) {
117            PsiFile file = diagnostic.getPsiFile();
118            List<TextRange> textRanges = diagnostic.getTextRanges();
119            if (textRanges.isEmpty()) return LineAndColumn.NONE;
120            TextRange firstRange = firstRange(textRanges);
121            return getLineAndColumnInPsiFile(file, firstRange);
122        }
123    
124        @NotNull
125        public static LineAndColumn getLineAndColumnInPsiFile(PsiFile file, TextRange range) {
126            Document document = file.getViewProvider().getDocument();
127            return offsetToLineAndColumn(document, range.getStartOffset());
128        }
129    
130        @NotNull
131        public static LineAndColumn offsetToLineAndColumn(@Nullable Document document, int offset) {
132            if (document == null) {
133                return new LineAndColumn(-1, offset, null);
134            }
135    
136            int lineNumber = document.getLineNumber(offset);
137            int lineStartOffset = document.getLineStartOffset(lineNumber);
138            int column = offset - lineStartOffset;
139    
140            int lineEndOffset = document.getLineEndOffset(lineNumber);
141            CharSequence lineContent = document.getCharsSequence().subSequence(lineStartOffset, lineEndOffset);
142    
143            return new LineAndColumn(lineNumber + 1, column + 1, lineContent.toString());
144        }
145    
146        public static void throwIfRunningOnServer(Throwable e) {
147            // This is needed for the Web Demo server to log the exceptions coming from the analyzer instead of showing them in the editor.
148            if (System.getProperty("kotlin.running.in.server.mode", "false").equals("true") || ApplicationManager.getApplication().isUnitTestMode()) {
149                if (e instanceof RuntimeException) {
150                    throw (RuntimeException) e;
151                }
152                if (e instanceof Error) {
153                    throw (Error) e;
154                }
155                throw new RuntimeException(e);
156            }
157        }
158    
159        @NotNull
160        public static TextRange firstRange(@NotNull List<TextRange> ranges) {
161            return Collections.min(ranges, TEXT_RANGE_COMPARATOR);
162        }
163    
164        @NotNull
165        public static List<Diagnostic> sortedDiagnostics(@NotNull Collection<Diagnostic> diagnostics) {
166            Comparator<Diagnostic> diagnosticComparator = new Comparator<Diagnostic>() {
167                @Override
168                public int compare(@NotNull Diagnostic d1, @NotNull Diagnostic d2) {
169                    String path1 = d1.getPsiFile().getViewProvider().getVirtualFile().getPath();
170                    String path2 = d2.getPsiFile().getViewProvider().getVirtualFile().getPath();
171                    if (!path1.equals(path2)) return path1.compareTo(path2);
172    
173                    TextRange range1 = firstRange(d1.getTextRanges());
174                    TextRange range2 = firstRange(d2.getTextRanges());
175    
176                    if (!range1.equals(range2)) {
177                        return TEXT_RANGE_COMPARATOR.compare(range1, range2);
178                    }
179    
180                    return d1.getFactory().getName().compareTo(d2.getFactory().getName());
181                }
182            };
183            List<Diagnostic> result = Lists.newArrayList(diagnostics);
184            Collections.sort(result, diagnosticComparator);
185            return result;
186        }
187    
188        public static final class LineAndColumn {
189    
190            public static final LineAndColumn NONE = new LineAndColumn(-1, -1, null);
191    
192            private final int line;
193            private final int column;
194            private final String lineContent;
195    
196            public LineAndColumn(int line, int column, @Nullable String lineContent) {
197                this.line = line;
198                this.column = column;
199                this.lineContent = lineContent;
200            }
201    
202            public int getLine() {
203                return line;
204            }
205    
206            public int getColumn() {
207                return column;
208            }
209    
210            @Nullable
211            public String getLineContent() {
212                return lineContent;
213            }
214    
215            // NOTE: This method is used for presenting positions to the user
216            @Override
217            public String toString() {
218                if (line < 0) {
219                    return "(offset: " + column + " line unknown)";
220                }
221                return "(" + line + "," + column + ")";
222            }
223        }
224    
225        public static boolean hasError(Diagnostics diagnostics) {
226            for (Diagnostic diagnostic : diagnostics.all()) {
227                if (diagnostic.getSeverity() == Severity.ERROR) return true;
228            }
229    
230            return false;
231        }
232    }