summaryrefslogtreecommitdiff
path: root/Meta/Lagom/Wasm/js_repl.cpp
blob: 9d77507ca589e62943e261c68679c03052dd1d9e (plain)
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
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
/*
 * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
 * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
 * Copyright (c) 2020-2022, Ali Mohammad Pur <mpfard@serenityos.org>
 *
 * SPDX-License-Identifier: BSD-2-Clause
 */

#include <LibCore/ArgsParser.h>
#include <LibCore/ConfigFile.h>
#include <LibCore/StandardPaths.h>
#include <LibCore/System.h>
#include <LibJS/AST.h>
#include <LibJS/Bytecode/BasicBlock.h>
#include <LibJS/Bytecode/Generator.h>
#include <LibJS/Bytecode/Interpreter.h>
#include <LibJS/Console.h>
#include <LibJS/Interpreter.h>
#include <LibJS/Parser.h>
#include <LibJS/Print.h>
#include <LibJS/Runtime/ConsoleObject.h>
#include <LibJS/Runtime/JSONObject.h>
#include <LibJS/Runtime/StringPrototype.h>
#include <LibJS/SourceTextModule.h>
#include <LibLine/Editor.h>
#include <LibMain/Main.h>
#include <LibTextCodec/Decoder.h>
#include <fcntl.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

#ifndef AK_OS_EMSCRIPTEN
#    error "This program is for Emscripten only"
#endif

#include <emscripten.h>

class ReplConsoleClient;

RefPtr<JS::VM> g_vm;
OwnPtr<JS::Interpreter> g_interpreter;
OwnPtr<ReplConsoleClient> g_console_client;
JS::Handle<JS::Value> g_last_value = JS::make_handle(JS::js_undefined());

EM_JS(void, user_display, (char const* string, u32 length), { globalDisplayToUser(UTF8ToString(string, length)); });

template<typename... Args>
void display(CheckedFormatString<Args...> format_string, Args const&... args)
{
    auto string = DeprecatedString::formatted(format_string.view(), args...);
    user_display(string.characters(), string.length());
}

template<typename... Args>
void displayln(CheckedFormatString<Args...> format_string, Args const&... args)
{
    display(format_string.view(), args...);
    user_display("\n", 1);
}

void displayln() { user_display("\n", 1); }

class UserDisplayStream final : public Stream {
    virtual ErrorOr<Bytes> read_some(Bytes) override { return Error::from_string_view("Not readable"sv); };
    virtual ErrorOr<size_t> write_some(ReadonlyBytes bytes) override
    {
        user_display(bit_cast<char const*>(bytes.data()), bytes.size());
        return bytes.size();
    }
    virtual bool is_eof() const override { return true; }
    virtual bool is_open() const override { return true; }
    virtual void close() override { }
};

ErrorOr<void> print(JS::Value value)
{
    UserDisplayStream stream;
    JS::PrintContext print_context {
        .vm = *g_vm,
        .stream = stream,
        .strip_ansi = true,
    };
    return JS::print(value, print_context);
}

class ReplObject final : public JS::GlobalObject {
    JS_OBJECT(ReplObject, JS::GlobalObject);

public:
    ReplObject(JS::Realm& realm)
        : GlobalObject(realm)
    {
    }
    virtual JS::ThrowCompletionOr<void> initialize(JS::Realm&) override;
    virtual ~ReplObject() override = default;

private:
    JS_DECLARE_NATIVE_FUNCTION(last_value_getter);
    JS_DECLARE_NATIVE_FUNCTION(print);
};

static bool s_dump_ast = false;
static bool s_run_bytecode = false;
static bool s_opt_bytecode = false;
static bool s_as_module = false;
static bool s_print_last_result = false;

