js.cpp 33 KB

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