feat: implements error messages for DuplicateDeclaration and UndefinedIdentifier errors

This commit is contained in:
Guy C 2025-02-06 19:49:17 +00:00
parent a635370522
commit 2ac7744e68
2 changed files with 29 additions and 1 deletions

View File

@ -12,3 +12,30 @@ enum Error {
case TypeMismatch(pos: Position, expected: SemType, got: SemType, msg: String) case TypeMismatch(pos: Position, expected: SemType, got: SemType, msg: String)
case InternalError(pos: Position, msg: String) case InternalError(pos: Position, msg: String)
} }
def printError(error: Error)(using errorContent: String): Unit = {
println("Semantic error:")
error match {
case Error.DuplicateDeclaration(ident) =>
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)
case Error.UndefinedIdentifier(ident, identType) =>
println(
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)
case Error.FunctionParamsMismatch(ident, expected, got) =>
println(s"Function ${ident.v} expects $expected parameters, got $got")
case Error.TypeMismatch(expected, got) =>
println(s"Type mismatch: expected $expected, got $got")
}
}
def highlight(line: Int, column: Int, size: Int)(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)}")
}

View File

@ -38,7 +38,8 @@ def compile(contents: String): Int = {
given ctx: typeChecker.TypeCheckerCtx = typeChecker.TypeCheckerCtx(names, errors) given ctx: typeChecker.TypeCheckerCtx = typeChecker.TypeCheckerCtx(names, errors)
typeChecker.check(prog) typeChecker.check(prog)
if (errors.result.nonEmpty) { if (errors.result.nonEmpty) {
errors.result.foreach(println) given errorContent: String = contents
errors.result.foreach(printError)
200 200
} else 0 } else 0
case Failure(msg) => case Failure(msg) =>