js.cpp 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093
  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/Function.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/PrimitiveString.h>
  36. #include <LibJS/Runtime/Promise.h>
  37. #include <LibJS/Runtime/ProxyObject.h>
  38. #include <LibJS/Runtime/RegExpObject.h>
  39. #include <LibJS/Runtime/ScriptFunction.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 = it.value_and_attributes(&array).value;
  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 = entry.value_and_attributes(&object).value;
  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::ScriptFunction>(object))
  211. out(" {}", static_cast<const JS::ScriptFunction&>(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 length = typed_array_base.array_length();
  342. print_type(object.class_name());
  343. out("\n length: ");
  344. print_value(JS::Value(length), seen_objects);
  345. out("\n byteLength: ");
  346. print_value(JS::Value(typed_array_base.byte_length()), seen_objects);
  347. out("\n buffer: ");
  348. print_type("ArrayBuffer");
  349. out(" @ {:p}", typed_array_base.viewed_array_buffer());
  350. if (!length)
  351. return;
  352. outln();
  353. // FIXME: This kinda sucks.
  354. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  355. if (is<JS::ClassName>(object)) { \
  356. out("[ "); \
  357. auto& typed_array = static_cast<const JS::ClassName&>(typed_array_base); \
  358. auto data = typed_array.data(); \
  359. for (size_t i = 0; i < length; ++i) { \
  360. if (i > 0) \
  361. out(", "); \
  362. print_number(data[i]); \
  363. } \
  364. out(" ]"); \
  365. return; \
  366. }
  367. JS_ENUMERATE_TYPED_ARRAYS
  368. #undef __JS_ENUMERATE
  369. VERIFY_NOT_REACHED();
  370. }
  371. static void print_data_view(const JS::Object& object, HashTable<JS::Object*>& seen_objects)
  372. {
  373. auto& data_view = static_cast<const JS::DataView&>(object);
  374. print_type("DataView");
  375. out("\n byteLength: ");
  376. print_value(JS::Value(data_view.byte_length()), seen_objects);
  377. out("\n byteOffset: ");
  378. print_value(JS::Value(data_view.byte_offset()), seen_objects);
  379. out("\n buffer: ");
  380. print_type("ArrayBuffer");
  381. out(" @ {:p}", data_view.viewed_array_buffer());
  382. }
  383. static void print_primitive_wrapper_object(const FlyString& name, const JS::Object& object, HashTable<JS::Object*>& seen_objects)
  384. {
  385. // BooleanObject, NumberObject, StringObject
  386. print_type(name);
  387. out(" ");
  388. print_value(object.value_of(), seen_objects);
  389. }
  390. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  391. {
  392. if (value.is_empty()) {
  393. out("\033[34;1m<empty>\033[0m");
  394. return;
  395. }
  396. if (value.is_object()) {
  397. if (seen_objects.contains(&value.as_object())) {
  398. // FIXME: Maybe we should only do this for circular references,
  399. // not for all reoccurring objects.
  400. out("<already printed Object {}>", &value.as_object());
  401. return;
  402. }
  403. seen_objects.set(&value.as_object());
  404. }
  405. if (value.is_object()) {
  406. auto& object = value.as_object();
  407. if (object.is_array())
  408. return print_array(static_cast<JS::Array&>(object), seen_objects);
  409. if (object.is_function())
  410. return print_function(object, seen_objects);
  411. if (is<JS::Date>(object))
  412. return print_date(object, seen_objects);
  413. if (is<JS::Error>(object))
  414. return print_error(object, seen_objects);
  415. if (is<JS::RegExpObject>(object))
  416. return print_regexp_object(object, seen_objects);
  417. if (is<JS::Map>(object))
  418. return print_map(object, seen_objects);
  419. if (is<JS::Set>(object))
  420. return print_set(object, seen_objects);
  421. if (is<JS::DataView>(object))
  422. return print_data_view(object, seen_objects);
  423. if (is<JS::ProxyObject>(object))
  424. return print_proxy_object(object, seen_objects);
  425. if (is<JS::Promise>(object))
  426. return print_promise(object, seen_objects);
  427. if (is<JS::ArrayBuffer>(object))
  428. return print_array_buffer(object, seen_objects);
  429. if (object.is_typed_array())
  430. return print_typed_array(object, seen_objects);
  431. if (is<JS::StringObject>(object))
  432. return print_primitive_wrapper_object("String", object, seen_objects);
  433. if (is<JS::NumberObject>(object))
  434. return print_primitive_wrapper_object("Number", object, seen_objects);
  435. if (is<JS::BooleanObject>(object))
  436. return print_primitive_wrapper_object("Boolean", object, seen_objects);
  437. return print_object(object, seen_objects);
  438. }
  439. if (value.is_string())
  440. out("\033[32;1m");
  441. else if (value.is_number() || value.is_bigint())
  442. out("\033[35;1m");
  443. else if (value.is_boolean())
  444. out("\033[33;1m");
  445. else if (value.is_null())
  446. out("\033[33;1m");
  447. else if (value.is_undefined())
  448. out("\033[34;1m");
  449. if (value.is_string())
  450. out("\"");
  451. else if (value.is_negative_zero())
  452. out("-");
  453. out("{}", value.to_string_without_side_effects());
  454. if (value.is_string())
  455. out("\"");
  456. out("\033[0m");
  457. }
  458. static void print(JS::Value value)
  459. {
  460. HashTable<JS::Object*> seen_objects;
  461. print_value(value, seen_objects);
  462. outln();
  463. }
  464. static bool write_to_file(const String& path)
  465. {
  466. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  467. for (size_t i = 0; i < repl_statements.size(); i++) {
  468. auto line = repl_statements[i];
  469. if (line.length() && i != repl_statements.size() - 1) {
  470. ssize_t nwritten = write(fd, line.characters(), line.length());
  471. if (nwritten < 0) {
  472. close(fd);
  473. return false;
  474. }
  475. }
  476. if (i != repl_statements.size() - 1) {
  477. char ch = '\n';
  478. ssize_t nwritten = write(fd, &ch, 1);
  479. if (nwritten != 1) {
  480. perror("write");
  481. close(fd);
  482. return false;
  483. }
  484. }
  485. }
  486. close(fd);
  487. return true;
  488. }
  489. static bool parse_and_run(JS::Interpreter& interpreter, const StringView& source)
  490. {
  491. auto parser = JS::Parser(JS::Lexer(source));
  492. auto program = parser.parse_program();
  493. if (s_dump_ast)
  494. program->dump(0);
  495. if (parser.has_errors()) {
  496. auto error = parser.errors()[0];
  497. auto hint = error.source_location_hint(source);
  498. if (!hint.is_empty())
  499. outln("{}", hint);
  500. vm->throw_exception<JS::SyntaxError>(interpreter.global_object(), error.to_string());
  501. } else {
  502. if (s_dump_bytecode || s_run_bytecode) {
  503. auto unit = JS::Bytecode::Generator::generate(*program);
  504. if (s_opt_bytecode) {
  505. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  506. passes.perform(unit);
  507. dbgln("Optimisation passes took {}us", passes.elapsed());
  508. }
  509. if (s_dump_bytecode) {
  510. for (auto& block : unit.basic_blocks)
  511. block.dump(unit);
  512. if (!unit.string_table->is_empty()) {
  513. outln();
  514. unit.string_table->dump();
  515. }
  516. }
  517. if (s_run_bytecode) {
  518. JS::Bytecode::Interpreter bytecode_interpreter(interpreter.global_object());
  519. bytecode_interpreter.run(unit);
  520. } else {
  521. return true;
  522. }
  523. } else {
  524. interpreter.run(interpreter.global_object(), *program);
  525. }
  526. }
  527. auto handle_exception = [&] {
  528. auto* exception = vm->exception();
  529. vm->clear_exception();
  530. out("Uncaught exception: ");
  531. print(exception->value());
  532. auto& traceback = exception->traceback();
  533. if (traceback.size() > 1) {
  534. unsigned repetitions = 0;
  535. for (size_t i = 0; i < traceback.size(); ++i) {
  536. auto& traceback_frame = traceback[i];
  537. if (i + 1 < traceback.size()) {
  538. auto& next_traceback_frame = traceback[i + 1];
  539. if (next_traceback_frame.function_name == traceback_frame.function_name) {
  540. repetitions++;
  541. continue;
  542. }
  543. }
  544. if (repetitions > 4) {
  545. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  546. // the name only once and show the number of repetitions instead. This prevents
  547. // printing ridiculously large call stacks of recursive functions.
  548. outln(" -> {}", traceback_frame.function_name);
  549. outln(" {} more calls", repetitions);
  550. } else {
  551. for (size_t j = 0; j < repetitions + 1; ++j)
  552. outln(" -> {}", traceback_frame.function_name);
  553. }
  554. repetitions = 0;
  555. }
  556. }
  557. };
  558. if (vm->exception()) {
  559. handle_exception();
  560. return false;
  561. }
  562. if (s_print_last_result)
  563. print(vm->last_value());
  564. if (vm->exception()) {
  565. handle_exception();
  566. return false;
  567. }
  568. return true;
  569. }
  570. static JS::Value load_file_impl(JS::VM& vm, JS::GlobalObject& global_object)
  571. {
  572. auto filename = vm.argument(0).to_string(global_object);
  573. if (vm.exception())
  574. return {};
  575. auto file = Core::File::construct(filename);
  576. if (!file->open(Core::OpenMode::ReadOnly)) {
  577. vm.throw_exception<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  578. return {};
  579. }
  580. auto file_contents = file->read_all();
  581. auto source = StringView { file_contents };
  582. auto parser = JS::Parser(JS::Lexer(source));
  583. auto program = parser.parse_program();
  584. if (parser.has_errors()) {
  585. auto& error = parser.errors()[0];
  586. vm.throw_exception<JS::SyntaxError>(global_object, error.to_string());
  587. return {};
  588. }
  589. // FIXME: Use eval()-like semantics and execute in current scope?
  590. vm.interpreter().run(global_object, *program);
  591. return JS::js_undefined();
  592. }
  593. void ReplObject::initialize_global_object()
  594. {
  595. Base::initialize_global_object();
  596. define_property("global", this, JS::Attribute::Enumerable);
  597. define_native_function("exit", exit_interpreter);
  598. define_native_function("help", repl_help);
  599. define_native_function("load", load_file, 1);
  600. define_native_function("save", save_to_file, 1);
  601. }
  602. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  603. {
  604. if (!vm.argument_count())
  605. return JS::Value(false);
  606. String save_path = vm.argument(0).to_string_without_side_effects();
  607. StringView path = StringView(save_path.characters());
  608. if (write_to_file(path)) {
  609. return JS::Value(true);
  610. }
  611. return JS::Value(false);
  612. }
  613. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  614. {
  615. if (!vm.argument_count())
  616. exit(0);
  617. auto exit_code = vm.argument(0).to_number(global_object);
  618. if (::vm->exception())
  619. return {};
  620. exit(exit_code.as_double());
  621. }
  622. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  623. {
  624. outln("REPL commands:");
  625. outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  626. outln(" help(): display this menu");
  627. outln(" load(file): load given JS file into running session. For example: load(\"foo.js\")");
  628. outln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  629. return JS::js_undefined();
  630. }
  631. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  632. {
  633. return load_file_impl(vm, global_object);
  634. }
  635. void ScriptObject::initialize_global_object()
  636. {
  637. Base::initialize_global_object();
  638. define_property("global", this, JS::Attribute::Enumerable);
  639. define_native_function("load", load_file, 1);
  640. }
  641. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_file)
  642. {
  643. return load_file_impl(vm, global_object);
  644. }
  645. static void repl(JS::Interpreter& interpreter)
  646. {
  647. while (!s_fail_repl) {
  648. String piece = read_next_piece();
  649. if (piece.is_empty())
  650. continue;
  651. repl_statements.append(piece);
  652. parse_and_run(interpreter, piece);
  653. }
  654. }
  655. static Function<void()> interrupt_interpreter;
  656. static void sigint_handler()
  657. {
  658. interrupt_interpreter();
  659. }
  660. class ReplConsoleClient final : public JS::ConsoleClient {
  661. public:
  662. ReplConsoleClient(JS::Console& console)
  663. : ConsoleClient(console)
  664. {
  665. }
  666. virtual JS::Value log() override
  667. {
  668. outln("{}", vm().join_arguments());
  669. return JS::js_undefined();
  670. }
  671. virtual JS::Value info() override
  672. {
  673. outln("(i) {}", vm().join_arguments());
  674. return JS::js_undefined();
  675. }
  676. virtual JS::Value debug() override
  677. {
  678. outln("\033[36;1m{}\033[0m", vm().join_arguments());
  679. return JS::js_undefined();
  680. }
  681. virtual JS::Value warn() override
  682. {
  683. outln("\033[33;1m{}\033[0m", vm().join_arguments());
  684. return JS::js_undefined();
  685. }
  686. virtual JS::Value error() override
  687. {
  688. outln("\033[31;1m{}\033[0m", vm().join_arguments());
  689. return JS::js_undefined();
  690. }
  691. virtual JS::Value clear() override
  692. {
  693. out("\033[3J\033[H\033[2J");
  694. fflush(stdout);
  695. return JS::js_undefined();
  696. }
  697. virtual JS::Value trace() override
  698. {
  699. outln("{}", vm().join_arguments());
  700. auto trace = get_trace();
  701. for (auto& function_name : trace) {
  702. if (function_name.is_empty())
  703. function_name = "<anonymous>";
  704. outln(" -> {}", function_name);
  705. }
  706. return JS::js_undefined();
  707. }
  708. virtual JS::Value count() override
  709. {
  710. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  711. auto counter_value = m_console.counter_increment(label);
  712. outln("{}: {}", label, counter_value);
  713. return JS::js_undefined();
  714. }
  715. virtual JS::Value count_reset() override
  716. {
  717. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  718. if (m_console.counter_reset(label))
  719. outln("{}: 0", label);
  720. else
  721. outln("\033[33;1m\"{}\" doesn't have a count\033[0m", label);
  722. return JS::js_undefined();
  723. }
  724. virtual JS::Value assert_() override
  725. {
  726. auto& vm = this->vm();
  727. if (!vm.argument(0).to_boolean()) {
  728. if (vm.argument_count() > 1) {
  729. out("\033[31;1mAssertion failed:\033[0m");
  730. outln(" {}", vm.join_arguments(1));
  731. } else {
  732. outln("\033[31;1mAssertion failed\033[0m");
  733. }
  734. }
  735. return JS::js_undefined();
  736. }
  737. };
  738. int main(int argc, char** argv)
  739. {
  740. bool gc_on_every_allocation = false;
  741. bool disable_syntax_highlight = false;
  742. Vector<String> script_paths;
  743. Core::ArgsParser args_parser;
  744. args_parser.set_general_help("This is a JavaScript interpreter.");
  745. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  746. args_parser.add_option(s_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  747. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  748. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  749. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  750. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  751. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  752. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  753. args_parser.parse(argc, argv);
  754. bool syntax_highlight = !disable_syntax_highlight;
  755. vm = JS::VM::create();
  756. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  757. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  758. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  759. // might want to revisit at a later point and disable warnings for promises created this way.
  760. vm->on_promise_unhandled_rejection = [](auto& promise) {
  761. // FIXME: Optionally make print_value() to print to stderr
  762. out("WARNING: A promise was rejected without any handlers");
  763. out(" (result: ");
  764. HashTable<JS::Object*> seen_objects;
  765. print_value(promise.result(), seen_objects);
  766. outln(")");
  767. };
  768. vm->on_promise_rejection_handled = [](auto& promise) {
  769. // FIXME: Optionally make print_value() to print to stderr
  770. out("WARNING: A handler was added to an already rejected promise");
  771. out(" (result: ");
  772. HashTable<JS::Object*> seen_objects;
  773. print_value(promise.result(), seen_objects);
  774. outln(")");
  775. };
  776. OwnPtr<JS::Interpreter> interpreter;
  777. interrupt_interpreter = [&] {
  778. auto error = JS::Error::create(interpreter->global_object(), "Received SIGINT");
  779. vm->throw_exception(interpreter->global_object(), error);
  780. };
  781. if (script_paths.is_empty()) {
  782. s_print_last_result = true;
  783. interpreter = JS::Interpreter::create<ReplObject>(*vm);
  784. ReplConsoleClient console_client(interpreter->global_object().console());
  785. interpreter->global_object().console().set_client(console_client);
  786. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  787. interpreter->vm().set_underscore_is_last_value(true);
  788. s_editor = Line::Editor::construct();
  789. s_editor->load_history(s_history_path);
  790. signal(SIGINT, [](int) {
  791. if (!s_editor->is_editing())
  792. sigint_handler();
  793. s_editor->save_history(s_history_path);
  794. });
  795. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  796. auto stylize = [&](Line::Span span, Line::Style styles) {
  797. if (syntax_highlight)
  798. editor.stylize(span, styles);
  799. };
  800. editor.strip_styles();
  801. size_t open_indents = s_repl_line_level;
  802. auto line = editor.line();
  803. JS::Lexer lexer(line);
  804. bool indenters_starting_line = true;
  805. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  806. auto length = token.value().length();
  807. auto start = token.line_column() - 1;
  808. auto end = start + length;
  809. if (indenters_starting_line) {
  810. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  811. indenters_starting_line = false;
  812. } else {
  813. --open_indents;
  814. }
  815. }
  816. switch (token.category()) {
  817. case JS::TokenCategory::Invalid:
  818. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  819. break;
  820. case JS::TokenCategory::Number:
  821. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  822. break;
  823. case JS::TokenCategory::String:
  824. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  825. break;
  826. case JS::TokenCategory::Punctuation:
  827. break;
  828. case JS::TokenCategory::Operator:
  829. break;
  830. case JS::TokenCategory::Keyword:
  831. switch (token.type()) {
  832. case JS::TokenType::BoolLiteral:
  833. case JS::TokenType::NullLiteral:
  834. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  835. break;
  836. default:
  837. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  838. break;
  839. }
  840. break;
  841. case JS::TokenCategory::ControlKeyword:
  842. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  843. break;
  844. case JS::TokenCategory::Identifier:
  845. stylize({ start, end }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  846. default:
  847. break;
  848. }
  849. }
  850. editor.set_prompt(prompt_for_level(open_indents));
  851. };
  852. auto complete = [&interpreter](const Line::Editor& editor) -> Vector<Line::CompletionSuggestion> {
  853. auto line = editor.line(editor.cursor());
  854. JS::Lexer lexer { line };
  855. enum {
  856. Initial,
  857. CompleteVariable,
  858. CompleteNullProperty,
  859. CompleteProperty,
  860. } mode { Initial };
  861. StringView variable_name;
  862. StringView property_name;
  863. // we're only going to complete either
  864. // - <N>
  865. // where N is part of the name of a variable
  866. // - <N>.<P>
  867. // where N is the complete name of a variable and
  868. // P is part of the name of one of its properties
  869. auto js_token = lexer.next();
  870. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  871. switch (mode) {
  872. case CompleteVariable:
  873. switch (js_token.type()) {
  874. case JS::TokenType::Period:
  875. // ...<name> <dot>
  876. mode = CompleteNullProperty;
  877. break;
  878. default:
  879. // not a dot, reset back to initial
  880. mode = Initial;
  881. break;
  882. }
  883. break;
  884. case CompleteNullProperty:
  885. if (js_token.is_identifier_name()) {
  886. // ...<name> <dot> <name>
  887. mode = CompleteProperty;
  888. property_name = js_token.value();
  889. } else {
  890. mode = Initial;
  891. }
  892. break;
  893. case CompleteProperty:
  894. // something came after the property access, reset to initial
  895. case Initial:
  896. if (js_token.is_identifier_name()) {
  897. // ...<name>...
  898. mode = CompleteVariable;
  899. variable_name = js_token.value();
  900. } else {
  901. mode = Initial;
  902. }
  903. break;
  904. }
  905. }
  906. bool last_token_has_trivia = js_token.trivia().length() > 0;
  907. if (mode == CompleteNullProperty) {
  908. mode = CompleteProperty;
  909. property_name = "";
  910. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  911. }
  912. if (mode == Initial || last_token_has_trivia)
  913. return {}; // we do not know how to complete this
  914. Vector<Line::CompletionSuggestion> results;
  915. Function<void(const JS::Shape&, const StringView&)> list_all_properties = [&results, &list_all_properties](const JS::Shape& shape, auto& property_pattern) {
  916. for (const auto& descriptor : shape.property_table()) {
  917. if (!descriptor.key.is_string())
  918. continue;
  919. auto key = descriptor.key.as_string();
  920. if (key.view().starts_with(property_pattern)) {
  921. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  922. if (!results.contains_slow(completion)) { // hide duplicates
  923. results.append(String(key));
  924. }
  925. }
  926. }
  927. if (const auto* prototype = shape.prototype()) {
  928. list_all_properties(prototype->shape(), property_pattern);
  929. }
  930. };
  931. switch (mode) {
  932. case CompleteProperty: {
  933. auto maybe_variable = vm->get_variable(variable_name, interpreter->global_object());
  934. if (maybe_variable.is_empty()) {
  935. maybe_variable = interpreter->global_object().get(FlyString(variable_name));
  936. if (maybe_variable.is_empty())
  937. break;
  938. }
  939. auto variable = maybe_variable;
  940. if (!variable.is_object())
  941. break;
  942. const auto* object = variable.to_object(interpreter->global_object());
  943. const auto& shape = object->shape();
  944. list_all_properties(shape, property_name);
  945. if (results.size())
  946. editor.suggest(property_name.length());
  947. break;
  948. }
  949. case CompleteVariable: {
  950. const auto& variable = interpreter->global_object();
  951. list_all_properties(variable.shape(), variable_name);
  952. if (results.size())
  953. editor.suggest(variable_name.length());
  954. break;
  955. }
  956. default:
  957. VERIFY_NOT_REACHED();
  958. }
  959. return results;
  960. };
  961. s_editor->on_tab_complete = move(complete);
  962. repl(*interpreter);
  963. s_editor->save_history(s_history_path);
  964. } else {
  965. interpreter = JS::Interpreter::create<ScriptObject>(*vm);
  966. ReplConsoleClient console_client(interpreter->global_object().console());
  967. interpreter->global_object().console().set_client(console_client);
  968. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  969. signal(SIGINT, [](int) {
  970. sigint_handler();
  971. });
  972. StringBuilder builder;
  973. for (auto& path : script_paths) {
  974. auto file = Core::File::construct(path);
  975. if (!file->open(Core::OpenMode::ReadOnly)) {
  976. warnln("Failed to open {}: {}", path, file->error_string());
  977. return 1;
  978. }
  979. auto file_contents = file->read_all();
  980. auto source = StringView { file_contents };
  981. builder.append(source);
  982. }
  983. if (!parse_and_run(*interpreter, builder.to_string()))
  984. return 1;
  985. }
  986. return 0;
  987. }