Debian Codegraph @

quickjs/repl.js

raw symbols SCIP
1 /*
2 * QuickJS Read Eval Print Loop
3 *
4 * Copyright (c) 2017-2020 Fabrice Bellard
5 * Copyright (c) 2017-2020 Charlie Gordon
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
20 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25 "use strip";
26
27 import * as std from "std";
28 import * as os from "os";
29
30 (function(g) {
31 /* add 'os' and 'std' bindings */
32 g.os = os;
33 g.std = std;
34
35 /* close global objects */
36 var Object = g.Object;
37 var String = g.String;
38 var Array = g.Array;
39 var Date = g.Date;
40 var Math = g.Math;
41 var isFinite = g.isFinite;
42 var parseFloat = g.parseFloat;
43
44 /* XXX: use preprocessor ? */
45 var config_numcalc = (typeof os.open === "undefined");
46 var has_jscalc = (typeof Fraction === "function");
47 var has_bignum = (typeof BigFloat === "function");
48
49 var colors = {
50 none: "\x1b[0m",
51 black: "\x1b[30m",
52 red: "\x1b[31m",
53 green: "\x1b[32m",
54 yellow: "\x1b[33m",
55 blue: "\x1b[34m",
56 magenta: "\x1b[35m",
57 cyan: "\x1b[36m",
58 white: "\x1b[37m",
59 gray: "\x1b[30;1m",
60 grey: "\x1b[30;1m",
61 bright_red: "\x1b[31;1m",
62 bright_green: "\x1b[32;1m",
63 bright_yellow: "\x1b[33;1m",
64 bright_blue: "\x1b[34;1m",
65 bright_magenta: "\x1b[35;1m",
66 bright_cyan: "\x1b[36;1m",
67 bright_white: "\x1b[37;1m",
68 };
69
70 var styles;
71 if (config_numcalc) {
72 styles = {
73 'default': 'black',
74 'comment': 'white',
75 'string': 'green',
76 'regex': 'cyan',
77 'number': 'green',
78 'keyword': 'blue',
79 'function': 'gray',
80 'type': 'bright_magenta',
81 'identifier': 'yellow',
82 'error': 'bright_red',
83 'result': 'black',
84 'error_msg': 'bright_red',
85 };
86 } else {
87 styles = {
88 'default': 'bright_green',
89 'comment': 'white',
90 'string': 'bright_cyan',
91 'regex': 'cyan',
92 'number': 'green',
93 'keyword': 'bright_white',
94 'function': 'bright_yellow',
95 'type': 'bright_magenta',
96 'identifier': 'bright_green',
97 'error': 'red',
98 'result': 'bright_white',
99 'error_msg': 'bright_red',
100 };
101 }
102
103 var history = [];
104 var clip_board = "";
105 var prec;
106 var expBits;
107 var log2_10;
108
109 var pstate = "";
110 var prompt = "";
111 var plen = 0;
112 var ps1;
113 if (config_numcalc)
114 ps1 = "> ";
115 else
116 ps1 = "qjs > ";
117 var ps2 = " ... ";
118 var utf8 = true;
119 var show_time = false;
120 var show_colors = true;
121 var eval_start_time;
122 var eval_time = 0;
123
124 var mexpr = "";
125 var level = 0;
126 var cmd = "";
127 var cursor_pos = 0;
128 var last_cmd = "";
129 var last_cursor_pos = 0;
130 var history_index;
131 var this_fun, last_fun;
132 var quote_flag = false;
133
134 var utf8_state = 0;
135 var utf8_val = 0;
136
137 var term_fd;
138 var term_read_buf;
139 var term_width;
140 /* current X position of the cursor in the terminal */
141 var term_cursor_x = 0;
142
143 function termInit() {
144 var tab;
145 term_fd = std.in.fileno();
146
147 /* get the terminal size */
148 term_width = 80;
149 if (os.isatty(term_fd)) {
150 if (os.ttyGetWinSize) {
151 tab = os.ttyGetWinSize(term_fd);
152 if (tab)
153 term_width = tab[0];
154 }
155 if (os.ttySetRaw) {
156 /* set the TTY to raw mode */
157 os.ttySetRaw(term_fd);
158 }
159 }
160
161 /* install a Ctrl-C signal handler */
162 os.signal(os.SIGINT, sigint_handler);
163
164 /* install a handler to read stdin */
165 term_read_buf = new Uint8Array(64);
166 os.setReadHandler(term_fd, term_read_handler);
167 }
168
169 function sigint_handler() {
170 /* send Ctrl-C to readline */
171 handle_byte(3);
172 }
173
174 function term_read_handler() {
175 var l, i;
176 l = os.read(term_fd, term_read_buf.buffer, 0, term_read_buf.length);
177 for(i = 0; i < l; i++)
178 handle_byte(term_read_buf[i]);
179 }
180
181 function handle_byte(c) {
182 if (!utf8) {
183 handle_char(c);
184 } else if (utf8_state !== 0 && (c >= 0x80 && c < 0xc0)) {
185 utf8_val = (utf8_val << 6) | (c & 0x3F);
186 utf8_state--;
187 if (utf8_state === 0) {
188 handle_char(utf8_val);
189 }
190 } else if (c >= 0xc0 && c < 0xf8) {
191 utf8_state = 1 + (c >= 0xe0) + (c >= 0xf0);
192 utf8_val = c & ((1 << (6 - utf8_state)) - 1);
193 } else {
194 utf8_state = 0;
195 handle_char(c);
196 }
197 }
198
199 function is_alpha(c) {
200 return typeof c === "string" &&
201 ((c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z'));
202 }
203
204 function is_digit(c) {
205 return typeof c === "string" && (c >= '0' && c <= '9');
206 }
207
208 function is_word(c) {
209 return typeof c === "string" &&
210 (is_alpha(c) || is_digit(c) || c == '_' || c == '$');
211 }
212
213 function ucs_length(str) {
214 var len, c, i, str_len = str.length;
215 len = 0;
216 /* we never count the trailing surrogate to have the
217 following property: ucs_length(str) =
218 ucs_length(str.substring(0, a)) + ucs_length(str.substring(a,
219 str.length)) for 0 <= a <= str.length */
220 for(i = 0; i < str_len; i++) {
221 c = str.charCodeAt(i);
222 if (c < 0xdc00 || c >= 0xe000)
223 len++;
224 }
225 return len;
226 }
227
228 function is_trailing_surrogate(c) {
229 var d;
230 if (typeof c !== "string")
231 return false;
232 d = c.codePointAt(0); /* can be NaN if empty string */
233 return d >= 0xdc00 && d < 0xe000;
234 }
235
236 function is_balanced(a, b) {
237 switch (a + b) {
238 case "()":
239 case "[]":
240 case "{}":
241 return true;
242 }
243 return false;
244 }
245
246 function print_color_text(str, start, style_names) {
247 var i, j;
248 for (j = start; j < str.length;) {
249 var style = style_names[i = j];
250 while (++j < str.length && style_names[j] == style)
251 continue;
252 std.puts(colors[styles[style] || 'default']);
253 std.puts(str.substring(i, j));
254 std.puts(colors['none']);
255 }
256 }
257
258 function print_csi(n, code) {
259 std.puts("\x1b[" + ((n != 1) ? n : "") + code);
260 }
261
262 /* XXX: handle double-width characters */
263 function move_cursor(delta) {
264 var i, l;
265 if (delta > 0) {
266 while (delta != 0) {
267 if (term_cursor_x == (term_width - 1)) {
268 std.puts("\n"); /* translated to CRLF */
269 term_cursor_x = 0;
270 delta--;
271 } else {
272 l = Math.min(term_width - 1 - term_cursor_x, delta);
273 print_csi(l, "C"); /* right */
274 delta -= l;
275 term_cursor_x += l;
276 }
277 }
278 } else {
279 delta = -delta;
280 while (delta != 0) {
281 if (term_cursor_x == 0) {
282 print_csi(1, "A"); /* up */
283 print_csi(term_width - 1, "C"); /* right */
284 delta--;
285 term_cursor_x = term_width - 1;
286 } else {
287 l = Math.min(delta, term_cursor_x);
288 print_csi(l, "D"); /* left */
289 delta -= l;
290 term_cursor_x -= l;
291 }
292 }
293 }
294 }
295
296 function update() {
297 var i, cmd_len;
298 /* cursor_pos is the position in 16 bit characters inside the
299 UTF-16 string 'cmd' */
300 if (cmd != last_cmd) {
301 if (!show_colors && last_cmd.substring(0, last_cursor_pos) == cmd.substring(0, last_cursor_pos)) {
302 /* optimize common case */
303 std.puts(cmd.substring(last_cursor_pos));
304 } else {
305 /* goto the start of the line */
306 move_cursor(-ucs_length(last_cmd.substring(0, last_cursor_pos)));
307 if (show_colors) {
308 var str = mexpr ? mexpr + '\n' + cmd : cmd;
309 var start = str.length - cmd.length;
310 var colorstate = colorize_js(str);
311 print_color_text(str, start, colorstate[2]);
312 } else {
313 std.puts(cmd);
314 }
315 }
316 term_cursor_x = (term_cursor_x + ucs_length(cmd)) % term_width;
317 if (term_cursor_x == 0) {
318 /* show the cursor on the next line */
319 std.puts(" \x08");
320 }
321 /* remove the trailing characters */
322 std.puts("\x1b[J");
323 last_cmd = cmd;
324 last_cursor_pos = cmd.length;
325 }
326 if (cursor_pos > last_cursor_pos) {
327 move_cursor(ucs_length(cmd.substring(last_cursor_pos, cursor_pos)));
328 } else if (cursor_pos < last_cursor_pos) {
329 move_cursor(-ucs_length(cmd.substring(cursor_pos, last_cursor_pos)));
330 }
331 last_cursor_pos = cursor_pos;
332 std.out.flush();
333 }
334
335 /* editing commands */
336 function insert(str) {
337 if (str) {
338 cmd = cmd.substring(0, cursor_pos) + str + cmd.substring(cursor_pos);
339 cursor_pos += str.length;
340 }
341 }
342
343 function quoted_insert() {
344 quote_flag = true;
345 }
346
347 function abort() {
348 cmd = "";
349 cursor_pos = 0;
350 return -2;
351 }
352
353 function alert() {
354 }
355
356 function beginning_of_line() {
357 cursor_pos = 0;
358 }
359
360 function end_of_line() {
361 cursor_pos = cmd.length;
362 }
363
364 function forward_char() {
365 if (cursor_pos < cmd.length) {
366 cursor_pos++;
367 while (is_trailing_surrogate(cmd.charAt(cursor_pos)))
368 cursor_pos++;
369 }
370 }
371
372 function backward_char() {
373 if (cursor_pos > 0) {
374 cursor_pos--;
375 while (is_trailing_surrogate(cmd.charAt(cursor_pos)))
376 cursor_pos--;
377 }
378 }
379
380 function skip_word_forward(pos) {
381 while (pos < cmd.length && !is_word(cmd.charAt(pos)))
382 pos++;
383 while (pos < cmd.length && is_word(cmd.charAt(pos)))
384 pos++;
385 return pos;
386 }
387
388 function skip_word_backward(pos) {
389 while (pos > 0 && !is_word(cmd.charAt(pos - 1)))
390 pos--;
391 while (pos > 0 && is_word(cmd.charAt(pos - 1)))
392 pos--;
393 return pos;
394 }
395
396 function forward_word() {
397 cursor_pos = skip_word_forward(cursor_pos);
398 }
399
400 function backward_word() {
401 cursor_pos = skip_word_backward(cursor_pos);
402 }
403
404 function accept_line() {
405 std.puts("\n");
406 history_add(cmd);
407 return -1;
408 }
409
410 function history_add(str) {
411 if (str) {
412 history.push(str);
413 }
414 history_index = history.length;
415 }
416
417 function previous_history() {
418 if (history_index > 0) {
419 if (history_index == history.length) {
420 history.push(cmd);
421 }
422 history_index--;
423 cmd = history[history_index];
424 cursor_pos = cmd.length;
425 }
426 }
427
428 function next_history() {
429 if (history_index < history.length - 1) {
430 history_index++;
431 cmd = history[history_index];
432 cursor_pos = cmd.length;
433 }
434 }
435
436 function history_search(dir) {
437 var pos = cursor_pos;
438 for (var i = 1; i <= history.length; i++) {
439 var index = (history.length + i * dir + history_index) % history.length;
440 if (history[index].substring(0, pos) == cmd.substring(0, pos)) {
441 history_index = index;
442 cmd = history[index];
443 return;
444 }
445 }
446 }
447
448 function history_search_backward() {
449 return history_search(-1);
450 }
451
452 function history_search_forward() {
453 return history_search(1);
454 }
455
456 function delete_char_dir(dir) {
457 var start, end;
458
459 start = cursor_pos;
460 if (dir < 0) {
461 start--;
462 while (is_trailing_surrogate(cmd.charAt(start)))
463 start--;
464 }
465 end = start + 1;
466 while (is_trailing_surrogate(cmd.charAt(end)))
467 end++;
468
469 if (start >= 0 && start < cmd.length) {
470 if (last_fun === kill_region) {
471 kill_region(start, end, dir);
472 } else {
473 cmd = cmd.substring(0, start) + cmd.substring(end);
474 cursor_pos = start;
475 }
476 }
477 }
478
479 function delete_char() {
480 delete_char_dir(1);
481 }
482
483 function control_d() {
484 if (cmd.length == 0) {
485 std.puts("\n");
486 return -3; /* exit read eval print loop */
487 } else {
488 delete_char_dir(1);
489 }
490 }
491
492 function backward_delete_char() {
493 delete_char_dir(-1);
494 }
495
496 function transpose_chars() {
497 var pos = cursor_pos;
498 if (cmd.length > 1 && pos > 0) {
499 if (pos == cmd.length)
500 pos--;
501 cmd = cmd.substring(0, pos - 1) + cmd.substring(pos, pos + 1) +
502 cmd.substring(pos - 1, pos) + cmd.substring(pos + 1);
503 cursor_pos = pos + 1;
504 }
505 }
506
507 function transpose_words() {
508 var p1 = skip_word_backward(cursor_pos);
509 var p2 = skip_word_forward(p1);
510 var p4 = skip_word_forward(cursor_pos);
511 var p3 = skip_word_backward(p4);
512
513 if (p1 < p2 && p2 <= cursor_pos && cursor_pos <= p3 && p3 < p4) {
514 cmd = cmd.substring(0, p1) + cmd.substring(p3, p4) +
515 cmd.substring(p2, p3) + cmd.substring(p1, p2);
516 cursor_pos = p4;
517 }
518 }
519
520 function upcase_word() {
521 var end = skip_word_forward(cursor_pos);
522 cmd = cmd.substring(0, cursor_pos) +
523 cmd.substring(cursor_pos, end).toUpperCase() +
524 cmd.substring(end);
525 }
526
527 function downcase_word() {
528 var end = skip_word_forward(cursor_pos);
529 cmd = cmd.substring(0, cursor_pos) +
530 cmd.substring(cursor_pos, end).toLowerCase() +
531 cmd.substring(end);
532 }
533
534 function kill_region(start, end, dir) {
535 var s = cmd.substring(start, end);
536 if (last_fun !== kill_region)
537 clip_board = s;
538 else if (dir < 0)
539 clip_board = s + clip_board;
540 else
541 clip_board = clip_board + s;
542
543 cmd = cmd.substring(0, start) + cmd.substring(end);
544 if (cursor_pos > end)
545 cursor_pos -= end - start;
546 else if (cursor_pos > start)
547 cursor_pos = start;
548 this_fun = kill_region;
549 }
550
551 function kill_line() {
552 kill_region(cursor_pos, cmd.length, 1);
553 }
554
555 function backward_kill_line() {
556 kill_region(0, cursor_pos, -1);
557 }
558
559 function kill_word() {
560 kill_region(cursor_pos, skip_word_forward(cursor_pos), 1);
561 }
562
563 function backward_kill_word() {
564 kill_region(skip_word_backward(cursor_pos), cursor_pos, -1);
565 }
566
567 function yank() {
568 insert(clip_board);
569 }
570
571 function control_c() {
572 if (last_fun === control_c) {
573 std.puts("\n");
574 std.exit(0);
575 } else {
576 std.puts("\n(Press Ctrl-C again to quit)\n");
577 readline_print_prompt();
578 }
579 }
580
581 function reset() {
582 cmd = "";
583 cursor_pos = 0;
584 }
585
586 function get_context_word(line, pos) {
587 var s = "";
588 while (pos > 0 && is_word(line[pos - 1])) {
589 pos--;
590 s = line[pos] + s;
591 }
592 return s;
593 }
594 function get_context_object(line, pos) {
595 var obj, base, c;
596 if (pos <= 0 || " ~!%^&*(-+={[|:;,<>?/".indexOf(line[pos - 1]) >= 0)
597 return g;
598 if (pos >= 2 && line[pos - 1] === ".") {
599 pos--;
600 obj = {};
601 switch (c = line[pos - 1]) {
602 case '\'':
603 case '\"':
604 return "a";
605 case ']':
606 return [];
607 case '}':
608 return {};
609 case '/':
610 return / /;
611 default:
612 if (is_word(c)) {
613 base = get_context_word(line, pos);
614 if (["true", "false", "null", "this"].includes(base) || !isNaN(+base))
615 return eval(base);
616 obj = get_context_object(line, pos - base.length);
617 if (obj === null || obj === void 0)
618 return obj;
619 if (obj === g && obj[base] === void 0)
620 return eval(base);
621 else
622 return obj[base];
623 }
624 return {};
625 }
626 }
627 return void 0;
628 }
629
630 function get_completions(line, pos) {
631 var s, obj, ctx_obj, r, i, j, paren;
632
633 s = get_context_word(line, pos);
634 ctx_obj = get_context_object(line, pos - s.length);
635 r = [];
636 /* enumerate properties from object and its prototype chain,
637 add non-numeric regular properties with s as e prefix
638 */
639 for (i = 0, obj = ctx_obj; i < 10 && obj !== null && obj !== void 0; i++) {
640 var props = Object.getOwnPropertyNames(obj);
641 /* add non-numeric regular properties */
642 for (j = 0; j < props.length; j++) {
643 var prop = props[j];
644 if (typeof prop == "string" && ""+(+prop) != prop && prop.startsWith(s))
645 r.push(prop);
646 }
647 obj = Object.getPrototypeOf(obj);
648 }
649 if (r.length > 1) {
650 /* sort list with internal names last and remove duplicates */
651 function symcmp(a, b) {
652 if (a[0] != b[0]) {
653 if (a[0] == '_')
654 return 1;
655 if (b[0] == '_')
656 return -1;
657 }
658 if (a < b)
659 return -1;
660 if (a > b)
661 return +1;
662 return 0;
663 }
664 r.sort(symcmp);
665 for(i = j = 1; i < r.length; i++) {
666 if (r[i] != r[i - 1])
667 r[j++] = r[i];
668 }
669 r.length = j;
670 }
671 /* 'tab' = list of completions, 'pos' = cursor position inside
672 the completions */
673 return { tab: r, pos: s.length, ctx: ctx_obj };
674 }
675
676 function completion() {
677 var tab, res, s, i, j, len, t, max_width, col, n_cols, row, n_rows;
678 res = get_completions(cmd, cursor_pos);
679 tab = res.tab;
680 if (tab.length === 0)
681 return;
682 s = tab[0];
683 len = s.length;
684 /* add the chars which are identical in all the completions */
685 for(i = 1; i < tab.length; i++) {
686 t = tab[i];
687 for(j = 0; j < len; j++) {
688 if (t[j] !== s[j]) {
689 len = j;
690 break;
691 }
692 }
693 }
694 for(i = res.pos; i < len; i++) {
695 insert(s[i]);
696 }
697 if (last_fun === completion && tab.length == 1) {
698 /* append parentheses to function names */
699 var m = res.ctx[tab[0]];
700 if (typeof m == "function") {
701 insert('(');
702 if (m.length == 0)
703 insert(')');
704 } else if (typeof m == "object") {
705 insert('.');
706 }
707 }
708 /* show the possible completions */
709 if (last_fun === completion && tab.length >= 2) {
710 max_width = 0;
711 for(i = 0; i < tab.length; i++)
712 max_width = Math.max(max_width, tab[i].length);
713 max_width += 2;
714 n_cols = Math.max(1, Math.floor((term_width + 1) / max_width));
715 n_rows = Math.ceil(tab.length / n_cols);
716 std.puts("\n");
717 /* display the sorted list column-wise */
718 for (row = 0; row < n_rows; row++) {
719 for (col = 0; col < n_cols; col++) {
720 i = col * n_rows + row;
721 if (i >= tab.length)
722 break;
723 s = tab[i];
724 if (col != n_cols - 1)
725 s = s.padEnd(max_width);
726 std.puts(s);
727 }
728 std.puts("\n");
729 }
730 /* show a new prompt */
731 readline_print_prompt();
732 }
733 }
734
735 var commands = { /* command table */
736 "\x01": beginning_of_line, /* ^A - bol */
737 "\x02": backward_char, /* ^B - backward-char */
738 "\x03": control_c, /* ^C - abort */
739 "\x04": control_d, /* ^D - delete-char or exit */
740 "\x05": end_of_line, /* ^E - eol */
741 "\x06": forward_char, /* ^F - forward-char */
742 "\x07": abort, /* ^G - bell */
743 "\x08": backward_delete_char, /* ^H - backspace */
744 "\x09": completion, /* ^I - history-search-backward */
745 "\x0a": accept_line, /* ^J - newline */
746 "\x0b": kill_line, /* ^K - delete to end of line */
747 "\x0d": accept_line, /* ^M - enter */
748 "\x0e": next_history, /* ^N - down */
749 "\x10": previous_history, /* ^P - up */
750 "\x11": quoted_insert, /* ^Q - quoted-insert */
751 "\x12": alert, /* ^R - reverse-search */
752 "\x13": alert, /* ^S - search */
753 "\x14": transpose_chars, /* ^T - transpose */
754 "\x18": reset, /* ^X - cancel */
755 "\x19": yank, /* ^Y - yank */
756 "\x1bOA": previous_history, /* ^[OA - up */
757 "\x1bOB": next_history, /* ^[OB - down */
758 "\x1bOC": forward_char, /* ^[OC - right */
759 "\x1bOD": backward_char, /* ^[OD - left */
760 "\x1bOF": forward_word, /* ^[OF - ctrl-right */
761 "\x1bOH": backward_word, /* ^[OH - ctrl-left */
762 "\x1b[1;5C": forward_word, /* ^[[1;5C - ctrl-right */
763 "\x1b[1;5D": backward_word, /* ^[[1;5D - ctrl-left */
764 "\x1b[1~": beginning_of_line, /* ^[[1~ - bol */
765 "\x1b[3~": delete_char, /* ^[[3~ - delete */
766 "\x1b[4~": end_of_line, /* ^[[4~ - eol */
767 "\x1b[5~": history_search_backward,/* ^[[5~ - page up */
768 "\x1b[6~": history_search_forward, /* ^[[5~ - page down */
769 "\x1b[A": previous_history, /* ^[[A - up */
770 "\x1b[B": next_history, /* ^[[B - down */
771 "\x1b[C": forward_char, /* ^[[C - right */
772 "\x1b[D": backward_char, /* ^[[D - left */
773 "\x1b[F": end_of_line, /* ^[[F - end */
774 "\x1b[H": beginning_of_line, /* ^[[H - home */
775 "\x1b\x7f": backward_kill_word, /* M-C-? - backward_kill_word */
776 "\x1bb": backward_word, /* M-b - backward_word */
777 "\x1bd": kill_word, /* M-d - kill_word */
778 "\x1bf": forward_word, /* M-f - backward_word */
779 "\x1bk": backward_kill_line, /* M-k - backward_kill_line */
780 "\x1bl": downcase_word, /* M-l - downcase_word */
781 "\x1bt": transpose_words, /* M-t - transpose_words */
782 "\x1bu": upcase_word, /* M-u - upcase_word */
783 "\x7f": backward_delete_char, /* ^? - delete */
784 };
785
786 function dupstr(str, count) {
787 var res = "";
788 while (count-- > 0)
789 res += str;
790 return res;
791 }
792
793 var readline_keys;
794 var readline_state;
795 var readline_cb;
796
797 function readline_print_prompt()
798 {
799 std.puts(prompt);
800 term_cursor_x = ucs_length(prompt) % term_width;
801 last_cmd = "";
802 last_cursor_pos = 0;
803 }
804
805 function readline_start(defstr, cb) {
806 cmd = defstr || "";
807 cursor_pos = cmd.length;
808 history_index = history.length;
809 readline_cb = cb;
810
811 prompt = pstate;
812
813 if (mexpr) {
814 prompt += dupstr(" ", plen - prompt.length);
815 prompt += ps2;
816 } else {
817 if (show_time) {
818 var t = eval_time / 1000;
819 prompt += t.toFixed(6) + " ";
820 }
821 plen = prompt.length;
822 prompt += ps1;
823 }
824 readline_print_prompt();
825 update();
826 readline_state = 0;
827 }
828
829 function handle_char(c1) {
830 var c;
831 c = String.fromCodePoint(c1);
832 switch(readline_state) {
833 case 0:
834 if (c == '\x1b') { /* '^[' - ESC */
835 readline_keys = c;
836 readline_state = 1;
837 } else {
838 handle_key(c);
839 }
840 break;
841 case 1: /* '^[ */
842 readline_keys += c;
843 if (c == '[') {
844 readline_state = 2;
845 } else if (c == 'O') {
846 readline_state = 3;
847 } else {
848 handle_key(readline_keys);
849 readline_state = 0;
850 }
851 break;
852 case 2: /* '^[[' - CSI */
853 readline_keys += c;
854 if (!(c == ';' || (c >= '0' && c <= '9'))) {
855 handle_key(readline_keys);
856 readline_state = 0;
857 }
858 break;
859 case 3: /* '^[O' - ESC2 */
860 readline_keys += c;
861 handle_key(readline_keys);
862 readline_state = 0;
863 break;
864 }
865 }
866
867 function handle_key(keys) {
868 var fun;
869
870 if (quote_flag) {
871 if (ucs_length(keys) === 1)
872 insert(keys);
873 quote_flag = false;
874 } else if (fun = commands[keys]) {
875 this_fun = fun;
876 switch (fun(keys)) {
877 case -1:
878 readline_cb(cmd);
879 return;
880 case -2:
881 readline_cb(null);
882 return;
883 case -3:
884 /* uninstall a Ctrl-C signal handler */
885 os.signal(os.SIGINT, null);
886 /* uninstall the stdin read handler */
887 os.setReadHandler(term_fd, null);
888 return;
889 }
890 last_fun = this_fun;
891 } else if (ucs_length(keys) === 1 && keys >= ' ') {
892 insert(keys);
893 last_fun = insert;
894 } else {
895 alert(); /* beep! */
896 }
897
898 cursor_pos = (cursor_pos < 0) ? 0 :
899 (cursor_pos > cmd.length) ? cmd.length : cursor_pos;
900 update();
901 }
902
903 var hex_mode = false;
904 var eval_mode = "std";
905
906 function number_to_string(a, radix) {
907 var s;
908 if (!isFinite(a)) {
909 /* NaN, Infinite */
910 return a.toString();
911 } else {
912 if (a == 0) {
913 if (1 / a < 0)
914 s = "-0";
915 else
916 s = "0";
917 } else {
918 if (radix == 16 && a === Math.floor(a)) {
919 var s;
920 if (a < 0) {
921 a = -a;
922 s = "-";
923 } else {
924 s = "";
925 }
926 s += "0x" + a.toString(16);
927 } else {
928 s = a.toString();
929 }
930 }
931 return s;
932 }
933 }
934
935 function bigfloat_to_string(a, radix) {
936 var s;
937 if (!BigFloat.isFinite(a)) {
938 /* NaN, Infinite */
939 if (eval_mode !== "math") {
940 return "BigFloat(" + a.toString() + ")";
941 } else {
942 return a.toString();
943 }
944 } else {
945 if (a == 0) {
946 if (1 / a < 0)
947 s = "-0";
948 else
949 s = "0";
950 } else {
951 if (radix == 16) {
952 var s;
953 if (a < 0) {
954 a = -a;
955 s = "-";
956 } else {
957 s = "";
958 }
959 s += "0x" + a.toString(16);
960 } else {
961 s = a.toString();
962 }
963 }
964 if (typeof a === "bigfloat" && eval_mode !== "math") {
965 s += "l";
966 } else if (eval_mode !== "std" && s.indexOf(".") < 0 &&
967 ((radix == 16 && s.indexOf("p") < 0) ||
968 (radix == 10 && s.indexOf("e") < 0))) {
969 /* add a decimal point so that the floating point type
970 is visible */
971 s += ".0";
972 }
973 return s;
974 }
975 }
976
977 function bigint_to_string(a, radix) {
978 var s;
979 if (radix == 16) {
980 var s;
981 if (a < 0) {
982 a = -a;
983 s = "-";
984 } else {
985 s = "";
986 }
987 s += "0x" + a.toString(16);
988 } else {
989 s = a.toString();
990 }
991 if (eval_mode === "std")
992 s += "n";
993 return s;
994 }
995
996 function print(a) {
997 var stack = [];
998
999 function print_rec(a) {
1000 var n, i, keys, key, type, s;
1001
1002 type = typeof(a);
1003 if (type === "object") {
1004 if (a === null) {
1005 std.puts(a);
1006 } else if (stack.indexOf(a) >= 0) {
1007 std.puts("[circular]");
1008 } else if (has_jscalc && (a instanceof Fraction ||
1009 a instanceof Complex ||
1010 a instanceof Mod ||
1011 a instanceof Polynomial ||
1012 a instanceof PolyMod ||
1013 a instanceof RationalFunction ||
1014 a instanceof Series)) {
1015 std.puts(a.toString());
1016 } else {
1017 stack.push(a);
1018 if (Array.isArray(a)) {
1019 n = a.length;
1020 std.puts("[ ");
1021 for(i = 0; i < n; i++) {
1022 if (i !== 0)
1023 std.puts(", ");
1024 if (i in a) {
1025 print_rec(a[i]);
1026 } else {
1027 std.puts("<empty>");
1028 }
1029 if (i > 20) {
1030 std.puts("...");
1031 break;
1032 }
1033 }
1034 std.puts(" ]");
1035 } else if (Object.__getClass(a) === "RegExp") {
1036 std.puts(a.toString());
1037 } else {
1038 keys = Object.keys(a);
1039 n = keys.length;
1040 std.puts("{ ");
1041 for(i = 0; i < n; i++) {
1042 if (i !== 0)
1043 std.puts(", ");
1044 key = keys[i];
1045 std.puts(key, ": ");
1046 print_rec(a[key]);
1047 }
1048 std.puts(" }");
1049 }
1050 stack.pop(a);
1051 }
1052 } else if (type === "string") {
1053 s = a.__quote();
1054 if (s.length > 79)
1055 s = s.substring(0, 75) + "...\"";
1056 std.puts(s);
1057 } else if (type === "number") {
1058 std.puts(number_to_string(a, hex_mode ? 16 : 10));
1059 } else if (type === "bigint") {
1060 std.puts(bigint_to_string(a, hex_mode ? 16 : 10));
1061 } else if (type === "bigfloat") {
1062 std.puts(bigfloat_to_string(a, hex_mode ? 16 : 10));
1063 } else if (type === "bigdecimal") {
1064 std.puts(a.toString() + "m");
1065 } else if (type === "symbol") {
1066 std.puts(String(a));
1067 } else if (type === "function") {
1068 std.puts("function " + a.name + "()");
1069 } else {
1070 std.puts(a);
1071 }
1072 }
1073 print_rec(a);
1074 }
1075
1076 function extract_directive(a) {
1077 var pos;
1078 if (a[0] !== '\\')
1079 return "";
1080 for (pos = 1; pos < a.length; pos++) {
1081 if (!is_alpha(a[pos]))
1082 break;
1083 }
1084 return a.substring(1, pos);
1085 }
1086
1087 /* return true if the string after cmd can be evaluted as JS */
1088 function handle_directive(cmd, expr) {
1089 var param, prec1, expBits1;
1090
1091 if (cmd === "h" || cmd === "?" || cmd == "help") {
1092 help();
1093 } else if (cmd === "load") {
1094 var filename = expr.substring(cmd.length + 1).trim();
1095 if (filename.lastIndexOf(".") <= filename.lastIndexOf("/"))
1096 filename += ".js";
1097 std.loadScript(filename);
1098 return false;
1099 } else if (cmd === "x") {
1100 hex_mode = true;
1101 } else if (cmd === "d") {
1102 hex_mode = false;
1103 } else if (cmd === "t") {
1104 show_time = !show_time;
1105 } else if (has_bignum && cmd === "p") {
1106 param = expr.substring(cmd.length + 1).trim().split(" ");
1107 if (param.length === 1 && param[0] === "") {
1108 std.puts("BigFloat precision=" + prec + " bits (~" +
1109 Math.floor(prec / log2_10) +
1110 " digits), exponent size=" + expBits + " bits\n");
1111 } else if (param[0] === "f16") {
1112 prec = 11;
1113 expBits = 5;
1114 } else if (param[0] === "f32") {
1115 prec = 24;
1116 expBits = 8;
1117 } else if (param[0] === "f64") {
1118 prec = 53;
1119 expBits = 11;
1120 } else if (param[0] === "f128") {
1121 prec = 113;
1122 expBits = 15;
1123 } else {
1124 prec1 = parseInt(param[0]);
1125 if (param.length >= 2)
1126 expBits1 = parseInt(param[1]);
1127 else
1128 expBits1 = BigFloatEnv.expBitsMax;
1129 if (Number.isNaN(prec1) ||
1130 prec1 < BigFloatEnv.precMin ||
1131 prec1 > BigFloatEnv.precMax) {
1132 std.puts("Invalid precision\n");
1133 return false;
1134 }
1135 if (Number.isNaN(expBits1) ||
1136 expBits1 < BigFloatEnv.expBitsMin ||
1137 expBits1 > BigFloatEnv.expBitsMax) {
1138 std.puts("Invalid exponent bits\n");
1139 return false;
1140 }
1141 prec = prec1;
1142 expBits = expBits1;
1143 }
1144 return false;
1145 } else if (has_bignum && cmd === "digits") {
1146 param = expr.substring(cmd.length + 1).trim();
1147 prec1 = Math.ceil(parseFloat(param) * log2_10);
1148 if (prec1 < BigFloatEnv.precMin ||
1149 prec1 > BigFloatEnv.precMax) {
1150 std.puts("Invalid precision\n");
1151 return false;
1152 }
1153 prec = prec1;
1154 expBits = BigFloatEnv.expBitsMax;
1155 return false;
1156 } else if (has_bignum && cmd === "mode") {
1157 param = expr.substring(cmd.length + 1).trim();
1158 if (param === "") {
1159 std.puts("Running mode=" + eval_mode + "\n");
1160 } else if (param === "std" || param === "math") {
1161 eval_mode = param;
1162 } else {
1163 std.puts("Invalid mode\n");
1164 }
1165 return false;
1166 } else if (cmd === "clear") {
1167 std.puts("\x1b[H\x1b[J");
1168 } else if (cmd === "q") {
1169 std.exit(0);
1170 } else if (has_jscalc && cmd === "a") {
1171 algebraicMode = true;
1172 } else if (has_jscalc && cmd === "n") {
1173 algebraicMode = false;
1174 } else {
1175 std.puts("Unknown directive: " + cmd + "\n");
1176 return false;
1177 }
1178 return true;
1179 }
1180
1181 if (config_numcalc) {
1182 /* called by the GUI */
1183 g.execCmd = function (cmd) {
1184 switch(cmd) {
1185 case "dec":
1186 hex_mode = false;
1187 break;
1188 case "hex":
1189 hex_mode = true;
1190 break;
1191 case "num":
1192 algebraicMode = false;
1193 break;
1194 case "alg":
1195 algebraicMode = true;
1196 break;
1197 }
1198 }
1199 }
1200
1201 function help() {
1202 function sel(n) {
1203 return n ? "*": " ";
1204 }
1205 std.puts("\\h this help\n" +
1206 "\\x " + sel(hex_mode) + "hexadecimal number display\n" +
1207 "\\d " + sel(!hex_mode) + "decimal number display\n" +
1208 "\\t " + sel(show_time) + "toggle timing display\n" +
1209 "\\clear clear the terminal\n");
1210 if (has_jscalc) {
1211 std.puts("\\a " + sel(algebraicMode) + "algebraic mode\n" +
1212 "\\n " + sel(!algebraicMode) + "numeric mode\n");
1213 }
1214 if (has_bignum) {
1215 std.puts("\\p [m [e]] set the BigFloat precision to 'm' bits\n" +
1216 "\\digits n set the BigFloat precision to 'ceil(n*log2(10))' bits\n");
1217 if (!has_jscalc) {
1218 std.puts("\\mode [std|math] change the running mode (current = " + eval_mode + ")\n");
1219 }
1220 }
1221 if (!config_numcalc) {
1222 std.puts("\\q exit\n");
1223 }
1224 }
1225
1226 function cmd_start() {
1227 if (!config_numcalc) {
1228 if (has_jscalc)
1229 std.puts('QJSCalc - Type "\\h" for help\n');
1230 else
1231 std.puts('QuickJS - Type "\\h" for help\n');
1232 }
1233 if (has_bignum) {
1234 log2_10 = Math.log(10) / Math.log(2);
1235 prec = 113;
1236 expBits = 15;
1237 if (has_jscalc) {
1238 eval_mode = "math";
1239 /* XXX: numeric mode should always be the default ? */
1240 g.algebraicMode = config_numcalc;
1241 }
1242 }
1243
1244 cmd_readline_start();
1245 }
1246
1247 function cmd_readline_start() {
1248 readline_start(dupstr(" ", level), readline_handle_cmd);
1249 }
1250
1251 function readline_handle_cmd(expr) {
1252 if (!handle_cmd(expr)) {
1253 cmd_readline_start();
1254 }
1255 }
1256
1257 /* return true if async termination */
1258 function handle_cmd(expr) {
1259 var colorstate, cmd;
1260
1261 if (expr === null) {
1262 expr = "";
1263 return false;
1264 }
1265 if (expr === "?") {
1266 help();
1267 return false;
1268 }
1269 cmd = extract_directive(expr);
1270 if (cmd.length > 0) {
1271 if (!handle_directive(cmd, expr)) {
1272 return false;
1273 }
1274 expr = expr.substring(cmd.length + 1);
1275 }
1276 if (expr === "")
1277 return false;
1278
1279 if (mexpr)
1280 expr = mexpr + '\n' + expr;
1281 colorstate = colorize_js(expr);
1282 pstate = colorstate[0];
1283 level = colorstate[1];
1284 if (pstate) {
1285 mexpr = expr;
1286 return false;
1287 }
1288 mexpr = "";
1289
1290 if (has_bignum) {
1291 /* XXX: async is not supported in this case */
1292 BigFloatEnv.setPrec(eval_and_print_start.bind(null, expr, false),
1293 prec, expBits);
1294 } else {
1295 eval_and_print_start(expr, true);
1296 }
1297 return true;
1298 }
1299
1300 function eval_and_print_start(expr, is_async) {
1301 var result;
1302
1303 try {
1304 if (eval_mode === "math")
1305 expr = '"use math"; void 0;' + expr;
1306 eval_start_time = os.now();
1307 /* eval as a script */
1308 result = std.evalScript(expr, { backtrace_barrier: true, async: is_async });
1309 if (is_async) {
1310 /* result is a promise */
1311 result.then(print_eval_result, print_eval_error);
1312 } else {
1313 print_eval_result(result);
1314 }
1315 } catch (error) {
1316 print_eval_error(error);
1317 }
1318 }
1319
1320 function print_eval_result(result) {
1321 eval_time = os.now() - eval_start_time;
1322 std.puts(colors[styles.result]);
1323 print(result);
1324 std.puts("\n");
1325 std.puts(colors.none);
1326 /* set the last result */
1327 g._ = result;
1328
1329 handle_cmd_end();
1330 }
1331
1332 function print_eval_error(error) {
1333 std.puts(colors[styles.error_msg]);
1334 if (error instanceof Error) {
1335 console.log(error);
1336 if (error.stack) {
1337 std.puts(error.stack);
1338 }
1339 } else {
1340 std.puts("Throw: ");
1341 console.log(error);
1342 }
1343 std.puts(colors.none);
1344
1345 handle_cmd_end();
1346 }
1347
1348 function handle_cmd_end() {
1349 level = 0;
1350 /* run the garbage collector after each command */
1351 std.gc();
1352 cmd_readline_start();
1353 }
1354
1355 function colorize_js(str) {
1356 var i, c, start, n = str.length;
1357 var style, state = "", level = 0;
1358 var primary, can_regex = 1;
1359 var r = [];
1360
1361 function push_state(c) { state += c; }
1362 function last_state(c) { return state.substring(state.length - 1); }
1363 function pop_state(c) {
1364 var c = last_state();
1365 state = state.substring(0, state.length - 1);
1366 return c;
1367 }
1368
1369 function parse_block_comment() {
1370 style = 'comment';
1371 push_state('/');
1372 for (i++; i < n - 1; i++) {
1373 if (str[i] == '*' && str[i + 1] == '/') {
1374 i += 2;
1375 pop_state('/');
1376 break;
1377 }
1378 }
1379 }
1380
1381 function parse_line_comment() {
1382 style = 'comment';
1383 for (i++; i < n; i++) {
1384 if (str[i] == '\n') {
1385 break;
1386 }
1387 }
1388 }
1389
1390 function parse_string(delim) {
1391 style = 'string';
1392 push_state(delim);
1393 while (i < n) {
1394 c = str[i++];
1395 if (c == '\n') {
1396 style = 'error';
1397 continue;
1398 }
1399 if (c == '\\') {
1400 if (i >= n)
1401 break;
1402 i++;
1403 } else
1404 if (c == delim) {
1405 pop_state();
1406 break;
1407 }
1408 }
1409 }
1410
1411 function parse_regex() {
1412 style = 'regex';
1413 push_state('/');
1414 while (i < n) {
1415 c = str[i++];
1416 if (c == '\n') {
1417 style = 'error';
1418 continue;
1419 }
1420 if (c == '\\') {
1421 if (i < n) {
1422 i++;
1423 }
1424 continue;
1425 }
1426 if (last_state() == '[') {
1427 if (c == ']') {
1428 pop_state()
1429 }
1430 // ECMA 5: ignore '/' inside char classes
1431 continue;
1432 }
1433 if (c == '[') {
1434 push_state('[');
1435 if (str[i] == '[' || str[i] == ']')
1436 i++;
1437 continue;
1438 }
1439 if (c == '/') {
1440 pop_state();
1441 while (i < n && is_word(str[i]))
1442 i++;
1443 break;
1444 }
1445 }
1446 }
1447
1448 function parse_number() {
1449 style = 'number';
1450 while (i < n && (is_word(str[i]) || (str[i] == '.' && (i == n - 1 || str[i + 1] != '.')))) {
1451 i++;
1452 }
1453 }
1454
1455 var js_keywords = "|" +
1456 "break|case|catch|continue|debugger|default|delete|do|" +
1457 "else|finally|for|function|if|in|instanceof|new|" +
1458 "return|switch|this|throw|try|typeof|while|with|" +
1459 "class|const|enum|import|export|extends|super|" +
1460 "implements|interface|let|package|private|protected|" +
1461 "public|static|yield|" +
1462 "undefined|null|true|false|Infinity|NaN|" +
1463 "eval|arguments|" +
1464 "await|";
1465
1466 var js_no_regex = "|this|super|undefined|null|true|false|Infinity|NaN|arguments|";
1467 var js_types = "|void|var|";
1468
1469 function parse_identifier() {
1470 can_regex = 1;
1471
1472 while (i < n && is_word(str[i]))
1473 i++;
1474
1475 var w = '|' + str.substring(start, i) + '|';
1476
1477 if (js_keywords.indexOf(w) >= 0) {
1478 style = 'keyword';
1479 if (js_no_regex.indexOf(w) >= 0)
1480 can_regex = 0;
1481 return;
1482 }
1483
1484 var i1 = i;
1485 while (i1 < n && str[i1] == ' ')
1486 i1++;
1487
1488 if (i1 < n && str[i1] == '(') {
1489 style = 'function';
1490 return;
1491 }
1492
1493 if (js_types.indexOf(w) >= 0) {
1494 style = 'type';
1495 return;
1496 }
1497
1498 style = 'identifier';
1499 can_regex = 0;
1500 }
1501
1502 function set_style(from, to) {
1503 while (r.length < from)
1504 r.push('default');
1505 while (r.length < to)
1506 r.push(style);
1507 }
1508
1509 for (i = 0; i < n;) {
1510 style = null;
1511 start = i;
1512 switch (c = str[i++]) {
1513 case ' ':
1514 case '\t':
1515 case '\r':
1516 case '\n':
1517 continue;
1518 case '+':
1519 case '-':
1520 if (i < n && str[i] == c) {
1521 i++;
1522 continue;
1523 }
1524 can_regex = 1;
1525 continue;
1526 case '/':
1527 if (i < n && str[i] == '*') { // block comment
1528 parse_block_comment();
1529 break;
1530 }
1531 if (i < n && str[i] == '/') { // line comment
1532 parse_line_comment();
1533 break;
1534 }
1535 if (can_regex) {
1536 parse_regex();
1537 can_regex = 0;
1538 break;
1539 }
1540 can_regex = 1;
1541 continue;
1542 case '\'':
1543 case '\"':
1544 case '`':
1545 parse_string(c);
1546 can_regex = 0;
1547 break;
1548 case '(':
1549 case '[':
1550 case '{':
1551 can_regex = 1;
1552 level++;
1553 push_state(c);
1554 continue;
1555 case ')':
1556 case ']':
1557 case '}':
1558 can_regex = 0;
1559 if (level > 0 && is_balanced(last_state(), c)) {
1560 level--;
1561 pop_state();
1562 continue;
1563 }
1564 style = 'error';
1565 break;
1566 default:
1567 if (is_digit(c)) {
1568 parse_number();
1569 can_regex = 0;
1570 break;
1571 }
1572 if (is_word(c) || c == '$') {
1573 parse_identifier();
1574 break;
1575 }
1576 can_regex = 1;
1577 continue;
1578 }
1579 if (style)
1580 set_style(start, i);
1581 }
1582 set_style(n, n);
1583 return [ state, level, r ];
1584 }
1585
1586 termInit();
1587
1588 cmd_start();
1589
1590 })(globalThis);