使用sweet.js宏删除日志语句

时间:2014-09-18 15:11:13

标签: sweet.js

我今天刚开始使用sweet.js,所以有些问题可能很容易解决......

我想从生源版本的源代码中删除日志语句。 sweet.js似乎足够灵活,可以做到这一点。

有各种日志声明和限制:

  • console.log( "wow");应该被移除,而console.warn( "wow");则应该不受影响。

  • this.log( "wow");也应该被移除

  • this.assert(foo, "foo is undefined").log( "object created");this.assert(foo, "foo is undefined").log( "object created").flush();等语句中应删除.log( ...)部分。

我目前的sweet.js宏包括工作的例子,而不是:

macro console {
    rule { .log( $args (,) ...); } => { 
        // was removed
    }
    rule { _ } => { ... }
}

macro this {
    rule { .log( $args (,) ...); } => { 
        // was removed
    }
    rule { _ } => { ... }
}

macro this {
    rule { .log( $args (,) ...); } => { 
        // was removed
    }
    rule { _ } => { ... }
}

    // works
console.log( "wow");

    // works
console
.log
( "wow")
;

    // works partially -> "console." is missing before "warn" : 
    // outputs 'warn("wow");' instead of 'console.warn("Wow");'
console.warn("wow")

    // doesnt work yet
    // should output 'this.assert(foo, "foo is undefined");'
this.assert(foo, "foo is undefined").log( "object created");

    // doesnt work yet
    // should output 'this.assert(foo, "foo is undefined").flush();' 
this.assert(foo, "foo is undefined").log( "object created").flush();

您可以在此处播放:sweetjs editor containing this example

欢迎任何帮助: - )

1 个答案:

答案 0 :(得分:2)

macro console {
  case { $console .$method( $args ... ) } => {
    return #{
      // was removed
    }
  }
}

macro log {
  case infix { . | $log ( $args ... ) } => {
    return #{
      // was removed
    }
  }
}

第二个是中缀宏,左右两边用|分隔 匹配分号不是必需的。

但是上面的宏也会删除所有warnerrortime等。 所以我把它改写成了这个符合问题所有条件的宏:

macro log {
  case infix { console . | $log ( $args ... ) } => {
    return #{
      // was removed
    }
  }
  case infix { . | $log ( $args ... ) } => {
    return #{
      // was removed
    }
  }
}