static ErrorOr<bool> parse_and_run(JS::Interpreter& interpreter, StringView source, StringView source_name)
{
    enum class ReturnEarly {
        No,
        Yes,
    };

    JS::ThrowCompletionOr<JS::Value> result { JS::js_undefined() };

    auto run_script_or_module = [&](auto& script_or_module) -> ErrorOr<ReturnEarly> {
        if (s_dump_ast)
            script_or_module->parse_node().dump(0);

        if (JS::Bytecode::g_dump_bytecode || s_run_bytecode) {
            auto executable_result = JS::Bytecode::Generator::generate(script_or_module->parse_node());
            if (executable_result.is_error()) {
                result = g_vm->throw_completion<JS::InternalError>(TRY(executable_result.error().to_string()));
                return ReturnEarly::No;
            }

            auto executable = executable_result.release_value();
            executable->name = source_name;
            if (s_opt_bytecode) {
                auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
                passes.perform(*executable);
            }

            if (JS::Bytecode::g_dump_bytecode)
                executable->dump();

            if (s_run_bytecode) {
                JS::Bytecode::Interpreter bytecode_interpreter(interpreter.realm());
                auto result_or_error = bytecode_interpreter.run_and_return_frame(*executable, nullptr);
                if (result_or_error.value.is_error())
                    result = result_or_error.value.release_error();
                else
                    result = result_or_error.frame->registers[0];
            } else {
                return ReturnEarly::Yes;
            }
        } else {
            result = interpreter.run(*script_or_module);
        }

        return ReturnEarly::No;
    };

    if (!s_as_module) {
        auto script_or_error = JS::Script::parse(source, interpreter.realm(), source_name);
        if (script_or_error.is_error()) {
            auto error = script_or_error.error()[0];
            auto hint = error.source_location_hint(source);
            if (!hint.is_empty())
                displayln("{}", hint);

            auto error_string = TRY(error.to_string());
            displayln("{}", error_string);
            result = interpreter.vm().throw_completion<JS::SyntaxError>(move(error_string));
        } else {
            auto return_early = TRY(run_script_or_module(script_or_error.value()));
            if (return_early == ReturnEarly::Yes)
                return true;
        }
    } else {
        auto module_or_error = JS::SourceTextModule::parse(source, interpreter.realm(), source_name);
        if (module_or_error.is_error()) {
            auto error = module_or_error.error()[0];
            auto hint = error.source_location_hint(source);
            if (!hint.is_empty())
                displayln("{}", hint);

            auto error_string = TRY(error.to_string());
            displayln("{}", error_string);
            result = interpreter.vm().throw_completion<JS::SyntaxError>(move(error_string));
        } else {
            auto return_early = TRY(run_script_or_module(module_or_error.value()));
            if (return_early == ReturnEarly::Yes)
                return true;
        }
    }

    auto handle_exception = [&](JS::Value thrown_value) {
        display("Uncaught exception: ");
        (void)print(thrown_value);

        if (!thrown_value.is_object() || !is<JS::Error>(thrown_value.as_object()))
            return;
        auto& traceback = static_cast<JS::Error const&>(thrown_value.as_object()).traceback();
        if (traceback.size() > 1) {
            unsigned repetitions = 0;
            for (size_t i = 0; i < traceback.size(); ++i) {
                auto& traceback_frame = traceback[i];
                if (i + 1 < traceback.size()) {
                    auto& next_traceback_frame = traceback[i + 1];
                    if (next_traceback_frame.function_name == traceback_frame.function_name) {
                        repetitions++;
                        continue;
                    }
                }
                if (repetitions > 4) {
                    // If more than 5 (1 + >4) consecutive function calls with the same name, print
                    // the name only once and show the number of repetitions instead. This prevents
                    // printing ridiculously large call stacks of recursive functions.
                    displayln(" -> {}", traceback_frame.function_name);
                    displayln(" {} more calls", repetitions);
                } else {
                    for (size_t j = 0; j < repetitions + 1; ++j)
                        displayln(" -> {}", traceback_frame.function_name);
                }
                repetitions = 0;
            }
        }
    };

    if (!result.is_error())
        g_last_value = JS::make_handle(result.value());

    if (result.is_error()) {
        VERIFY(result.throw_completion().value().has_value());
        handle_exception(*result.release_error().value());
        return false;
    }

    if (s_print_last_result) {
        (void)print(result.value());
        display("\n");
    }

    return true;
}

