调用方法的Sweet.js宏 [英] Sweet.js macro that calls a method
问题描述
我正在尝试编写一个sweet.js
宏,该宏需要生成方法调用语法obj.method()
,但是method
作为字面量表达式传递给该宏.例如:
I'm trying to write a sweet.js
macro which needs to generate method call syntax, obj.method()
, but the method
is passed in to the macro as a literal expression. For example:
mcall(obj, toString().length);
// becomes
obj.toString().length;
我有一些接近的东西:
macro mcall {
rule { ($o, $m:expr) } => { $o.$m }
}
mcall(obj, toString().length);
但是,这显然扩展为:
obj . ( toString ( ) . length );
这些多余的括号是从哪里来的,我该如何去除它们?我应该使用案例规则和#{}
吗?我尝试了这种排列,但是在没有额外括号的情况下仍然无法成功生成方法调用.
Where are these extra parentheses coming from, and how do I get rid of them? Should I be using case rules and #{}
? I tried permutations of that but still couldn't succeed at generating a method call without extra parentheses.
推荐答案
因此,当前在sweet.js令牌中,绑定到:expr
模式变量的令牌被包裹在括号中,以帮助获得优先权以使其正常工作.这是一种hack,很快就会得到修复(此处有更多讨论: https://github.com/mozilla/sweet.js/issues/314 ).
So currently in sweet.js tokens bound to an :expr
pattern variable get wrapped in parens to help with getting precedence to work correctly. This is kind of a hack and will get fixed soon (some more discussion here: https://github.com/mozilla/sweet.js/issues/314).
您的示例的简单解决方案是不使用:expr
,因为您实际上并不需要它:
The simple solution for your example is to just not use :expr
since you don't really need it:
macro mcall {
rule { ($o, $m ...) } => { $o.$m ... }
}
侧面说明:使用:expr
在技术上是错误的,因为不允许.
的RHS是不受限制的表达式(例如,2+4
匹配$m:expr
,但obj.2+4
是语法错误).
Side note: using :expr
is technically wrong here since the RHS of a .
is not allowed to be an unrestricted expression (eg 2+4
matches $m:expr
but obj.2+4
is a syntax error).
这篇关于调用方法的Sweet.js宏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!