从另一个引用一个sweet.js宏的正确方法是什么?

时间:2015-02-23 19:05:36

标签: sweet.js

tl;dr

当我在单独的文件中有宏时,我得到一个错误,但如果宏在同一个文件中,它似乎有效。

test-macro-1.js:

macro genVar {
  case {$name ($varName, $varVal, $name2)} => {
    letstx $ident = [makeIdent(unwrapSyntax(#{$varName}), #{$name2})];
    return #{var $ident = $varVal}
  }
}

export genVar;

test-macro-2.js:

macro someVars {
  case {$name ()} => {
    return #{
      genVar('foo', 'hello world', $name);
      genVar('bar', 'goodbye cruel world', $name)
    }
  }
}

export someVars;

test.js:

someVars();

console.log('foo=%s', foo);
console.log('bar=%s', bar);

results:

$ sjs -r --module ./test-macro-1.js --module ./test-macro-2.js test.js
/usr/local/lib/node_modules/sweet.js/lib/sweet.js:90
                    throw new SyntaxError(syn.printSyntaxError(source$2, err))
                          ^
SyntaxError: [macro] Macro `someVars` could not be matched with `...`
1: someVars();
   ^
    at expand$2 (/usr/local/lib/node_modules/sweet.js/lib/sweet.js:90:27)
    at parse (/usr/local/lib/node_modules/sweet.js/lib/sweet.js:123:29)
    at Object.compile (/usr/local/lib/node_modules/sweet.js/lib/sweet.js:129:19)
    at Object.exports.run (/usr/local/lib/node_modules/sweet.js/lib/sjs.js:85:27)
    at Object.<anonymous> (/usr/local/lib/node_modules/sweet.js/bin/sjs:7:23)
    at Module._compile (module.js:460:26)
    at Object.Module._extensions..js (module.js:478:10)
    at Module.load (module.js:355:32)
    at Function.Module._load (module.js:310:12)
    at Function.Module.runMain (module.js:501:10)

但是......如果我将宏放在同一个文件中,如下所示:

test-macro-1.js:

macro genVar {
  case {$name ($varName, $varVal, $name2)} => {
    letstx $ident = [makeIdent(unwrapSyntax(#{$varName}), #{$name2})];
    return #{var $ident = $varVal}
  }
}

export genVar;

macro someVars {
  case {$name ()} => {
    return #{
      genVar('foo', 'hello world', $name);
      genVar('bar', 'goodbye cruel world', $name)
    }
  }
}

export someVars;

results:

$ sjs -r --module ./test-macro-1.js test.js
var foo = 'hello world';
var bar = 'goodbye cruel world';
console.log('foo=%s', foo);
console.log('bar=%s', bar);

那些有经验的人对于将宏安排到文件中以实现模块化和功能的正确方法有任何指导吗?

1 个答案:

答案 0 :(得分:1)

我们目前所谓的&#34;模块的限制&#34;系统很遗憾。从模块导出的宏只会绑定在正在导出的文件和编译目标中(因此genVar仅绑定在test-macro-1.jstest.js)中。通常人们所做的是在一个文件macros.js中定义所有宏,并使用它来编译东西。

我们正在研究一个真正的module system来解决这个问题和其他难点,但还没有准备好。

相关问题