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