js.cpp 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547
  1. /*
  2. * Copyright (c) 2020, Andreas Kling <kling@serenityos.org>
  3. * All rights reserved.
  4. *
  5. * Redistribution and use in source and binary forms, with or without
  6. * modification, are permitted provided that the following conditions are met:
  7. *
  8. * 1. Redistributions of source code must retain the above copyright notice, this
  9. * list of conditions and the following disclaimer.
  10. *
  11. * 2. Redistributions in binary form must reproduce the above copyright notice,
  12. * this list of conditions and the following disclaimer in the documentation
  13. * and/or other materials provided with the distribution.
  14. *
  15. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  16. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  17. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  18. * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
  19. * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
  20. * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
  21. * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
  22. * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
  23. * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  24. * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  25. */
  26. #include <AK/ByteBuffer.h>
  27. #include <AK/NonnullOwnPtr.h>
  28. #include <AK/StringBuilder.h>
  29. #include <LibCore/ArgsParser.h>
  30. #include <LibCore/File.h>
  31. #include <LibJS/AST.h>
  32. #include <LibJS/Interpreter.h>
  33. #include <LibJS/Parser.h>
  34. #include <LibJS/Runtime/Array.h>
  35. #include <LibJS/Runtime/Date.h>
  36. #include <LibJS/Runtime/Error.h>
  37. #include <LibJS/Runtime/Function.h>
  38. #include <LibJS/Runtime/GlobalObject.h>
  39. #include <LibJS/Runtime/Object.h>
  40. #include <LibJS/Runtime/PrimitiveString.h>
  41. #include <LibJS/Runtime/Shape.h>
  42. #include <LibJS/Runtime/Value.h>
  43. #include <LibLine/Editor.h>
  44. #include <stdio.h>
  45. Vector<String> repl_statements;
  46. class ReplObject : public JS::GlobalObject {
  47. public:
  48. ReplObject();
  49. virtual ~ReplObject() override;
  50. private:
  51. virtual const char* class_name() const override { return "ReplObject"; }
  52. static JS::Value exit_interpreter(JS::Interpreter&);
  53. static JS::Value repl_help(JS::Interpreter&);
  54. static JS::Value load_file(JS::Interpreter&);
  55. static JS::Value save_to_file(JS::Interpreter&);
  56. };
  57. bool dump_ast = false;
  58. static OwnPtr<Line::Editor> editor;
  59. String read_next_piece()
  60. {
  61. StringBuilder piece;
  62. int level = 0;
  63. StringBuilder prompt_builder;
  64. do {
  65. prompt_builder.clear();
  66. prompt_builder.append("> ");
  67. for (auto i = 0; i < level; ++i)
  68. prompt_builder.append(" ");
  69. String line = editor->get_line(prompt_builder.build());
  70. editor->add_to_history(line);
  71. piece.append(line);
  72. auto lexer = JS::Lexer(line);
  73. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  74. switch (token.type()) {
  75. case JS::TokenType::BracketOpen:
  76. case JS::TokenType::CurlyOpen:
  77. case JS::TokenType::ParenOpen:
  78. level++;
  79. break;
  80. case JS::TokenType::BracketClose:
  81. case JS::TokenType::CurlyClose:
  82. case JS::TokenType::ParenClose:
  83. level--;
  84. break;
  85. default:
  86. break;
  87. }
  88. }
  89. } while (level > 0);
  90. return piece.to_string();
  91. }
  92. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  93. static void print_array(const JS::Array& array, HashTable<JS::Object*>& seen_objects)
  94. {
  95. fputs("[ ", stdout);
  96. for (size_t i = 0; i < array.elements().size(); ++i) {
  97. print_value(array.elements()[i], seen_objects);
  98. if (i != array.elements().size() - 1)
  99. fputs(", ", stdout);
  100. }
  101. fputs(" ]", stdout);
  102. }
  103. static void print_object(const JS::Object& object, HashTable<JS::Object*>& seen_objects)
  104. {
  105. fputs("{ ", stdout);
  106. for (size_t i = 0; i < object.elements().size(); ++i) {
  107. printf("\"\033[33;1m%zu\033[0m\": ", i);
  108. print_value(object.elements()[i], seen_objects);
  109. if (i != object.elements().size() - 1)
  110. fputs(", ", stdout);
  111. }
  112. if (!object.elements().is_empty() && object.shape().property_count())
  113. fputs(", ", stdout);
  114. size_t index = 0;
  115. for (auto& it : object.shape().property_table()) {
  116. printf("\"\033[33;1m%s\033[0m\": ", it.key.characters());
  117. print_value(object.get_direct(it.value.offset), seen_objects);
  118. if (index != object.shape().property_count() - 1)
  119. fputs(", ", stdout);
  120. ++index;
  121. }
  122. fputs(" }", stdout);
  123. }
  124. static void print_function(const JS::Object& function, HashTable<JS::Object*>&)
  125. {
  126. printf("\033[34;1m[%s]\033[0m", function.class_name());
  127. }
  128. static void print_date(const JS::Object& date, HashTable<JS::Object*>&)
  129. {
  130. printf("\033[34;1mDate %s\033[0m", static_cast<const JS::Date&>(date).string().characters());
  131. }
  132. static void print_error(const JS::Object& object, HashTable<JS::Object*>&)
  133. {
  134. auto& error = static_cast<const JS::Error&>(object);
  135. printf("\033[34;1m[%s]\033[0m", error.name().characters());
  136. if (!error.message().is_empty())
  137. printf(": %s", error.message().characters());
  138. }
  139. void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  140. {
  141. if (value.is_object()) {
  142. if (seen_objects.contains(&value.as_object())) {
  143. // FIXME: Maybe we should only do this for circular references,
  144. // not for all reoccurring objects.
  145. printf("<already printed Object %p>", &value.as_object());
  146. return;
  147. }
  148. seen_objects.set(&value.as_object());
  149. }
  150. if (value.is_array())
  151. return print_array(static_cast<const JS::Array&>(value.as_object()), seen_objects);
  152. if (value.is_object()) {
  153. auto& object = value.as_object();
  154. if (object.is_function())
  155. return print_function(object, seen_objects);
  156. if (object.is_date())
  157. return print_date(object, seen_objects);
  158. if (object.is_error())
  159. return print_error(object, seen_objects);
  160. return print_object(object, seen_objects);
  161. }
  162. if (value.is_string())
  163. printf("\033[31;1m");
  164. else if (value.is_number())
  165. printf("\033[35;1m");
  166. else if (value.is_boolean())
  167. printf("\033[32;1m");
  168. else if (value.is_null())
  169. printf("\033[33;1m");
  170. else if (value.is_undefined())
  171. printf("\033[34;1m");
  172. if (value.is_string())
  173. putchar('"');
  174. printf("%s", value.to_string().characters());
  175. if (value.is_string())
  176. putchar('"');
  177. printf("\033[0m");
  178. }
  179. static void print(JS::Value value)
  180. {
  181. HashTable<JS::Object*> seen_objects;
  182. print_value(value, seen_objects);
  183. putchar('\n');
  184. }
  185. bool file_has_shebang(AK::ByteBuffer file_contents)
  186. {
  187. if (file_contents.size() >= 2 && file_contents[0] == '#' && file_contents[1] == '!')
  188. return true;
  189. return false;
  190. }
  191. StringView strip_shebang(AK::ByteBuffer file_contents)
  192. {
  193. size_t i = 0;
  194. for (i = 2; i < file_contents.size(); ++i) {
  195. if (file_contents[i] == '\n')
  196. break;
  197. }
  198. return StringView((const char*)file_contents.data() + i, file_contents.size() - i);
  199. }
  200. bool write_to_file(const StringView& path)
  201. {
  202. int fd = open_with_path_length(path.characters_without_null_termination(), path.length(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  203. for (size_t i = 0; i < repl_statements.size(); i++) {
  204. auto line = repl_statements[i];
  205. if (line.length() && i != repl_statements.size() - 1) {
  206. ssize_t nwritten = write(fd, line.characters(), line.length());
  207. if (nwritten < 0) {
  208. close(fd);
  209. return false;
  210. }
  211. }
  212. if (i != repl_statements.size() - 1) {
  213. char ch = '\n';
  214. ssize_t nwritten = write(fd, &ch, 1);
  215. if (nwritten != 1) {
  216. perror("write");
  217. close(fd);
  218. return false;
  219. }
  220. }
  221. }
  222. close(fd);
  223. return true;
  224. }
  225. ReplObject::ReplObject()
  226. {
  227. put_native_function("exit", exit_interpreter);
  228. put_native_function("help", repl_help);
  229. put_native_function("load", load_file, 1);
  230. put_native_function("save", save_to_file, 1);
  231. }
  232. ReplObject::~ReplObject()
  233. {
  234. }
  235. JS::Value ReplObject::save_to_file(JS::Interpreter& interpreter)
  236. {
  237. if (!interpreter.argument_count())
  238. return JS::Value(false);
  239. String save_path = interpreter.argument(0).to_string();
  240. StringView path = StringView(save_path.characters());
  241. if (write_to_file(path)) {
  242. return JS::Value(true);
  243. }
  244. return JS::Value(false);
  245. }
  246. JS::Value ReplObject::exit_interpreter(JS::Interpreter& interpreter)
  247. {
  248. if (!interpreter.argument_count())
  249. exit(0);
  250. int exit_code = interpreter.argument(0).to_number().as_double();
  251. exit(exit_code);
  252. return JS::js_undefined();
  253. }
  254. JS::Value ReplObject::repl_help(JS::Interpreter& interpreter)
  255. {
  256. StringBuilder help_text;
  257. help_text.append("REPL commands:\n");
  258. help_text.append(" exit(code): exit the REPL with specified code. Defaults to 0.\n");
  259. help_text.append(" help(): display this menu\n");
  260. help_text.append(" load(files): Accepts file names as params to load into running session. For example repl.load(\"js/1.js\", \"js/2.js\", \"js/3.js\")\n");
  261. String result = help_text.to_string();
  262. return js_string(interpreter, result);
  263. }
  264. JS::Value ReplObject::load_file(JS::Interpreter& interpreter)
  265. {
  266. if (!interpreter.argument_count())
  267. return JS::Value(false);
  268. for (auto& file : interpreter.call_frame().arguments) {
  269. String file_name = file.as_string()->string();
  270. auto js_file = Core::File::construct(file_name);
  271. if (!js_file->open(Core::IODevice::ReadOnly)) {
  272. fprintf(stderr, "Failed to open %s: %s\n", file_name.characters(), js_file->error_string());
  273. }
  274. auto file_contents = js_file->read_all();
  275. StringView source;
  276. if (file_has_shebang(file_contents)) {
  277. source = strip_shebang(file_contents);
  278. } else {
  279. source = file_contents;
  280. }
  281. auto program = JS::Parser(JS::Lexer(source)).parse_program();
  282. if (dump_ast)
  283. program->dump(0);
  284. interpreter.run(*program);
  285. print(interpreter.last_value());
  286. }
  287. return JS::Value(true);
  288. }
  289. void repl(JS::Interpreter& interpreter)
  290. {
  291. while (true) {
  292. String piece = read_next_piece();
  293. if (piece.is_empty())
  294. continue;
  295. repl_statements.append(piece);
  296. auto program = JS::Parser(JS::Lexer(piece)).parse_program();
  297. if (dump_ast)
  298. program->dump(0);
  299. interpreter.run(*program);
  300. if (interpreter.exception()) {
  301. printf("Uncaught exception: ");
  302. print(interpreter.exception()->value());
  303. interpreter.clear_exception();
  304. } else {
  305. print(interpreter.last_value());
  306. }
  307. }
  308. }
  309. JS::Value assert_impl(JS::Interpreter& interpreter)
  310. {
  311. if (!interpreter.argument_count())
  312. return interpreter.throw_exception<JS::Error>("TypeError", "No arguments specified");
  313. auto assertion_value = interpreter.argument(0);
  314. if (!assertion_value.is_boolean())
  315. return interpreter.throw_exception<JS::Error>("TypeError", "The first argument is not a boolean");
  316. if (!assertion_value.to_boolean())
  317. return interpreter.throw_exception<JS::Error>("AssertionError", "The assertion failed!");
  318. return assertion_value;
  319. }
  320. int main(int argc, char** argv)
  321. {
  322. bool gc_on_every_allocation = false;
  323. bool print_last_result = false;
  324. bool syntax_highlight = false;
  325. bool test_mode = false;
  326. const char* script_path = nullptr;
  327. Core::ArgsParser args_parser;
  328. args_parser.add_option(dump_ast, "Dump the AST", "dump-ast", 'A');
  329. args_parser.add_option(print_last_result, "Print last result", "print-last-result", 'l');
  330. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  331. args_parser.add_option(syntax_highlight, "Enable live syntax highlighting", "syntax-highlight", 's');
  332. args_parser.add_option(test_mode, "Run the interpretter with added functionality for the test harness", "test-mode", 't');
  333. args_parser.add_positional_argument(script_path, "Path to script file", "script", Core::ArgsParser::Required::No);
  334. args_parser.parse(argc, argv);
  335. if (script_path == nullptr) {
  336. auto interpreter = JS::Interpreter::create<ReplObject>();
  337. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  338. interpreter->global_object().put("global", &interpreter->global_object());
  339. if (test_mode) {
  340. interpreter->global_object().put_native_function("assert", assert_impl);
  341. }
  342. editor = make<Line::Editor>();
  343. editor->initialize();
  344. if (syntax_highlight)
  345. editor->on_display_refresh = [](Line::Editor& editor) {
  346. editor.strip_styles();
  347. StringBuilder builder;
  348. builder.append({ editor.buffer().data(), editor.buffer().size() });
  349. // FIXME: The lexer returns weird position information without this
  350. builder.append(" ");
  351. String str = builder.build();
  352. JS::Lexer lexer(str, false);
  353. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  354. auto length = token.value().length();
  355. auto start = token.line_column() - 2;
  356. auto end = start + length;
  357. switch (token.type()) {
  358. case JS::TokenType::Invalid:
  359. case JS::TokenType::Eof:
  360. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Red), Line::Style::Underline });
  361. break;
  362. case JS::TokenType::NumericLiteral:
  363. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Magenta) });
  364. break;
  365. case JS::TokenType::StringLiteral:
  366. case JS::TokenType::RegexLiteral:
  367. case JS::TokenType::UnterminatedStringLiteral:
  368. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Red) });
  369. break;
  370. case JS::TokenType::BracketClose:
  371. case JS::TokenType::BracketOpen:
  372. case JS::TokenType::Caret:
  373. case JS::TokenType::Comma:
  374. case JS::TokenType::CurlyClose:
  375. case JS::TokenType::CurlyOpen:
  376. case JS::TokenType::ParenClose:
  377. case JS::TokenType::ParenOpen:
  378. case JS::TokenType::Semicolon:
  379. case JS::TokenType::Period:
  380. break;
  381. case JS::TokenType::Ampersand:
  382. case JS::TokenType::AmpersandEquals:
  383. case JS::TokenType::Asterisk:
  384. case JS::TokenType::AsteriskAsteriskEquals:
  385. case JS::TokenType::AsteriskEquals:
  386. case JS::TokenType::DoubleAmpersand:
  387. case JS::TokenType::DoubleAsterisk:
  388. case JS::TokenType::DoublePipe:
  389. case JS::TokenType::DoubleQuestionMark:
  390. case JS::TokenType::Equals:
  391. case JS::TokenType::EqualsEquals:
  392. case JS::TokenType::EqualsEqualsEquals:
  393. case JS::TokenType::ExclamationMark:
  394. case JS::TokenType::ExclamationMarkEquals:
  395. case JS::TokenType::ExclamationMarkEqualsEquals:
  396. case JS::TokenType::GreaterThan:
  397. case JS::TokenType::GreaterThanEquals:
  398. case JS::TokenType::LessThan:
  399. case JS::TokenType::LessThanEquals:
  400. case JS::TokenType::Minus:
  401. case JS::TokenType::MinusEquals:
  402. case JS::TokenType::MinusMinus:
  403. case JS::TokenType::Percent:
  404. case JS::TokenType::PercentEquals:
  405. case JS::TokenType::Pipe:
  406. case JS::TokenType::PipeEquals:
  407. case JS::TokenType::Plus:
  408. case JS::TokenType::PlusEquals:
  409. case JS::TokenType::PlusPlus:
  410. case JS::TokenType::QuestionMark:
  411. case JS::TokenType::QuestionMarkPeriod:
  412. case JS::TokenType::ShiftLeft:
  413. case JS::TokenType::ShiftLeftEquals:
  414. case JS::TokenType::ShiftRight:
  415. case JS::TokenType::ShiftRightEquals:
  416. case JS::TokenType::Slash:
  417. case JS::TokenType::SlashEquals:
  418. case JS::TokenType::Tilde:
  419. case JS::TokenType::UnsignedShiftRight:
  420. case JS::TokenType::UnsignedShiftRightEquals:
  421. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Magenta) });
  422. break;
  423. case JS::TokenType::NullLiteral:
  424. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Yellow), Line::Style::Bold });
  425. break;
  426. case JS::TokenType::BoolLiteral:
  427. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Green), Line::Style::Bold });
  428. break;
  429. case JS::TokenType::Class:
  430. case JS::TokenType::Const:
  431. case JS::TokenType::Delete:
  432. case JS::TokenType::Function:
  433. case JS::TokenType::In:
  434. case JS::TokenType::Instanceof:
  435. case JS::TokenType::Interface:
  436. case JS::TokenType::Let:
  437. case JS::TokenType::New:
  438. case JS::TokenType::Typeof:
  439. case JS::TokenType::Var:
  440. case JS::TokenType::Void:
  441. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Blue), Line::Style::Bold });
  442. break;
  443. case JS::TokenType::Await:
  444. case JS::TokenType::Catch:
  445. case JS::TokenType::Do:
  446. case JS::TokenType::Else:
  447. case JS::TokenType::Finally:
  448. case JS::TokenType::For:
  449. case JS::TokenType::If:
  450. case JS::TokenType::Return:
  451. case JS::TokenType::Try:
  452. case JS::TokenType::While:
  453. case JS::TokenType::Yield:
  454. editor.stylize({ start, end }, { Line::Style::Foreground(Line::Style::Color::Cyan), Line::Style::Italic });
  455. break;
  456. case JS::TokenType::Identifier:
  457. default:
  458. break;
  459. }
  460. }
  461. };
  462. repl(*interpreter);
  463. } else {
  464. auto interpreter = JS::Interpreter::create<JS::GlobalObject>();
  465. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  466. interpreter->global_object().put("global", &interpreter->global_object());
  467. if (test_mode) {
  468. interpreter->global_object().put_native_function("assert", assert_impl);
  469. }
  470. auto file = Core::File::construct(script_path);
  471. if (!file->open(Core::IODevice::ReadOnly)) {
  472. fprintf(stderr, "Failed to open %s: %s\n", script_path, file->error_string());
  473. return 1;
  474. }
  475. auto file_contents = file->read_all();
  476. StringView source;
  477. if (file_has_shebang(file_contents)) {
  478. source = strip_shebang(file_contents);
  479. } else {
  480. source = file_contents;
  481. }
  482. auto program = JS::Parser(JS::Lexer(source)).parse_program();
  483. if (dump_ast)
  484. program->dump(0);
  485. auto result = interpreter->run(*program);
  486. if (interpreter->exception()) {
  487. printf("Uncaught exception: ");
  488. print(interpreter->exception()->value());
  489. interpreter->clear_exception();
  490. return 1;
  491. }
  492. if (print_last_result)
  493. print(result);
  494. }
  495. return 0;
  496. }