标量隐式宏应该返回什么以告诉编译器

标量隐式宏应该返回什么以告诉编译器

本文介绍了标量隐式宏应该返回什么以告诉编译器“忘记我的结果,继续搜索"?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

限时删除!!

我有一个带有贪婪签名的隐式宏

I have an implicit macro with a greedy signature

implicit def materializeHelper[C <: Any]: Helper[C] = macro materializeHelperImpl[C]

def materializeHelperImpl[C <: Any: ctx.WeakTypeTag](ctx: blackbox.Context): ctx.Expr[Helper[C]] = ???

根据它的签名,它将为任何C生成一个 Helper [C] .但是它的主体更加挑剔.它只接受作为密封特征的 C .宏应该返回什么来告诉编译器忘记我的结果,继续进行隐式搜索,就像我不存在一样"?

According to it's signature it would materialize a Helper[C] for any C. But the body is much more picky. It only accepts Cs which are sealed traits.What should the macro return to tell the compiler "forget my result, continue your implicit search as if I didn't exist"?

当前我正在返回一个空块( q""),这是不理想的,因为当所述隐式用作中间规则时,编译器会实现一个 null .例如,在以下行中,当宏返回空( q"")时, helper 参数设置为null.

Currently I am returning an empty block (q""), which is not ideal because the compiler materializes a null when said implicit is used as an intermediate rule. For example, in the following line, the helper parameter is set to null when the macro returns empty (q"").

implicit def parser[C <: Any](implicit helper: Helper[C]): Parser[C] = new Parser[C](helper)

我的意图是,在 C 不是密封特征的情况下,编译器将丢弃前面提到的两个隐式值,并继续搜索另一个更具体的隐式值.

And my intention is that, in the case that C is not a sealed trait, the compiler discards both beforementioned implicit and continue the search for another more specific implicit value.

推荐答案

您没有使宏实现类型的类 Helper 白盒.

You didn't make your macro materializing type class Helper whitebox.

隐式宏.默认隐式值.怎么样?

https://docs.scala-lang.org/overviews/macros/blackbox-whitebox.html

使用自定义错误消息调用 c.abort 更为习惯.尽管它们看起来不那么习惯(尽管最好是这样),但也可能引发异常,调用 c.error ,返回 EmptyTree (在这种情况下,它不会进行类型检查).有明确的编译错误消息).

It's more idiomatical to call c.abort with custom error message. Throwing an exception, calling c.error, returning EmptyTree (it just doesn't typecheck in such case) are also possible although they seem a little less idiomatical (it's better to have clear compile error message).

这篇关于标量隐式宏应该返回什么以告诉编译器“忘记我的结果,继续搜索"?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

1403页,肝出来的..

09-06 22:07