Skip to content

Commit c036044

Browse files
committed
Fix lexing of templated strings in pretokeniser, and detect templated strings with no templates and treat them as normal strings (allows pretokenisation) - fix espruino/Espruino#2577
1 parent 65b2e0e commit c036044

File tree

1 file changed

+18
-6
lines changed

1 file changed

+18
-6
lines changed

plugins/pretokenise.js

Lines changed: 18 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -137,21 +137,33 @@
137137
}
138138

139139
var lex = (function() {
140-
var t = acorn.tokenizer(code);
140+
let t = acorn.tokenizer(code, { ecmaVersion : 2020 });
141141
return { next : function() {
142-
var tk = t.getToken();
142+
let tk = t.getToken();
143+
let tkStr = code.substring(tk.start, tk.end), tkValue = tk.value;
143144
if (tk.type.label=="eof") return undefined;
144-
var tp = "?";
145-
if (tk.type.label=="template") tp="TEMPLATEDSTRING";
145+
let tp = "?";
146+
if (tk.type.label=="`") { // template string
147+
// acorn splits these up into tokens, so we have to work through to the end, then just include the full text
148+
let tk2, hasTemplate = false;
149+
do {
150+
tk2 = t.getToken();
151+
if (tk2.type.label=="${")
152+
hasTemplate = true;
153+
} while (tk2.type.label!="`");
154+
tkStr = code.substring(tk.start, tk2.end);
155+
tp = hasTemplate ? "TEMPLATEDSTRING" : "STRING"; // if we don't have any templates, treat as a normal string (https://github.com/espruino/Espruino/issues/2577)
156+
tkValue = hasTemplate ? tkStr : eval(tkStr); // don't evaluate if it has templates as it must be done at runtime!
157+
}
146158
if (tk.type.label=="string") tp="STRING";
147159
if (tk.type.label=="num") tp="NUMBER";
148160
if (tk.type.keyword || tk.type.label=="name") tp="ID";
149161
if (tp=="?" && tk.start+1==tk.end) tp="CHAR";
150162
return {
151163
startIdx : tk.start,
152164
endIdx : tk.end,
153-
str : code.substring(tk.start, tk.end),
154-
value : tk.value,
165+
str : tkStr,
166+
value : tkValue,
155167
type : tp
156168
};
157169
}};

0 commit comments

Comments
 (0)