Repository navigation
Expand file tree
/
Copy pathFileCompile.cpp
More file actions
350 lines (322 loc) · 13 KB
/
Copy pathFileCompile.cpp
File metadata and controls
350 lines (322 loc) · 13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
#include "ns/loader/FileCompile.h"
#include <array>
#include <climits>
#include <optional>
#include <string_view>
#include <utility>
#include "loader/ImportInternal.h"
#include "loader/LoaderStateInternal.h"
#include "ns/AppFiles.h"
#include "ns/JsError.h"
#include "ns/LoaderConfig.h"
#include "ns/V8Helpers.h"
#include "ns/loader/CodeCacheQueue.h"
#include "ns/loader/LoaderState.h"
namespace nativescript::common::loader {
namespace {
// `text` as a V8 string; throws JsError, prefixed with `failure`, when V8
// cannot make one (too long, out of memory).
v8::Local<v8::String> NewString(v8::Isolate* isolate, std::string_view text,
const std::string& failure) {
if (text.size() > INT_MAX) {
throw JsError(failure + ": too large", JsErrorType::kRangeError);
}
v8::TryCatch tc(isolate);
v8::Local<v8::String> out;
if (!v8::String::NewFromUtf8(isolate, text.data(), v8::NewStringType::kNormal,
static_cast<int>(text.size()))
.ToLocal(&out)) {
JsError::ThrowCaught(isolate, tc, failure);
}
return out;
}
struct PreparedSource {
v8::Local<v8::String> text;
v8::Local<v8::String> origin;
std::optional<CodeCacheEntry> cache;
// A fresh cache for exactly the bytes in `text`, or null.
std::unique_ptr<v8::ScriptCompiler::CachedData> cached;
};
FileInfo StatSource(const std::string& logicalPath) {
std::optional<FileInfo> info = platform::Stat(logicalPath);
if (!info || !info->isFile) {
throw JsError("Cannot find module " + logicalPath);
}
return std::move(*info);
}
v8::Local<v8::String> ReadSource(v8::Isolate* isolate,
const std::string& logicalPath,
SourceWrap wrap) {
std::string body;
if (!platform::ReadFile(logicalPath, body)) {
throw JsError("Cannot read module " + logicalPath);
}
const std::string failure = "Cannot read module " + logicalPath;
if (wrap.prefix.empty() && wrap.suffix.empty()) {
return NewString(isolate, body, failure);
}
std::string wrapped;
wrapped.reserve(wrap.prefix.size() + body.size() + wrap.suffix.size());
wrapped.append(wrap.prefix).append(body).append(wrap.suffix);
body = std::string();
return NewString(isolate, wrapped, failure);
}
PreparedSource Prepare(v8::Isolate* isolate, const std::string& logicalPath,
const std::string& scriptOrigin, SourceWrap wrap,
CodeCacheKind kind, const char* originFailure,
const FileInfo& info) {
PreparedSource prepared;
prepared.text = ReadSource(isolate, logicalPath, wrap);
prepared.origin =
NewString(isolate, scriptOrigin, originFailure + logicalPath);
const LoaderConfig& config = LoaderConfigFor(isolate);
prepared.cache = CodeCacheEntryFor(logicalPath, kind, info, config);
if (prepared.cache) {
std::optional<CodeCacheBytes> bytes = LoadCodeCache(*prepared.cache);
// The cache matches the Stat taken before the read. Only a debug build
// pays a second Stat to confirm the bytes read still match it; V8 checks
// a cache against the source's length alone.
if (bytes && (!config.isDebug ||
SourceUnchanged(logicalPath, prepared.cache->source))) {
prepared.cached = ToCachedData(std::move(*bytes));
}
}
return prepared;
}
constexpr const char* kEsModuleOriginFailure =
"Failed to create URL string for ES module ";
v8::ScriptOrigin ModuleScriptOrigin(v8::Local<v8::String> name) {
return v8::ScriptOrigin(name, 0, 0, false, -1, v8::Local<v8::Value>(), false,
false, /*is_module=*/true);
}
v8::MaybeLocal<v8::Module> CompilePrepared(v8::Isolate* isolate,
PreparedSource prepared) {
v8::ScriptOrigin origin = ModuleScriptOrigin(prepared.origin);
// The Source owns the cached data; `cached` stays valid for the verdict.
v8::ScriptCompiler::CachedData* cached = prepared.cached.release();
v8::ScriptCompiler::Source source(prepared.text, origin, cached);
v8::Local<v8::Module> module;
if (!v8::ScriptCompiler::CompileModule(
isolate, &source,
cached != nullptr ? v8::ScriptCompiler::kConsumeCodeCache
: v8::ScriptCompiler::kNoCompileOptions)
.ToLocal(&module)) {
return v8::MaybeLocal<v8::Module>();
}
if (prepared.cache && (cached == nullptr || cached->rejected)) {
QueueCodeCache(isolate, module->GetUnboundModuleScript(),
std::move(*prepared.cache));
}
return module;
}
bool EndsWith(std::string_view text, std::string_view suffix) {
return text.size() >= suffix.size() &&
text.substr(text.size() - suffix.size()) == suffix;
}
// Node's lists (node_contextify.cc), matched against V8's message the same
// way: a CommonJS compile that fails with one of the first is ES module
// syntax; with one of the others, the source may be valid only as a module.
constexpr std::array<std::string_view, 3> kEsModuleSyntaxErrors = {
"Cannot use import statement outside a module",
"Unexpected token 'export'",
"Cannot use 'import.meta' outside a module",
};
constexpr std::array<std::string_view, 8> kMaybeEsModuleErrors = {
"Identifier 'module' has already been declared",
"Identifier 'exports' has already been declared",
"Identifier 'require' has already been declared",
"Identifier '__filename' has already been declared",
"Identifier '__dirname' has already been declared",
"await is only valid in async functions and the top level bodies of "
"modules",
"missing ) after argument list",
"SyntaxError: Unexpected",
};
template <size_t N>
bool ContainsAny(std::string_view message,
const std::array<std::string_view, N>& needles) {
for (std::string_view needle : needles) {
if (message.find(needle) != std::string_view::npos) {
return true;
}
}
return false;
}
struct Detection {
ModuleFormat format = ModuleFormat::kCommonJs;
// The module the second compile made, when there was one.
v8::Local<v8::Module> module;
};
Detection DetectModuleFormat(v8::Isolate* isolate,
v8::Local<v8::Context> context,
v8::Local<v8::String> text,
v8::Local<v8::String> origin) {
std::string message;
{
v8::TryCatch tc(isolate);
v8::ScriptOrigin scriptOrigin(origin);
v8::ScriptCompiler::Source source(text, scriptOrigin);
std::array<v8::Local<v8::String>, 5> params = {
ToV8String(isolate, "exports"), ToV8String(isolate, "require"),
ToV8String(isolate, "module"), ToV8String(isolate, "__filename"),
ToV8String(isolate, "__dirname")};
if (!v8::ScriptCompiler::CompileFunction(context, &source, params.size(),
params.data(), 0, nullptr)
.IsEmpty()) {
return {};
}
if (tc.HasTerminated() || isolate->IsExecutionTerminating()) {
throw Terminated();
}
if (tc.Message().IsEmpty()) {
return {};
}
message = ToString(isolate, tc.Message()->Get());
}
if (ContainsAny(message, kEsModuleSyntaxErrors)) {
return {ModuleFormat::kEsModule, {}};
}
if (!ContainsAny(message, kMaybeEsModuleErrors)) {
return {};
}
v8::TryCatch tc(isolate);
v8::ScriptOrigin scriptOrigin = ModuleScriptOrigin(origin);
v8::ScriptCompiler::Source source(text, scriptOrigin);
v8::Local<v8::Module> module;
if (v8::ScriptCompiler::CompileModule(isolate, &source).ToLocal(&module)) {
return {ModuleFormat::kEsModule, module};
}
if (tc.HasTerminated() || isolate->IsExecutionTerminating()) {
throw Terminated();
}
return {};
}
std::optional<ModuleFormat> RememberedFormat(ModuleLoaderState* state,
const std::string& logicalPath,
const FileInfo& info) {
if (state == nullptr) {
return std::nullopt;
}
auto it = state->detectedFormats.find(logicalPath);
if (it == state->detectedFormats.end() || it->second.size != info.size ||
it->second.freshnessToken != info.freshnessToken) {
return std::nullopt;
}
return it->second.format;
}
void RememberFormat(ModuleLoaderState* state, const std::string& logicalPath,
const FileInfo& info, ModuleFormat format) {
if (state == nullptr || info.freshnessToken.empty()) {
return;
}
state->detectedFormats[logicalPath] =
DetectedModuleFormat{info.size, info.freshnessToken, format};
}
v8::Local<v8::Module> CommonJsModuleFor(v8::Isolate* isolate,
const std::string& logicalPath,
const std::string& scriptOrigin) {
return CreateCommonJsModule(
isolate,
NewString(isolate, scriptOrigin, kEsModuleOriginFailure + logicalPath));
}
v8::MaybeLocal<v8::Module> CompileJsFileModule(
v8::Isolate* isolate, v8::Local<v8::Context> context,
const std::string& logicalPath, const std::string& scriptOrigin) {
const FileInfo info = StatSource(logicalPath);
ModuleLoaderState* state = LoaderStateFor(isolate);
std::optional<CodeCacheEntry> cache = CodeCacheEntryFor(
logicalPath, CodeCacheKind::kEsModule, info, LoaderConfigFor(isolate));
std::optional<ModuleFormat> format =
RememberedFormat(state, logicalPath, info);
if (!format && cache) {
format = FreshModuleFormat(*cache);
if (format) {
RememberFormat(state, logicalPath, info, *format);
}
}
if (format == ModuleFormat::kCommonJs) {
return CommonJsModuleFor(isolate, logicalPath, scriptOrigin);
}
if (format == ModuleFormat::kEsModule) {
return CompilePrepared(isolate, Prepare(isolate, logicalPath, scriptOrigin,
{}, CodeCacheKind::kEsModule,
kEsModuleOriginFailure, info));
}
v8::Local<v8::String> text = ReadSource(isolate, logicalPath, {});
v8::Local<v8::String> origin =
NewString(isolate, scriptOrigin, kEsModuleOriginFailure + logicalPath);
Detection detection = DetectModuleFormat(isolate, context, text, origin);
RememberFormat(state, logicalPath, info, detection.format);
if (detection.format == ModuleFormat::kCommonJs) {
if (cache) {
cache->format = ModuleFormat::kCommonJs;
PostCodeCacheWrite(std::move(*cache), nullptr, 0);
}
return CreateCommonJsModule(isolate, origin);
}
if (!detection.module.IsEmpty()) {
if (cache) {
QueueCodeCache(isolate, detection.module->GetUnboundModuleScript(),
std::move(*cache));
}
return detection.module;
}
PreparedSource prepared;
prepared.text = text;
prepared.origin = origin;
prepared.cache = std::move(cache);
return CompilePrepared(isolate, std::move(prepared));
}
} // namespace
v8::MaybeLocal<v8::Module> CompileFileEsModule(
v8::Isolate* isolate, const std::string& logicalPath,
const std::string& scriptOrigin) {
return CompilePrepared(
isolate,
Prepare(isolate, logicalPath, scriptOrigin, {}, CodeCacheKind::kEsModule,
kEsModuleOriginFailure, StatSource(logicalPath)));
}
v8::MaybeLocal<v8::Module> CompileFileModule(v8::Isolate* isolate,
v8::Local<v8::Context> context,
const std::string& logicalPath,
const std::string& scriptOrigin) {
if (EndsWith(logicalPath, ".mjs")) {
return CompileFileEsModule(isolate, logicalPath, scriptOrigin);
}
if (EndsWith(logicalPath, ".js")) {
return CompileJsFileModule(isolate, context, logicalPath, scriptOrigin);
}
StatSource(logicalPath);
return CommonJsModuleFor(isolate, logicalPath, scriptOrigin);
}
v8::MaybeLocal<v8::Script> CompileFileClassicScript(
v8::Isolate* isolate, v8::Local<v8::Context> context,
const std::string& logicalPath, const std::string& scriptOrigin,
SourceWrap wrap) {
PreparedSource prepared = Prepare(
isolate, logicalPath, scriptOrigin, wrap, CodeCacheKind::kClassicScript,
"Failed to create URL string for script ", StatSource(logicalPath));
v8::ScriptOrigin origin(prepared.origin);
v8::ScriptCompiler::CachedData* cached = prepared.cached.release();
v8::ScriptCompiler::Source source(prepared.text, origin, cached);
v8::Local<v8::Script> script;
if (!v8::ScriptCompiler::Compile(context, &source,
cached != nullptr
? v8::ScriptCompiler::kConsumeCodeCache
: v8::ScriptCompiler::kNoCompileOptions)
.ToLocal(&script)) {
return v8::MaybeLocal<v8::Script>();
}
if (prepared.cache && (cached == nullptr || cached->rejected)) {
QueueCodeCache(isolate, script->GetUnboundScript(),
std::move(*prepared.cache));
}
return script;
}
std::unique_ptr<v8::ScriptCompiler::CachedData> ToCachedData(
CodeCacheBytes bytes) {
return std::make_unique<v8::ScriptCompiler::CachedData>(
bytes.data.release(), bytes.length,
v8::ScriptCompiler::CachedData::BufferOwned);
}
} // namespace nativescript::common::loader