js.cpp 36 KB

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