ThomasC__
ThomasC__

Reputation: 321

SweetJS : Write a macro for a specific library

I'm currently working on a little project which consists about writing macros for Ramda. Here is an example :

let map = macro {
    rule { $f $array } => { R.map($f, $array) }
    rule { $f } => { R.map($f) }
}

I tried to compile this simple sample of code as a beginning :

var R = require('ramda');

function log (value) {
    console.log(value);
}

map log [1, 2, 3];

Because of hygiene, the compiled code looks like this :

var R$759 = require('ramda');
function log$761(value$762) {
    console.log(value$762);
}                   
R.map(log$761)[1, 2, 3];

My problem is that I don't know how to make reference to ramda.

Has anyone tried to write macros for a specific library and encountered this problem ?

Upvotes: 1

Views: 137

Answers (1)

timdisney
timdisney

Reputation: 5337

At the moment the ways to do it are a little hacky. In the next release when we get ES6 modules this will actually be taken care of automatically for you but until then the best option is to have an initialization macro (this is what ki and contracts.js do). This works by having a shared variable in scope for all of your macros and then having the user first invoke an import macro that does the necessary require:

var r_lib;
macro import {
    rule { $name from $path } => { 
        r_lib = require($path);
    }
}
let map = macro {
    rule { $f $l } => { r_lib.map($f, $l) }
}

import R from "ramda"

map log [1,2,3]

Upvotes: 2

Related Questions