js.cpp 52 KB

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