js.cpp 33 KB

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