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.vfs.VirtualFile;
020    import com.intellij.openapi.vfs.impl.jar.CoreJarVirtualFile;
021    import com.intellij.openapi.vfs.local.CoreLocalVirtualFile;
022    import com.intellij.psi.PsiElement;
023    import com.intellij.psi.PsiFile;
024    import org.jetbrains.annotations.NotNull;
025    import org.jetbrains.annotations.Nullable;
026    import org.jetbrains.kotlin.diagnostics.DiagnosticUtils;
027    
028    import static com.intellij.openapi.util.io.FileUtil.toSystemDependentName;
029    
030    public class MessageUtil {
031        private MessageUtil() {}
032    
033        @NotNull
034        public static CompilerMessageLocation psiElementToMessageLocation(@NotNull PsiElement element) {
035            PsiFile file = element.getContainingFile();
036            DiagnosticUtils.LineAndColumn lineAndColumn = DiagnosticUtils.getLineAndColumnInPsiFile(file, element.getTextRange());
037            return psiFileToMessageLocation(file, "<no path>", lineAndColumn.getLine(), lineAndColumn.getColumn());
038        }
039    
040        @NotNull
041        public static CompilerMessageLocation psiFileToMessageLocation(@NotNull PsiFile file, @Nullable String defaultValue, int line, int column) {
042            String path;
043            VirtualFile virtualFile = file.getVirtualFile();
044            if (virtualFile == null) {
045                path = defaultValue;
046            }
047            else {
048                path = virtualFile.getPath();
049                // Convert path to platform-dependent format when virtualFile is local file.
050                if (virtualFile instanceof CoreLocalVirtualFile || virtualFile instanceof CoreJarVirtualFile) {
051                    path = toSystemDependentName(path);
052                }
053            }
054            return CompilerMessageLocation.create(path, line, column);
055        }
056    }