Search code examples
javascriptsweet.js

access parents variable in Sweet.js


I'm creating a new object orientation system and I need to access the variables of the parent of the macro. I have the following:

macro module {
    rule { $i:ident { $e ... } } => {
        var $i = {
            $e ...
        }
    }
}

macro fn {
    rule { $i:ident { $e ... } } => {
        $e ...
    }
}

module x {
    fn name { 

    }
}

I want be able to, in fn macro, have available the module name, in this case, x, because maybe I want to do something like $parentModule.prototype.myFunc. But if I do $e$e it doesn't works properly. Is it possible?


Solution

  • There's a few ways to do this but I think the simplest thing to do is use named patterns:

    macro module {
        rule { 
            $i:ident {
                $mbody:(fn $name:ident { $body ...}) ...
            }
        } => {
            $i.prototype.$mbody$name ...
        }
    }
    
    module x {
        fn name { 
    
        }
    }