JS::ThrowCompletionOr<void> ReplObject::initialize(JS::Realm& realm)
{
    MUST_OR_THROW_OOM(Base::initialize(realm));

    define_direct_property("global", this, JS::Attribute::Enumerable);
    u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
    define_native_function(realm, "print", print, 1, attr);

    define_native_accessor(
        realm,
        "_",
        [](JS::VM&) {
            return g_last_value.value();
        },
        [](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
            auto& global_object = vm.get_global_object();
            VERIFY(is<ReplObject>(global_object));
            displayln("Disable writing last value to '_'");

            // We must delete first otherwise this setter gets called recursively.
            TRY(global_object.internal_delete(JS::PropertyKey { "_" }));

            auto value = vm.argument(0);
            TRY(global_object.internal_set(JS::PropertyKey { "_" }, value, &global_object));
            return value;
        },
        attr);

    return {};
}

JS_DEFINE_NATIVE_FUNCTION(ReplObject::print)
{
    auto result = ::print(vm.argument(0));
    if (result.is_error())
        return g_vm->throw_completion<JS::InternalError>(TRY_OR_THROW_OOM(*g_vm, String::formatted("Failed to print value: {}", result.error())));

    displayln();

    return JS::js_undefined();
}

class ReplConsoleClient final : public JS::ConsoleClient {
public:
    ReplConsoleClient(JS::Console& console)
        : ConsoleClient(console)
    {
    }

    virtual void clear() override
    {
        display("FIXME: clear");
        m_group_stack_depth = 0;
    }

    virtual void end_group() override
    {
        if (m_group_stack_depth > 0)
            m_group_stack_depth--;
    }

    // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
    virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
    {
        DeprecatedString indent = DeprecatedString::repeated("  "sv, m_group_stack_depth);

        if (log_level == JS::Console::LogLevel::Trace) {
            auto trace = arguments.get<JS::Console::Trace>();
            StringBuilder builder;
            if (!trace.label.is_empty())
                builder.appendff("{}{}\n", indent, trace.label);

            for (auto& function_name : trace.stack)
                builder.appendff("{}-> {}\n", indent, function_name);

            displayln("{}", builder.string_view());
            return JS::js_undefined();
        }

        if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
            auto group = arguments.get<JS::Console::Group>();
            displayln("{}{}", indent, group.label);
            m_group_stack_depth++;
            return JS::js_undefined();
        }

        auto output = DeprecatedString::join(' ', arguments.get<JS::MarkedVector<JS::Value>>());
        switch (log_level) {
        case JS::Console::LogLevel::Debug:
            displayln("{}{}", indent, output);
            break;
        case JS::Console::LogLevel::Error:
        case JS::Console::LogLevel::Assert:
            displayln("{}{}", indent, output);
            break;
        case JS::Console::LogLevel::Info:
            displayln("{}(i) {}", indent, output);
            break;
        case JS::Console::LogLevel::Log:
            displayln("{}{}", indent, output);
            break;
        case JS::Console::LogLevel::Warn:
        case JS::Console::LogLevel::CountReset:
            displayln("{}{}", indent, output);
            break;
        default:
            displayln("{}{}", indent, output);
            break;
        }
        return JS::js_undefined();
    }

private:
    int m_group_stack_depth { 0 };
};

extern "C" int initialize_repl(char const* time_zone)
{
    if (time_zone)
        setenv("TZ", time_zone, 1);

    g_vm = MUST(JS::VM::create());
    g_vm->enable_default_host_import_module_dynamically_hook();

    // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
    // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
    // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
    // might want to revisit at a later point and disable warnings for promises created this way.
    g_vm->on_promise_unhandled_rejection = [](auto& promise) {
        display("WARNING: A promise was rejected without any handlers");
        display(" (result: ");
        (void)print(promise.result());
        displayln(")");
    };
    g_vm->on_promise_rejection_handled = [](auto& promise) {
        display("WARNING: A handler was added to an already rejected promise");
        display(" (result: ");
        (void)print(promise.result());
        displayln(")");
    };
    OwnPtr<JS::Interpreter> interpreter;

    s_print_last_result = true;
    interpreter = JS::Interpreter::create<ReplObject>(*g_vm);
    auto console_object = interpreter->realm().intrinsics().console_object();
    g_console_client = make<ReplConsoleClient>(console_object->console());
    console_object->console().set_client(*g_console_client);
    g_interpreter = move(interpreter);

    return 0;
}

extern "C" bool execute(char const* source)
{
    if (auto result = parse_and_run(*g_interpreter, { source, strlen(source) }, "REPL"sv); result.is_error()) {
        displayln("{}", result.error());
        return false;
    } else {
        return result.value();
    }
}