js.cpp 33 KB

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