js.cpp 40 KB

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