js.cpp 45 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Assertions.h>
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Format.h>
  10. #include <AK/NonnullOwnPtr.h>
  11. #include <AK/StringBuilder.h>
  12. #include <LibCore/ArgsParser.h>
  13. #include <LibCore/File.h>
  14. #include <LibCore/StandardPaths.h>
  15. #include <LibJS/AST.h>
  16. #include <LibJS/Bytecode/BasicBlock.h>
  17. #include <LibJS/Bytecode/Generator.h>
  18. #include <LibJS/Bytecode/Interpreter.h>
  19. #include <LibJS/Bytecode/PassManager.h>
  20. #include <LibJS/Console.h>
  21. #include <LibJS/Interpreter.h>
  22. #include <LibJS/Parser.h>
  23. #include <LibJS/Runtime/Array.h>
  24. #include <LibJS/Runtime/ArrayBuffer.h>
  25. #include <LibJS/Runtime/BooleanObject.h>
  26. #include <LibJS/Runtime/DataView.h>
  27. #include <LibJS/Runtime/Date.h>
  28. #include <LibJS/Runtime/Error.h>
  29. #include <LibJS/Runtime/FunctionObject.h>
  30. #include <LibJS/Runtime/GlobalObject.h>
  31. #include <LibJS/Runtime/Intl/DisplayNames.h>
  32. #include <LibJS/Runtime/Map.h>
  33. #include <LibJS/Runtime/NativeFunction.h>
  34. #include <LibJS/Runtime/NumberObject.h>
  35. #include <LibJS/Runtime/Object.h>
  36. #include <LibJS/Runtime/OrdinaryFunctionObject.h>
  37. #include <LibJS/Runtime/PrimitiveString.h>
  38. #include <LibJS/Runtime/Promise.h>
  39. #include <LibJS/Runtime/ProxyObject.h>
  40. #include <LibJS/Runtime/RegExpObject.h>
  41. #include <LibJS/Runtime/Set.h>
  42. #include <LibJS/Runtime/Shape.h>
  43. #include <LibJS/Runtime/StringObject.h>
  44. #include <LibJS/Runtime/Temporal/Calendar.h>
  45. #include <LibJS/Runtime/Temporal/Duration.h>
  46. #include <LibJS/Runtime/Temporal/Instant.h>
  47. #include <LibJS/Runtime/Temporal/PlainDate.h>
  48. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  49. #include <LibJS/Runtime/Temporal/PlainTime.h>
  50. #include <LibJS/Runtime/Temporal/TimeZone.h>
  51. #include <LibJS/Runtime/Temporal/ZonedDateTime.h>
  52. #include <LibJS/Runtime/TypedArray.h>
  53. #include <LibJS/Runtime/Value.h>
  54. #include <LibLine/Editor.h>
  55. #include <fcntl.h>
  56. #include <signal.h>
  57. #include <stdio.h>
  58. #include <unistd.h>
  59. RefPtr<JS::VM> vm;
  60. Vector<String> repl_statements;
  61. class ReplObject final : public JS::GlobalObject {
  62. JS_OBJECT(ReplObject, JS::GlobalObject);
  63. public:
  64. ReplObject() = default;
  65. virtual void initialize_global_object() override;
  66. virtual ~ReplObject() override = default;
  67. private:
  68. JS_DECLARE_NATIVE_FUNCTION(exit_interpreter);
  69. JS_DECLARE_NATIVE_FUNCTION(repl_help);
  70. JS_DECLARE_NATIVE_FUNCTION(load_file);
  71. JS_DECLARE_NATIVE_FUNCTION(save_to_file);
  72. };
  73. class ScriptObject final : public JS::GlobalObject {
  74. JS_OBJECT(ScriptObject, JS::GlobalObject);
  75. public:
  76. ScriptObject() = default;
  77. virtual void initialize_global_object() override;
  78. virtual ~ScriptObject() override = default;
  79. private:
  80. JS_DECLARE_NATIVE_FUNCTION(load_file);
  81. };
  82. static bool s_dump_ast = false;
  83. static bool s_dump_bytecode = false;
  84. static bool s_run_bytecode = false;
  85. static bool s_opt_bytecode = false;
  86. static bool s_as_module = false;
  87. static bool s_print_last_result = false;
  88. static RefPtr<Line::Editor> s_editor;
  89. static String s_history_path = String::formatted("{}/.js-history", Core::StandardPaths::home_directory());
  90. static int s_repl_line_level = 0;
  91. static bool s_fail_repl = false;
  92. static String prompt_for_level(int level)
  93. {
  94. static StringBuilder prompt_builder;
  95. prompt_builder.clear();
  96. prompt_builder.append("> ");
  97. for (auto i = 0; i < level; ++i)
  98. prompt_builder.append(" ");
  99. return prompt_builder.build();
  100. }
  101. static String read_next_piece()
  102. {
  103. StringBuilder piece;
  104. auto line_level_delta_for_next_line { 0 };
  105. do {
  106. auto line_result = s_editor->get_line(prompt_for_level(s_repl_line_level));
  107. line_level_delta_for_next_line = 0;
  108. if (line_result.is_error()) {
  109. s_fail_repl = true;
  110. return "";
  111. }
  112. auto& line = line_result.value();
  113. s_editor->add_to_history(line);
  114. piece.append(line);
  115. piece.append('\n');
  116. auto lexer = JS::Lexer(line);
  117. enum {
  118. NotInLabelOrObjectKey,
  119. InLabelOrObjectKeyIdentifier,
  120. InLabelOrObjectKey
  121. } label_state { NotInLabelOrObjectKey };
  122. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  123. switch (token.type()) {
  124. case JS::TokenType::BracketOpen:
  125. case JS::TokenType::CurlyOpen:
  126. case JS::TokenType::ParenOpen:
  127. label_state = NotInLabelOrObjectKey;
  128. s_repl_line_level++;
  129. break;
  130. case JS::TokenType::BracketClose:
  131. case JS::TokenType::CurlyClose:
  132. case JS::TokenType::ParenClose:
  133. label_state = NotInLabelOrObjectKey;
  134. s_repl_line_level--;
  135. break;
  136. case JS::TokenType::Identifier:
  137. case JS::TokenType::StringLiteral:
  138. if (label_state == NotInLabelOrObjectKey)
  139. label_state = InLabelOrObjectKeyIdentifier;
  140. else
  141. label_state = NotInLabelOrObjectKey;
  142. break;
  143. case JS::TokenType::Colon:
  144. if (label_state == InLabelOrObjectKeyIdentifier)
  145. label_state = InLabelOrObjectKey;
  146. else
  147. label_state = NotInLabelOrObjectKey;
  148. break;
  149. default:
  150. break;
  151. }
  152. }
  153. if (label_state == InLabelOrObjectKey) {
  154. // If there's a label or object literal key at the end of this line,
  155. // prompt for more lines but do not change the line level.
  156. line_level_delta_for_next_line += 1;
  157. }
  158. } while (s_repl_line_level + line_level_delta_for_next_line > 0);
  159. return piece.to_string();
  160. }
  161. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  162. static void print_type(FlyString const& name)
  163. {
  164. out("[\033[36;1m{}\033[0m]", name);
  165. }
  166. static void print_separator(bool& first)
  167. {
  168. out(first ? " " : ", ");
  169. first = false;
  170. }
  171. static void print_array(JS::Array& array, HashTable<JS::Object*>& seen_objects)
  172. {
  173. out("[");
  174. bool first = true;
  175. for (auto it = array.indexed_properties().begin(false); it != array.indexed_properties().end(); ++it) {
  176. print_separator(first);
  177. auto value = array.get(it.index());
  178. // The V8 repl doesn't throw an exception here, and instead just
  179. // prints 'undefined'. We may choose to replicate that behavior in
  180. // the future, but for now lets just catch the error
  181. if (vm->exception())
  182. return;
  183. print_value(value, seen_objects);
  184. }
  185. if (!first)
  186. out(" ");
  187. out("]");
  188. }
  189. static void print_object(JS::Object& object, HashTable<JS::Object*>& seen_objects)
  190. {
  191. out("{{");
  192. bool first = true;
  193. for (auto& entry : object.indexed_properties()) {
  194. print_separator(first);
  195. out("\"\033[33;1m{}\033[0m\": ", entry.index());
  196. auto value = object.get(entry.index());
  197. // The V8 repl doesn't throw an exception here, and instead just
  198. // prints 'undefined'. We may choose to replicate that behavior in
  199. // the future, but for now lets just catch the error
  200. if (vm->exception())
  201. return;
  202. print_value(value, seen_objects);
  203. }
  204. for (auto& it : object.shape().property_table_ordered()) {
  205. print_separator(first);
  206. if (it.key.is_string()) {
  207. out("\"\033[33;1m{}\033[0m\": ", it.key.to_display_string());
  208. } else {
  209. out("[\033[33;1m{}\033[0m]: ", it.key.to_display_string());
  210. }
  211. print_value(object.get_direct(it.value.offset), seen_objects);
  212. }
  213. if (!first)
  214. out(" ");
  215. out("}}");
  216. }
  217. static void print_function(JS::Object const& object, HashTable<JS::Object*>&)
  218. {
  219. print_type(object.class_name());
  220. if (is<JS::OrdinaryFunctionObject>(object))
  221. out(" {}", static_cast<JS::OrdinaryFunctionObject const&>(object).name());
  222. else if (is<JS::NativeFunction>(object))
  223. out(" {}", static_cast<JS::NativeFunction const&>(object).name());
  224. }
  225. static void print_date(JS::Object const& object, HashTable<JS::Object*>&)
  226. {
  227. print_type("Date");
  228. out(" \033[34;1m{}\033[0m", static_cast<JS::Date const&>(object).string());
  229. }
  230. static void print_error(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  231. {
  232. auto name = object.get_without_side_effects(vm->names.name).value_or(JS::js_undefined());
  233. auto message = object.get_without_side_effects(vm->names.message).value_or(JS::js_undefined());
  234. if (name.is_accessor() || message.is_accessor()) {
  235. print_value(&object, seen_objects);
  236. } else {
  237. auto name_string = name.to_string_without_side_effects();
  238. auto message_string = message.to_string_without_side_effects();
  239. print_type(name_string);
  240. if (!message_string.is_empty())
  241. out(" \033[31;1m{}\033[0m", message_string);
  242. }
  243. }
  244. static void print_regexp_object(JS::Object const& object, HashTable<JS::Object*>&)
  245. {
  246. auto& regexp_object = static_cast<JS::RegExpObject const&>(object);
  247. // Use RegExp.prototype.source rather than RegExpObject::pattern() so we get proper escaping
  248. auto source = regexp_object.get("source").to_primitive_string(object.global_object())->string();
  249. print_type("RegExp");
  250. out(" \033[34;1m/{}/{}\033[0m", source, regexp_object.flags());
  251. }
  252. static void print_proxy_object(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  253. {
  254. auto& proxy_object = static_cast<JS::ProxyObject const&>(object);
  255. print_type("Proxy");
  256. out("\n target: ");
  257. print_value(&proxy_object.target(), seen_objects);
  258. out("\n handler: ");
  259. print_value(&proxy_object.handler(), seen_objects);
  260. }
  261. static void print_map(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  262. {
  263. auto& map = static_cast<JS::Map const&>(object);
  264. auto& entries = map.entries();
  265. print_type("Map");
  266. out(" {{");
  267. bool first = true;
  268. for (auto& entry : entries) {
  269. print_separator(first);
  270. print_value(entry.key, seen_objects);
  271. out(" => ");
  272. print_value(entry.value, seen_objects);
  273. }
  274. if (!first)
  275. out(" ");
  276. out("}}");
  277. }
  278. static void print_set(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  279. {
  280. auto& set = static_cast<JS::Set const&>(object);
  281. auto& values = set.values();
  282. print_type("Set");
  283. out(" {{");
  284. bool first = true;
  285. for (auto& value : values) {
  286. print_separator(first);
  287. print_value(value, seen_objects);
  288. }
  289. if (!first)
  290. out(" ");
  291. out("}}");
  292. }
  293. static void print_promise(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  294. {
  295. auto& promise = static_cast<JS::Promise const&>(object);
  296. print_type("Promise");
  297. switch (promise.state()) {
  298. case JS::Promise::State::Pending:
  299. out("\n state: ");
  300. out("\033[36;1mPending\033[0m");
  301. break;
  302. case JS::Promise::State::Fulfilled:
  303. out("\n state: ");
  304. out("\033[32;1mFulfilled\033[0m");
  305. out("\n result: ");
  306. print_value(promise.result(), seen_objects);
  307. break;
  308. case JS::Promise::State::Rejected:
  309. out("\n state: ");
  310. out("\033[31;1mRejected\033[0m");
  311. out("\n result: ");
  312. print_value(promise.result(), seen_objects);
  313. break;
  314. default:
  315. VERIFY_NOT_REACHED();
  316. }
  317. }
  318. static void print_array_buffer(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  319. {
  320. auto& array_buffer = static_cast<JS::ArrayBuffer const&>(object);
  321. auto& buffer = array_buffer.buffer();
  322. auto byte_length = array_buffer.byte_length();
  323. print_type("ArrayBuffer");
  324. out("\n byteLength: ");
  325. print_value(JS::Value((double)byte_length), seen_objects);
  326. if (!byte_length)
  327. return;
  328. outln();
  329. for (size_t i = 0; i < byte_length; ++i) {
  330. out("{:02x}", buffer[i]);
  331. if (i + 1 < byte_length) {
  332. if ((i + 1) % 32 == 0)
  333. outln();
  334. else if ((i + 1) % 16 == 0)
  335. out(" ");
  336. else
  337. out(" ");
  338. }
  339. }
  340. }
  341. template<typename T>
  342. static void print_number(T number) requires IsArithmetic<T>
  343. {
  344. out("\033[35;1m");
  345. out("{}", number);
  346. out("\033[0m");
  347. }
  348. static void print_typed_array(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  349. {
  350. auto& typed_array_base = static_cast<JS::TypedArrayBase const&>(object);
  351. auto& array_buffer = *typed_array_base.viewed_array_buffer();
  352. auto length = typed_array_base.array_length();
  353. print_type(object.class_name());
  354. out("\n length: ");
  355. print_value(JS::Value(length), seen_objects);
  356. out("\n byteLength: ");
  357. print_value(JS::Value(typed_array_base.byte_length()), seen_objects);
  358. out("\n buffer: ");
  359. print_type("ArrayBuffer");
  360. if (array_buffer.is_detached())
  361. out(" (detached)");
  362. out(" @ {:p}", &array_buffer);
  363. if (!length || array_buffer.is_detached())
  364. return;
  365. outln();
  366. // FIXME: This kinda sucks.
  367. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  368. if (is<JS::ClassName>(object)) { \
  369. out("[ "); \
  370. auto& typed_array = static_cast<JS::ClassName const&>(typed_array_base); \
  371. auto data = typed_array.data(); \
  372. for (size_t i = 0; i < length; ++i) { \
  373. if (i > 0) \
  374. out(", "); \
  375. print_number(data[i]); \
  376. } \
  377. out(" ]"); \
  378. return; \
  379. }
  380. JS_ENUMERATE_TYPED_ARRAYS
  381. #undef __JS_ENUMERATE
  382. VERIFY_NOT_REACHED();
  383. }
  384. static void print_data_view(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  385. {
  386. auto& data_view = static_cast<JS::DataView const&>(object);
  387. print_type("DataView");
  388. out("\n byteLength: ");
  389. print_value(JS::Value(data_view.byte_length()), seen_objects);
  390. out("\n byteOffset: ");
  391. print_value(JS::Value(data_view.byte_offset()), seen_objects);
  392. out("\n buffer: ");
  393. print_type("ArrayBuffer");
  394. out(" @ {:p}", data_view.viewed_array_buffer());
  395. }
  396. static void print_temporal_calendar(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  397. {
  398. auto& calendar = static_cast<JS::Temporal::Calendar const&>(object);
  399. print_type("Temporal.Calendar");
  400. out(" ");
  401. print_value(JS::js_string(object.vm(), calendar.identifier()), seen_objects);
  402. }
  403. static void print_temporal_duration(JS::Object const& object, HashTable<JS::Object*>&)
  404. {
  405. auto& duration = static_cast<JS::Temporal::Duration const&>(object);
  406. print_type("Temporal.Duration");
  407. out(" \033[34;1m{} y, {} M, {} w, {} d, {} h, {} m, {} s, {} ms, {} us, {} ns\033[0m", duration.years(), duration.months(), duration.weeks(), duration.days(), duration.hours(), duration.minutes(), duration.seconds(), duration.milliseconds(), duration.microseconds(), duration.nanoseconds());
  408. }
  409. static void print_temporal_instant(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  410. {
  411. auto& instant = static_cast<JS::Temporal::Instant const&>(object);
  412. print_type("Temporal.Instant");
  413. out(" ");
  414. // FIXME: Print human readable date and time, like in print_date() - ideally handling arbitrarily large values since we get a bigint.
  415. print_value(&instant.nanoseconds(), seen_objects);
  416. }
  417. static void print_temporal_plain_date(JS::Object const& object, HashTable<JS::Object*>&)
  418. {
  419. auto& plain_date = static_cast<JS::Temporal::PlainDate const&>(object);
  420. print_type("Temporal.PlainDate");
  421. out(" \033[34;1m{:04}-{:02}-{:02}\033[0m", plain_date.iso_year(), plain_date.iso_month(), plain_date.iso_day());
  422. }
  423. static void print_temporal_plain_date_time(JS::Object const& object, HashTable<JS::Object*>&)
  424. {
  425. auto& plain_date_time = static_cast<JS::Temporal::PlainDateTime const&>(object);
  426. print_type("Temporal.PlainDateTime");
  427. out(" \033[34;1m{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}{:03}{:03}\033[0m", plain_date_time.iso_year(), plain_date_time.iso_month(), plain_date_time.iso_day(), plain_date_time.iso_hour(), plain_date_time.iso_minute(), plain_date_time.iso_second(), plain_date_time.iso_millisecond(), plain_date_time.iso_microsecond(), plain_date_time.iso_nanosecond());
  428. }
  429. static void print_temporal_plain_time(JS::Object const& object, HashTable<JS::Object*>&)
  430. {
  431. auto& plain_time = static_cast<JS::Temporal::PlainTime const&>(object);
  432. print_type("Temporal.PlainTime");
  433. out(" \033[34;1m{:02}:{:02}:{:02}.{:03}{:03}{:03}\033[0m", plain_time.iso_hour(), plain_time.iso_minute(), plain_time.iso_second(), plain_time.iso_millisecond(), plain_time.iso_microsecond(), plain_time.iso_nanosecond());
  434. }
  435. static void print_temporal_time_zone(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  436. {
  437. auto& time_zone = static_cast<JS::Temporal::TimeZone const&>(object);
  438. print_type("Temporal.TimeZone");
  439. out(" ");
  440. print_value(JS::js_string(object.vm(), time_zone.identifier()), seen_objects);
  441. if (time_zone.offset_nanoseconds().has_value()) {
  442. out("\n offset (ns): ");
  443. print_value(JS::Value(*time_zone.offset_nanoseconds()), seen_objects);
  444. }
  445. }
  446. static void print_temporal_zoned_date_time(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  447. {
  448. auto& zoned_date_time = static_cast<JS::Temporal::ZonedDateTime const&>(object);
  449. print_type("Temporal.ZonedDateTime");
  450. out("\n epochNanoseconds: ");
  451. print_value(&zoned_date_time.nanoseconds(), seen_objects);
  452. out("\n timeZone: ");
  453. print_value(&zoned_date_time.time_zone(), seen_objects);
  454. out("\n calendar: ");
  455. print_value(&zoned_date_time.calendar(), seen_objects);
  456. }
  457. static void print_intl_display_names(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  458. {
  459. auto& display_names = static_cast<JS::Intl::DisplayNames const&>(object);
  460. print_type("Intl.DisplayNames");
  461. out("\n locale: ");
  462. print_value(js_string(object.vm(), display_names.locale()), seen_objects);
  463. out("\n type: ");
  464. print_value(js_string(object.vm(), display_names.type_string()), seen_objects);
  465. out("\n style: ");
  466. print_value(js_string(object.vm(), display_names.style_string()), seen_objects);
  467. out("\n fallback: ");
  468. print_value(js_string(object.vm(), display_names.fallback_string()), seen_objects);
  469. }
  470. static void print_primitive_wrapper_object(FlyString const& name, JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  471. {
  472. // BooleanObject, NumberObject, StringObject
  473. print_type(name);
  474. out(" ");
  475. print_value(object.value_of(), seen_objects);
  476. }
  477. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  478. {
  479. if (value.is_empty()) {
  480. out("\033[34;1m<empty>\033[0m");
  481. return;
  482. }
  483. if (value.is_object()) {
  484. if (seen_objects.contains(&value.as_object())) {
  485. // FIXME: Maybe we should only do this for circular references,
  486. // not for all reoccurring objects.
  487. out("<already printed Object {}>", &value.as_object());
  488. return;
  489. }
  490. seen_objects.set(&value.as_object());
  491. }
  492. if (value.is_object()) {
  493. auto& object = value.as_object();
  494. if (is<JS::Array>(object))
  495. return print_array(static_cast<JS::Array&>(object), seen_objects);
  496. if (object.is_function())
  497. return print_function(object, seen_objects);
  498. if (is<JS::Date>(object))
  499. return print_date(object, seen_objects);
  500. if (is<JS::Error>(object))
  501. return print_error(object, seen_objects);
  502. if (is<JS::RegExpObject>(object))
  503. return print_regexp_object(object, seen_objects);
  504. if (is<JS::Map>(object))
  505. return print_map(object, seen_objects);
  506. if (is<JS::Set>(object))
  507. return print_set(object, seen_objects);
  508. if (is<JS::DataView>(object))
  509. return print_data_view(object, seen_objects);
  510. if (is<JS::ProxyObject>(object))
  511. return print_proxy_object(object, seen_objects);
  512. if (is<JS::Promise>(object))
  513. return print_promise(object, seen_objects);
  514. if (is<JS::ArrayBuffer>(object))
  515. return print_array_buffer(object, seen_objects);
  516. if (object.is_typed_array())
  517. return print_typed_array(object, seen_objects);
  518. if (is<JS::StringObject>(object))
  519. return print_primitive_wrapper_object("String", object, seen_objects);
  520. if (is<JS::NumberObject>(object))
  521. return print_primitive_wrapper_object("Number", object, seen_objects);
  522. if (is<JS::BooleanObject>(object))
  523. return print_primitive_wrapper_object("Boolean", object, seen_objects);
  524. if (is<JS::Temporal::Calendar>(object))
  525. return print_temporal_calendar(object, seen_objects);
  526. if (is<JS::Temporal::Duration>(object))
  527. return print_temporal_duration(object, seen_objects);
  528. if (is<JS::Temporal::Instant>(object))
  529. return print_temporal_instant(object, seen_objects);
  530. if (is<JS::Temporal::PlainDate>(object))
  531. return print_temporal_plain_date(object, seen_objects);
  532. if (is<JS::Temporal::PlainDateTime>(object))
  533. return print_temporal_plain_date_time(object, seen_objects);
  534. if (is<JS::Temporal::PlainTime>(object))
  535. return print_temporal_plain_time(object, seen_objects);
  536. if (is<JS::Temporal::TimeZone>(object))
  537. return print_temporal_time_zone(object, seen_objects);
  538. if (is<JS::Temporal::ZonedDateTime>(object))
  539. return print_temporal_zoned_date_time(object, seen_objects);
  540. if (is<JS::Intl::DisplayNames>(object))
  541. return print_intl_display_names(object, seen_objects);
  542. return print_object(object, seen_objects);
  543. }
  544. if (value.is_string())
  545. out("\033[32;1m");
  546. else if (value.is_number() || value.is_bigint())
  547. out("\033[35;1m");
  548. else if (value.is_boolean())
  549. out("\033[33;1m");
  550. else if (value.is_null())
  551. out("\033[33;1m");
  552. else if (value.is_undefined())
  553. out("\033[34;1m");
  554. if (value.is_string())
  555. out("\"");
  556. else if (value.is_negative_zero())
  557. out("-");
  558. out("{}", value.to_string_without_side_effects());
  559. if (value.is_string())
  560. out("\"");
  561. out("\033[0m");
  562. }
  563. static void print(JS::Value value)
  564. {
  565. HashTable<JS::Object*> seen_objects;
  566. print_value(value, seen_objects);
  567. outln();
  568. }
  569. static bool write_to_file(String const& path)
  570. {
  571. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  572. for (size_t i = 0; i < repl_statements.size(); i++) {
  573. auto line = repl_statements[i];
  574. if (line.length() && i != repl_statements.size() - 1) {
  575. ssize_t nwritten = write(fd, line.characters(), line.length());
  576. if (nwritten < 0) {
  577. close(fd);
  578. return false;
  579. }
  580. }
  581. if (i != repl_statements.size() - 1) {
  582. char ch = '\n';
  583. ssize_t nwritten = write(fd, &ch, 1);
  584. if (nwritten != 1) {
  585. perror("write");
  586. close(fd);
  587. return false;
  588. }
  589. }
  590. }
  591. close(fd);
  592. return true;
  593. }
  594. static bool parse_and_run(JS::Interpreter& interpreter, StringView const& source)
  595. {
  596. auto program_type = s_as_module ? JS::Program::Type::Module : JS::Program::Type::Script;
  597. auto parser = JS::Parser(JS::Lexer(source), program_type);
  598. auto program = parser.parse_program();
  599. if (s_dump_ast)
  600. program->dump(0);
  601. if (parser.has_errors()) {
  602. auto error = parser.errors()[0];
  603. auto hint = error.source_location_hint(source);
  604. if (!hint.is_empty())
  605. outln("{}", hint);
  606. vm->throw_exception<JS::SyntaxError>(interpreter.global_object(), error.to_string());
  607. } else {
  608. if (s_dump_bytecode || s_run_bytecode) {
  609. auto unit = JS::Bytecode::Generator::generate(*program);
  610. if (s_opt_bytecode) {
  611. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  612. passes.perform(unit);
  613. dbgln("Optimisation passes took {}us", passes.elapsed());
  614. }
  615. if (s_dump_bytecode) {
  616. for (auto& block : unit.basic_blocks)
  617. block.dump(unit);
  618. if (!unit.string_table->is_empty()) {
  619. outln();
  620. unit.string_table->dump();
  621. }
  622. }
  623. if (s_run_bytecode) {
  624. JS::Bytecode::Interpreter bytecode_interpreter(interpreter.global_object());
  625. bytecode_interpreter.run(unit);
  626. } else {
  627. return true;
  628. }
  629. } else {
  630. interpreter.run(interpreter.global_object(), *program);
  631. }
  632. }
  633. auto handle_exception = [&] {
  634. auto* exception = vm->exception();
  635. vm->clear_exception();
  636. out("Uncaught exception: ");
  637. print(exception->value());
  638. auto& traceback = exception->traceback();
  639. if (traceback.size() > 1) {
  640. unsigned repetitions = 0;
  641. for (size_t i = 0; i < traceback.size(); ++i) {
  642. auto& traceback_frame = traceback[i];
  643. if (i + 1 < traceback.size()) {
  644. auto& next_traceback_frame = traceback[i + 1];
  645. if (next_traceback_frame.function_name == traceback_frame.function_name) {
  646. repetitions++;
  647. continue;
  648. }
  649. }
  650. if (repetitions > 4) {
  651. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  652. // the name only once and show the number of repetitions instead. This prevents
  653. // printing ridiculously large call stacks of recursive functions.
  654. outln(" -> {}", traceback_frame.function_name);
  655. outln(" {} more calls", repetitions);
  656. } else {
  657. for (size_t j = 0; j < repetitions + 1; ++j)
  658. outln(" -> {}", traceback_frame.function_name);
  659. }
  660. repetitions = 0;
  661. }
  662. }
  663. };
  664. if (vm->exception()) {
  665. handle_exception();
  666. return false;
  667. }
  668. if (s_print_last_result)
  669. print(vm->last_value());
  670. if (vm->exception()) {
  671. handle_exception();
  672. return false;
  673. }
  674. return true;
  675. }
  676. static JS::Value load_file_impl(JS::VM& vm, JS::GlobalObject& global_object)
  677. {
  678. auto filename = vm.argument(0).to_string(global_object);
  679. if (vm.exception())
  680. return {};
  681. auto file = Core::File::construct(filename);
  682. if (!file->open(Core::OpenMode::ReadOnly)) {
  683. vm.throw_exception<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  684. return {};
  685. }
  686. auto file_contents = file->read_all();
  687. auto source = StringView { file_contents };
  688. auto parser = JS::Parser(JS::Lexer(source));
  689. auto program = parser.parse_program();
  690. if (parser.has_errors()) {
  691. auto& error = parser.errors()[0];
  692. vm.throw_exception<JS::SyntaxError>(global_object, error.to_string());
  693. return {};
  694. }
  695. // FIXME: Use eval()-like semantics and execute in current scope?
  696. vm.interpreter().run(global_object, *program);
  697. return JS::js_undefined();
  698. }
  699. void ReplObject::initialize_global_object()
  700. {
  701. Base::initialize_global_object();
  702. define_direct_property("global", this, JS::Attribute::Enumerable);
  703. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  704. define_native_function("exit", exit_interpreter, 0, attr);
  705. define_native_function("help", repl_help, 0, attr);
  706. define_native_function("load", load_file, 1, attr);
  707. define_native_function("save", save_to_file, 1, attr);
  708. }
  709. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  710. {
  711. if (!vm.argument_count())
  712. return JS::Value(false);
  713. String save_path = vm.argument(0).to_string_without_side_effects();
  714. StringView path = StringView(save_path.characters());
  715. if (write_to_file(path)) {
  716. return JS::Value(true);
  717. }
  718. return JS::Value(false);
  719. }
  720. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  721. {
  722. if (!vm.argument_count())
  723. exit(0);
  724. auto exit_code = vm.argument(0).to_number(global_object);
  725. if (::vm->exception())
  726. return {};
  727. exit(exit_code.as_double());
  728. }
  729. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  730. {
  731. outln("REPL commands:");
  732. outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  733. outln(" help(): display this menu");
  734. outln(" load(file): load given JS file into running session. For example: load(\"foo.js\")");
  735. outln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  736. return JS::js_undefined();
  737. }
  738. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  739. {
  740. return load_file_impl(vm, global_object);
  741. }
  742. void ScriptObject::initialize_global_object()
  743. {
  744. Base::initialize_global_object();
  745. define_direct_property("global", this, JS::Attribute::Enumerable);
  746. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  747. define_native_function("load", load_file, 1, attr);
  748. }
  749. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_file)
  750. {
  751. return load_file_impl(vm, global_object);
  752. }
  753. static void repl(JS::Interpreter& interpreter)
  754. {
  755. while (!s_fail_repl) {
  756. String piece = read_next_piece();
  757. if (piece.is_empty())
  758. continue;
  759. repl_statements.append(piece);
  760. parse_and_run(interpreter, piece);
  761. }
  762. }
  763. static Function<void()> interrupt_interpreter;
  764. static void sigint_handler()
  765. {
  766. interrupt_interpreter();
  767. }
  768. class ReplConsoleClient final : public JS::ConsoleClient {
  769. public:
  770. ReplConsoleClient(JS::Console& console)
  771. : ConsoleClient(console)
  772. {
  773. }
  774. virtual JS::Value log() override
  775. {
  776. outln("{}", vm().join_arguments());
  777. return JS::js_undefined();
  778. }
  779. virtual JS::Value info() override
  780. {
  781. outln("(i) {}", vm().join_arguments());
  782. return JS::js_undefined();
  783. }
  784. virtual JS::Value debug() override
  785. {
  786. outln("\033[36;1m{}\033[0m", vm().join_arguments());
  787. return JS::js_undefined();
  788. }
  789. virtual JS::Value warn() override
  790. {
  791. outln("\033[33;1m{}\033[0m", vm().join_arguments());
  792. return JS::js_undefined();
  793. }
  794. virtual JS::Value error() override
  795. {
  796. outln("\033[31;1m{}\033[0m", vm().join_arguments());
  797. return JS::js_undefined();
  798. }
  799. virtual JS::Value clear() override
  800. {
  801. out("\033[3J\033[H\033[2J");
  802. fflush(stdout);
  803. return JS::js_undefined();
  804. }
  805. virtual JS::Value trace() override
  806. {
  807. outln("{}", vm().join_arguments());
  808. auto trace = get_trace();
  809. for (auto& function_name : trace) {
  810. if (function_name.is_empty())
  811. function_name = "<anonymous>";
  812. outln(" -> {}", function_name);
  813. }
  814. return JS::js_undefined();
  815. }
  816. virtual JS::Value count() override
  817. {
  818. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  819. auto counter_value = m_console.counter_increment(label);
  820. outln("{}: {}", label, counter_value);
  821. return JS::js_undefined();
  822. }
  823. virtual JS::Value count_reset() override
  824. {
  825. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  826. if (m_console.counter_reset(label))
  827. outln("{}: 0", label);
  828. else
  829. outln("\033[33;1m\"{}\" doesn't have a count\033[0m", label);
  830. return JS::js_undefined();
  831. }
  832. virtual JS::Value assert_() override
  833. {
  834. auto& vm = this->vm();
  835. if (!vm.argument(0).to_boolean()) {
  836. if (vm.argument_count() > 1) {
  837. out("\033[31;1mAssertion failed:\033[0m");
  838. outln(" {}", vm.join_arguments(1));
  839. } else {
  840. outln("\033[31;1mAssertion failed\033[0m");
  841. }
  842. }
  843. return JS::js_undefined();
  844. }
  845. };
  846. int main(int argc, char** argv)
  847. {
  848. bool gc_on_every_allocation = false;
  849. bool disable_syntax_highlight = false;
  850. Vector<String> script_paths;
  851. Core::ArgsParser args_parser;
  852. args_parser.set_general_help("This is a JavaScript interpreter.");
  853. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  854. args_parser.add_option(s_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  855. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  856. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  857. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  858. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  859. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  860. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  861. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  862. args_parser.parse(argc, argv);
  863. bool syntax_highlight = !disable_syntax_highlight;
  864. vm = JS::VM::create();
  865. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  866. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  867. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  868. // might want to revisit at a later point and disable warnings for promises created this way.
  869. vm->on_promise_unhandled_rejection = [](auto& promise) {
  870. // FIXME: Optionally make print_value() to print to stderr
  871. out("WARNING: A promise was rejected without any handlers");
  872. out(" (result: ");
  873. HashTable<JS::Object*> seen_objects;
  874. print_value(promise.result(), seen_objects);
  875. outln(")");
  876. };
  877. vm->on_promise_rejection_handled = [](auto& promise) {
  878. // FIXME: Optionally make print_value() to print to stderr
  879. out("WARNING: A handler was added to an already rejected promise");
  880. out(" (result: ");
  881. HashTable<JS::Object*> seen_objects;
  882. print_value(promise.result(), seen_objects);
  883. outln(")");
  884. };
  885. OwnPtr<JS::Interpreter> interpreter;
  886. interrupt_interpreter = [&] {
  887. auto error = JS::Error::create(interpreter->global_object(), "Received SIGINT");
  888. vm->throw_exception(interpreter->global_object(), error);
  889. };
  890. if (script_paths.is_empty()) {
  891. s_print_last_result = true;
  892. interpreter = JS::Interpreter::create<ReplObject>(*vm);
  893. ReplConsoleClient console_client(interpreter->global_object().console());
  894. interpreter->global_object().console().set_client(console_client);
  895. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  896. interpreter->vm().set_underscore_is_last_value(true);
  897. s_editor = Line::Editor::construct();
  898. s_editor->load_history(s_history_path);
  899. signal(SIGINT, [](int) {
  900. if (!s_editor->is_editing())
  901. sigint_handler();
  902. s_editor->save_history(s_history_path);
  903. });
  904. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  905. auto stylize = [&](Line::Span span, Line::Style styles) {
  906. if (syntax_highlight)
  907. editor.stylize(span, styles);
  908. };
  909. editor.strip_styles();
  910. size_t open_indents = s_repl_line_level;
  911. auto line = editor.line();
  912. JS::Lexer lexer(line);
  913. bool indenters_starting_line = true;
  914. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  915. auto length = Utf8View { token.value() }.length();
  916. auto start = token.line_column() - 1;
  917. auto end = start + length;
  918. if (indenters_starting_line) {
  919. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  920. indenters_starting_line = false;
  921. } else {
  922. --open_indents;
  923. }
  924. }
  925. switch (token.category()) {
  926. case JS::TokenCategory::Invalid:
  927. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  928. break;
  929. case JS::TokenCategory::Number:
  930. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  931. break;
  932. case JS::TokenCategory::String:
  933. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  934. break;
  935. case JS::TokenCategory::Punctuation:
  936. break;
  937. case JS::TokenCategory::Operator:
  938. break;
  939. case JS::TokenCategory::Keyword:
  940. switch (token.type()) {
  941. case JS::TokenType::BoolLiteral:
  942. case JS::TokenType::NullLiteral:
  943. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  944. break;
  945. default:
  946. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  947. break;
  948. }
  949. break;
  950. case JS::TokenCategory::ControlKeyword:
  951. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  952. break;
  953. case JS::TokenCategory::Identifier:
  954. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  955. break;
  956. default:
  957. break;
  958. }
  959. }
  960. editor.set_prompt(prompt_for_level(open_indents));
  961. };
  962. auto complete = [&interpreter](Line::Editor const& editor) -> Vector<Line::CompletionSuggestion> {
  963. auto line = editor.line(editor.cursor());
  964. JS::Lexer lexer { line };
  965. enum {
  966. Initial,
  967. CompleteVariable,
  968. CompleteNullProperty,
  969. CompleteProperty,
  970. } mode { Initial };
  971. StringView variable_name;
  972. StringView property_name;
  973. // we're only going to complete either
  974. // - <N>
  975. // where N is part of the name of a variable
  976. // - <N>.<P>
  977. // where N is the complete name of a variable and
  978. // P is part of the name of one of its properties
  979. auto js_token = lexer.next();
  980. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  981. switch (mode) {
  982. case CompleteVariable:
  983. switch (js_token.type()) {
  984. case JS::TokenType::Period:
  985. // ...<name> <dot>
  986. mode = CompleteNullProperty;
  987. break;
  988. default:
  989. // not a dot, reset back to initial
  990. mode = Initial;
  991. break;
  992. }
  993. break;
  994. case CompleteNullProperty:
  995. if (js_token.is_identifier_name()) {
  996. // ...<name> <dot> <name>
  997. mode = CompleteProperty;
  998. property_name = js_token.value();
  999. } else {
  1000. mode = Initial;
  1001. }
  1002. break;
  1003. case CompleteProperty:
  1004. // something came after the property access, reset to initial
  1005. case Initial:
  1006. if (js_token.type() == JS::TokenType::Identifier) {
  1007. // ...<name>...
  1008. mode = CompleteVariable;
  1009. variable_name = js_token.value();
  1010. } else {
  1011. mode = Initial;
  1012. }
  1013. break;
  1014. }
  1015. }
  1016. bool last_token_has_trivia = js_token.trivia().length() > 0;
  1017. if (mode == CompleteNullProperty) {
  1018. mode = CompleteProperty;
  1019. property_name = "";
  1020. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  1021. }
  1022. if (mode == Initial || last_token_has_trivia)
  1023. return {}; // we do not know how to complete this
  1024. Vector<Line::CompletionSuggestion> results;
  1025. Function<void(JS::Shape const&, StringView const&)> list_all_properties = [&results, &list_all_properties](JS::Shape const& shape, auto& property_pattern) {
  1026. for (auto const& descriptor : shape.property_table()) {
  1027. if (!descriptor.key.is_string())
  1028. continue;
  1029. auto key = descriptor.key.as_string();
  1030. if (key.view().starts_with(property_pattern)) {
  1031. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  1032. if (!results.contains_slow(completion)) { // hide duplicates
  1033. results.append(String(key));
  1034. }
  1035. }
  1036. }
  1037. if (auto const* prototype = shape.prototype()) {
  1038. list_all_properties(prototype->shape(), property_pattern);
  1039. }
  1040. };
  1041. switch (mode) {
  1042. case CompleteProperty: {
  1043. auto maybe_variable = vm->get_variable(variable_name, interpreter->global_object());
  1044. if (maybe_variable.is_empty()) {
  1045. maybe_variable = interpreter->global_object().get(FlyString(variable_name));
  1046. if (maybe_variable.is_empty())
  1047. break;
  1048. }
  1049. auto variable = maybe_variable;
  1050. if (!variable.is_object())
  1051. break;
  1052. auto const* object = variable.to_object(interpreter->global_object());
  1053. auto const& shape = object->shape();
  1054. list_all_properties(shape, property_name);
  1055. if (results.size())
  1056. editor.suggest(property_name.length());
  1057. break;
  1058. }
  1059. case CompleteVariable: {
  1060. auto const& variable = interpreter->global_object();
  1061. list_all_properties(variable.shape(), variable_name);
  1062. if (results.size())
  1063. editor.suggest(variable_name.length());
  1064. break;
  1065. }
  1066. default:
  1067. VERIFY_NOT_REACHED();
  1068. }
  1069. return results;
  1070. };
  1071. s_editor->on_tab_complete = move(complete);
  1072. repl(*interpreter);
  1073. s_editor->save_history(s_history_path);
  1074. } else {
  1075. interpreter = JS::Interpreter::create<ScriptObject>(*vm);
  1076. ReplConsoleClient console_client(interpreter->global_object().console());
  1077. interpreter->global_object().console().set_client(console_client);
  1078. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  1079. signal(SIGINT, [](int) {
  1080. sigint_handler();
  1081. });
  1082. StringBuilder builder;
  1083. for (auto& path : script_paths) {
  1084. auto file = Core::File::construct(path);
  1085. if (!file->open(Core::OpenMode::ReadOnly)) {
  1086. warnln("Failed to open {}: {}", path, file->error_string());
  1087. return 1;
  1088. }
  1089. auto file_contents = file->read_all();
  1090. auto source = StringView { file_contents };
  1091. builder.append(source);
  1092. }
  1093. if (!parse_and_run(*interpreter, builder.to_string()))
  1094. return 1;
  1095. }
  1096. return 0;
  1097. }