2

How would you create a string from an argument to a sweet.js macro? For example:

let foo = macro {
    rule {
        $name
    } => {
        console.log('$name', $name);
    }
}

var x = 42;

foo x

Will output:

console.log(x, x);

When I'd prefer it to output:

console.log('x', x);

So the first argument has quotes around it.

Aaron Powell
  • 24,927
  • 18
  • 98
  • 150

1 Answers1

5

You can use a case macro:

let foo = macro {
    case {_
        $name
    } => {
        letstx $name_str = [makeValue(unwrapSyntax(#{$name}), #{here})];
        return #{
            console.log($name_str, $name);
        }
    }
}

var x = 42;

foo x

The basic idea is that you make a new string token (via makeValue) using the string value of the identifiers mached by $name (unwrapSyntax gives us the value of the given syntax objects, in the case of identifiers it is the identifier string). Then letstx allows us to bind our newly created syntax object for use inside the #{} template.

timdisney
  • 5,287
  • 9
  • 35
  • 31
  • Excellent, I thought I might have to use a case macro but every time I tried to work out how I ended up with syntax errors but your explanation clears it up nicely – Aaron Powell Feb 18 '14 at 21:55