dimanche 12 avril 2015

When typechecking code from within a macro, is it possible to detect a typecheck failure caused by a macro expansion within that code?

I would like to write a macro that compiles code that it receives as a String literal and detect a typecheck error in the compiled code that is due to a macro expansion failure (either the macro was aborted, or the expanded macro failed to typecheck)


I was thinking something like this:



def myMacro(c: Context)(codeStringLiteral: c.Expr[String]): c.Expr[Unit] = {
val codeString = getString(codeStringLiteral) // this part is easy
val ast = c.parse(code)
val actualCode = util.Try(c.typecheck(ast)).recover{ case t: TypecheckException =>
if(t.isMacroExpansionFailure) doOneThing
else doOtherThing
}
c.Expr(actualCode.get)
}


Is this possible?


Context


Such a macro would make testing other macros much more pleasant by deferring to runtime a failure that is due to a macro expansion, thus allowing one to execute the entire test suite even when a test case for your macro is broken.


Of course, it is easy enough to simply differ typechecking entirely to runtime, but it would be really nifty to only differ errors that are due to the macro you are writing under test and fail at compile time if it's the test code itself that is at fault.


Of course, it's possible for an unrelated macro to fail, but it's unlikely to happen very often.






Aucun commentaire:

Enregistrer un commentaire