js.cpp 47 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256
  1. /*
  2. * Copyright (c) 2020-2021, Andreas Kling <kling@serenityos.org>
  3. * Copyright (c) 2020-2021, Linus Groh <linusg@serenityos.org>
  4. *
  5. * SPDX-License-Identifier: BSD-2-Clause
  6. */
  7. #include <AK/Assertions.h>
  8. #include <AK/ByteBuffer.h>
  9. #include <AK/Format.h>
  10. #include <AK/NonnullOwnPtr.h>
  11. #include <AK/StringBuilder.h>
  12. #include <LibCore/ArgsParser.h>
  13. #include <LibCore/File.h>
  14. #include <LibCore/StandardPaths.h>
  15. #include <LibJS/AST.h>
  16. #include <LibJS/Bytecode/BasicBlock.h>
  17. #include <LibJS/Bytecode/Generator.h>
  18. #include <LibJS/Bytecode/Interpreter.h>
  19. #include <LibJS/Bytecode/PassManager.h>
  20. #include <LibJS/Console.h>
  21. #include <LibJS/Interpreter.h>
  22. #include <LibJS/Parser.h>
  23. #include <LibJS/Runtime/Array.h>
  24. #include <LibJS/Runtime/ArrayBuffer.h>
  25. #include <LibJS/Runtime/BooleanObject.h>
  26. #include <LibJS/Runtime/DataView.h>
  27. #include <LibJS/Runtime/Date.h>
  28. #include <LibJS/Runtime/Error.h>
  29. #include <LibJS/Runtime/FunctionObject.h>
  30. #include <LibJS/Runtime/GlobalObject.h>
  31. #include <LibJS/Runtime/Intl/DisplayNames.h>
  32. #include <LibJS/Runtime/Intl/Locale.h>
  33. #include <LibJS/Runtime/Map.h>
  34. #include <LibJS/Runtime/NativeFunction.h>
  35. #include <LibJS/Runtime/NumberObject.h>
  36. #include <LibJS/Runtime/Object.h>
  37. #include <LibJS/Runtime/OrdinaryFunctionObject.h>
  38. #include <LibJS/Runtime/PrimitiveString.h>
  39. #include <LibJS/Runtime/Promise.h>
  40. #include <LibJS/Runtime/ProxyObject.h>
  41. #include <LibJS/Runtime/RegExpObject.h>
  42. #include <LibJS/Runtime/Set.h>
  43. #include <LibJS/Runtime/Shape.h>
  44. #include <LibJS/Runtime/StringObject.h>
  45. #include <LibJS/Runtime/Temporal/Calendar.h>
  46. #include <LibJS/Runtime/Temporal/Duration.h>
  47. #include <LibJS/Runtime/Temporal/Instant.h>
  48. #include <LibJS/Runtime/Temporal/PlainDate.h>
  49. #include <LibJS/Runtime/Temporal/PlainDateTime.h>
  50. #include <LibJS/Runtime/Temporal/PlainTime.h>
  51. #include <LibJS/Runtime/Temporal/PlainYearMonth.h>
  52. #include <LibJS/Runtime/Temporal/TimeZone.h>
  53. #include <LibJS/Runtime/Temporal/ZonedDateTime.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() = default;
  67. virtual void initialize_global_object() override;
  68. virtual ~ReplObject() override = default;
  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. class ScriptObject final : public JS::GlobalObject {
  76. JS_OBJECT(ScriptObject, JS::GlobalObject);
  77. public:
  78. ScriptObject() = default;
  79. virtual void initialize_global_object() override;
  80. virtual ~ScriptObject() override = default;
  81. private:
  82. JS_DECLARE_NATIVE_FUNCTION(load_file);
  83. };
  84. static bool s_dump_ast = false;
  85. static bool s_dump_bytecode = false;
  86. static bool s_run_bytecode = false;
  87. static bool s_opt_bytecode = false;
  88. static bool s_as_module = false;
  89. static bool s_print_last_result = false;
  90. static RefPtr<Line::Editor> s_editor;
  91. static String s_history_path = String::formatted("{}/.js-history", Core::StandardPaths::home_directory());
  92. static int s_repl_line_level = 0;
  93. static bool s_fail_repl = false;
  94. static String prompt_for_level(int level)
  95. {
  96. static StringBuilder prompt_builder;
  97. prompt_builder.clear();
  98. prompt_builder.append("> ");
  99. for (auto i = 0; i < level; ++i)
  100. prompt_builder.append(" ");
  101. return prompt_builder.build();
  102. }
  103. static String read_next_piece()
  104. {
  105. StringBuilder piece;
  106. auto line_level_delta_for_next_line { 0 };
  107. do {
  108. auto line_result = s_editor->get_line(prompt_for_level(s_repl_line_level));
  109. line_level_delta_for_next_line = 0;
  110. if (line_result.is_error()) {
  111. s_fail_repl = true;
  112. return "";
  113. }
  114. auto& line = line_result.value();
  115. s_editor->add_to_history(line);
  116. piece.append(line);
  117. piece.append('\n');
  118. auto lexer = JS::Lexer(line);
  119. enum {
  120. NotInLabelOrObjectKey,
  121. InLabelOrObjectKeyIdentifier,
  122. InLabelOrObjectKey
  123. } label_state { NotInLabelOrObjectKey };
  124. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  125. switch (token.type()) {
  126. case JS::TokenType::BracketOpen:
  127. case JS::TokenType::CurlyOpen:
  128. case JS::TokenType::ParenOpen:
  129. label_state = NotInLabelOrObjectKey;
  130. s_repl_line_level++;
  131. break;
  132. case JS::TokenType::BracketClose:
  133. case JS::TokenType::CurlyClose:
  134. case JS::TokenType::ParenClose:
  135. label_state = NotInLabelOrObjectKey;
  136. s_repl_line_level--;
  137. break;
  138. case JS::TokenType::Identifier:
  139. case JS::TokenType::StringLiteral:
  140. if (label_state == NotInLabelOrObjectKey)
  141. label_state = InLabelOrObjectKeyIdentifier;
  142. else
  143. label_state = NotInLabelOrObjectKey;
  144. break;
  145. case JS::TokenType::Colon:
  146. if (label_state == InLabelOrObjectKeyIdentifier)
  147. label_state = InLabelOrObjectKey;
  148. else
  149. label_state = NotInLabelOrObjectKey;
  150. break;
  151. default:
  152. break;
  153. }
  154. }
  155. if (label_state == InLabelOrObjectKey) {
  156. // If there's a label or object literal key at the end of this line,
  157. // prompt for more lines but do not change the line level.
  158. line_level_delta_for_next_line += 1;
  159. }
  160. } while (s_repl_line_level + line_level_delta_for_next_line > 0);
  161. return piece.to_string();
  162. }
  163. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects);
  164. static void print_type(FlyString const& name)
  165. {
  166. out("[\033[36;1m{}\033[0m]", name);
  167. }
  168. static void print_separator(bool& first)
  169. {
  170. out(first ? " " : ", ");
  171. first = false;
  172. }
  173. static void print_array(JS::Array& array, HashTable<JS::Object*>& seen_objects)
  174. {
  175. out("[");
  176. bool first = true;
  177. for (auto it = array.indexed_properties().begin(false); it != array.indexed_properties().end(); ++it) {
  178. print_separator(first);
  179. auto value = array.get(it.index());
  180. // The V8 repl doesn't throw an exception here, and instead just
  181. // prints 'undefined'. We may choose to replicate that behavior in
  182. // the future, but for now lets just catch the error
  183. if (vm->exception())
  184. return;
  185. print_value(value, seen_objects);
  186. }
  187. if (!first)
  188. out(" ");
  189. out("]");
  190. }
  191. static void print_object(JS::Object& object, HashTable<JS::Object*>& seen_objects)
  192. {
  193. out("{{");
  194. bool first = true;
  195. for (auto& entry : object.indexed_properties()) {
  196. print_separator(first);
  197. out("\"\033[33;1m{}\033[0m\": ", entry.index());
  198. auto value = object.get(entry.index());
  199. // The V8 repl doesn't throw an exception here, and instead just
  200. // prints 'undefined'. We may choose to replicate that behavior in
  201. // the future, but for now lets just catch the error
  202. if (vm->exception())
  203. return;
  204. print_value(value, seen_objects);
  205. }
  206. for (auto& it : object.shape().property_table_ordered()) {
  207. print_separator(first);
  208. if (it.key.is_string()) {
  209. out("\"\033[33;1m{}\033[0m\": ", it.key.to_display_string());
  210. } else {
  211. out("[\033[33;1m{}\033[0m]: ", it.key.to_display_string());
  212. }
  213. print_value(object.get_direct(it.value.offset), seen_objects);
  214. }
  215. if (!first)
  216. out(" ");
  217. out("}}");
  218. }
  219. static void print_function(JS::Object const& object, HashTable<JS::Object*>&)
  220. {
  221. print_type(object.class_name());
  222. if (is<JS::OrdinaryFunctionObject>(object))
  223. out(" {}", static_cast<JS::OrdinaryFunctionObject const&>(object).name());
  224. else if (is<JS::NativeFunction>(object))
  225. out(" {}", static_cast<JS::NativeFunction const&>(object).name());
  226. }
  227. static void print_date(JS::Object const& object, HashTable<JS::Object*>&)
  228. {
  229. print_type("Date");
  230. out(" \033[34;1m{}\033[0m", static_cast<JS::Date const&>(object).string());
  231. }
  232. static void print_error(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  233. {
  234. auto name = object.get_without_side_effects(vm->names.name).value_or(JS::js_undefined());
  235. auto message = object.get_without_side_effects(vm->names.message).value_or(JS::js_undefined());
  236. if (name.is_accessor() || message.is_accessor()) {
  237. print_value(&object, seen_objects);
  238. } else {
  239. auto name_string = name.to_string_without_side_effects();
  240. auto message_string = message.to_string_without_side_effects();
  241. print_type(name_string);
  242. if (!message_string.is_empty())
  243. out(" \033[31;1m{}\033[0m", message_string);
  244. }
  245. }
  246. static void print_regexp_object(JS::Object const& object, HashTable<JS::Object*>&)
  247. {
  248. auto& regexp_object = static_cast<JS::RegExpObject const&>(object);
  249. // Use RegExp.prototype.source rather than RegExpObject::pattern() so we get proper escaping
  250. auto source = regexp_object.get("source").to_primitive_string(object.global_object())->string();
  251. print_type("RegExp");
  252. out(" \033[34;1m/{}/{}\033[0m", source, regexp_object.flags());
  253. }
  254. static void print_proxy_object(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  255. {
  256. auto& proxy_object = static_cast<JS::ProxyObject const&>(object);
  257. print_type("Proxy");
  258. out("\n target: ");
  259. print_value(&proxy_object.target(), seen_objects);
  260. out("\n handler: ");
  261. print_value(&proxy_object.handler(), seen_objects);
  262. }
  263. static void print_map(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  264. {
  265. auto& map = static_cast<JS::Map const&>(object);
  266. auto& entries = map.entries();
  267. print_type("Map");
  268. out(" {{");
  269. bool first = true;
  270. for (auto& entry : entries) {
  271. print_separator(first);
  272. print_value(entry.key, seen_objects);
  273. out(" => ");
  274. print_value(entry.value, seen_objects);
  275. }
  276. if (!first)
  277. out(" ");
  278. out("}}");
  279. }
  280. static void print_set(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  281. {
  282. auto& set = static_cast<JS::Set const&>(object);
  283. auto& values = set.values();
  284. print_type("Set");
  285. out(" {{");
  286. bool first = true;
  287. for (auto& value : values) {
  288. print_separator(first);
  289. print_value(value, seen_objects);
  290. }
  291. if (!first)
  292. out(" ");
  293. out("}}");
  294. }
  295. static void print_promise(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  296. {
  297. auto& promise = static_cast<JS::Promise const&>(object);
  298. print_type("Promise");
  299. switch (promise.state()) {
  300. case JS::Promise::State::Pending:
  301. out("\n state: ");
  302. out("\033[36;1mPending\033[0m");
  303. break;
  304. case JS::Promise::State::Fulfilled:
  305. out("\n state: ");
  306. out("\033[32;1mFulfilled\033[0m");
  307. out("\n result: ");
  308. print_value(promise.result(), seen_objects);
  309. break;
  310. case JS::Promise::State::Rejected:
  311. out("\n state: ");
  312. out("\033[31;1mRejected\033[0m");
  313. out("\n result: ");
  314. print_value(promise.result(), seen_objects);
  315. break;
  316. default:
  317. VERIFY_NOT_REACHED();
  318. }
  319. }
  320. static void print_array_buffer(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  321. {
  322. auto& array_buffer = static_cast<JS::ArrayBuffer const&>(object);
  323. auto& buffer = array_buffer.buffer();
  324. auto byte_length = array_buffer.byte_length();
  325. print_type("ArrayBuffer");
  326. out("\n byteLength: ");
  327. print_value(JS::Value((double)byte_length), seen_objects);
  328. if (!byte_length)
  329. return;
  330. outln();
  331. for (size_t i = 0; i < byte_length; ++i) {
  332. out("{:02x}", buffer[i]);
  333. if (i + 1 < byte_length) {
  334. if ((i + 1) % 32 == 0)
  335. outln();
  336. else if ((i + 1) % 16 == 0)
  337. out(" ");
  338. else
  339. out(" ");
  340. }
  341. }
  342. }
  343. template<typename T>
  344. static void print_number(T number) requires IsArithmetic<T>
  345. {
  346. out("\033[35;1m");
  347. out("{}", number);
  348. out("\033[0m");
  349. }
  350. static void print_typed_array(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  351. {
  352. auto& typed_array_base = static_cast<JS::TypedArrayBase const&>(object);
  353. auto& array_buffer = *typed_array_base.viewed_array_buffer();
  354. auto length = typed_array_base.array_length();
  355. print_type(object.class_name());
  356. out("\n length: ");
  357. print_value(JS::Value(length), seen_objects);
  358. out("\n byteLength: ");
  359. print_value(JS::Value(typed_array_base.byte_length()), seen_objects);
  360. out("\n buffer: ");
  361. print_type("ArrayBuffer");
  362. if (array_buffer.is_detached())
  363. out(" (detached)");
  364. out(" @ {:p}", &array_buffer);
  365. if (!length || array_buffer.is_detached())
  366. return;
  367. outln();
  368. // FIXME: This kinda sucks.
  369. #define __JS_ENUMERATE(ClassName, snake_name, PrototypeName, ConstructorName, ArrayType) \
  370. if (is<JS::ClassName>(object)) { \
  371. out("[ "); \
  372. auto& typed_array = static_cast<JS::ClassName const&>(typed_array_base); \
  373. auto data = typed_array.data(); \
  374. for (size_t i = 0; i < length; ++i) { \
  375. if (i > 0) \
  376. out(", "); \
  377. print_number(data[i]); \
  378. } \
  379. out(" ]"); \
  380. return; \
  381. }
  382. JS_ENUMERATE_TYPED_ARRAYS
  383. #undef __JS_ENUMERATE
  384. VERIFY_NOT_REACHED();
  385. }
  386. static void print_data_view(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  387. {
  388. auto& data_view = static_cast<JS::DataView const&>(object);
  389. print_type("DataView");
  390. out("\n byteLength: ");
  391. print_value(JS::Value(data_view.byte_length()), seen_objects);
  392. out("\n byteOffset: ");
  393. print_value(JS::Value(data_view.byte_offset()), seen_objects);
  394. out("\n buffer: ");
  395. print_type("ArrayBuffer");
  396. out(" @ {:p}", data_view.viewed_array_buffer());
  397. }
  398. static void print_temporal_calendar(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  399. {
  400. auto& calendar = static_cast<JS::Temporal::Calendar const&>(object);
  401. print_type("Temporal.Calendar");
  402. out(" ");
  403. print_value(JS::js_string(object.vm(), calendar.identifier()), seen_objects);
  404. }
  405. static void print_temporal_duration(JS::Object const& object, HashTable<JS::Object*>&)
  406. {
  407. auto& duration = static_cast<JS::Temporal::Duration const&>(object);
  408. print_type("Temporal.Duration");
  409. out(" \033[34;1m{} y, {} M, {} w, {} d, {} h, {} m, {} s, {} ms, {} us, {} ns\033[0m", duration.years(), duration.months(), duration.weeks(), duration.days(), duration.hours(), duration.minutes(), duration.seconds(), duration.milliseconds(), duration.microseconds(), duration.nanoseconds());
  410. }
  411. static void print_temporal_instant(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  412. {
  413. auto& instant = static_cast<JS::Temporal::Instant const&>(object);
  414. print_type("Temporal.Instant");
  415. out(" ");
  416. // FIXME: Print human readable date and time, like in print_date() - ideally handling arbitrarily large values since we get a bigint.
  417. print_value(&instant.nanoseconds(), seen_objects);
  418. }
  419. static void print_temporal_plain_date(JS::Object const& object, HashTable<JS::Object*>&)
  420. {
  421. auto& plain_date = static_cast<JS::Temporal::PlainDate const&>(object);
  422. print_type("Temporal.PlainDate");
  423. out(" \033[34;1m{:04}-{:02}-{:02}\033[0m", plain_date.iso_year(), plain_date.iso_month(), plain_date.iso_day());
  424. }
  425. static void print_temporal_plain_date_time(JS::Object const& object, HashTable<JS::Object*>&)
  426. {
  427. auto& plain_date_time = static_cast<JS::Temporal::PlainDateTime const&>(object);
  428. print_type("Temporal.PlainDateTime");
  429. out(" \033[34;1m{:04}-{:02}-{:02} {:02}:{:02}:{:02}.{:03}{:03}{:03}\033[0m", plain_date_time.iso_year(), plain_date_time.iso_month(), plain_date_time.iso_day(), plain_date_time.iso_hour(), plain_date_time.iso_minute(), plain_date_time.iso_second(), plain_date_time.iso_millisecond(), plain_date_time.iso_microsecond(), plain_date_time.iso_nanosecond());
  430. }
  431. static void print_temporal_plain_time(JS::Object const& object, HashTable<JS::Object*>&)
  432. {
  433. auto& plain_time = static_cast<JS::Temporal::PlainTime const&>(object);
  434. print_type("Temporal.PlainTime");
  435. out(" \033[34;1m{:02}:{:02}:{:02}.{:03}{:03}{:03}\033[0m", plain_time.iso_hour(), plain_time.iso_minute(), plain_time.iso_second(), plain_time.iso_millisecond(), plain_time.iso_microsecond(), plain_time.iso_nanosecond());
  436. }
  437. static void print_temporal_plain_year_month(JS::Object const& object, HashTable<JS::Object*>&)
  438. {
  439. auto& plain_year_month = static_cast<JS::Temporal::PlainYearMonth const&>(object);
  440. print_type("Temporal.PlainYearMonth");
  441. // Also has an [[ISODay]] internal slot, but showing that here seems rather unexpected.
  442. out(" \033[34;1m{:04}-{:02}\033[0m", plain_year_month.iso_year(), plain_year_month.iso_month());
  443. }
  444. static void print_temporal_time_zone(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  445. {
  446. auto& time_zone = static_cast<JS::Temporal::TimeZone const&>(object);
  447. print_type("Temporal.TimeZone");
  448. out(" ");
  449. print_value(JS::js_string(object.vm(), time_zone.identifier()), seen_objects);
  450. if (time_zone.offset_nanoseconds().has_value()) {
  451. out("\n offset (ns): ");
  452. print_value(JS::Value(*time_zone.offset_nanoseconds()), seen_objects);
  453. }
  454. }
  455. static void print_temporal_zoned_date_time(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  456. {
  457. auto& zoned_date_time = static_cast<JS::Temporal::ZonedDateTime const&>(object);
  458. print_type("Temporal.ZonedDateTime");
  459. out("\n epochNanoseconds: ");
  460. print_value(&zoned_date_time.nanoseconds(), seen_objects);
  461. out("\n timeZone: ");
  462. print_value(&zoned_date_time.time_zone(), seen_objects);
  463. out("\n calendar: ");
  464. print_value(&zoned_date_time.calendar(), seen_objects);
  465. }
  466. static void print_intl_display_names(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  467. {
  468. auto& display_names = static_cast<JS::Intl::DisplayNames const&>(object);
  469. print_type("Intl.DisplayNames");
  470. out("\n locale: ");
  471. print_value(js_string(object.vm(), display_names.locale()), seen_objects);
  472. out("\n type: ");
  473. print_value(js_string(object.vm(), display_names.type_string()), seen_objects);
  474. out("\n style: ");
  475. print_value(js_string(object.vm(), display_names.style_string()), seen_objects);
  476. out("\n fallback: ");
  477. print_value(js_string(object.vm(), display_names.fallback_string()), seen_objects);
  478. }
  479. static void print_intl_locale(JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  480. {
  481. auto& locale = static_cast<JS::Intl::Locale const&>(object);
  482. print_type("Intl.Locale");
  483. out("\n locale: ");
  484. print_value(js_string(object.vm(), locale.locale()), seen_objects);
  485. if (locale.has_calendar()) {
  486. out("\n calendar: ");
  487. print_value(js_string(object.vm(), locale.calendar()), seen_objects);
  488. }
  489. if (locale.has_case_first()) {
  490. out("\n caseFirst: ");
  491. print_value(js_string(object.vm(), locale.case_first()), seen_objects);
  492. }
  493. if (locale.has_collation()) {
  494. out("\n collation: ");
  495. print_value(js_string(object.vm(), locale.collation()), seen_objects);
  496. }
  497. if (locale.has_hour_cycle()) {
  498. out("\n hourCycle: ");
  499. print_value(js_string(object.vm(), locale.hour_cycle()), seen_objects);
  500. }
  501. if (locale.has_numbering_system()) {
  502. out("\n numberingSystem: ");
  503. print_value(js_string(object.vm(), locale.numbering_system()), seen_objects);
  504. }
  505. out("\n numeric: ");
  506. print_value(JS::Value(locale.numeric()), seen_objects);
  507. }
  508. static void print_primitive_wrapper_object(FlyString const& name, JS::Object const& object, HashTable<JS::Object*>& seen_objects)
  509. {
  510. // BooleanObject, NumberObject, StringObject
  511. print_type(name);
  512. out(" ");
  513. print_value(object.value_of(), seen_objects);
  514. }
  515. static void print_value(JS::Value value, HashTable<JS::Object*>& seen_objects)
  516. {
  517. if (value.is_empty()) {
  518. out("\033[34;1m<empty>\033[0m");
  519. return;
  520. }
  521. if (value.is_object()) {
  522. if (seen_objects.contains(&value.as_object())) {
  523. // FIXME: Maybe we should only do this for circular references,
  524. // not for all reoccurring objects.
  525. out("<already printed Object {}>", &value.as_object());
  526. return;
  527. }
  528. seen_objects.set(&value.as_object());
  529. }
  530. if (value.is_object()) {
  531. auto& object = value.as_object();
  532. if (is<JS::Array>(object))
  533. return print_array(static_cast<JS::Array&>(object), seen_objects);
  534. if (object.is_function())
  535. return print_function(object, seen_objects);
  536. if (is<JS::Date>(object))
  537. return print_date(object, seen_objects);
  538. if (is<JS::Error>(object))
  539. return print_error(object, seen_objects);
  540. if (is<JS::RegExpObject>(object))
  541. return print_regexp_object(object, seen_objects);
  542. if (is<JS::Map>(object))
  543. return print_map(object, seen_objects);
  544. if (is<JS::Set>(object))
  545. return print_set(object, seen_objects);
  546. if (is<JS::DataView>(object))
  547. return print_data_view(object, seen_objects);
  548. if (is<JS::ProxyObject>(object))
  549. return print_proxy_object(object, seen_objects);
  550. if (is<JS::Promise>(object))
  551. return print_promise(object, seen_objects);
  552. if (is<JS::ArrayBuffer>(object))
  553. return print_array_buffer(object, seen_objects);
  554. if (object.is_typed_array())
  555. return print_typed_array(object, seen_objects);
  556. if (is<JS::StringObject>(object))
  557. return print_primitive_wrapper_object("String", object, seen_objects);
  558. if (is<JS::NumberObject>(object))
  559. return print_primitive_wrapper_object("Number", object, seen_objects);
  560. if (is<JS::BooleanObject>(object))
  561. return print_primitive_wrapper_object("Boolean", object, seen_objects);
  562. if (is<JS::Temporal::Calendar>(object))
  563. return print_temporal_calendar(object, seen_objects);
  564. if (is<JS::Temporal::Duration>(object))
  565. return print_temporal_duration(object, seen_objects);
  566. if (is<JS::Temporal::Instant>(object))
  567. return print_temporal_instant(object, seen_objects);
  568. if (is<JS::Temporal::PlainDate>(object))
  569. return print_temporal_plain_date(object, seen_objects);
  570. if (is<JS::Temporal::PlainDateTime>(object))
  571. return print_temporal_plain_date_time(object, seen_objects);
  572. if (is<JS::Temporal::PlainTime>(object))
  573. return print_temporal_plain_time(object, seen_objects);
  574. if (is<JS::Temporal::PlainYearMonth>(object))
  575. return print_temporal_plain_year_month(object, seen_objects);
  576. if (is<JS::Temporal::TimeZone>(object))
  577. return print_temporal_time_zone(object, seen_objects);
  578. if (is<JS::Temporal::ZonedDateTime>(object))
  579. return print_temporal_zoned_date_time(object, seen_objects);
  580. if (is<JS::Intl::DisplayNames>(object))
  581. return print_intl_display_names(object, seen_objects);
  582. if (is<JS::Intl::Locale>(object))
  583. return print_intl_locale(object, seen_objects);
  584. return print_object(object, seen_objects);
  585. }
  586. if (value.is_string())
  587. out("\033[32;1m");
  588. else if (value.is_number() || value.is_bigint())
  589. out("\033[35;1m");
  590. else if (value.is_boolean())
  591. out("\033[33;1m");
  592. else if (value.is_null())
  593. out("\033[33;1m");
  594. else if (value.is_undefined())
  595. out("\033[34;1m");
  596. if (value.is_string())
  597. out("\"");
  598. else if (value.is_negative_zero())
  599. out("-");
  600. out("{}", value.to_string_without_side_effects());
  601. if (value.is_string())
  602. out("\"");
  603. out("\033[0m");
  604. }
  605. static void print(JS::Value value)
  606. {
  607. HashTable<JS::Object*> seen_objects;
  608. print_value(value, seen_objects);
  609. outln();
  610. }
  611. static bool write_to_file(String const& path)
  612. {
  613. int fd = open(path.characters(), O_WRONLY | O_CREAT | O_TRUNC, 0666);
  614. for (size_t i = 0; i < repl_statements.size(); i++) {
  615. auto line = repl_statements[i];
  616. if (line.length() && i != repl_statements.size() - 1) {
  617. ssize_t nwritten = write(fd, line.characters(), line.length());
  618. if (nwritten < 0) {
  619. close(fd);
  620. return false;
  621. }
  622. }
  623. if (i != repl_statements.size() - 1) {
  624. char ch = '\n';
  625. ssize_t nwritten = write(fd, &ch, 1);
  626. if (nwritten != 1) {
  627. perror("write");
  628. close(fd);
  629. return false;
  630. }
  631. }
  632. }
  633. close(fd);
  634. return true;
  635. }
  636. static bool parse_and_run(JS::Interpreter& interpreter, StringView const& source)
  637. {
  638. auto program_type = s_as_module ? JS::Program::Type::Module : JS::Program::Type::Script;
  639. auto parser = JS::Parser(JS::Lexer(source), program_type);
  640. auto program = parser.parse_program();
  641. if (s_dump_ast)
  642. program->dump(0);
  643. if (parser.has_errors()) {
  644. auto error = parser.errors()[0];
  645. auto hint = error.source_location_hint(source);
  646. if (!hint.is_empty())
  647. outln("{}", hint);
  648. vm->throw_exception<JS::SyntaxError>(interpreter.global_object(), error.to_string());
  649. } else {
  650. if (s_dump_bytecode || s_run_bytecode) {
  651. auto unit = JS::Bytecode::Generator::generate(*program);
  652. if (s_opt_bytecode) {
  653. auto& passes = JS::Bytecode::Interpreter::optimization_pipeline();
  654. passes.perform(unit);
  655. dbgln("Optimisation passes took {}us", passes.elapsed());
  656. }
  657. if (s_dump_bytecode) {
  658. for (auto& block : unit.basic_blocks)
  659. block.dump(unit);
  660. if (!unit.string_table->is_empty()) {
  661. outln();
  662. unit.string_table->dump();
  663. }
  664. }
  665. if (s_run_bytecode) {
  666. JS::Bytecode::Interpreter bytecode_interpreter(interpreter.global_object());
  667. bytecode_interpreter.run(unit);
  668. } else {
  669. return true;
  670. }
  671. } else {
  672. interpreter.run(interpreter.global_object(), *program);
  673. }
  674. }
  675. auto handle_exception = [&] {
  676. auto* exception = vm->exception();
  677. vm->clear_exception();
  678. out("Uncaught exception: ");
  679. print(exception->value());
  680. auto& traceback = exception->traceback();
  681. if (traceback.size() > 1) {
  682. unsigned repetitions = 0;
  683. for (size_t i = 0; i < traceback.size(); ++i) {
  684. auto& traceback_frame = traceback[i];
  685. if (i + 1 < traceback.size()) {
  686. auto& next_traceback_frame = traceback[i + 1];
  687. if (next_traceback_frame.function_name == traceback_frame.function_name) {
  688. repetitions++;
  689. continue;
  690. }
  691. }
  692. if (repetitions > 4) {
  693. // If more than 5 (1 + >4) consecutive function calls with the same name, print
  694. // the name only once and show the number of repetitions instead. This prevents
  695. // printing ridiculously large call stacks of recursive functions.
  696. outln(" -> {}", traceback_frame.function_name);
  697. outln(" {} more calls", repetitions);
  698. } else {
  699. for (size_t j = 0; j < repetitions + 1; ++j)
  700. outln(" -> {}", traceback_frame.function_name);
  701. }
  702. repetitions = 0;
  703. }
  704. }
  705. };
  706. if (vm->exception()) {
  707. handle_exception();
  708. return false;
  709. }
  710. if (s_print_last_result)
  711. print(vm->last_value());
  712. if (vm->exception()) {
  713. handle_exception();
  714. return false;
  715. }
  716. return true;
  717. }
  718. static JS::Value load_file_impl(JS::VM& vm, JS::GlobalObject& global_object)
  719. {
  720. auto filename = vm.argument(0).to_string(global_object);
  721. if (vm.exception())
  722. return {};
  723. auto file = Core::File::construct(filename);
  724. if (!file->open(Core::OpenMode::ReadOnly)) {
  725. vm.throw_exception<JS::Error>(global_object, String::formatted("Failed to open '{}': {}", filename, file->error_string()));
  726. return {};
  727. }
  728. auto file_contents = file->read_all();
  729. auto source = StringView { file_contents };
  730. auto parser = JS::Parser(JS::Lexer(source));
  731. auto program = parser.parse_program();
  732. if (parser.has_errors()) {
  733. auto& error = parser.errors()[0];
  734. vm.throw_exception<JS::SyntaxError>(global_object, error.to_string());
  735. return {};
  736. }
  737. // FIXME: Use eval()-like semantics and execute in current scope?
  738. vm.interpreter().run(global_object, *program);
  739. return JS::js_undefined();
  740. }
  741. void ReplObject::initialize_global_object()
  742. {
  743. Base::initialize_global_object();
  744. define_direct_property("global", this, JS::Attribute::Enumerable);
  745. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  746. define_native_function("exit", exit_interpreter, 0, attr);
  747. define_native_function("help", repl_help, 0, attr);
  748. define_native_function("load", load_file, 1, attr);
  749. define_native_function("save", save_to_file, 1, attr);
  750. }
  751. JS_DEFINE_NATIVE_FUNCTION(ReplObject::save_to_file)
  752. {
  753. if (!vm.argument_count())
  754. return JS::Value(false);
  755. String save_path = vm.argument(0).to_string_without_side_effects();
  756. StringView path = StringView(save_path.characters());
  757. if (write_to_file(path)) {
  758. return JS::Value(true);
  759. }
  760. return JS::Value(false);
  761. }
  762. JS_DEFINE_NATIVE_FUNCTION(ReplObject::exit_interpreter)
  763. {
  764. if (!vm.argument_count())
  765. exit(0);
  766. auto exit_code = vm.argument(0).to_number(global_object);
  767. if (::vm->exception())
  768. return {};
  769. exit(exit_code.as_double());
  770. }
  771. JS_DEFINE_NATIVE_FUNCTION(ReplObject::repl_help)
  772. {
  773. outln("REPL commands:");
  774. outln(" exit(code): exit the REPL with specified code. Defaults to 0.");
  775. outln(" help(): display this menu");
  776. outln(" load(file): load given JS file into running session. For example: load(\"foo.js\")");
  777. outln(" save(file): write REPL input history to the given file. For example: save(\"foo.txt\")");
  778. return JS::js_undefined();
  779. }
  780. JS_DEFINE_NATIVE_FUNCTION(ReplObject::load_file)
  781. {
  782. return load_file_impl(vm, global_object);
  783. }
  784. void ScriptObject::initialize_global_object()
  785. {
  786. Base::initialize_global_object();
  787. define_direct_property("global", this, JS::Attribute::Enumerable);
  788. u8 attr = JS::Attribute::Configurable | JS::Attribute::Writable | JS::Attribute::Enumerable;
  789. define_native_function("load", load_file, 1, attr);
  790. }
  791. JS_DEFINE_NATIVE_FUNCTION(ScriptObject::load_file)
  792. {
  793. return load_file_impl(vm, global_object);
  794. }
  795. static void repl(JS::Interpreter& interpreter)
  796. {
  797. while (!s_fail_repl) {
  798. String piece = read_next_piece();
  799. if (piece.is_empty())
  800. continue;
  801. repl_statements.append(piece);
  802. parse_and_run(interpreter, piece);
  803. }
  804. }
  805. static Function<void()> interrupt_interpreter;
  806. static void sigint_handler()
  807. {
  808. interrupt_interpreter();
  809. }
  810. class ReplConsoleClient final : public JS::ConsoleClient {
  811. public:
  812. ReplConsoleClient(JS::Console& console)
  813. : ConsoleClient(console)
  814. {
  815. }
  816. virtual JS::Value log() override
  817. {
  818. outln("{}", vm().join_arguments());
  819. return JS::js_undefined();
  820. }
  821. virtual JS::Value info() override
  822. {
  823. outln("(i) {}", vm().join_arguments());
  824. return JS::js_undefined();
  825. }
  826. virtual JS::Value debug() override
  827. {
  828. outln("\033[36;1m{}\033[0m", vm().join_arguments());
  829. return JS::js_undefined();
  830. }
  831. virtual JS::Value warn() override
  832. {
  833. outln("\033[33;1m{}\033[0m", vm().join_arguments());
  834. return JS::js_undefined();
  835. }
  836. virtual JS::Value error() override
  837. {
  838. outln("\033[31;1m{}\033[0m", vm().join_arguments());
  839. return JS::js_undefined();
  840. }
  841. virtual JS::Value clear() override
  842. {
  843. out("\033[3J\033[H\033[2J");
  844. fflush(stdout);
  845. return JS::js_undefined();
  846. }
  847. virtual JS::Value trace() override
  848. {
  849. outln("{}", vm().join_arguments());
  850. auto trace = get_trace();
  851. for (auto& function_name : trace) {
  852. if (function_name.is_empty())
  853. function_name = "<anonymous>";
  854. outln(" -> {}", function_name);
  855. }
  856. return JS::js_undefined();
  857. }
  858. virtual JS::Value count() override
  859. {
  860. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  861. auto counter_value = m_console.counter_increment(label);
  862. outln("{}: {}", label, counter_value);
  863. return JS::js_undefined();
  864. }
  865. virtual JS::Value count_reset() override
  866. {
  867. auto label = vm().argument_count() ? vm().argument(0).to_string_without_side_effects() : "default";
  868. if (m_console.counter_reset(label))
  869. outln("{}: 0", label);
  870. else
  871. outln("\033[33;1m\"{}\" doesn't have a count\033[0m", label);
  872. return JS::js_undefined();
  873. }
  874. virtual JS::Value assert_() override
  875. {
  876. auto& vm = this->vm();
  877. if (!vm.argument(0).to_boolean()) {
  878. if (vm.argument_count() > 1) {
  879. out("\033[31;1mAssertion failed:\033[0m");
  880. outln(" {}", vm.join_arguments(1));
  881. } else {
  882. outln("\033[31;1mAssertion failed\033[0m");
  883. }
  884. }
  885. return JS::js_undefined();
  886. }
  887. };
  888. int main(int argc, char** argv)
  889. {
  890. bool gc_on_every_allocation = false;
  891. bool disable_syntax_highlight = false;
  892. Vector<String> script_paths;
  893. Core::ArgsParser args_parser;
  894. args_parser.set_general_help("This is a JavaScript interpreter.");
  895. args_parser.add_option(s_dump_ast, "Dump the AST", "dump-ast", 'A');
  896. args_parser.add_option(s_dump_bytecode, "Dump the bytecode", "dump-bytecode", 'd');
  897. args_parser.add_option(s_run_bytecode, "Run the bytecode", "run-bytecode", 'b');
  898. args_parser.add_option(s_opt_bytecode, "Optimize the bytecode", "optimize-bytecode", 'p');
  899. args_parser.add_option(s_as_module, "Treat as module", "as-module", 'm');
  900. args_parser.add_option(s_print_last_result, "Print last result", "print-last-result", 'l');
  901. args_parser.add_option(gc_on_every_allocation, "GC on every allocation", "gc-on-every-allocation", 'g');
  902. args_parser.add_option(disable_syntax_highlight, "Disable live syntax highlighting", "no-syntax-highlight", 's');
  903. args_parser.add_positional_argument(script_paths, "Path to script files", "scripts", Core::ArgsParser::Required::No);
  904. args_parser.parse(argc, argv);
  905. bool syntax_highlight = !disable_syntax_highlight;
  906. vm = JS::VM::create();
  907. // NOTE: These will print out both warnings when using something like Promise.reject().catch(...) -
  908. // which is, as far as I can tell, correct - a promise is created, rejected without handler, and a
  909. // handler then attached to it. The Node.js REPL doesn't warn in this case, so it's something we
  910. // might want to revisit at a later point and disable warnings for promises created this way.
  911. vm->on_promise_unhandled_rejection = [](auto& promise) {
  912. // FIXME: Optionally make print_value() to print to stderr
  913. out("WARNING: A promise was rejected without any handlers");
  914. out(" (result: ");
  915. HashTable<JS::Object*> seen_objects;
  916. print_value(promise.result(), seen_objects);
  917. outln(")");
  918. };
  919. vm->on_promise_rejection_handled = [](auto& promise) {
  920. // FIXME: Optionally make print_value() to print to stderr
  921. out("WARNING: A handler was added to an already rejected promise");
  922. out(" (result: ");
  923. HashTable<JS::Object*> seen_objects;
  924. print_value(promise.result(), seen_objects);
  925. outln(")");
  926. };
  927. OwnPtr<JS::Interpreter> interpreter;
  928. interrupt_interpreter = [&] {
  929. auto error = JS::Error::create(interpreter->global_object(), "Received SIGINT");
  930. vm->throw_exception(interpreter->global_object(), error);
  931. };
  932. if (script_paths.is_empty()) {
  933. s_print_last_result = true;
  934. interpreter = JS::Interpreter::create<ReplObject>(*vm);
  935. ReplConsoleClient console_client(interpreter->global_object().console());
  936. interpreter->global_object().console().set_client(console_client);
  937. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  938. interpreter->vm().set_underscore_is_last_value(true);
  939. s_editor = Line::Editor::construct();
  940. s_editor->load_history(s_history_path);
  941. signal(SIGINT, [](int) {
  942. if (!s_editor->is_editing())
  943. sigint_handler();
  944. s_editor->save_history(s_history_path);
  945. });
  946. s_editor->on_display_refresh = [syntax_highlight](Line::Editor& editor) {
  947. auto stylize = [&](Line::Span span, Line::Style styles) {
  948. if (syntax_highlight)
  949. editor.stylize(span, styles);
  950. };
  951. editor.strip_styles();
  952. size_t open_indents = s_repl_line_level;
  953. auto line = editor.line();
  954. JS::Lexer lexer(line);
  955. bool indenters_starting_line = true;
  956. for (JS::Token token = lexer.next(); token.type() != JS::TokenType::Eof; token = lexer.next()) {
  957. auto length = Utf8View { token.value() }.length();
  958. auto start = token.line_column() - 1;
  959. auto end = start + length;
  960. if (indenters_starting_line) {
  961. if (token.type() != JS::TokenType::ParenClose && token.type() != JS::TokenType::BracketClose && token.type() != JS::TokenType::CurlyClose) {
  962. indenters_starting_line = false;
  963. } else {
  964. --open_indents;
  965. }
  966. }
  967. switch (token.category()) {
  968. case JS::TokenCategory::Invalid:
  969. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Red), Line::Style::Underline });
  970. break;
  971. case JS::TokenCategory::Number:
  972. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Magenta) });
  973. break;
  974. case JS::TokenCategory::String:
  975. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Green), Line::Style::Bold });
  976. break;
  977. case JS::TokenCategory::Punctuation:
  978. break;
  979. case JS::TokenCategory::Operator:
  980. break;
  981. case JS::TokenCategory::Keyword:
  982. switch (token.type()) {
  983. case JS::TokenType::BoolLiteral:
  984. case JS::TokenType::NullLiteral:
  985. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Yellow), Line::Style::Bold });
  986. break;
  987. default:
  988. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Blue), Line::Style::Bold });
  989. break;
  990. }
  991. break;
  992. case JS::TokenCategory::ControlKeyword:
  993. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::Cyan), Line::Style::Italic });
  994. break;
  995. case JS::TokenCategory::Identifier:
  996. stylize({ start, end, Line::Span::CodepointOriented }, { Line::Style::Foreground(Line::Style::XtermColor::White), Line::Style::Bold });
  997. break;
  998. default:
  999. break;
  1000. }
  1001. }
  1002. editor.set_prompt(prompt_for_level(open_indents));
  1003. };
  1004. auto complete = [&interpreter](Line::Editor const& editor) -> Vector<Line::CompletionSuggestion> {
  1005. auto line = editor.line(editor.cursor());
  1006. JS::Lexer lexer { line };
  1007. enum {
  1008. Initial,
  1009. CompleteVariable,
  1010. CompleteNullProperty,
  1011. CompleteProperty,
  1012. } mode { Initial };
  1013. StringView variable_name;
  1014. StringView property_name;
  1015. // we're only going to complete either
  1016. // - <N>
  1017. // where N is part of the name of a variable
  1018. // - <N>.<P>
  1019. // where N is the complete name of a variable and
  1020. // P is part of the name of one of its properties
  1021. auto js_token = lexer.next();
  1022. for (; js_token.type() != JS::TokenType::Eof; js_token = lexer.next()) {
  1023. switch (mode) {
  1024. case CompleteVariable:
  1025. switch (js_token.type()) {
  1026. case JS::TokenType::Period:
  1027. // ...<name> <dot>
  1028. mode = CompleteNullProperty;
  1029. break;
  1030. default:
  1031. // not a dot, reset back to initial
  1032. mode = Initial;
  1033. break;
  1034. }
  1035. break;
  1036. case CompleteNullProperty:
  1037. if (js_token.is_identifier_name()) {
  1038. // ...<name> <dot> <name>
  1039. mode = CompleteProperty;
  1040. property_name = js_token.value();
  1041. } else {
  1042. mode = Initial;
  1043. }
  1044. break;
  1045. case CompleteProperty:
  1046. // something came after the property access, reset to initial
  1047. case Initial:
  1048. if (js_token.type() == JS::TokenType::Identifier) {
  1049. // ...<name>...
  1050. mode = CompleteVariable;
  1051. variable_name = js_token.value();
  1052. } else {
  1053. mode = Initial;
  1054. }
  1055. break;
  1056. }
  1057. }
  1058. bool last_token_has_trivia = js_token.trivia().length() > 0;
  1059. if (mode == CompleteNullProperty) {
  1060. mode = CompleteProperty;
  1061. property_name = "";
  1062. last_token_has_trivia = false; // <name> <dot> [tab] is sensible to complete.
  1063. }
  1064. if (mode == Initial || last_token_has_trivia)
  1065. return {}; // we do not know how to complete this
  1066. Vector<Line::CompletionSuggestion> results;
  1067. Function<void(JS::Shape const&, StringView const&)> list_all_properties = [&results, &list_all_properties](JS::Shape const& shape, auto& property_pattern) {
  1068. for (auto const& descriptor : shape.property_table()) {
  1069. if (!descriptor.key.is_string())
  1070. continue;
  1071. auto key = descriptor.key.as_string();
  1072. if (key.view().starts_with(property_pattern)) {
  1073. Line::CompletionSuggestion completion { key, Line::CompletionSuggestion::ForSearch };
  1074. if (!results.contains_slow(completion)) { // hide duplicates
  1075. results.append(String(key));
  1076. }
  1077. }
  1078. }
  1079. if (auto const* prototype = shape.prototype()) {
  1080. list_all_properties(prototype->shape(), property_pattern);
  1081. }
  1082. };
  1083. switch (mode) {
  1084. case CompleteProperty: {
  1085. auto maybe_variable = vm->get_variable(variable_name, interpreter->global_object());
  1086. if (maybe_variable.is_empty()) {
  1087. maybe_variable = interpreter->global_object().get(FlyString(variable_name));
  1088. if (maybe_variable.is_empty())
  1089. break;
  1090. }
  1091. auto variable = maybe_variable;
  1092. if (!variable.is_object())
  1093. break;
  1094. auto const* object = variable.to_object(interpreter->global_object());
  1095. auto const& shape = object->shape();
  1096. list_all_properties(shape, property_name);
  1097. if (results.size())
  1098. editor.suggest(property_name.length());
  1099. break;
  1100. }
  1101. case CompleteVariable: {
  1102. auto const& variable = interpreter->global_object();
  1103. list_all_properties(variable.shape(), variable_name);
  1104. if (results.size())
  1105. editor.suggest(variable_name.length());
  1106. break;
  1107. }
  1108. default:
  1109. VERIFY_NOT_REACHED();
  1110. }
  1111. return results;
  1112. };
  1113. s_editor->on_tab_complete = move(complete);
  1114. repl(*interpreter);
  1115. s_editor->save_history(s_history_path);
  1116. } else {
  1117. interpreter = JS::Interpreter::create<ScriptObject>(*vm);
  1118. ReplConsoleClient console_client(interpreter->global_object().console());
  1119. interpreter->global_object().console().set_client(console_client);
  1120. interpreter->heap().set_should_collect_on_every_allocation(gc_on_every_allocation);
  1121. signal(SIGINT, [](int) {
  1122. sigint_handler();
  1123. });
  1124. StringBuilder builder;
  1125. for (auto& path : script_paths) {
  1126. auto file = Core::File::construct(path);
  1127. if (!file->open(Core::OpenMode::ReadOnly)) {
  1128. warnln("Failed to open {}: {}", path, file->error_string());
  1129. return 1;
  1130. }
  1131. auto file_contents = file->read_all();
  1132. auto source = StringView { file_contents };
  1133. builder.append(source);
  1134. }
  1135. if (!parse_and_run(*interpreter, builder.to_string()))
  1136. return 1;
  1137. }
  1138. return 0;
  1139. }