Nice macro errors with JuliaSyntax

Now with the introduce of JuliaSyntax in newer versions of julia, we get much more friendly syntax error messages. For example:

julia> foo ()
ERROR: ParseError:
# Error @ REPL[28]:1:4
foo ()
#  ╙ ── whitespace is not allowed here
Stacktrace:
 [1] top-level scope
   @ none:1

Now, i’m wondering if we could have these nice error messages in macros. For instance, a macro may require a particular syntax/expression, and if provided with the wrong one, it will throw an error:

macro singleton(expr::Expr)
    isdef(expr) || throw("Expected a function declaration")
    ...
end

I usually call throw(something) explaining to the user what went wrong, which result in an error like:

julia> @singleton x^2
ERROR: LoadError: "Expected a function declaration"
Stacktrace:
 [1] var"@singleton"(__source__::LineNumberNode, __module__::Module, expr::Expr)
   @ Main .\REPL[38]:2
in expression starting at REPL[41]:1

But, what if we could have nicer errors:

julia> @singleton x^2
ERROR: SyntaxError:
# Error @ REPL[41]:1
@singleton x^2
#          ╙ ── Expected function declaration
Stacktrace:
 [1] var"@singleton"(__source__::LineNumberNode, __module__::Module, expr::Expr)
   @ Main .\REPL[38]:2
in expression starting at REPL[41]:1
1 Like

I think that is what Diagnostics does in JuliaSyntax:

2 Likes

Diagnostics seems to be what i’m looking for, but the problem is finding the position in the code where the macro is called along with its arguments. Right now, i only managed to use Diagnostics to highlight the entire line.