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.codegen; 018 019 import com.intellij.openapi.application.ApplicationManager; 020 import com.intellij.openapi.util.Computable; 021 import com.intellij.psi.PsiElement; 022 import org.jetbrains.annotations.NotNull; 023 import org.jetbrains.annotations.Nullable; 024 import org.jetbrains.jet.lang.diagnostics.DiagnosticUtils; 025 026 public class CompilationException extends RuntimeException { 027 private final PsiElement element; 028 029 public CompilationException(@NotNull String message, @Nullable Throwable cause, @NotNull PsiElement element) { 030 super(getMessage(message, cause, element), cause); 031 this.element = element; 032 } 033 034 @NotNull 035 public PsiElement getElement() { 036 return element; 037 } 038 039 040 private static String where(@NotNull Throwable cause) { 041 StackTraceElement[] stackTrace = cause.getStackTrace(); 042 if (stackTrace != null && stackTrace.length > 0) { 043 return stackTrace[0].getFileName() + ":" + stackTrace[0].getLineNumber(); 044 } 045 return "unknown"; 046 } 047 048 public static String getMessage(@NotNull final String message, @Nullable final Throwable cause, @NotNull final PsiElement element) { 049 return ApplicationManager.getApplication().runReadAction(new Computable<String>() { 050 @Override 051 public String compute() { 052 StringBuilder result = 053 new StringBuilder("Back-end (JVM) Internal error: ").append(message).append("\n"); 054 if (cause != null) { 055 String causeMessage = cause.getMessage(); 056 result.append("Cause: ").append(causeMessage == null ? cause.toString() : causeMessage).append("\n"); 057 } 058 result.append("File being compiled and position: ").append(DiagnosticUtils.atLocation(element)).append("\n"); 059 result.append("PsiElement: ").append(element.getText()).append("\n"); 060 if (cause != null) { 061 result.append("The root cause was thrown at: ").append(where(cause)); 062 } 063 064 return result.toString(); 065 } 066 }); 067 } 068 }