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(@Nullable PsiElement element) {
035            if (element == null) return CompilerMessageLocation.NO_LOCATION;
036            PsiFile file = element.getContainingFile();
037            return psiFileToMessageLocation(file, "<no path>", DiagnosticUtils.getLineAndColumnInPsiFile(file, element.getTextRange()));
038        }
039    
040        @NotNull
041        public static CompilerMessageLocation psiFileToMessageLocation(
042                @NotNull PsiFile file,
043                @Nullable String defaultValue,
044                @NotNull DiagnosticUtils.LineAndColumn lineAndColumn
045        ) {
046            String path;
047            VirtualFile virtualFile = file.getVirtualFile();
048            if (virtualFile == null) {
049                path = defaultValue;
050            }
051            else {
052                path = virtualFile.getPath();
053                // Convert path to platform-dependent format when virtualFile is local file.
054                if (virtualFile instanceof CoreLocalVirtualFile || virtualFile instanceof CoreJarVirtualFile) {
055                    path = toSystemDependentName(path);
056                }
057            }
058            return CompilerMessageLocation.create(path, lineAndColumn.getLine(), lineAndColumn.getColumn(), lineAndColumn.getLineContent());
059        }
060    }