js.cpp 37 KB

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