js.cpp 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230
  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/Function.h>
  36. #include <LibJS/Runtime/Object.h>
  37. #include <LibJS/Runtime/PrimitiveString.h>
  38. #include <LibJS/Runtime/Value.h>
  39. #include <LibLineEdit/LineEditor.h>
  40. #include <stdio.h>
  41. bool dump_ast = false;
  42. static LineEditor editor {};
  43. String read_next_piece()
  44. {
  45. StringBuilder piece;
  46. int level = 0;
  47. StringBuilder prompt_builder;
  48. do {
  49. prompt_builder.clear();
  50. prompt_builder.append("> ");
  51. for (auto i = 0; i < level; ++i)
  52. prompt_builder.append(" ");
  53. String line = editor.get_line(prompt_builder.build());
  54. piece.append(line);
  55. auto lexer = JS::Lexer(line);
  56. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  57. switch (token.type()) {
  58. case JS::TokenType::BracketOpen:
  59. case JS::TokenType::CurlyOpen:
  60. case JS::TokenType::ParenOpen:
  61. level++;
  62. break;
  63. case JS::TokenType::BracketClose:
  64. case JS::TokenType::CurlyClose:
  65. case JS::TokenType::ParenClose:
  66. level--;
  67. break;
  68. default:
  69. break;
  70. }
  71. }
  72. } while (level > 0);
  73. return piece.to_string();
  74. }
  75. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  76. static void print_array(const JS::Array* array, HashTable<JS::Object*>& seen_objects)
  77. {
  78. fputs("[ ", stdout);
  79. for (size_t i = 0; i < array->elements().size(); ++i) {
  80. print_value(array->elements()[i], seen_objects);
  81. if (i != array->elements().size() - 1)
  82. fputs(", ", stdout);
  83. }
  84. fputs(" ]", stdout);
  85. }
  86. static void print_object(const JS::Object* object, HashTable<JS::Object*>& seen_objects)
  87. {
  88. fputs("{ ", stdout);
  89. size_t index = 0;
  90. for (auto& it : object->own_properties()) {
  91. printf("\"\033[33;1m%s\033[0m\": ", it.key.characters());
  92. print_value(it.value, seen_objects);
  93. if (index != object->own_properties().size() - 1)
  94. fputs(", ", stdout);
  95. ++index;
  96. }
  97. fputs(" }", stdout);
  98. }
  99. static void print_function(const JS::Object* function, HashTable<JS::Object*>&)
  100. {
  101. printf("\033[34;1m[%s]\033[0m", function->class_name());
  102. }
  103. void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  104. {
  105. if (value.is_object()) {
  106. if (seen_objects.contains(value.as_object())) {
  107. // FIXME: Maybe we should only do this for circular references,
  108. // not for all reoccurring objects.
  109. printf("<already printed Object %p>", value.as_object());
  110. return;
  111. }
  112. seen_objects.set(value.as_object());
  113. }
  114. if (value.is_array())
  115. return print_array(static_cast<const JS::Array*>(value.as_object()), seen_objects);
  116. if (value.is_object() && value.as_object()->is_function())
  117. return print_function(value.as_object(), seen_objects);
  118. if (value.is_object())
  119. return print_object(value.as_object(), seen_objects);
  120. if (value.is_string())
  121. printf("\033[31;1m");
  122. else if (value.is_number())
  123. printf("\033[35;1m");
  124. else if (value.is_boolean())
  125. printf("\033[32;1m");
  126. else if (value.is_null())
  127. printf("\033[33;1m");
  128. else if (value.is_undefined())
  129. printf("\033[34;1m");
  130. if (value.is_string())
  131. putchar('"');
  132. printf("%s", value.to_string().characters());
  133. if (value.is_string())
  134. putchar('"');
  135. printf("\033[0m");
  136. }
  137. static void print(JS::Value value)
  138. {
  139. HashTable<JS::Object*> seen_objects;
  140. print_value(value, seen_objects);
  141. putchar('\n');
  142. }
  143. void repl(JS::Interpreter& interpreter)
  144. {
  145. while (true) {
  146. String piece = read_next_piece();
  147. if (piece.is_empty())
  148. break;
  149. auto program = JS::Parser(JS::Lexer(piece)).parse_program();
  150. if (dump_ast)
  151. program->dump(0);
  152. auto result = interpreter.run(*program);
  153. print(result);
  154. }
  155. }
  156. int main(int argc, char** argv)
  157. {
  158. bool gc_on_every_allocation = false;
  159. bool print_last_result = false;
  160. const char* script_path = nullptr;
  161. Core::ArgsParser args_parser;
  162. args_parser.add_option(dump_ast, "Dump the AST", "dump-ast", 'A');
  163. args_parser.add_option(print_last_result, "Print last result", "print-last-result", 'l');
  164. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  165. args_parser.add_positional_argument(script_path, "Path to script file", "script", Core::ArgsParser::Required::No);
  166. args_parser.parse(argc, argv);
  167. JS::Interpreter interpreter;
  168. interpreter.heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  169. interpreter.global_object().put("global", &interpreter.global_object());
  170. if (script_path == nullptr) {
  171. editor.initialize();
  172. repl(interpreter);
  173. } else {
  174. auto file = Core::File::construct(script_path);
  175. if (!file->open(Core::IODevice::ReadOnly)) {
  176. fprintf(stderr, "Failed to open %s: %s\n", script_path, file->error_string());
  177. return 1;
  178. }
  179. auto file_contents = file->read_all();
  180. StringView source;
  181. if (file_contents.size() >= 2 && file_contents[0] == '#' && file_contents[1] == '!') {
  182. size_t i = 0;
  183. for (i = 2; i < file_contents.size(); ++i) {
  184. if (file_contents[i] == '\n')
  185. break;
  186. }
  187. source = StringView((const char*)file_contents.data() + i, file_contents.size() - i);
  188. } else {
  189. source = file_contents;
  190. }
  191. auto program = JS::Parser(JS::Lexer(source)).parse_program();
  192. if (dump_ast)
  193. program->dump(0);
  194. auto result = interpreter.run(*program);
  195. if (print_last_result)
  196. printf("%s\n", result.to_string().characters());
  197. }
  198. return 0;
  199. }