js.cpp 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856
  1. /*
  2. * Copyright (c) 2020-2023, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2023, Linus Groh <linusg@serenityos.org>
  4. * Copyright (c) 2020-2022, Ali Mohammad Pur <mpfard@serenityos.org>
  5. *
  6. * SPDX-License-Identifier: BSD-2-Clause
  7. */
  8. #include <AK/JsonValue.h>
  9. #include <AK/StringBuilder.h>
  10. #include <LibCore/ArgsParser.h>
  11. #include <LibCore/ConfigFile.h>
  12. #include <LibCore/StandardPaths.h>
  13. #include <LibCore/System.h>
  14. #include <LibJS/Bytecode/BasicBlock.h>
  15. #include <LibJS/Bytecode/Generator.h>
  16. #include <LibJS/Bytecode/Interpreter.h>
  17. #include <LibJS/Console.h>
  18. #include <LibJS/Contrib/Test262/GlobalObject.h>
  19. #include <LibJS/Parser.h>
  20. #include <LibJS/Print.h>
  21. #include <LibJS/Runtime/ConsoleObject.h>
  22. #include <LibJS/Runtime/DeclarativeEnvironment.h>
  23. #include <LibJS/Runtime/GlobalEnvironment.h>
  24. #include <LibJS/Runtime/JSONObject.h>
  25. #include <LibJS/Runtime/StringPrototype.h>
  26. #include <LibJS/Runtime/ValueInlines.h>
  27. #include <LibJS/SourceTextModule.h>
  28. #include <LibLine/Editor.h>
  29. #include <LibMain/Main.h>
  30. #include <LibTextCodec/Decoder.h>
  31. #include <signal.h>
  32. RefPtr<JS::VM> g_vm;
  33. Vector<String> g_repl_statements;
  34. JS::Handle<JS::Value> g_last_value = JS::make_handle(JS::js_undefined());
  35. class ReplObject final : public JS::GlobalObject {
  36. JS_OBJECT(ReplObject, JS::GlobalObject);
  37. public:
  38. ReplObject(JS::Realm& realm)
  39. : GlobalObject(realm)
  40. {
  41. }
  42. virtual void initialize(JS::Realm&) override;
  43. virtual ~ReplObject() override = default;
  44. private:
  45. JS_DECLARE_NATIVE_FUNCTION(exit_interpreter);
  46. JS_DECLARE_NATIVE_FUNCTION(repl_help);
  47. JS_DECLARE_NATIVE_FUNCTION(save_to_file);
  48. JS_DECLARE_NATIVE_FUNCTION(load_ini);
  49. JS_DECLARE_NATIVE_FUNCTION(load_json);
  50. JS_DECLARE_NATIVE_FUNCTION(last_value_getter);
  51. JS_DECLARE_NATIVE_FUNCTION(print);
  52. };
  53. class ScriptObject final : public JS::GlobalObject {
  54. JS_OBJECT(ScriptObject, JS::GlobalObject);
  55. public:
  56. ScriptObject(JS::Realm& realm)
  57. : JS::GlobalObject(realm)
  58. {
  59. }
  60. virtual void initialize(JS::Realm&) override;
  61. virtual ~ScriptObject() override = default;
  62. private:
  63. JS_DECLARE_NATIVE_FUNCTION(load_ini);
  64. JS_DECLARE_NATIVE_FUNCTION(load_json);
  65. JS_DECLARE_NATIVE_FUNCTION(print);
  66. };
  67. static bool s_dump_ast = false;
  68. static bool s_as_module = false;
  69. static bool s_print_last_result = false;
  70. static bool s_strip_ansi = false;
  71. static bool s_disable_source_location_hints = false;
  72. static RefPtr<Line::Editor> s_editor;
  73. static String s_history_path = String {};
  74. static int s_repl_line_level = 0;
  75. static bool s_keep_running_repl = true;
  76. static int s_exit_code = 0;
  77. static ErrorOr<void> print(JS::Value value, Stream& stream)
  78. {
  79. JS::PrintContext print_context { .vm = *g_vm, .stream = stream, .strip_ansi = s_strip_ansi };
  80. return JS::print(value, print_context);
  81. }
  82. enum class PrintTarget {
  83. StandardError,
  84. StandardOutput,
  85. };
  86. static ErrorOr<void> print(JS::Value value, PrintTarget target = PrintTarget::StandardOutput)
  87. {
  88. auto stream = TRY(target == PrintTarget::StandardError ? Core::File::standard_error() : Core::File::standard_output());
  89. return print(value, *stream);
  90. }
  91. static ErrorOr<String> prompt_for_level(int level)
  92. {
  93. static StringBuilder prompt_builder;
  94. prompt_builder.clear();
  95. prompt_builder.append("> "sv);
  96. for (auto i = 0; i < level; ++i)
  97. prompt_builder.append(" "sv);
  98. return prompt_builder.to_string();
  99. }
  100. static ErrorOr<String> read_next_piece()
  101. {
  102. StringBuilder piece;
  103. auto line_level_delta_for_next_line { 0 };
  104. do {
  105. auto line_result = s_editor->get_line(TRY(prompt_for_level(s_repl_line_level)).to_byte_string());
  106. line_level_delta_for_next_line = 0;
  107. if (line_result.is_error()) {
  108. s_keep_running_repl = false;
  109. return String {};
  110. }
  111. auto& line = line_result.value();
  112. s_editor->add_to_history(line);
  113. piece.append(line);
  114. piece.append('\n');
  115. auto lexer = JS::Lexer(line);
  116. enum {
  117. NotInLabelOrObjectKey,
  118. InLabelOrObjectKeyIdentifier,
  119. InLabelOrObjectKey
  120. } label_state { NotInLabelOrObjectKey };
  121. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  122. switch (token.type()) {
  123. case JS::TokenType::BracketOpen:
  124. case JS::TokenType::CurlyOpen:
  125. case JS::TokenType::ParenOpen:
  126. label_state = NotInLabelOrObjectKey;
  127. s_repl_line_level++;
  128. break;
  129. case JS::TokenType::BracketClose:
  130. case JS::TokenType::CurlyClose:
  131. case JS::TokenType::ParenClose:
  132. label_state = NotInLabelOrObjectKey;
  133. s_repl_line_level--;
  134. break;
  135. case JS::TokenType::Identifier:
  136. case JS::TokenType::StringLiteral:
  137. if (label_state == NotInLabelOrObjectKey)
  138. label_state = InLabelOrObjectKeyIdentifier;
  139. else
  140. label_state = NotInLabelOrObjectKey;
  141. break;
  142. case JS::TokenType::Colon:
  143. if (label_state == InLabelOrObjectKeyIdentifier)
  144. label_state = InLabelOrObjectKey;
  145. else
  146. label_state = NotInLabelOrObjectKey;
  147. break;
  148. default:
  149. break;
  150. }
  151. }
  152. if (label_state == InLabelOrObjectKey) {
  153. // If there's a label or object literal key at the end of this line,
  154. // prompt for more lines but do not change the line level.
  155. line_level_delta_for_next_line += 1;
  156. }
  157. } while (s_repl_line_level + line_level_delta_for_next_line > 0);
  158. return piece.to_string();
  159. }
  160. static ErrorOr<void> write_to_file(String const& path)
  161. {
  162. auto file = TRY(Core::File::open(path, Core::File::OpenMode::Write, 0666));
  163. for (size_t i = 0; i < g_repl_statements.size(); i++) {
  164. auto line = g_repl_statements[i].bytes();
  165. if (line.size() > 0 && i != g_repl_statements.size() - 1) {
  166. TRY(file->write_until_depleted(line));
  167. }
  168. if (i != g_repl_statements.size() - 1) {
  169. TRY(file->write_value('\n'));
  170. }
  171. }
  172. file->close();
  173. return {};
  174. }
  175. static ErrorOr<bool> parse_and_run(JS::Realm& realm, StringView source, StringView source_name)
  176. {
  177. auto& vm = realm.vm();
  178. JS::ThrowCompletionOr<JS::Value> result { JS::js_undefined() };
  179. auto run_script_or_module = [&](auto& script_or_module) {
  180. if (s_dump_ast)
  181. script_or_module->parse_node().dump(0);
  182. result = vm.bytecode_interpreter().run(*script_or_module);
  183. };
  184. if (!s_as_module) {
  185. auto script_or_error = JS::Script::parse(source, realm, source_name);
  186. if (script_or_error.is_error()) {
  187. auto error = script_or_error.error()[0];
  188. auto hint = error.source_location_hint(source);
  189. if (!hint.is_empty())
  190. outln("{}", hint);
  191. auto error_string = TRY(error.to_string());
  192. outln("{}", error_string);
  193. result = vm.throw_completion<JS::SyntaxError>(move(error_string));
  194. } else {
  195. run_script_or_module(script_or_error.value());
  196. }
  197. } else {
  198. auto module_or_error = JS::SourceTextModule::parse(source, realm, source_name);
  199. if (module_or_error.is_error()) {
  200. auto error = module_or_error.error()[0];
  201. auto hint = error.source_location_hint(source);
  202. if (!hint.is_empty())
  203. outln("{}", hint);
  204. auto error_string = TRY(error.to_string());
  205. outln("{}", error_string);
  206. result = vm.throw_completion<JS::SyntaxError>(move(error_string));
  207. } else {
  208. run_script_or_module(module_or_error.value());
  209. }
  210. }
  211. auto handle_exception = [&](JS::Value thrown_value) -> ErrorOr<void> {
  212. warnln("Uncaught exception: ");
  213. TRY(print(thrown_value, PrintTarget::StandardError));
  214. warnln();
  215. if (!thrown_value.is_object() || !is<JS::Error>(thrown_value.as_object()))
  216. return {};
  217. warnln("{}", static_cast<JS::Error const&>(thrown_value.as_object()).stack_string(JS::CompactTraceback::Yes));
  218. return {};
  219. };
  220. if (!result.is_error())
  221. g_last_value = JS::make_handle(result.value());
  222. if (result.is_error()) {
  223. VERIFY(result.throw_completion().value().has_value());
  224. TRY(handle_exception(*result.release_error().value()));
  225. return false;
  226. }
  227. if (s_print_last_result) {
  228. TRY(print(result.value()));
  229. warnln();
  230. }
  231. return true;
  232. }
  233. static JS::ThrowCompletionOr<JS::Value> load_ini_impl(JS::VM& vm)
  234. {
  235. auto& realm = *vm.current_realm();
  236. auto filename = TRY(vm.argument(0).to_byte_string(vm));
  237. auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read);
  238. if (file_or_error.is_error())
  239. return vm.throw_completion<JS::Error>(TRY_OR_THROW_OOM(vm, String::formatted("Failed to open '{}': {}", filename, file_or_error.error())));
  240. auto config_file = MUST(Core::ConfigFile::open(filename, file_or_error.release_value()));
  241. auto object = JS::Object::create(realm, realm.intrinsics().object_prototype());
  242. for (auto const& group : config_file->groups()) {
  243. auto group_object = JS::Object::create(realm, realm.intrinsics().object_prototype());
  244. for (auto const& key : config_file->keys(group)) {
  245. auto entry = config_file->read_entry(group, key);
  246. group_object->define_direct_property(key, JS::PrimitiveString::create(vm, move(entry)), JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable);
  247. }
  248. object->define_direct_property(group, group_object, JS::Attribute::Enumerable | JS::Attribute::Configurable | JS::Attribute::Writable);
  249. }
  250. return object;
  251. }
  252. static JS::ThrowCompletionOr<JS::Value> load_json_impl(JS::VM& vm)
  253. {
  254. auto filename = TRY(vm.argument(0).to_string(vm));
  255. auto file_or_error = Core::File::open(filename, Core::File::OpenMode::Read);
  256. if (file_or_error.is_error())
  257. return vm.throw_completion<JS::Error>(TRY_OR_THROW_OOM(vm, String::formatted("Failed to open '{}': {}", filename, file_or_error.error())));
  258. auto file_contents_or_error = file_or_error.value()->read_until_eof();
  259. if (file_contents_or_error.is_error())
  260. return vm.throw_completion<JS::Error>(TRY_OR_THROW_OOM(vm, String::formatted("Failed to read '{}': {}", filename, file_contents_or_error.error())));
  261. auto json = JsonValue::from_string(file_contents_or_error.value());
  262. if (json.is_error())
  263. return vm.throw_completion<JS::SyntaxError>(JS::ErrorType::JsonMalformed);
  264. return JS::JSONObject::parse_json_value(vm, json.value());
  265. }
  266. void ReplObject::initialize(JS::Realm& realm)
  267. {
  268. Base::initialize(realm);
  269. define_direct_property("global", this, JS::Attribute::Enumerable);
  270. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  271. define_native_function(realm, "exit", exit_interpreter, 0, attr);
  272. define_native_function(realm, "help", repl_help, 0, attr);
  273. define_native_function(realm, "save", save_to_file, 1, attr);
  274. define_native_function(realm, "loadINI", load_ini, 1, attr);
  275. define_native_function(realm, "loadJSON", load_json, 1, attr);
  276. define_native_function(realm, "print", print, 1, attr);
  277. define_native_accessor(
  278. realm,
  279. "_",
  280. [](JS::VM&) {
  281. return g_last_value.value();
  282. },
  283. [](JS::VM& vm) -> JS::ThrowCompletionOr<JS::Value> {
  284. auto& global_object = vm.get_global_object();
  285. VERIFY(is<ReplObject>(global_object));
  286. outln("Disable writing last value to '_'");
  287. // We must delete first otherwise this setter gets called recursively.
  288. TRY(global_object.internal_delete(JS::PropertyKey { "_" }));
  289. auto value = vm.argument(0);
  290. TRY(global_object.internal_set(JS::PropertyKey { "_" }, value, &global_object));
  291. return value;
  292. },
  293. attr);
  294. }
  295. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  296. {
  297. if (!vm.argument_count())
  298. return JS::Value(false);
  299. auto const save_path = TRY(vm.argument(0).to_string(vm));
  300. if (!write_to_file(save_path).is_error()) {
  301. return JS::Value(true);
  302. }
  303. return JS::Value(false);
  304. }
  305. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  306. {
  307. if (vm.argument_count() != 0)
  308. s_exit_code = TRY(vm.argument(0).to_number(vm)).as_double();
  309. s_keep_running_repl = false;
  310. return JS::js_undefined();
  311. }
  312. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  313. {
  314. warnln("REPL commands:");
  315. warnln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  316. warnln(" help(): display this menu");
  317. warnln(" loadINI(file): load the given file as INI.");
  318. warnln(" loadJSON(file): load the given file as JSON.");
  319. warnln(" print(value): pretty-print the given JS value.");
  320. warnln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  321. return JS::js_undefined();
  322. }
  323. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_ini)
  324. {
  325. return load_ini_impl(vm);
  326. }
  327. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_json)
  328. {
  329. return load_json_impl(vm);
  330. }
  331. JS_DEFINE_NATIVE_FUNCTION(ReplObject::print)
  332. {
  333. auto result = ::print(vm.argument(0));
  334. if (result.is_error())
  335. return g_vm->throw_completion<JS::InternalError>(TRY_OR_THROW_OOM(*g_vm, String::formatted("Failed to print value: {}", result.error())));
  336. outln();
  337. return JS::js_undefined();
  338. }
  339. void ScriptObject::initialize(JS::Realm& realm)
  340. {
  341. Base::initialize(realm);
  342. define_direct_property("global", this, JS::Attribute::Enumerable);
  343. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  344. define_native_function(realm, "loadINI", load_ini, 1, attr);
  345. define_native_function(realm, "loadJSON", load_json, 1, attr);
  346. define_native_function(realm, "print", print, 1, attr);
  347. }
  348. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_ini)
  349. {
  350. return load_ini_impl(vm);
  351. }
  352. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_json)
  353. {
  354. return load_json_impl(vm);
  355. }
  356. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::print)
  357. {
  358. auto result = ::print(vm.argument(0));
  359. if (result.is_error())
  360. return g_vm->throw_completion<JS::InternalError>(TRY_OR_THROW_OOM(*g_vm, String::formatted("Failed to print value: {}", result.error())));
  361. outln();
  362. return JS::js_undefined();
  363. }
  364. static ErrorOr<void> repl(JS::Realm& realm)
  365. {
  366. while (s_keep_running_repl) {
  367. auto const piece = TRY(read_next_piece());
  368. if (Utf8View { piece }.trim(JS::whitespace_characters).is_empty())
  369. continue;
  370. g_repl_statements.append(piece);
  371. TRY(parse_and_run(realm, piece, "REPL"sv));
  372. }
  373. return {};
  374. }
  375. static Function<void()> interrupt_interpreter;
  376. static void sigint_handler()
  377. {
  378. interrupt_interpreter();
  379. }
  380. class ReplConsoleClient final : public JS::ConsoleClient {
  381. public:
  382. ReplConsoleClient(JS::Console& console)
  383. : ConsoleClient(console)
  384. {
  385. }
  386. virtual void clear() override
  387. {
  388. out("\033[3J\033[H\033[2J");
  389. m_group_stack_depth = 0;
  390. fflush(stdout);
  391. }
  392. virtual void end_group() override
  393. {
  394. if (m_group_stack_depth > 0)
  395. m_group_stack_depth--;
  396. }
  397. // 2.3. Printer(logLevel, args[, options]), https://console.spec.whatwg.org/#printer
  398. virtual JS::ThrowCompletionOr<JS::Value> printer(JS::Console::LogLevel log_level, PrinterArguments arguments) override
  399. {
  400. auto indent = TRY_OR_THROW_OOM(*g_vm, String::repeated(' ', m_group_stack_depth * 2));
  401. if (log_level == JS::Console::LogLevel::Trace) {
  402. auto trace = arguments.get<JS::Console::Trace>();
  403. StringBuilder builder;
  404. if (!trace.label.is_empty())
  405. builder.appendff("{}\033[36;1m{}\033[0m\n", indent, trace.label);
  406. for (auto& function_name : trace.stack)
  407. builder.appendff("{}-> {}\n", indent, function_name);
  408. outln("{}", builder.string_view());
  409. return JS::js_undefined();
  410. }
  411. if (log_level == JS::Console::LogLevel::Group || log_level == JS::Console::LogLevel::GroupCollapsed) {
  412. auto group = arguments.get<JS::Console::Group>();
  413. outln("{}\033[36;1m{}\033[0m", indent, group.label);
  414. m_group_stack_depth++;
  415. return JS::js_undefined();
  416. }
  417. auto output = TRY(generically_format_values(arguments.get<JS::MarkedVector<JS::Value>>()));
  418. #ifdef AK_OS_SERENITY
  419. m_console.output_debug_message(log_level, output);
  420. #endif
  421. switch (log_level) {
  422. case JS::Console::LogLevel::Debug:
  423. outln("{}\033[36;1m{}\033[0m", indent, output);
  424. break;
  425. case JS::Console::LogLevel::Error:
  426. case JS::Console::LogLevel::Assert:
  427. outln("{}\033[31;1m{}\033[0m", indent, output);
  428. break;
  429. case JS::Console::LogLevel::Info:
  430. outln("{}(i) {}", indent, output);
  431. break;
  432. case JS::Console::LogLevel::Log:
  433. outln("{}{}", indent, output);
  434. break;
  435. case JS::Console::LogLevel::Warn:
  436. case JS::Console::LogLevel::CountReset:
  437. outln("{}\033[33;1m{}\033[0m", indent, output);
  438. break;
  439. default:
  440. outln("{}{}", indent, output);
  441. break;
  442. }
  443. return JS::js_undefined();
  444. }
  445. private:
  446. int m_group_stack_depth { 0 };
  447. };
  448. ErrorOr<int> serenity_main(Main::Arguments arguments)
  449. {
  450. TRY(Core::System::pledge("stdio rpath wpath cpath tty sigaction map_fixed"));
  451. bool gc_on_every_allocation = false;
  452. bool disable_syntax_highlight = false;
  453. bool disable_debug_printing = false;
  454. bool use_test262_global = false;
  455. StringView evaluate_script;
  456. Vector<StringView> script_paths;
  457. Core::ArgsParser args_parser;
  458. args_parser.set_general_help("This is a JavaScript interpreter.");
  459. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  460. args_parser.add_option(JS::Bytecode::g_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  461. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  462. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  463. args_parser.add_option(s_strip_ansi, "Disable ANSI colors", "disable-ansi-colors", 'i');
  464. args_parser.add_option(s_disable_source_location_hints, "Disable source location hints", "disable-source-location-hints", 'h');
  465. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  466. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  467. args_parser.add_option(disable_debug_printing, "Disable debug output", "disable-debug-output", {});
  468. args_parser.add_option(evaluate_script, "Evaluate argument as a script", "evaluate", 'c', "script");
  469. args_parser.add_option(use_test262_global, "Use test262 global ($262)", "use-test262-global", {});
  470. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  471. args_parser.parse(arguments);
  472. bool syntax_highlight = !disable_syntax_highlight;
  473. AK::set_debug_enabled(!disable_debug_printing);
  474. s_history_path = TRY(String::formatted("{}/.js-history", Core::StandardPaths::home_directory()));
  475. g_vm = TRY(JS::VM::create());
  476. g_vm->set_dynamic_imports_allowed(true);
  477. if (!disable_debug_printing) {
  478. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  479. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  480. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  481. // might want to revisit at a later point and disable warnings for promises created this way.
  482. g_vm->on_promise_unhandled_rejection = [](auto& promise) {
  483. warn("WARNING: A promise was rejected without any handlers");
  484. warn(" (result: ");
  485. (void)print(promise.result(), PrintTarget::StandardError);
  486. warnln(")");
  487. };
  488. g_vm->on_promise_rejection_handled = [](auto& promise) {
  489. warn("WARNING: A handler was added to an already rejected promise");
  490. warn(" (result: ");
  491. (void)print(promise.result(), PrintTarget::StandardError);
  492. warnln(")");
  493. };
  494. }
  495. // FIXME: Figure out some way to interrupt the interpreter now that vm.exception() is gone.
  496. if (evaluate_script.is_empty() && script_paths.is_empty()) {
  497. s_print_last_result = true;
  498. auto root_execution_context = JS::create_simple_execution_context<ReplObject>(*g_vm);
  499. auto& realm = *root_execution_context->realm;
  500. auto& console_object = *realm.intrinsics().console_object();
  501. ReplConsoleClient console_client(console_object.console());
  502. console_object.console().set_client(console_client);
  503. g_vm->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  504. auto& global_environment = realm.global_environment();
  505. s_editor = Line::Editor::construct();
  506. s_editor->load_history(s_history_path.to_byte_string());
  507. signal(SIGINT, [](int) {
  508. if (!s_editor->is_editing())
  509. sigint_handler();
  510. s_editor->save_history(s_history_path.to_byte_string());
  511. });
  512. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  513. auto stylize = [&](Line::Span span, Line::Style styles) {
  514. if (syntax_highlight)
  515. editor.stylize(span, styles);
  516. };
  517. editor.strip_styles();
  518. size_t open_indents = s_repl_line_level;
  519. auto line = editor.line();
  520. JS::Lexer lexer(line);
  521. bool indenters_starting_line = true;
  522. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  523. auto length = Utf8View { token.value() }.length();
  524. auto start = token.offset();
  525. auto end = start + length;
  526. if (indenters_starting_line) {
  527. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  528. indenters_starting_line = false;
  529. } else {
  530. --open_indents;
  531. }
  532. }
  533. switch (token.category()) {
  534. case JS::TokenCategory::Invalid:
  535. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  536. break;
  537. case JS::TokenCategory::Number:
  538. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  539. break;
  540. case JS::TokenCategory::String:
  541. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  542. break;
  543. case JS::TokenCategory::Punctuation:
  544. break;
  545. case JS::TokenCategory::Operator:
  546. break;
  547. case JS::TokenCategory::Keyword:
  548. switch (token.type()) {
  549. case JS::TokenType::BoolLiteral:
  550. case JS::TokenType::NullLiteral:
  551. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  552. break;
  553. default:
  554. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  555. break;
  556. }
  557. break;
  558. case JS::TokenCategory::ControlKeyword:
  559. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  560. break;
  561. case JS::TokenCategory::Identifier:
  562. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  563. break;
  564. default:
  565. break;
  566. }
  567. }
  568. editor.set_prompt(prompt_for_level(open_indents).release_value_but_fixme_should_propagate_errors().to_byte_string());
  569. };
  570. auto complete = [&realm, &global_environment](Line::Editor const& editor) -> Vector<Line::CompletionSuggestion> {
  571. auto line = editor.line(editor.cursor());
  572. JS::Lexer lexer { line };
  573. enum {
  574. Initial,
  575. CompleteVariable,
  576. CompleteNullProperty,
  577. CompleteProperty,
  578. } mode { Initial };
  579. StringView variable_name;
  580. StringView property_name;
  581. // we're only going to complete either
  582. // - <N>
  583. // where N is part of the name of a variable
  584. // - <N>.<P>
  585. // where N is the complete name of a variable and
  586. // P is part of the name of one of its properties
  587. auto js_token = lexer.next();
  588. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  589. switch (mode) {
  590. case CompleteVariable:
  591. switch (js_token.type()) {
  592. case JS::TokenType::Period:
  593. // ...<name> <dot>
  594. mode = CompleteNullProperty;
  595. break;
  596. default:
  597. // not a dot, reset back to initial
  598. mode = Initial;
  599. break;
  600. }
  601. break;
  602. case CompleteNullProperty:
  603. if (js_token.is_identifier_name()) {
  604. // ...<name> <dot> <name>
  605. mode = CompleteProperty;
  606. property_name = js_token.value();
  607. } else {
  608. mode = Initial;
  609. }
  610. break;
  611. case CompleteProperty:
  612. // something came after the property access, reset to initial
  613. case Initial:
  614. if (js_token.type() == JS::TokenType::Identifier) {
  615. // ...<name>...
  616. mode = CompleteVariable;
  617. variable_name = js_token.value();
  618. } else {
  619. mode = Initial;
  620. }
  621. break;
  622. }
  623. }
  624. bool last_token_has_trivia = js_token.trivia().length() > 0;
  625. if (mode == CompleteNullProperty) {
  626. mode = CompleteProperty;
  627. property_name = ""sv;
  628. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  629. }
  630. if (mode == Initial || last_token_has_trivia)
  631. return {}; // we do not know how to complete this
  632. Vector<Line::CompletionSuggestion> results;
  633. Function<void(JS::Shape const&, StringView)> list_all_properties = [&results, &list_all_properties](JS::Shape const& shape, auto property_pattern) {
  634. for (auto const& descriptor : shape.property_table()) {
  635. if (!descriptor.key.is_string())
  636. continue;
  637. auto key = descriptor.key.as_string();
  638. if (key.view().starts_with(property_pattern)) {
  639. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  640. if (!results.contains_slow(completion)) { // hide duplicates
  641. results.append(ByteString(key));
  642. results.last().invariant_offset = property_pattern.length();
  643. }
  644. }
  645. }
  646. if (auto const* prototype = shape.prototype()) {
  647. list_all_properties(prototype->shape(), property_pattern);
  648. }
  649. };
  650. switch (mode) {
  651. case CompleteProperty: {
  652. auto reference_or_error = g_vm->resolve_binding(variable_name, &global_environment);
  653. if (reference_or_error.is_error())
  654. return {};
  655. auto value_or_error = reference_or_error.value().get_value(*g_vm);
  656. if (value_or_error.is_error())
  657. return {};
  658. auto variable = value_or_error.value();
  659. VERIFY(!variable.is_empty());
  660. if (!variable.is_object())
  661. break;
  662. auto const object = MUST(variable.to_object(*g_vm));
  663. auto const& shape = object->shape();
  664. list_all_properties(shape, property_name);
  665. break;
  666. }
  667. case CompleteVariable: {
  668. auto const& variable = realm.global_object();
  669. list_all_properties(variable.shape(), variable_name);
  670. for (auto const& name : global_environment.declarative_record().bindings()) {
  671. if (name.starts_with(variable_name)) {
  672. results.empend(name);
  673. results.last().invariant_offset = variable_name.length();
  674. }
  675. }
  676. break;
  677. }
  678. default:
  679. VERIFY_NOT_REACHED();
  680. }
  681. return results;
  682. };
  683. s_editor->on_tab_complete = move(complete);
  684. TRY(repl(realm));
  685. s_editor->save_history(s_history_path.to_byte_string());
  686. } else {
  687. OwnPtr<JS::ExecutionContext> root_execution_context;
  688. if (use_test262_global)
  689. root_execution_context = JS::create_simple_execution_context<JS::Test262::GlobalObject>(*g_vm);
  690. else
  691. root_execution_context = JS::create_simple_execution_context<ScriptObject>(*g_vm);
  692. auto& realm = *root_execution_context->realm;
  693. auto& console_object = *realm.intrinsics().console_object();
  694. ReplConsoleClient console_client(console_object.console());
  695. console_object.console().set_client(console_client);
  696. g_vm->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  697. signal(SIGINT, [](int) {
  698. sigint_handler();
  699. });
  700. StringBuilder builder;
  701. StringView source_name;
  702. if (evaluate_script.is_empty()) {
  703. if (script_paths.size() > 1)
  704. warnln("Warning: Multiple files supplied, this will concatenate the sources and resolve modules as if it was the first file");
  705. for (auto& path : script_paths) {
  706. auto file = TRY(Core::File::open(path, Core::File::OpenMode::Read));
  707. auto file_contents = TRY(file->read_until_eof());
  708. auto source = StringView { file_contents };
  709. if (Utf8View { file_contents }.validate()) {
  710. builder.append(source);
  711. } else {
  712. auto decoder = TextCodec::decoder_for("windows-1252"sv);
  713. VERIFY(decoder.has_value());
  714. auto utf8_source = TRY(TextCodec::convert_input_to_utf8_using_given_decoder_unless_there_is_a_byte_order_mark(*decoder, source));
  715. builder.append(utf8_source);
  716. }
  717. }
  718. source_name = script_paths[0];
  719. } else {
  720. builder.append(evaluate_script);
  721. source_name = "eval"sv;
  722. }
  723. // We resolve modules as if it is the first file
  724. if (!TRY(parse_and_run(realm, builder.string_view(), source_name)))
  725. return 1;
  726. }
  727. return s_exit_code;
  728. }