r/ProgrammingLanguages • u/Calm-Bullfrog-6823 • 14d ago
Help How should I structure diagnostics and error reporting in a compiler written in TypeScript?
I'm making a programming language, it's based on Luau and C++ and its called L++! however im having some issues implementing diagnostics since they dont technicallly stop execution, but some of my code has typescript type errors since it relies in, stopping execution! for example normally this would work:
function foo(param: someUnion): someType {
if (someUnion.type === "coolType") {
return someTypeValue
} else {
throw new Error()
}
}
with diagnostics:
function foo(param: someUnion): someType {
if (someUnion.type === "coolType") {
return someTypeValue
} else {
//error since not all paths return someType
reporter.report(new Diagnostic())
}
}
i'd like to know how to fix this, and/or if there are any established ways to do diagnostics, thanks in advance!
2
u/Positive_Total_4414 12d ago
Ok, so imagine the error was somehow "fixed". What do you expect your program to do after that?
I mean, in the case where you throw an error obviously the execution will terminate, which is clear. What do you expect to happen in your second example?
1
u/snugar_i 11d ago
The code you posted is code written in your language, or the compiler of your language? What do the diagnostics do? They report the error and then what?
1
u/Key_River7180 Nain. 10d ago
I have no clue on how to code JS, so here pseudocode:
enum Kind
CLEANUP,
INFO,
WARN,
ERROR,
FATAL
record Diagnostic
Diagnostic* next,
Kind* kind,
String* msg,
Int line, Int column
Diagnostic[] diagnostics
function SerializeToTerminal(diagnostics)
in function tearDown() or however you call your closing function:
SerializeToTerminal(diagnostics)
...1
u/Turbulent_Humor_3213 5d ago
I'd separate reporting an error from deciding whether compilation can continue.
For your example, if foo can't produce a valid someType, it shouldn't pretend it can. You could return someType | undefined, or use a Result type to represent success or failure.
Another common approach is error recovery: report the diagnostic, return a placeholder value, and continue analyzing so you can collect more errors in a single pass.
Also, not every error needs to be recoverable. For cases where continuing doesn't make sense, throwing an internal exception and catching it at a higher level is perfectly reasonable.
The key is that reporting a diagnostic doesn't have to stop compilation, but the function still needs a well-defined way to handle failure.
2
u/Inconstant_Moo 🧿 Pipefish 13d ago
If I understand the problem (and I may not) it's that the diagnostic doesn't return a value you can then use to continue execution.
I'm not sure there is a way round that. This is why errors bubble up and unwind the stack.