2014-10-30 45 views
0

假設有一個地方叫m功能,調用這樣是否可以將sweet.js宏`m`展開爲符號`m`?

//foo.js 
m("foo") 

我有一個sweet.js宏定義了一個名爲m宏觀其目的是要採取foo.js和擴大m(基本運行在編譯時)

在某些情況下,我想不會擴大m,因爲不像宏,功能可作爲左右一等公民通過功能

doSomething(m) //don't want to expand this as a macro 

如果我在宏中沒有涵蓋這種情況的情況,sweet.js會抱怨,所以我需要一個可以擴展到相同符號的catch-all規則。

macro m { 
    //simplification to demonstrate a case that recursively expand macro 
    case { _ ($foo, $bar) } => { return #{m($foo)} } 
    //does syntax unwrapping in real case 
    case { _ ($foo) } => { return #{$foo} } 

    //**this tries to recursively expand `m`, which is not what I want** 
    case { _ } => { return #{m} } 
} 

如何讓m宏擴展到m功能,考慮到宏觀的其他情況下確實需要遞歸擴展m宏?

回答

1

你要let綁定宏:

let m = macro { 
    case { _ ($foo, $bar) } => { return #{$foo} } 
    case { _ ($foo) } => { return #{$foo} } 

    // `m` is bound to the surrounding scope, not the macro 
    case { _ } => { return #{m} } 
} 

編輯:

對不起,沒有看過你的問題完全在第一時間:)

這裏有一個更好的解決方案,你只需要將它分成兩個不同的宏,一個可以做實際的遞歸工作,另一個可以處理非遞歸基本情況:

function m() {} 
macro m_impl { 
    case { _ ($foo, $bar) } => { return #{m_impl($foo)} } 
    case { _ ($foo) } => { return #{$foo} } 
} 

let m = macro { 
    case { _ ($foo, $bar) } => { return #{m_impl($foo, $bar)} } 
    case { _ } => { return #{m} } 
} 

m (100, 200); 
doSomething(m) 
+0

當某些案例規則確實需要將宏展開爲m時(如第一種情況),這不起作用 – LeoHorie 2014-11-06 04:19:01

+0

啊,抱歉太快地讀出你的問題。希望對您有更好的解決方案進行編輯。 – timdisney 2014-11-07 23:31:43

+0

啊哈,完美的解決方案!謝謝! – LeoHorie 2014-11-08 04:31:01

相關問題