Import source code printer for diagnostic messages

This commit is contained in:
Sam Vervaeck 2020-05-23 22:36:18 +02:00
parent 2a873484c4
commit 846536023d

View file

@ -17,6 +17,13 @@ export interface Diagnostic {
node?: Syntax;
}
export function countDigits(num: number) {
if (num === 0) {
return 1
}
return Math.ceil(Math.log10(num+1))
}
export class DiagnosticPrinter {
public hasErrors = false;
@ -28,6 +35,29 @@ export class DiagnosticPrinter {
this.hasErrors = true;
out += chalk.bold.red('error: ');
}
if (diagnostic.node !== undefined) {
// message = this.fileManager.getFileName(diag.location.fileId)+': '+message
const content = this.fileManager.getContent(diag.location.fileId)
const startLine = Math.max(0, diag.location.start.line-1-DIAG_NUM_EXTRA_LINES)
const lines = content.split('\n')
const endLine = Math.min(lines.length-1, (diag.location.end !== undefined ? diag.location.end.line : startLine)+DIAG_NUM_EXTRA_LINES)
const gutterWidth = Math.max(2, countDigits(endLine+1))
for (let i = startLine; i < endLine; i++) {
console.error(' '+chalk.bgWhite.black(' '.repeat(gutterWidth-countDigits(i+1))+(i+1).toString())+' '+lines[i])
const gutter = ' '+chalk.bgWhite.black(' '.repeat(gutterWidth))+' '
if (diag.location.end !== undefined) {
if (i === diag.location.start.line-1 && i === diag.location.end.line-1) {
console.error(gutter+' '.repeat(diag.location.start.column-1)+chalk.red('~'.repeat(diag.location.end.column-diag.location.start.column)))
} else if (i === diag.location.start.line-1) {
console.error(gutter+' '.repeat(diag.location.start.column-1)+chalk.red('~'.repeat(lines[i].length-diag.location.start.column+1)))
} else if (i === diag.location.end.line-1) {
console.error(gutter+chalk.red('~'.repeat(diag.location.end.column-1)))
} else if (i > diag.location.start.line-1 && i < diag.location.end.line-1) {
console.error(gutter+chalk.red('~'.repeat(lines[i].length)))
}
}
}
}
if (diagnostic.args !== undefined) {
out += format(diagnostic.message, diagnostic.args);
} else {