Search code examples
javascriptmacrossweet.js

Sweet.js - How to put variable in identifier name and string variable?


I'm brand new to Sweet.js. My first simple macro is the following

macro test {
  rule {
    $className($entityName)
  } => {
    function test$className()
    {
      console.print("$className");
      console.print("$entityName");
    }
  }
}

test me(More)

which produces

function test$className() {
    console.print(me);
    console.print(More);
}

but I'd like it to produce this:

function testMe() {
    console.print("me");
    console.print("More");
}

but any variants I've tried for it haven't worked. Any suggestions?


Solution

  • You'll need to use a case macro to construct the exact tokens you want:

    macro test {
        case {_
            $className($entityName)
        } => {
            var classStr = unwrapSyntax(#{$className}[0]);
            var entityStr = unwrapSyntax(#{$entityName}[0]);
            letstx $fnName = [makeIdent("test" + classStr, #{here})];
            letstx $classStr = [makeValue(classStr, #{here})];
            letstx $entityStr = [makeValue(entityStr, #{here})];
            return #{
                function $fnName()
                {
                    console.print($classStr);
                    console.print($entityStr);
                }
            }
        }
    }
    
    test me(More)