melody icon indicating copy to clipboard operation
melody copied to clipboard

Support for variable interpolation inside template strings

Open trezy opened this issue 2 years ago • 1 comments

Copied from this Reddit conversation

I'd love to see support for interpolation of template literals in the compiled RegEx from the Babel plugin. For example, I can almost accomplish this with the Babel compiler using Melody's raw method:

// Original
new RegExp(/*melody*/ `
  "foo"; 
  \`\${bar}\`;
  "baz";
`)

// Compiled
new RegExp("foo${bar}baz")

It seems that this could be fixed just by wrapping the string output in backticks instead of quotes. I originally assumed this would have unintended consequences, but since $, {, and } are all special RegEx characters, they're automatically escaped in string literals. This protects us from misinterpreted literals:

// Original
new RegExp(/*melody*/ `
  "foo";
  "${bar}";
  "baz";
`)

// Compiled
new RegExp("foo\$\{bar\}baz")

I did come up with this while sleepy, sp=o it's entirely possible that I may be missing something. 🤔

trezy avatar Apr 06 '22 14:04 trezy

Hey @trezy, I could theoretically change the plugin to output a template string assuming the input was a template string which should cause your first example to work, I'm wondering if \`\${bar}\`; isn't a bit unintuitive to say the least.

The problem is that since the compiler is basically being used by the plugin rather than the plugin being the "main product", I'd like to avoid creating special syntax for the compiler stage.

I could introduce some plugin only syntax that would be converted to a normal template string interpolation in the output, e.g.

// Original
new RegExp(/*melody*/ `
  "foo"; 
  {{bar}}
  "baz";
`)

// Additional step before compilation
new RegExp(/*melody*/ `
  "foo"; 
  \`\${bar}\`
  "baz";
`)

// Compiled
new RegExp(`foo${bar}baz`)

Would that work?

Note that syntax highlighting / language tools might not notice issues with this syntax (e.g. changing a variable name and not changing it in the template)

Edit: an alternative might be directly detecting

// Original
new RegExp(/*melody*/ `
  "foo"; 
  ${bar}
  "baz";
`)

and transforming that, would need to look into it

yoav-lavi avatar Apr 08 '22 12:04 yoav-lavi