From a2c81883f49e90fb077d7556f1a4d3e58f662363 Mon Sep 17 00:00:00 2001 From: Guy C Date: Thu, 6 Feb 2025 20:46:45 +0000 Subject: [PATCH] refactor: improvements to semantic error printing format Co-authored by: al4423 --- src/main/wacc/Error.scala | 29 +++++++++++++++++++++++------ 1 file changed, 23 insertions(+), 6 deletions(-) diff --git a/src/main/wacc/Error.scala b/src/main/wacc/Error.scala index a90c340..87e0a35 100644 --- a/src/main/wacc/Error.scala +++ b/src/main/wacc/Error.scala @@ -20,12 +20,12 @@ def printError(error: Error)(using errorContent: String): Unit = { println( s"Duplicate declaration of identifier ${ident.v} at line: ${ident.getPosition.line} column: ${ident.getPosition.column}" ) - highlight(ident.getPosition.line, ident.getPosition.column, ident.v.length) + highlight(ident) case Error.UndefinedIdentifier(ident, identType) => println( - s"Undefined ${identType.toString.toLowerCase} ${ident.v} at line: ${ident.getPosition.line} column: ${ident.getPosition.column}" + s"Undefined ${identType.toString.toLowerCase()} ${ident.v} at line: ${ident.getPosition.line} column: ${ident.getPosition.column}" ) - highlight(ident.getPosition.line, ident.getPosition.column, ident.v.length) + highlight(ident) case Error.FunctionParamsMismatch(ident, expected, got) => println(s"Function ${ident.v} expects $expected parameters, got $got") case Error.TypeMismatch(expected, got) => @@ -34,8 +34,25 @@ def printError(error: Error)(using errorContent: String): Unit = { } -def highlight(line: Int, column: Int, size: Int)(using errorContent: String): Unit = { +def highlight(ident: ast.Ident)(using errorContent: String): Unit = { val lines = errorContent.split("\n") - val linePointer = " " * (column) + ("^" * (size)) + "\n" - println(s">${lines(line - 2)}\n>${lines(line - 1)}\n$linePointer>${lines(line)}") + + val preLine = if (ident.getPosition.line > 1) lines(ident.getPosition.line - 2) else "" + val midLine = lines(ident.getPosition.line - 1) + val postLine = lines(ident.getPosition.line) + val linePointer = " " * (ident.getPosition.column) + ("^" * (ident.v.length)) + "\n" + + println( + s">$preLine\n>$midLine\n$linePointer>$postLine" + ) + + // var lines: Iterator[String] = errorContent.linesIterator + + // lines = lines.drop(Math.max(0, ident.getPosition.line - 2)) + // println(s">${lines.next()}") + // if (lines.hasNext) + // println(s">${lines.next()}") + // println(" " * (ident.getPosition.column) + ("^" * (ident.v.length))) + // if(lines.hasNext) + // println(s">${lines.next()}") }