js.cpp 39 KB

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