js.cpp 36 KB

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