Transpile backtick characters (`) correctly into JS

In Lua they don't (appear?) to be syntactically relevant, but in JS they very much are, especially with the way that the Lua syntax is compiled into JS.

For example:

```lua
return "This is a `string with backticks` in it"
```

Is compiled to JS as:

```
return [`This is a `string with backticks` in it`]
```

Where "string with backticks" is evaluated as literal JS code. This is _potentially_ a security issue because a specially-formatted string could evaluate arbitrary JS code. More annoyingly, though, it means that any string with backticks in it is probably going to cause the JS interpeter to crash.

This commit fixes that by escaping backtick characters with a \, so the compiled JS above would instead look like:

```
return [`This is a \`string with backticks\` in it`]
```

Much better!
pull/15/head
Nicholas Husher 2 years ago committed by Teodor Tanasoaia
parent 2f1cf03d42
commit b9af44bfde

@ -223,6 +223,7 @@ const generate = (node: luaparse.Node): string | MemExpr => {
const S = node.value
.replace(/([^\\])?\\(\d{1,3})/g, (_, pre, dec) => `${pre || ''}${String.fromCharCode(dec)}`)
.replace(/\\/g, '\\\\')
.replace(/`/g, '\\`')
return `\`${S}\``
}

@ -40,4 +40,17 @@ let exitCode = 0
}
}
{
const luaEnv = luainjs.createEnv()
let str
try {
str = luaEnv.parse('return "Backtick `literals` in strings work"').exec()
} catch (e) {
throw Error('Backticks in strings transpile into invalid code!')
}
if (str !== 'Backtick `literals` in strings work') {
throw Error('Backticks in strings transpile incorrectly!')
}
}
process.exit(exitCode)

Loading…
Cancel
Save