js.cpp 54 KB

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