js.cpp 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096
  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. define_native_function("exit", exit_interpreter);
  601. define_native_function("help", repl_help);
  602. define_native_function("load", load_file, 1);
  603. define_native_function("save", save_to_file, 1);
  604. }
  605. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  606. {
  607. if (!vm.argument_count())
  608. return JS::Value(false);
  609. String save_path = vm.argument(0).to_string_without_side_effects();
  610. StringView path = StringView(save_path.characters());
  611. if (write_to_file(path)) {
  612. return JS::Value(true);
  613. }
  614. return JS::Value(false);
  615. }
  616. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  617. {
  618. if (!vm.argument_count())
  619. exit(0);
  620. auto exit_code = vm.argument(0).to_number(global_object);
  621. if (::vm->exception())
  622. return {};
  623. exit(exit_code.as_double());
  624. }
  625. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  626. {
  627. outln("REPL commands:");
  628. outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  629. outln(" help(): display this menu");
  630. outln(" load(file): load given JS file into running session. For example: load(\"foo.js\")");
  631. outln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  632. return JS::js_undefined();
  633. }
  634. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  635. {
  636. return load_file_impl(vm, global_object);
  637. }
  638. void ScriptObject::initialize_global_object()
  639. {
  640. Base::initialize_global_object();
  641. define_direct_property("global", this, JS::Attribute::Enumerable);
  642. define_native_function("load", load_file, 1);
  643. }
  644. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_file)
  645. {
  646. return load_file_impl(vm, global_object);
  647. }
  648. static void repl(JS::Interpreter& interpreter)
  649. {
  650. while (!s_fail_repl) {
  651. String piece = read_next_piece();
  652. if (piece.is_empty())
  653. continue;
  654. repl_statements.append(piece);
  655. parse_and_run(interpreter, piece);
  656. }
  657. }
  658. static Function<void()> interrupt_interpreter;
  659. static void sigint_handler()
  660. {
  661. interrupt_interpreter();
  662. }
  663. class ReplConsoleClient final : public JS::ConsoleClient {
  664. public:
  665. ReplConsoleClient(JS::Console& console)
  666. : ConsoleClient(console)
  667. {
  668. }
  669. virtual JS::Value log() override
  670. {
  671. outln("{}", vm().join_arguments());
  672. return JS::js_undefined();
  673. }
  674. virtual JS::Value info() override
  675. {
  676. outln("(i) {}", vm().join_arguments());
  677. return JS::js_undefined();
  678. }
  679. virtual JS::Value debug() override
  680. {
  681. outln("\033[36;1m{}\033[0m", vm().join_arguments());
  682. return JS::js_undefined();
  683. }
  684. virtual JS::Value warn() override
  685. {
  686. outln("\033[33;1m{}\033[0m", vm().join_arguments());
  687. return JS::js_undefined();
  688. }
  689. virtual JS::Value error() override
  690. {
  691. outln("\033[31;1m{}\033[0m", vm().join_arguments());
  692. return JS::js_undefined();
  693. }
  694. virtual JS::Value clear() override
  695. {
  696. out("\033[3J\033[H\033[2J");
  697. fflush(stdout);
  698. return JS::js_undefined();
  699. }
  700. virtual JS::Value trace() override
  701. {
  702. outln("{}", vm().join_arguments());
  703. auto trace = get_trace();
  704. for (auto& function_name : trace) {
  705. if (function_name.is_empty())
  706. function_name = "<anonymous>";
  707. outln(" -> {}", function_name);
  708. }
  709. return JS::js_undefined();
  710. }
  711. virtual JS::Value count() override
  712. {
  713. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  714. auto counter_value = m_console.counter_increment(label);
  715. outln("{}: {}", label, counter_value);
  716. return JS::js_undefined();
  717. }
  718. virtual JS::Value count_reset() override
  719. {
  720. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  721. if (m_console.counter_reset(label))
  722. outln("{}: 0", label);
  723. else
  724. outln("\033[33;1m\"{}\" doesn't have a count\033[0m", label);
  725. return JS::js_undefined();
  726. }
  727. virtual JS::Value assert_() override
  728. {
  729. auto& vm = this->vm();
  730. if (!vm.argument(0).to_boolean()) {
  731. if (vm.argument_count() > 1) {
  732. out("\033[31;1mAssertion failed:\033[0m");
  733. outln(" {}", vm.join_arguments(1));
  734. } else {
  735. outln("\033[31;1mAssertion failed\033[0m");
  736. }
  737. }
  738. return JS::js_undefined();
  739. }
  740. };
  741. int main(int argc, char** argv)
  742. {
  743. bool gc_on_every_allocation = false;
  744. bool disable_syntax_highlight = false;
  745. Vector<String> script_paths;
  746. Core::ArgsParser args_parser;
  747. args_parser.set_general_help("This is a JavaScript interpreter.");
  748. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  749. args_parser.add_option(s_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  750. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  751. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  752. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  753. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  754. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  755. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  756. args_parser.parse(argc, argv);
  757. bool syntax_highlight = !disable_syntax_highlight;
  758. vm = JS::VM::create();
  759. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  760. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  761. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  762. // might want to revisit at a later point and disable warnings for promises created this way.
  763. vm->on_promise_unhandled_rejection = [](auto& promise) {
  764. // FIXME: Optionally make print_value() to print to stderr
  765. out("WARNING: A promise was rejected without any handlers");
  766. out(" (result: ");
  767. HashTable<JS::Object*> seen_objects;
  768. print_value(promise.result(), seen_objects);
  769. outln(")");
  770. };
  771. vm->on_promise_rejection_handled = [](auto& promise) {
  772. // FIXME: Optionally make print_value() to print to stderr
  773. out("WARNING: A handler was added to an already rejected promise");
  774. out(" (result: ");
  775. HashTable<JS::Object*> seen_objects;
  776. print_value(promise.result(), seen_objects);
  777. outln(")");
  778. };
  779. OwnPtr<JS::Interpreter> interpreter;
  780. interrupt_interpreter = [&] {
  781. auto error = JS::Error::create(interpreter->global_object(), "Received SIGINT");
  782. vm->throw_exception(interpreter->global_object(), error);
  783. };
  784. if (script_paths.is_empty()) {
  785. s_print_last_result = true;
  786. interpreter = JS::Interpreter::create<ReplObject>(*vm);
  787. ReplConsoleClient console_client(interpreter->global_object().console());
  788. interpreter->global_object().console().set_client(console_client);
  789. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  790. interpreter->vm().set_underscore_is_last_value(true);
  791. s_editor = Line::Editor::construct();
  792. s_editor->load_history(s_history_path);
  793. signal(SIGINT, [](int) {
  794. if (!s_editor->is_editing())
  795. sigint_handler();
  796. s_editor->save_history(s_history_path);
  797. });
  798. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  799. auto stylize = [&](Line::Span span, Line::Style styles) {
  800. if (syntax_highlight)
  801. editor.stylize(span, styles);
  802. };
  803. editor.strip_styles();
  804. size_t open_indents = s_repl_line_level;
  805. auto line = editor.line();
  806. JS::Lexer lexer(line);
  807. bool indenters_starting_line = true;
  808. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  809. auto length = token.value().length();
  810. auto start = token.line_column() - 1;
  811. auto end = start + length;
  812. if (indenters_starting_line) {
  813. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  814. indenters_starting_line = false;
  815. } else {
  816. --open_indents;
  817. }
  818. }
  819. switch (token.category()) {
  820. case JS::TokenCategory::Invalid:
  821. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  822. break;
  823. case JS::TokenCategory::Number:
  824. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  825. break;
  826. case JS::TokenCategory::String:
  827. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  828. break;
  829. case JS::TokenCategory::Punctuation:
  830. break;
  831. case JS::TokenCategory::Operator:
  832. break;
  833. case JS::TokenCategory::Keyword:
  834. switch (token.type()) {
  835. case JS::TokenType::BoolLiteral:
  836. case JS::TokenType::NullLiteral:
  837. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  838. break;
  839. default:
  840. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  841. break;
  842. }
  843. break;
  844. case JS::TokenCategory::ControlKeyword:
  845. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  846. break;
  847. case JS::TokenCategory::Identifier:
  848. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  849. default:
  850. break;
  851. }
  852. }
  853. editor.set_prompt(prompt_for_level(open_indents));
  854. };
  855. auto complete = [&interpreter](const Line::Editor& editor) -> Vector<Line::CompletionSuggestion> {
  856. auto line = editor.line(editor.cursor());
  857. JS::Lexer lexer { line };
  858. enum {
  859. Initial,
  860. CompleteVariable,
  861. CompleteNullProperty,
  862. CompleteProperty,
  863. } mode { Initial };
  864. StringView variable_name;
  865. StringView property_name;
  866. // we're only going to complete either
  867. // - <N>
  868. // where N is part of the name of a variable
  869. // - <N>.<P>
  870. // where N is the complete name of a variable and
  871. // P is part of the name of one of its properties
  872. auto js_token = lexer.next();
  873. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  874. switch (mode) {
  875. case CompleteVariable:
  876. switch (js_token.type()) {
  877. case JS::TokenType::Period:
  878. // ...<name> <dot>
  879. mode = CompleteNullProperty;
  880. break;
  881. default:
  882. // not a dot, reset back to initial
  883. mode = Initial;
  884. break;
  885. }
  886. break;
  887. case CompleteNullProperty:
  888. if (js_token.is_identifier_name()) {
  889. // ...<name> <dot> <name>
  890. mode = CompleteProperty;
  891. property_name = js_token.value();
  892. } else {
  893. mode = Initial;
  894. }
  895. break;
  896. case CompleteProperty:
  897. // something came after the property access, reset to initial
  898. case Initial:
  899. if (js_token.is_identifier_name()) {
  900. // ...<name>...
  901. mode = CompleteVariable;
  902. variable_name = js_token.value();
  903. } else {
  904. mode = Initial;
  905. }
  906. break;
  907. }
  908. }
  909. bool last_token_has_trivia = js_token.trivia().length() > 0;
  910. if (mode == CompleteNullProperty) {
  911. mode = CompleteProperty;
  912. property_name = "";
  913. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  914. }
  915. if (mode == Initial || last_token_has_trivia)
  916. return {}; // we do not know how to complete this
  917. Vector<Line::CompletionSuggestion> results;
  918. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  919. for (const auto& descriptor : shape.property_table()) {
  920. if (!descriptor.key.is_string())
  921. continue;
  922. auto key = descriptor.key.as_string();
  923. if (key.view().starts_with(property_pattern)) {
  924. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  925. if (!results.contains_slow(completion)) { // hide duplicates
  926. results.append(String(key));
  927. }
  928. }
  929. }
  930. if (const auto* prototype = shape.prototype()) {
  931. list_all_properties(prototype->shape(), property_pattern);
  932. }
  933. };
  934. switch (mode) {
  935. case CompleteProperty: {
  936. auto maybe_variable = vm->get_variable(variable_name, interpreter->global_object());
  937. if (maybe_variable.is_empty()) {
  938. maybe_variable = interpreter->global_object().get(FlyString(variable_name));
  939. if (maybe_variable.is_empty())
  940. break;
  941. }
  942. auto variable = maybe_variable;
  943. if (!variable.is_object())
  944. break;
  945. const auto* object = variable.to_object(interpreter->global_object());
  946. const auto& shape = object->shape();
  947. list_all_properties(shape, property_name);
  948. if (results.size())
  949. editor.suggest(property_name.length());
  950. break;
  951. }
  952. case CompleteVariable: {
  953. const auto& variable = interpreter->global_object();
  954. list_all_properties(variable.shape(), variable_name);
  955. if (results.size())
  956. editor.suggest(variable_name.length());
  957. break;
  958. }
  959. default:
  960. VERIFY_NOT_REACHED();
  961. }
  962. return results;
  963. };
  964. s_editor->on_tab_complete = move(complete);
  965. repl(*interpreter);
  966. s_editor->save_history(s_history_path);
  967. } else {
  968. interpreter = JS::Interpreter::create<ScriptObject>(*vm);
  969. ReplConsoleClient console_client(interpreter->global_object().console());
  970. interpreter->global_object().console().set_client(console_client);
  971. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  972. signal(SIGINT, [](int) {
  973. sigint_handler();
  974. });
  975. StringBuilder builder;
  976. for (auto& path : script_paths) {
  977. auto file = Core::File::construct(path);
  978. if (!file->open(Core::OpenMode::ReadOnly)) {
  979. warnln("Failed to open {}: {}", path, file->error_string());
  980. return 1;
  981. }
  982. auto file_contents = file->read_all();
  983. auto source = StringView { file_contents };
  984. builder.append(source);
  985. }
  986. if (!parse_and_run(*interpreter, builder.to_string()))
  987. return 1;
  988. }
  989. return 0;
  990. }