slige/compiler/diagnostics.ts

55 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-01-22 21:40:29 +00:00
import { Ctx, File } from "./ctx.ts";
export type Span = {
begin: Pos;
end: Pos;
};
export type Pos = {
idx: number;
line: number;
col: number;
};
2025-01-23 09:18:33 +00:00
export type Report = {
2025-01-22 21:40:29 +00:00
severity: "fatal" | "error" | "warning" | "info";
origin?: string;
msg: string;
file?: File;
span?: Span;
pos?: Pos;
};
2025-01-23 09:18:33 +00:00
export function prettyPrintReport(ctx: Ctx, rep: Report) {
const { severity, msg } = rep;
const origin = rep.origin ? `${rep.origin}: ` : "";
2025-01-22 21:40:29 +00:00
console.error(`${origin}${severity}: ${msg}`);
2025-01-23 09:18:33 +00:00
if (rep.file && (rep.span || rep.pos)) {
const { absPath: path } = ctx.fileInfo(rep.file);
const { line, col } = rep.span?.begin ?? rep.pos!;
2025-01-22 21:40:29 +00:00
console.error(` at ./${path}:${line}:${col}`);
2025-01-23 09:18:33 +00:00
}
}
export function printStackTrace() {
class StackTracer extends Error {
constructor() {
super("StackTracer");
}
}
try {
throw new StackTracer();
} catch (error) {
if (!(error instanceof StackTracer)) {
throw error;
2025-01-22 21:40:29 +00:00
}
2025-01-23 09:18:33 +00:00
console.log(
error.stack?.replace(
"Error: StackTracer",
"Stack trace:",
) ??
error,
);
2025-01-22 21:40:29 +00:00
}
}