Search code examples
javascriptmacrossweet.js

sweet.js cannot return #`else`


main.js

import {另} from './chinese-macros';
另 {
}

chinese-macros.js

export syntax 另 = function(ctx) {
    return #`else`;
}

main.js should compile to else {} but I get this error message instead:

throw this.createError(start, "not a valid expression");

Any help would be greatly appreciated.


Solution

  • else {} by itself is an invalid expression, that's why you're receiving that error message. What (I believe) you're doing is trying to replace if and else into Chinese. So assuming you've made a macro for an if statement, the compiler will end up evaluating the macro for if, then separately evaluating for the else macro.

    What you should do instead is build up a macro for the if/else-if/else statement in one macro, much like how the tutorial builds one for a cond expression: http://sweetjs.org/doc/1.0/tutorial.html#_sweet_cond. Notice how they iterate through keywords starting with case then default, and throwing an error if none of those two appear (invalid syntax). It's the same idea for what you want to achieve except doing if, else if, and else in that order... while adding more error handling and accounting for the different syntax.