gpt4 book ai didi

metaprogramming - Nemerle 宏的中缀格式

转载 作者:行者123 更新时间:2023-12-01 09:40:35 25 4
gpt4 key购买 nike

假设我需要一些非常特殊的乘法运算符。它可以在以下宏中实现:

macro @<<!(op1, op2)
{
<[ ( $op1 * $op2 ) ]>
}

我可以像这样使用它

def val = 2 <<! 3

还有它的工作。

但我真正想要的是一些类似于“英语”的运算符,用于正在开发的 DSL:

macro @multiply(op1, op2)
{
<[ ( $op1 * $op2 ) ]>
}

如果我尝试像这样使用它

def val = 2 multiply 3

编译器因 'expected ;' 而失败错误

有什么问题?如何实现这个中缀格式的宏?

最佳答案

直接来自编译器源代码:

namespace Nemerle.English
{
[assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "and", false, 160, 161)]
[assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "or", false, 150, 151)]
[assembly: Nemerle.Internal.OperatorAttribute ("Nemerle.English", "not", true, 181, 180)]

macro @and (e1, e2) {
<[ $e1 && $e2 ]>
}

macro @or (e1, e2) {
<[ $e1 || $e2 ]>
}

macro @not (e) {
<[ ! $e ]>
}

你需要在周围撒上 OperatorAttributes,它就会起作用。顺便说一句,OperatorAttribute 定义如下:

public class OperatorAttribute : NemerleAttribute
{
public mutable env : string;
public mutable name : string;
public mutable IsUnary : bool;
public mutable left : int;
public mutable right : int;
}

关于metaprogramming - Nemerle 宏的中缀格式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/223556/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com