Commit a8cb6a72 authored by Mathias Bynens's avatar Mathias Bynens Committed by Commit Bot

[d8] Treat .mjs files as modules

This patch makes `d8` recognize files with the `.mjs` extension as
modules instead of classic scripts. This change can be tested by saving
the following JavaScript program as both `module.mjs` and as
`script.js`:

    console.log(this === undefined ? 'strict' : 'sloppy');

Then, run these files in `d8` without passing the `--module` flag:

    $ d8 module.mjs
    strict

    $ d8 script.js
    sloppy

The use of `.mjs` matches not just Google’s recommendation [1] but also
the current modules implementation in Node.js [2].

[1] https://developers.google.com/web/fundamentals/primers/modules
[2] https://nodejs.org/api/esm.html

Bug: v8:7950
Change-Id: I8f39420dc24a5eedd7e88d3b1aa48207ebfeff6e
Reviewed-on: https://chromium-review.googlesource.com/1140314
Commit-Queue: Mathias Bynens <mathias@chromium.org>
Reviewed-by: 's avatarGeorg Neis <neis@chromium.org>
Cr-Commit-Position: refs/heads/master@{#54502}
parent 1062ffb9
......@@ -2423,6 +2423,14 @@ SourceGroup::~SourceGroup() {
thread_ = nullptr;
}
bool ends_with(const char* input, const char* suffix) {
size_t input_length = strlen(input);
size_t suffix_length = strlen(suffix);
if (suffix_length <= input_length) {
return strcmp(input + input_length - suffix_length, suffix) == 0;
}
return false;
}
void SourceGroup::Execute(Isolate* isolate) {
bool exception_was_thrown = false;
......@@ -2446,6 +2454,13 @@ void SourceGroup::Execute(Isolate* isolate) {
}
++i;
continue;
} else if (ends_with(arg, ".mjs")) {
Shell::options.script_executed = true;
if (!Shell::ExecuteModule(isolate, arg)) {
exception_was_thrown = true;
break;
}
continue;
} else if (strcmp(arg, "--module") == 0 && i + 1 < end_offset_) {
// Treat the next file as a module.
arg = argv_[++i];
......@@ -2905,8 +2920,8 @@ bool Shell::SetOptions(int argc, char* argv[]) {
current->Begin(argv, i + 1);
} else if (strcmp(str, "--module") == 0) {
// Pass on to SourceGroup, which understands this option.
} else if (strncmp(argv[i], "--", 2) == 0) {
printf("Warning: unknown flag %s.\nTry --help for options\n", argv[i]);
} else if (strncmp(str, "--", 2) == 0) {
printf("Warning: unknown flag %s.\nTry --help for options\n", str);
} else if (strcmp(str, "-e") == 0 && i + 1 < argc) {
options.script_executed = true;
} else if (strncmp(str, "-", 1) != 0) {
......
......@@ -638,6 +638,7 @@ void FlagList::PrintHelp() {
" -e execute a string in V8\n"
" --shell run an interactive JavaScript shell\n"
" --module execute a file as a JavaScript module\n\n"
"Note: the --module option is implicitly enabled for *.mjs files.\n\n"
"Options:\n";
for (const Flag& f : flags) {
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment