js.cpp 34 KB

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