js.cpp 34 KB

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