Search code examples
sweet.js

remove log statements using a sweet.js macro


I just started with sweet.js today so some problems might be easy to solve ...

I want to remove log statements from my sources for production releases. sweet.js seems to be flexible enough to do this.

There are various kinds of log statements and restrictions :

  • console.log( "wow"); should be removed whereas console.warn( "wow");and so should be untouched.

  • this.log( "wow"); should also be removed

  • in statements like this.assert(foo, "foo is undefined").log( "object created"); and this.assert(foo, "foo is undefined").log( "object created").flush(); the .log( ...) part should be stripped out.

my current sweet.js macro including examples whats working and whats not :

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();

You can play with it here : sweetjs editor containing this example

Any help is welcome :-)


Solution

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

    The second one is infix macro, left and right sides are separated by |.
    Matching semicolons is not necessary.

    But above macros also delete all of warn, error, time etc. So I've rewritten it to this macro which complies to all conditions in the question:

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