Debian Codegraph @

common/core_main.cc

raw
1 /*****************************************************************************
2 * Free42 -- an HP-42S calculator simulator
3 * Copyright (C) 2004-2026 Thomas Okken
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License, version 2,
7 * as published by the Free Software Foundation.
8 *
9 * This program is distributed in the hope that it will be useful,
10 * but WITHOUT ANY WARRANTY; without even the implied warranty of
11 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 * GNU General Public License for more details.
13 *
14 * You should have received a copy of the GNU General Public License
15 * along with this program; if not, see http://www.gnu.org/licenses/.
16 *****************************************************************************/
17
18 #include <stdio.h>
19 #include <stdlib.h>
20 #include <string.h>
21 #include <stdarg.h>
22 #include <errno.h>
23
24 #include "core_main.h"
25 #include "core_commands2.h"
26 #include "core_commands4.h"
27 #include "core_commands7.h"
28 #include "core_display.h"
29 #include "core_display.h"
30 #include "core_helpers.h"
31 #include "core_keydown.h"
32 #include "core_math1.h"
33 #include "core_sto_rcl.h"
34 #include "core_tables.h"
35 #include "core_variables.h"
36 #include "shell.h"
37 #include "shell_spool.h"
38
39 #ifndef BCD_MATH
40 // We need these locally for BID128->double conversion
41 #include "bid_conf.h"
42 #include "bid_functions.h"
43 #endif
44
45 #ifdef WINDOWS
46 FILE *my_fopen(const char *name, const char *mode);
47 int my_rename(const char *oldname, const char *newname);
48 int my_remove(const char *name);
49 #else
50 #define my_fopen fopen
51 #define my_rename rename
52 #define my_remove remove
53 #endif
54
55
56 static void set_shift(bool state) {
57 if (mode_shift != state) {
58 mode_shift = state;
59 set_annunciators(-1, state, -1, -1, -1, -1);
60 }
61 }
62
63 static bool initialized = false;
64 bool quitting = false;
65
66 static void continue_running();
67 static void stop_interruptible();
68 static bool handle_error(int error);
69
70 int repeating = 0;
71 int repeating_shift;
72 int repeating_key;
73
74 static int4 oldpc;
75
76 core_settings_struct core_settings;
77
78 void core_init(int read_saved_state, int4 version, const char *state_file_name, int offset) {
79
80 /* Possible values for read_saved_state:
81 * 0: state file not present (Memory Clear)
82 * 1: state file present and looks OK so far
83 * 2: state file present but not OK (State File Corrupt)
84 */
85
86 phloat_init();
87
88 char *state_file_name_crash = NULL;
89 if (read_saved_state == 1) {
90 // Before loading state, rename the state file by appending .crash
91 // to its name. We'll rename it back, right after loading is done.
92 // This way, if we crash while loading state, we end up with a
93 // renamed state file, so the next time the app is run, it will
94 // launch with Memory Clear rather than just crashing on startup over
95 // and over, and, on iOS and Android, needing to be deleted and
96 // reinstalled.
97 size_t bufsize = strlen(state_file_name) + 24;
98 state_file_name_crash = (char *) malloc(bufsize);
99 uint4 date, time;
100 int weekday;
101 shell_get_time_date(&time, &date, &weekday);
102 snprintf(state_file_name_crash, bufsize, "%s.%08u%08u.crash", state_file_name, date, time);
103 my_rename(state_file_name, state_file_name_crash);
104 gfile = my_fopen(state_file_name_crash, "rb");
105 if (gfile == NULL)
106 read_saved_state = 0;
107 else if (offset > 0)
108 fseek(gfile, offset, SEEK_SET);
109 } else
110 gfile = NULL;
111
112 bool clear, too_new = false;
113 int reason = 0;
114 if (read_saved_state != 1 || !load_state(version, &clear, &too_new)) {
115 reason = too_new ? 2 : (read_saved_state != 0 && !clear) ? 1 : 0;
116 hard_reset(reason);
117 }
118 if (gfile != NULL)
119 fclose(gfile);
120 if (state_file_name_crash != NULL) {
121 if (reason == 0) {
122 my_rename(state_file_name_crash, state_file_name);
123 } else {
124 char *tmp = (char *) malloc(strlen(state_file_name_crash) + 3);
125 strcpy(tmp, state_file_name_crash);
126 tmp[strlen(state_file_name_crash) - 6] = 0;
127 strcat(tmp, reason == 1 ? ".corrupt" : ".too_new");
128 my_rename(state_file_name_crash, tmp);
129 free(tmp);
130 }
131 free(state_file_name_crash);
132 }
133
134 initialized = true;
135 quitting = false;
136
137 repaint_display();
138 #if defined(ANDROID) || defined(IPHONE)
139 mode_popup_unknown = true;
140 #endif
141 shell_annunciators(mode_updown,
142 mode_shift,
143 0 /*print*/,
144 mode_running,
145 !flags.f.rad && flags.f.grad,
146 flags.f.rad || flags.f.grad);
147 }
148
149 void core_save_state(const char *state_file_name) {
150 if (mode_interruptible != NULL)
151 stop_interruptible();
152 set_running(false);
153
154 size_t bufsize = strlen(state_file_name) + 24;
155 char *state_file_name_crash = (char *) malloc(bufsize);
156 uint4 date, time;
157 int weekday;
158 shell_get_time_date(&time, &date, &weekday);
159 snprintf(state_file_name_crash, bufsize, "%s.%08u%08u.crash", state_file_name, date, time);
160
161 gfile = my_fopen(state_file_name_crash, "wb");
162 if (gfile != NULL) {
163 bool success;
164 save_state(&success);
165 fclose(gfile);
166 if (success) {
167 my_remove(state_file_name);
168 my_rename(state_file_name_crash, state_file_name);
169 }
170 }
171 }
172
173 void core_cleanup() {
174 if (!initialized)
175 return;
176
177 initialized = false;
178 for (int i = 0; i <= sp; i++)
179 free_vartype(stack[i]);
180 sp = -1;
181 free(stack);
182 stack = NULL;
183 stack_capacity = 0;
184 free_vartype(lastx);
185 lastx = NULL;
186 purge_all_vars();
187 clear_all_prgms();
188 if (vars != NULL) {
189 free(vars);
190 vars = NULL;
191 vars_capacity = 0;
192 }
193 clean_vartype_pools();
194 }
195
196 void set_annunciators(int updn, int shf, int prt, int run, int g, int rad) {
197 if (!initialized || quitting)
198 return;
199
200 shell_annunciators(updn, shf, prt, run, g, rad);
201 }
202
203 void core_repaint_display() {
204 if (!initialized || quitting)
205 return;
206
207 repaint_display();
208 }
209
210 bool core_menu() {
211 return mode_clall || get_front_menu() != MENU_NONE;
212 }
213
214 bool alpha_active() {
215 int menu = get_front_menu();
216 return menu >= MENU_ALPHA1 && menu <= MENU_ALPHA_MISC2;
217 }
218
219 bool core_alpha_menu() {
220 return !mode_getkey && alpha_active();
221 }
222
223 bool core_hex_menu() {
224 return get_front_menu() == MENU_BASE_A_THRU_F;
225 }
226
227 static int ascii2hp(char *dst, int dstlen, const char *src, int srclen = -1);
228
229 int core_special_menu_key(int which) {
230 return special_menu_key(which);
231 }
232
233 static bool core_keydown_2(int key, bool *enqueued, int *repeat);
234
235 bool core_keydown(int key, bool *enqueued, int *repeat) {
236 if (key >= 1024 && key != 1034) {
237 int code = key - 1024;
238 char ubuf[5];
239 int n = 0;
240 if (code < 128) {
241 ubuf[n++] = code;
242 } else if (code < 2048) {
243 ubuf[n++] = (code >> 6) | 0xc0;
244 ubuf[n++] = (code & 63) | 0x80;
245 } else if (code < 65536) {
246 ubuf[n++] = (code >> 12) | 0xe0;
247 ubuf[n++] = ((code >> 6) & 63) | 0x80;
248 ubuf[n++] = (code & 63) | 0x80;
249 } else if (code < 1114112) {
250 ubuf[n++] = (code >> 18) | 0xf0;
251 ubuf[n++] = ((code >> 12) & 63) | 0x80;
252 ubuf[n++] = ((code >> 6) & 63) | 0x80;
253 ubuf[n++] = (code & 63) | 0x80;
254 } else {
255 fail:
256 set_shift(false);
257 squeak();
258 return core_keydown_2(0, enqueued, repeat);
259 }
260 ubuf[n] = 0;
261 char hpbuf[5];
262 int len = ascii2hp(hpbuf, 1, ubuf);
263 if (len == 0)
264 goto fail;
265 if (hpbuf[0] == 30)
266 hpbuf[0] = 94;
267 key = 1024 + (hpbuf[0] & 255);
268 }
269 return core_keydown_2(key, enqueued, repeat);
270 }
271
272 bool core_keydown_command(const char *name, bool is_text, bool *enqueued, int *repeat) {
273 char hpname[70];
274 int len = ascii2hp(hpname, 63, name);
275 if (is_text) {
276 int ch = hpname[0] & 255;
277 if (len == 0) {
278 ch = 0;
279 set_shift(false);
280 squeak();
281 }
282 return core_keydown_2(ch == 0 ? 0 : ch + 1024, enqueued, repeat);
283 } else {
284 int cmd = find_builtin(hpname, len);
285 if (cmd == CMD_NONE) {
286 set_shift(false);
287 squeak();
288 }
289 return core_keydown_2(cmd == CMD_NONE ? 0 : cmd + 2048, enqueued, repeat);
290 }
291 }
292
293 static bool core_keydown_2(int key, bool *enqueued, int *repeat) {
294
295 *enqueued = 0;
296 *repeat = 0;
297
298 if (!initialized || quitting)
299 return false;
300
301 if (key != 0)
302 no_keystrokes_yet = false;
303
304 if (key == KEY_SHIFT) {
305 set_shift(!mode_shift);
306 if (!mode_menu_static) {
307 int menuid = get_front_menu();
308 if (menuid == MENU_TOP_FCN || menuid == MENU_PGM_FCN1 || menuid == MENU_STAT1
309 || menuid == MENU_BASE2 || menuid == MENU_BASE3
310 || menuid == MENU_CUSTOM1 || menuid == MENU_CUSTOM2 || menuid == MENU_CUSTOM3)
311 redisplay();
312 }
313 return (mode_running && !mode_getkey && !mode_pause) || keybuf_head != keybuf_tail;
314 }
315
316 if (mode_pause) {
317 if (key == 0)
318 return false;
319 mode_pause = false;
320 set_running(false);
321 if (!mode_shift && (key == KEY_RUN || key == KEY_EXIT)) {
322 redisplay();
323 return false;
324 }
325 }
326
327 if (mode_interruptible != NULL) {
328 /* We're in the middle of an interruptible function
329 * (e.g., INVRT, PRP); queue up any keystrokes and invoke
330 * the appropriate callback to keep the function moving along
331 */
332 int error;
333 bool keep_running;
334 if (key != 0) {
335 /* Enqueue... */
336 *enqueued = 1;
337 if (key == KEY_EXIT ||
338 (mode_stoppable && !mode_shift && key == KEY_RUN)) {
339 keybuf_tail = keybuf_head;
340 stop_interruptible();
341 return false;
342 } else {
343 if (((keybuf_head + 1) & 15) != keybuf_tail) {
344 if (mode_shift)
345 key = -key;
346 keybuf[keybuf_head] = key;
347 keybuf_head = (keybuf_head + 1) & 15;
348 }
349 }
350 set_shift(false);
351 }
352 error = mode_interruptible(false);
353 if (error == ERR_INTERRUPTIBLE)
354 /* Still not done */
355 return true;
356 mode_interruptible = NULL;
357 keep_running = handle_error(error);
358 if (mode_running) {
359 if (!keep_running)
360 set_running(false);
361 } else {
362 set_annunciators(-1, -1, -1, 0, -1, -1);
363 pending_command = CMD_NONE;
364 }
365 if (mode_running || keybuf_tail != keybuf_head)
366 return true;
367 else {
368 redisplay();
369 return false;
370 }
371 }
372
373 if (mode_running && !mode_getkey) {
374 /* We're running; queue up any keystrokes and invoke
375 * continue_running() to keep the program moving along
376 */
377 if (key != 0) {
378 if (key == KEY_EXIT) {
379 keybuf_tail = keybuf_head;
380 set_shift(false);
381 set_running(false);
382 pending_command = CMD_CANCELLED;
383 return false;
384 }
385 /* Enqueue... */
386 *enqueued = 1;
387 if (!mode_shift && key == KEY_RUN) {
388 keybuf_tail = keybuf_head;
389 set_running(false);
390 redisplay();
391 return false;
392 }
393 if (((keybuf_head + 1) & 15) != keybuf_tail) {
394 if (mode_shift)
395 key = -key;
396 keybuf[keybuf_head] = key;
397 keybuf_head = (keybuf_head + 1) & 15;
398 }
399 set_shift(false);
400 }
401 continue_running();
402 if ((mode_running && !mode_getkey && !mode_pause) || keybuf_tail != keybuf_head)
403 return true;
404 else {
405 if (mode_getkey)
406 /* Technically, the program is still running, but we turn
407 * off the 'running' annunciator so that the user has some
408 * cue that they may now type. (Actually, I'm doing it
409 * purely because the HP-42S does it, too!)
410 */
411 set_annunciators(-1, -1, -1, 0, -1, -1);
412 else if (!mode_pause)
413 redisplay();
414 return false;
415 }
416 }
417
418 /* If we get here, mode_running must be false.
419 * or a program is running but hanging in GETKEY;
420 */
421
422 if (keybuf_tail != keybuf_head) {
423 /* We're not running, or a program is waiting in GETKEY;
424 * feed queued-up keystroke to keydown()
425 */
426 int oldshift = 0;
427 int oldkey = keybuf[keybuf_tail];
428 if (oldkey < 0) {
429 oldkey = -oldkey;
430 oldshift = 1;
431 }
432 keybuf_tail = (keybuf_tail + 1) & 15;
433 /* If we're in GETKEY mode, the 'running' annunciator is off;
434 * see the code circa 30 lines back.
435 * We now turn it back on since program execution resumes.
436 */
437 if (mode_getkey && mode_running)
438 set_annunciators(-1, -1, -1, 1, -1, -1);
439 /* Feed the dequeued key to the usual suspects */
440 keydown(oldshift, oldkey);
441 core_keyup();
442 /* We've just de-queued a key; may have to enqueue
443 * one as well, if the user is actually managing to
444 * type while we're unwinding the keyboard buffer
445 */
446 if (key != 0) {
447 if (((keybuf_head + 1) & 15) != keybuf_tail) {
448 if (mode_shift)
449 key = -key;
450 keybuf[keybuf_head] = key;
451 keybuf_head = (keybuf_head + 1) & 15;
452 }
453 set_shift(false);
454 }
455 return (mode_running && !mode_getkey) || keybuf_head != keybuf_tail;
456 }
457
458 /* No program is running, or it is running but waiting for a
459 * keystroke (GETKEY); handle any new keystroke that has just come in
460 */
461 if (key != 0) {
462 int shift = mode_shift;
463 set_shift(false);
464 if (mode_getkey && mode_running)
465 set_annunciators(-1, -1, -1, 1, -1, -1);
466 keydown(shift, key);
467 if (repeating != 0) {
468 *repeat = repeating;
469 repeating = 0;
470 }
471 return mode_running && !mode_getkey;
472 }
473
474 /* Nothing going on at all! */
475 return false;
476 }
477
478 int dequeue_key() {
479 if (keybuf_tail == keybuf_head)
480 return 0;
481 int key = keybuf[keybuf_tail];
482 keybuf_tail = (keybuf_tail + 1) & 15;
483 bool shift = key < 0;
484 if (shift)
485 key = -key;
486 if (key > 2048) {
487 key = find_cmd_getkey_mapping(key - 2048);
488 if (key == 0)
489 squeak();
490 }
491 else if (shift)
492 key += 37;
493 return key;
494 }
495
496 int core_repeat() {
497 if (!initialized || quitting)
498 return 0;
499
500 keydown(repeating_shift, repeating_key);
501 int rpt = repeating;
502 repeating = 0;
503 return rpt;
504 }
505
506 void core_keytimeout1() {
507 if (!initialized || quitting)
508 return;
509
510 if (pending_command == CMD_LINGER1 || pending_command == CMD_LINGER2)
511 return;
512 if (pending_command == CMD_RUN || pending_command == CMD_SST
513 || pending_command == CMD_SST_UP || pending_command == CMD_SST_RT) {
514 int saved_pending_command = pending_command;
515 if (pc == -1)
516 pc = 0;
517 prgm_highlight_row = 1;
518 flags.f.prgm_mode = 2; /* HACK - magic value to tell redisplay() */
519 /* not to suppress option menu highlights */
520 pending_command = CMD_NONE;
521 redisplay();
522 flags.f.prgm_mode = 0;
523 pending_command = saved_pending_command;
524 } else if (pending_command != CMD_NONE && pending_command != CMD_CANCELLED
525 && (cmd_array[pending_command].flags & FLAG_NO_SHOW) == 0) {
526 display_command(0);
527 /* If the program catalog was left up by GTO or XEQ,
528 * don't paint over it */
529 if (mode_transientmenu == MENU_NONE || pending_command == CMD_NULL) {
530 bool saved_prgm_mode = flags.f.prgm_mode;
531 flags.f.prgm_mode = 0;
532 display_x(1);
533 flags.f.prgm_mode = saved_prgm_mode;
534 }
535 flush_display();
536 }
537 }
538
539 void core_keytimeout2() {
540 if (!initialized || quitting)
541 return;
542
543 if (pending_command == CMD_LINGER1 || pending_command == CMD_LINGER2)
544 return;
545 remove_program_catalog = 0;
546 if (pending_command != CMD_NONE && pending_command != CMD_CANCELLED
547 && (cmd_array[pending_command].flags & FLAG_NO_SHOW) == 0) {
548 clear_row(0);
549 draw_string(0, 0, "NULL", 4);
550 bool saved_prgm_mode = flags.f.prgm_mode;
551 flags.f.prgm_mode = 0;
552 display_x(1);
553 flags.f.prgm_mode = saved_prgm_mode;
554 flush_display();
555 pending_command = CMD_CANCELLED;
556 }
557 }
558
559 bool core_timeout3(bool repaint) {
560 if (!initialized || quitting)
561 return false;
562
563 if (mode_pause) {
564 if (repaint) {
565 /* The PSE ended normally */
566 mode_pause = false;
567 if (mode_goose >= 0)
568 mode_goose = -1 - mode_goose;
569 }
570 return true;
571 }
572 /* Remove the output of SHOW, MEM, or shift-VARMENU from the display */
573 if (pending_command == CMD_LINGER1)
574 pending_command = CMD_CANCELLED;
575 else if (pending_command == CMD_LINGER2) {
576 flags.f.message = 0;
577 flags.f.two_line_message = 0;
578 pending_command = CMD_NONE;
579 if (repaint)
580 redisplay();
581 }
582 return false;
583 }
584
585 bool core_keyup() {
586 if (!initialized || quitting)
587 return false;
588
589 if (mode_pause) {
590 /* The only way this can happen is if they key in question was Shift */
591 return false;
592 }
593
594 int error = ERR_NONE;
595
596 if (pending_command == CMD_LINGER1 || pending_command == CMD_LINGER2) {
597 pending_command = CMD_LINGER2;
598 return mode_running || keybuf_head != keybuf_tail;
599 }
600
601 if (pending_command == CMD_SILENT_OFF) {
602 #ifdef IPHONE
603 if (off_enabled()) {
604 shell_always_on(0);
605 quitting = true;
606 shell_powerdown();
607 } else {
608 set_running(false);
609 squeak();
610 }
611 #else
612 shell_always_on(0);
613 quitting = true;
614 shell_powerdown();
615 #endif
616 pending_command = CMD_NONE;
617 return false;
618 }
619
620 if (pending_command == CMD_NONE)
621 return mode_running || mode_interruptible != NULL || keybuf_head != keybuf_tail;
622
623 if (remove_program_catalog) {
624 if (mode_transientmenu == MENU_CATALOG)
625 set_menu(MENULEVEL_TRANSIENT, MENU_NONE);
626 else if (mode_plainmenu == MENU_CATALOG)
627 set_menu(MENULEVEL_PLAIN, MENU_NONE);
628 remove_program_catalog = 0;
629 }
630
631 if (pending_command == CMD_CANCELLED || pending_command == CMD_NULL) {
632 pending_command = CMD_NONE;
633 redisplay();
634 return mode_running || keybuf_head != keybuf_tail;
635 }
636
637 mode_varmenu = pending_command == CMD_VMSTO
638 || pending_command == CMD_VMSTO2
639 || pending_command == CMD_VMSOLVE
640 || pending_command == CMD_VMEXEC;
641
642 if (input_length > 0) {
643 /* INPUT active */
644 if (pending_command == CMD_RUN || pending_command == CMD_SST
645 || pending_command == CMD_SST_UP || pending_command == CMD_SST_RT) {
646 int err;
647 if (sp == -1) {
648 vartype_real zero;
649 zero.type = TYPE_REAL;
650 zero.x = 0;
651 stack[++sp] = (vartype *) &zero;
652 err = generic_sto(&input_arg, 0);
653 sp--;
654 } else {
655 err = generic_sto(&input_arg, 0);
656 }
657 input_length = 0;
658 if (err != ERR_NONE) {
659 pending_command = CMD_NONE;
660 display_error(err);
661 redisplay();
662 return mode_running || keybuf_head != keybuf_tail;
663 }
664 } else if (pending_command == CMD_GTO
665 || pending_command == CMD_GTODOT
666 || pending_command == CMD_GTODOTDOT
667 || pending_command == CMD_RTN)
668 /* NOTE: set_running(true) also ends INPUT mode, so commands that
669 * cause program execution to start do not have to be handled here.
670 */
671 input_length = 0;
672 }
673
674 if (pending_command == CMD_VMEXEC || pending_command == CMD_PMEXEC) {
675 string_copy(reg_alpha, &reg_alpha_length,
676 pending_command_arg.val.text, pending_command_arg.length);
677 goto do_run;
678 }
679 if (pending_command == CMD_RUN || pending_command == CMD_SST_UP) {
680 do_run:
681 if ((flags.f.trace_print || flags.f.normal_print)
682 && flags.f.printer_exists)
683 print_command(pending_command, &pending_command_arg);
684 if (pending_command == CMD_SST_UP)
685 step_out();
686 pending_command = CMD_NONE;
687 if (pc == -1)
688 pc = 0;
689 set_running(true);
690 return true;
691 }
692
693 if (pending_command == CMD_SST || pending_command == CMD_SST_RT) {
694 int cmd;
695 arg_struct arg;
696 oldpc = pc;
697 if (pc == -1)
698 pc = 0;
699 get_next_command(&pc, &cmd, &arg, 1, NULL);
700 if (pending_command == CMD_SST_RT
701 && (cmd == CMD_XEQ || cmd == CMD_SOLVE || cmd == CMD_INTEG)) {
702 pc = oldpc;
703 step_over();
704 goto do_run;
705 }
706 if ((flags.f.trace_print || flags.f.normal_print)
707 && flags.f.printer_exists) {
708 if (cmd == CMD_LBL)
709 print_text(NULL, 0, true);
710 print_program_line(current_prgm, oldpc);
711 }
712 mode_disable_stack_lift = false;
713 set_running(true);
714 error = handle(cmd, &arg);
715 set_running(false);
716 mode_pause = false;
717 } else {
718 if ((flags.f.trace_print || flags.f.normal_print)
719 && flags.f.printer_exists)
720 print_command(pending_command, &pending_command_arg);
721 mode_disable_stack_lift = false;
722 error = handle(pending_command, &pending_command_arg);
723 mode_pause = false;
724 }
725
726 if (quitting)
727 return false;
728
729 if (error == ERR_INTERRUPTIBLE) {
730 set_annunciators(-1, -1, -1, 1, -1, -1);
731 pending_command = CMD_NONE;
732 return true;
733 }
734
735 handle_error(error);
736 pending_command = CMD_NONE;
737 if (!mode_getkey && !mode_pause)
738 redisplay();
739 return (mode_running && !mode_getkey && !mode_pause) || keybuf_head != keybuf_tail;
740 }
741
742 bool core_powercycle() {
743 bool need_redisplay = false;
744
745 if (mode_interruptible != NULL)
746 stop_interruptible();
747
748 no_keystrokes_yet = true;
749
750 keybuf_tail = keybuf_head;
751 set_shift(false);
752 #if (!defined(ANDROID) && !defined(IPHONE))
753 shell_always_on(0);
754 #endif
755 pending_command = CMD_NONE;
756
757 if (mode_getkey) {
758 /* A real HP-42S can't be switched off while GETKEY is active: pressing
759 * OFF on the keyboard returns code 70 and stops program execution; and
760 * when the auto-poweroff timeout expires, code 70 is returned but
761 * program execution continues.
762 * Since Free42 can be shut down in a way the HP-42S can't, by exiting
763 * the application, I have to fake it a bit; I put 70 in X as if the
764 * user had done OFF twice on a real 42S.
765 */
766 vartype *seventy = new_real(70);
767 if (seventy != NULL) {
768 if (recall_result(seventy) != ERR_NONE)
769 goto nomem;
770 flags.f.stack_lift_disable = 0;
771 } else {
772 nomem:
773 display_error(ERR_INSUFFICIENT_MEMORY);
774 flags.f.auto_exec = 0;
775 }
776 if (!flags.f.auto_exec)
777 need_redisplay = true;
778 mode_getkey = false;
779 }
780
781 if (flags.f.big_stack && !core_settings.allow_big_stack) {
782 arg_struct dummy_arg;
783 docmd_4stk(&dummy_arg);
784 need_redisplay = true;
785 }
786
787 if (flags.f.auto_exec) {
788 if (mode_command_entry)
789 finish_command_entry(false);
790 if (flags.f.prgm_mode) {
791 if (mode_alpha_entry) {
792 pc = incomplete_saved_pc;
793 prgm_highlight_row = incomplete_saved_highlight_row;
794 } else if (mode_number_entry) {
795 arg_struct arg;
796 arg.type = ARGTYPE_DOUBLE;
797 arg.val_d = entered_number;
798 cmdline[cmdline_length] = 0;
799 store_command(pc, CMD_NUMBER, &arg, cmdline);
800 prgm_highlight_row = 1;
801 }
802 flags.f.prgm_mode = false;
803 }
804 mode_alpha_entry = false;
805 mode_number_entry = false;
806 set_menu(MENULEVEL_ALPHA, MENU_NONE);
807 set_running(true);
808 flags.f.auto_exec = 0;
809 need_redisplay = false;
810 } else {
811 if (mode_running) {
812 set_running(false);
813 need_redisplay = true;
814 }
815 }
816
817 #ifdef BCD_MATH
818 if (need_redisplay || state_file_number_format != NUMBER_FORMAT_BID128)
819 redisplay();
820 #else
821 if (need_redisplay || state_file_number_format != NUMBER_FORMAT_BINARY)
822 redisplay();
823 #endif
824
825 return mode_running;
826 }
827
828 void core_update_allow_big_stack() {
829 if (prgms == NULL)
830 // Hack to deal with the Mac version calling this function
831 // after already having called core_quit()
832 return;
833 if (flags.f.big_stack && !core_settings.allow_big_stack) {
834 arg_struct dummy_arg;
835 docmd_4stk(&dummy_arg);
836 }
837 redisplay();
838 }
839
840 char *core_list_programs() {
841 int bufsize = 1024;
842 char *buf = (char *) malloc(bufsize);
843 if (buf == NULL)
844 return NULL;
845 int lastidx = -1;
846 int bufptr = 4;
847 int label;
848 int count = 0;
849 for (label = 0; label < labels_count; label++) {
850 int len = labels[label].length;
851 char name[51];
852 int namelen = 0;
853 int end = 0;
854 int i;
855
856 if (len == 0) {
857 if (labels[label].prgm == lastidx)
858 continue;
859 if (label == labels_count - 1) {
860 string2buf(name, 21, &namelen, ".END.", 5);
861 namelen = 5;
862 } else {
863 string2buf(name, 21, &namelen, "END", 3);
864 namelen = 3;
865 }
866 end = 1;
867 } else {
868 name[namelen++] = '"';
869 namelen += hp2ascii(name + namelen, labels[label].name, len);
870 name[namelen++] = '"';
871 end = labels[label + 1].length == 0;
872 }
873
874 lastidx = labels[label].prgm;
875
876 if (bufptr + namelen + 1 >= bufsize) {
877 bufsize += 1024;
878 char *newbuf = (char *) realloc(buf, bufsize);
879 if (newbuf == NULL) {
880 if (bufptr > 0 && buf[bufptr - 1] != 0) {
881 buf[bufptr - 1] = 0;
882 count++;
883 }
884 goto done;
885 }
886 buf = newbuf;
887 }
888 for (i = 0; i < namelen; i++)
889 buf[bufptr++] = name[i];
890 if (end) {
891 buf[bufptr++] = 0;
892 count++;
893 } else {
894 buf[bufptr++] = ' ';
895 }
896 }
897 done:
898 buf[0] = (char) (count >> 24);
899 buf[1] = (char) (count >> 16);
900 buf[2] = (char) (count >> 8);
901 buf[3] = (char) count;
902 return buf;
903 }
904
905 static void export_hp42s(int index) {
906 int4 pc = 0;
907 int cmd;
908 arg_struct arg;
909 int saved_prgm = current_prgm;
910 unsigned char code_flags, code_name, code_std_1, code_std_2;
911 char cmdbuf[50];
912 int cmdlen;
913 char buf[1000];
914 int buflen = 0;
915 int i;
916
917 current_prgm = index;
918 do {
919 const char *orig_num;
920 get_next_command(&pc, &cmd, &arg, 0, &orig_num);
921 code_flags = (cmd_array[cmd].flags & (FLAG_SPECIAL | FLAG_ILLEGAL)) >> 5;
922 code_name = cmd_array[cmd].scode;
923 code_std_1 = cmd_array[cmd].code1;
924 code_std_2 = cmd_array[cmd].code2;
925 cmdlen = 0;
926 switch (code_flags) {
927 case 1:
928 /* A command that requires some special attention */
929 if (cmd == CMD_STO) {
930 if (arg.type == ARGTYPE_NUM && arg.val.num <= 15)
931 cmdbuf[cmdlen++] = 0x30 + arg.val.num;
932 else
933 goto normal;
934 } else if (cmd == CMD_RCL) {
935 if (arg.type == ARGTYPE_NUM && arg.val.num <= 15)
936 cmdbuf[cmdlen++] = 0x20 + arg.val.num;
937 else
938 goto normal;
939 } else if (cmd == CMD_FIX || cmd == CMD_SCI || cmd == CMD_ENG) {
940 char byte2;
941 if (arg.type != ARGTYPE_NUM || arg.val.num <= 9)
942 goto normal;
943 cmdbuf[cmdlen++] = (char) 0xf1;
944 if (arg.val.num == 10) {
945 switch (cmd) {
946 case CMD_FIX: byte2 = (char) 0xd5; break;
947 case CMD_SCI: byte2 = (char) 0xd6; break;
948 case CMD_ENG: byte2 = (char) 0xd7; break;
949 }
950 } else {
951 switch (cmd) {
952 case CMD_FIX: byte2 = (char) 0xe5; break;
953 case CMD_SCI: byte2 = (char) 0xe6; break;
954 case CMD_ENG: byte2 = (char) 0xe7; break;
955 }
956 }
957 cmdbuf[cmdlen++] = byte2;
958 } else if (cmd == CMD_SIZE) {
959 cmdbuf[cmdlen++] = (char) 0xf3;
960 cmdbuf[cmdlen++] = (char) 0xf7;
961 cmdbuf[cmdlen++] = arg.val.num >> 8;
962 cmdbuf[cmdlen++] = arg.val.num;
963 } else if (cmd == CMD_LBL) {
964 if (arg.type == ARGTYPE_NUM) {
965 if (arg.val.num <= 14)
966 cmdbuf[cmdlen++] = 0x01 + arg.val.num;
967 else
968 goto normal;
969 } else if (arg.type == ARGTYPE_STR) {
970 cmdbuf[cmdlen++] = (char) 0xc0;
971 cmdbuf[cmdlen++] = 0x00;
972 cmdbuf[cmdlen++] = 0xf1 + arg.length;
973 cmdbuf[cmdlen++] = 0x00;
974 for (i = 0; i < arg.length; i++)
975 cmdbuf[cmdlen++] = arg.val.text[i];
976 } else
977 goto normal;
978 } else if (cmd == CMD_INPUT) {
979 if (arg.type == ARGTYPE_IND_NUM
980 || arg.type == ARGTYPE_IND_STK)
981 code_std_2 = 0xee;
982 goto normal;
983 } else if (cmd == CMD_XEQ) {
984 if (arg.type == ARGTYPE_NUM || arg.type == ARGTYPE_STK
985 || arg.type == ARGTYPE_LCLBL) {
986 code_std_1 = 0xe0;
987 code_std_2 = 0x00;
988 goto normal;
989 } else if (arg.type == ARGTYPE_STR) {
990 cmdbuf[cmdlen++] = 0x1e;
991 cmdbuf[cmdlen++] = 0xf0 + arg.length;
992 for (i = 0; i < arg.length; i++)
993 cmdbuf[cmdlen++] = arg.val.text[i];
994 } else
995 goto normal;
996 } else if (cmd == CMD_GTO) {
997 if (arg.type == ARGTYPE_NUM && arg.val.num <= 14) {
998 cmdbuf[cmdlen++] = 0xb1 + arg.val.num;
999 cmdbuf[cmdlen++] = 0x00;
1000 } else if (arg.type == ARGTYPE_NUM
1001 || arg.type == ARGTYPE_STK
1002 || arg.type == ARGTYPE_LCLBL) {
1003 code_std_1 = 0xd0;
1004 code_std_2 = 0x00;
1005 goto normal;
1006 } else if (arg.type == ARGTYPE_IND_NUM
1007 || arg.type == ARGTYPE_IND_STK) {
1008 cmdbuf[cmdlen++] = (char) 0xae;
1009 if (arg.type == ARGTYPE_IND_NUM)
1010 arg.type = ARGTYPE_NUM;
1011 else
1012 arg.type = ARGTYPE_STK;
1013 goto non_string_suffix;
1014 } else if (arg.type == ARGTYPE_STR) {
1015 cmdbuf[cmdlen++] = 0x1d;
1016 cmdbuf[cmdlen++] = 0xf0 + arg.length;
1017 for (i = 0; i < arg.length; i++)
1018 cmdbuf[cmdlen++] = arg.val.text[i];
1019 } else
1020 goto normal;
1021 } else if (cmd == CMD_END) {
1022 cmdbuf[cmdlen++] = (char) 0xc0;
1023 cmdbuf[cmdlen++] = 0x00;
1024 cmdbuf[cmdlen++] = 0x0d;
1025 } else if (cmd == CMD_NUMBER) {
1026 const char *p;
1027 if (orig_num != NULL)
1028 p = orig_num;
1029 else
1030 p = phloat2program(arg.val_d);
1031 char c;
1032 while ((c = *p++) != 0) {
1033 if (c >= '0' && c <= '9')
1034 cmdbuf[cmdlen++] = 0x10 + c - '0';
1035 else if (c == '.' || c == ',')
1036 cmdbuf[cmdlen++] = 0x1a;
1037 else if (c == 24)
1038 cmdbuf[cmdlen++] = 0x1b;
1039 else if (c == '-')
1040 cmdbuf[cmdlen++] = 0x1c;
1041 else
1042 /* Should not happen */
1043 continue;
1044 }
1045 cmdbuf[cmdlen++] = 0x00;
1046 } else if (cmd == CMD_STRING) {
1047 cmdbuf[cmdlen++] = 0xf0 + arg.length;
1048 for (i = 0; i < arg.length; i++)
1049 cmdbuf[cmdlen++] = arg.val.text[i];
1050 } else if (cmd >= CMD_ASGN01 && cmd <= CMD_ASGN18) {
1051 if (arg.type == ARGTYPE_STR) {
1052 cmdbuf[cmdlen++] = 0xf2 + arg.length;
1053 cmdbuf[cmdlen++] = (char) 0xc0;
1054 for (i = 0; i < arg.length; i++)
1055 cmdbuf[cmdlen++] = arg.val.text[i];
1056 } else {
1057 /* arg.type == ARGTYPE_COMMAND; we don't use that
1058 * any more, but just to be safe (in case anyone ever
1059 * actually used this in a program), we handle it
1060 * anyway.
1061 */
1062 const command_spec *cs = &cmd_array[arg.val.cmd];
1063 cmdbuf[cmdlen++] = 0xf2 + cs->name_length;
1064 cmdbuf[cmdlen++] = (char) 0xc0;
1065 for (i = 0; i < cs->name_length; i++)
1066 cmdbuf[cmdlen++] = cs->name[i];
1067 }
1068 cmdbuf[cmdlen++] = cmd - CMD_ASGN01;
1069 } else if ((cmd >= CMD_KEY1G && cmd <= CMD_KEY9G)
1070 || (cmd >= CMD_KEY1X && cmd <= CMD_KEY9X)) {
1071 int keyg = cmd <= CMD_KEY9G;
1072 int keynum = cmd - (keyg ? CMD_KEY1G : CMD_KEY1X) + 1;
1073 if (arg.type == ARGTYPE_STR || arg.type == ARGTYPE_IND_STR){
1074 cmdbuf[cmdlen++] = 0xf2 + arg.length;
1075 cmdbuf[cmdlen++] = keyg ? 0xc3 : 0xc2;
1076 if (arg.type == ARGTYPE_IND_STR)
1077 cmdbuf[cmdlen - 1] += 8;
1078 cmdbuf[cmdlen++] = keynum;
1079 for (i = 0; i < arg.length; i++)
1080 cmdbuf[cmdlen++] = arg.val.text[i];
1081 } else {
1082 cmdbuf[cmdlen++] = (char) 0xf3;
1083 cmdbuf[cmdlen++] = keyg ? 0xe3 : 0xe2;
1084 cmdbuf[cmdlen++] = keynum;
1085 goto non_string_suffix;
1086 }
1087 } else if (cmd == CMD_XROM) {
1088 if (arg.type == ARGTYPE_NUM) {
1089 cmdbuf[cmdlen++] = (char) (0xa0 + ((arg.val.num >> 8) & 7));
1090 cmdbuf[cmdlen++] = (char) arg.val.num;
1091 } else {
1092 cmdbuf[cmdlen++] = (char) (0xf0 + arg.length);
1093 for (int i = 0; i < arg.length; i++)
1094 cmdbuf[cmdlen++] = arg.val.text[i];
1095 }
1096 } else if (cmd == CMD_XSTR) {
1097 int len = arg.length;
1098 if (len == 0) {
1099 cmdbuf[cmdlen++] = (char) 0xf2;
1100 cmdbuf[cmdlen++] = (char) 0xa7;
1101 cmdbuf[cmdlen++] = (char) 0x41;
1102 } else {
1103 /* Writing directly to 'buf' here, not using 'cmdbuf', */
1104 /* since XSTR can be very long and may not fit in one */
1105 /* piece. */
1106 const char *ptr = arg.val.xstr;
1107 while (len > 0) {
1108 if (buflen + 16 > 1000 - 50) {
1109 if (fwrite(buf, 1, buflen, gfile) != buflen)
1110 goto done;
1111 buflen = 0;
1112 }
1113 int slen = len <= 13 ? len : 13;
1114 buf[buflen++] = (char) (0xf2 + slen);
1115 buf[buflen++] = (char) 0xa7;
1116 buf[buflen++] = (char) (slen < len ? 0x49 : 0x41);
1117 memcpy(buf + buflen, ptr, slen);
1118 buflen += slen;
1119 ptr += slen;
1120 len -= slen;
1121 }
1122 }
1123 } else {
1124 /* Shouldn't happen */
1125 continue;
1126 }
1127 break;
1128 case 0:
1129 normal:
1130 if (arg.type == ARGTYPE_STR || arg.type == ARGTYPE_IND_STR) {
1131 int i;
1132 if ((code_name & 0x80) == 0) {
1133 cmdbuf[cmdlen++] = 0xf0 + arg.length + 2;
1134 cmdbuf[cmdlen++] = (char) 0xa7;
1135 } else {
1136 cmdbuf[cmdlen++] = 0xf0 + arg.length + 1;
1137 }
1138 cmdbuf[cmdlen++] = arg.type == ARGTYPE_STR ? code_name
1139 : code_name + 8;
1140 for (i = 0; i < arg.length; i++)
1141 cmdbuf[cmdlen++] = arg.val.text[i];
1142 } else {
1143 unsigned char suffix;
1144 if (code_std_1 != 0) {
1145 if (code_std_1 == 0xf2 && (code_std_2 & 0x80) == 0) {
1146 cmdbuf[cmdlen++] = (char) 0xf3;
1147 cmdbuf[cmdlen++] = (char) 0xa7;
1148 } else {
1149 cmdbuf[cmdlen++] = code_std_1;
1150 }
1151 }
1152 cmdbuf[cmdlen++] = code_std_2;
1153
1154 non_string_suffix:
1155 suffix = 0;
1156 switch (arg.type) {
1157 case ARGTYPE_NONE:
1158 goto no_suffix;
1159 case ARGTYPE_IND_NUM:
1160 suffix = 0x80;
1161 case ARGTYPE_NUM:
1162 suffix += arg.val.num;
1163 break;
1164 case ARGTYPE_IND_STK:
1165 suffix = 0x80;
1166 case ARGTYPE_STK:
1167 switch (arg.val.stk) {
1168 case 'X': suffix += 0x73; break;
1169 case 'Y': suffix += 0x72; break;
1170 case 'Z': suffix += 0x71; break;
1171 case 'T': suffix += 0x70; break;
1172 case 'L': suffix += 0x74; break;
1173 default:
1174 /* Shouldn't happen */
1175 continue;
1176 }
1177 break;
1178 case ARGTYPE_LCLBL:
1179 if (arg.val.lclbl >= 'A' && arg.val.lclbl <= 'J')
1180 suffix = arg.val.lclbl - 'A' + 0x66;
1181 else if (arg.val.lclbl >= 'a' &&
1182 arg.val.lclbl <= 'e')
1183 suffix = arg.val.lclbl - 'a' + 0x7b;
1184 else
1185 /* Shouldn't happen */
1186 continue;
1187 break;
1188 default:
1189 /* Shouldn't happen */
1190 /* Values not handled above are ARGTYPE_NEG_NUM,
1191 * which is converted to ARGTYPE_NUM by
1192 * get_next_command(); ARGTYPE_DOUBLE, which only
1193 * occurs with CMD_NUMBER, which is handled in the
1194 * special-case section, above; ARGTYPE_COMMAND,
1195 * which is handled in the special-case section;
1196 * and ARGTYPE_LBLINDEX, which is converted to
1197 * ARGTYPE_STR before being stored in a program.
1198 */
1199 continue;
1200 }
1201 cmdbuf[cmdlen++] = suffix;
1202 no_suffix:
1203 ;
1204 }
1205 break;
1206 case 2:
1207 default:
1208 /* Illegal command */
1209 continue;
1210 }
1211 if (buflen + cmdlen > 1000 - 50) {
1212 if (fwrite(buf, 1, buflen, gfile) != buflen)
1213 goto done;
1214 buflen = 0;
1215 }
1216 for (i = 0; i < cmdlen; i++)
1217 buf[buflen++] = cmdbuf[i];
1218 } while (cmd != CMD_END && pc < prgms[index].size);
1219 if (buflen > 0)
1220 fwrite(buf, 1, buflen, gfile);
1221 done:
1222 current_prgm = saved_prgm;
1223 }
1224
1225 int4 core_program_size(int prgm_index) {
1226 int4 pc = 0;
1227 int cmd;
1228 arg_struct arg;
1229 int saved_prgm = current_prgm;
1230 unsigned char code_flags, code_std_1, code_std_2;
1231 //unsigned char code_name;
1232 int4 size = 0;
1233
1234 current_prgm = prgm_index;
1235 do {
1236 const char *orig_num;
1237 get_next_command(&pc, &cmd, &arg, 0, &orig_num);
1238 code_flags = (cmd_array[cmd].flags & (FLAG_SPECIAL | FLAG_ILLEGAL)) >> 5;
1239 //code_name = cmd_array[cmd].scode;
1240 code_std_1 = cmd_array[cmd].code1;
1241 code_std_2 = cmd_array[cmd].code2;
1242 switch (code_flags) {
1243 case 1:
1244 /* A command that requires some special attention */
1245 if (cmd == CMD_STO) {
1246 if (arg.type == ARGTYPE_NUM && arg.val.num <= 15)
1247 size += 1;
1248 else
1249 goto normal;
1250 } else if (cmd == CMD_RCL) {
1251 if (arg.type == ARGTYPE_NUM && arg.val.num <= 15)
1252 size += 1;
1253 else
1254 goto normal;
1255 } else if (cmd == CMD_FIX || cmd == CMD_SCI || cmd == CMD_ENG) {
1256 goto normal;
1257 } else if (cmd == CMD_SIZE) {
1258 size += 4;
1259 } else if (cmd == CMD_LBL) {
1260 if (arg.type == ARGTYPE_NUM) {
1261 if (arg.val.num <= 14)
1262 size += 1;
1263 else
1264 goto normal;
1265 } else if (arg.type == ARGTYPE_STR) {
1266 size += arg.length + 4;
1267 } else
1268 goto normal;
1269 } else if (cmd == CMD_INPUT) {
1270 goto normal;
1271 } else if (cmd == CMD_XEQ) {
1272 if (arg.type == ARGTYPE_NUM || arg.type == ARGTYPE_STK
1273 || arg.type == ARGTYPE_LCLBL) {
1274 size += 3;
1275 } else if (arg.type == ARGTYPE_STR) {
1276 size += arg.length + 2;
1277 } else
1278 goto normal;
1279 } else if (cmd == CMD_GTO) {
1280 if (arg.type == ARGTYPE_NUM && arg.val.num <= 14) {
1281 size += 2;
1282 } else if (arg.type == ARGTYPE_NUM
1283 || arg.type == ARGTYPE_STK
1284 || arg.type == ARGTYPE_LCLBL) {
1285 size += 3;
1286 } else if (arg.type == ARGTYPE_STR) {
1287 size += arg.length + 2;
1288 } else
1289 goto normal;
1290 } else if (cmd == CMD_END) {
1291 /* Not counted for the line 00 total */
1292 } else if (cmd == CMD_NUMBER) {
1293 const char *p;
1294 if (orig_num != NULL)
1295 p = orig_num;
1296 else
1297 p = phloat2program(arg.val_d);
1298 size += (int4) strlen(p) + 1;
1299 } else if (cmd == CMD_STRING) {
1300 size += arg.length + 1;
1301 } else if (cmd >= CMD_ASGN01 && cmd <= CMD_ASGN18) {
1302 if (arg.type == ARGTYPE_STR)
1303 size += arg.length + 3;
1304 else
1305 /* arg.type == ARGTYPE_COMMAND; we don't use that
1306 * any more, but just to be safe (in case anyone ever
1307 * actually used this in a program), we handle it
1308 * anyway.
1309 */
1310 size += cmd_array[arg.val.cmd].name_length + 3;
1311 } else if ((cmd >= CMD_KEY1G && cmd <= CMD_KEY9G)
1312 || (cmd >= CMD_KEY1X && cmd <= CMD_KEY9X)) {
1313 if (arg.type == ARGTYPE_STR || arg.type == ARGTYPE_IND_STR)
1314 size += arg.length + 3;
1315 else
1316 size += 4;
1317 } else if (cmd == CMD_XROM) {
1318 if (arg.type == ARGTYPE_NUM)
1319 size += 2;
1320 else
1321 size += arg.length + 1;
1322 } else if (cmd == CMD_XSTR) {
1323 int n = (arg.length + 12) / 13;
1324 if (n == 0)
1325 n = 1;
1326 size += arg.length + n * 3;
1327 } else {
1328 /* Shouldn't happen */
1329 continue;
1330 }
1331 break;
1332 case 0:
1333 normal:
1334 if (arg.type == ARGTYPE_STR || arg.type == ARGTYPE_IND_STR) {
1335 size += arg.length + 2;
1336 } else {
1337 size += code_std_1 == 0 ? 1 : 2;
1338 if (arg.type != ARGTYPE_NONE)
1339 size += 1;
1340 }
1341 if (code_std_1 == 0xf2 && (code_std_2 & 0x80) == 0)
1342 /* Extra extension */
1343 size += 1;
1344 break;
1345 case 2:
1346 default:
1347 /* Illegal command */
1348 continue;
1349 }
1350 } while (cmd != CMD_END && pc < prgms[prgm_index].size);
1351 current_prgm = saved_prgm;
1352 return size;
1353 }
1354
1355 void core_export_programs(int count, const int *indexes, const char *raw_file_name) {
1356 if (raw_file_name != NULL) {
1357 #ifdef IPHONE
1358 if (strncmp(raw_file_name, "mem:", 4) == 0) {
1359 char *buf;
1360 ssize_t size;
1361 memcpy(&buf, raw_file_name + 5, sizeof(char *));
1362 memcpy(&size, raw_file_name + 13, sizeof(ssize_t));
1363 gfile = fmemopen(buf, size, "wb");
1364 } else {
1365 #endif
1366 gfile = my_fopen(raw_file_name, "wb");
1367 if (gfile == NULL) {
1368 char msg[1024];
1369 int err = errno;
1370 snprintf(msg, 1024, "Could not open \"%s\" for writing: %s (%d)", raw_file_name, strerror(err), err);
1371 shell_message(msg);
1372 return;
1373 }
1374 #ifdef IPHONE
1375 }
1376 #endif
1377 }
1378 for (int i = 0; i < count; i++) {
1379 int p = indexes[i];
1380 export_hp42s(p);
1381 }
1382 if (raw_file_name != NULL) {
1383 if (ferror(gfile))
1384 shell_message("An error occurred during program export.");
1385 fclose(gfile);
1386 }
1387 }
1388
1389 static int hp42tofree42[] = {
1390 /* Flag values: 0 = simple 1-byte command; 1 = 1-byte command with
1391 * embedded argument; 2 = 2-byte command, argument follows;
1392 * 3 = everything else, special case handling required.
1393 */
1394
1395 /* 00-0F */
1396 /* NULL, LBL 00-14 */
1397 CMD_NULL | 0x3000,
1398 CMD_LBL | 0x1000,
1399 CMD_LBL | 0x1000,
1400 CMD_LBL | 0x1000,
1401 CMD_LBL | 0x1000,
1402 CMD_LBL | 0x1000,
1403 CMD_LBL | 0x1000,
1404 CMD_LBL | 0x1000,
1405 CMD_LBL | 0x1000,
1406 CMD_LBL | 0x1000,
1407 CMD_LBL | 0x1000,
1408 CMD_LBL | 0x1000,
1409 CMD_LBL | 0x1000,
1410 CMD_LBL | 0x1000,
1411 CMD_LBL | 0x1000,
1412 CMD_LBL | 0x1000,
1413
1414 /* 10-1F */
1415 /* 0-9, ., E, -, GTO "", XEQ "", W "" */
1416 CMD_NULL | 0x3000,
1417 CMD_NULL | 0x3000,
1418 CMD_NULL | 0x3000,
1419 CMD_NULL | 0x3000,
1420 CMD_NULL | 0x3000,
1421 CMD_NULL | 0x3000,
1422 CMD_NULL | 0x3000,
1423 CMD_NULL | 0x3000,
1424 CMD_NULL | 0x3000,
1425 CMD_NULL | 0x3000,
1426 CMD_NULL | 0x3000,
1427 CMD_NULL | 0x3000,
1428 CMD_NULL | 0x3000,
1429 CMD_NULL | 0x3000,
1430 CMD_NULL | 0x3000,
1431 CMD_NULL | 0x3000,
1432
1433 /* 20-2F */
1434 /* RCL 00-15 */
1435 CMD_RCL | 0x1000,
1436 CMD_RCL | 0x1000,
1437 CMD_RCL | 0x1000,
1438 CMD_RCL | 0x1000,
1439 CMD_RCL | 0x1000,
1440 CMD_RCL | 0x1000,
1441 CMD_RCL | 0x1000,
1442 CMD_RCL | 0x1000,
1443 CMD_RCL | 0x1000,
1444 CMD_RCL | 0x1000,
1445 CMD_RCL | 0x1000,
1446 CMD_RCL | 0x1000,
1447 CMD_RCL | 0x1000,
1448 CMD_RCL | 0x1000,
1449 CMD_RCL | 0x1000,
1450 CMD_RCL | 0x1000,
1451
1452 /* 30-3F */
1453 /* STO 00-15 */
1454 CMD_STO | 0x1000,
1455 CMD_STO | 0x1000,
1456 CMD_STO | 0x1000,
1457 CMD_STO | 0x1000,
1458 CMD_STO | 0x1000,
1459 CMD_STO | 0x1000,
1460 CMD_STO | 0x1000,
1461 CMD_STO | 0x1000,
1462 CMD_STO | 0x1000,
1463 CMD_STO | 0x1000,
1464 CMD_STO | 0x1000,
1465 CMD_STO | 0x1000,
1466 CMD_STO | 0x1000,
1467 CMD_STO | 0x1000,
1468 CMD_STO | 0x1000,
1469 CMD_STO | 0x1000,
1470
1471 /* 40-4F */
1472 CMD_ADD | 0x0000,
1473 CMD_SUB | 0x0000,
1474 CMD_MUL | 0x0000,
1475 CMD_DIV | 0x0000,
1476 CMD_X_LT_Y | 0x0000,
1477 CMD_X_GT_Y | 0x0000,
1478 CMD_X_LE_Y | 0x0000,
1479 CMD_SIGMAADD | 0x0000,
1480 CMD_SIGMASUB | 0x0000,
1481 CMD_HMSADD | 0x0000,
1482 CMD_HMSSUB | 0x0000,
1483 CMD_MOD | 0x0000,
1484 CMD_PERCENT | 0x0000,
1485 CMD_PERCENT_CH | 0x0000,
1486 CMD_TO_REC | 0x0000,
1487 CMD_TO_POL | 0x0000,
1488
1489 /* 50-5F */
1490 CMD_LN | 0x0000,
1491 CMD_SQUARE | 0x0000,
1492 CMD_SQRT | 0x0000,
1493 CMD_Y_POW_X | 0x0000,
1494 CMD_CHS | 0x0000,
1495 CMD_E_POW_X | 0x0000,
1496 CMD_LOG | 0x0000,
1497 CMD_10_POW_X | 0x0000,
1498 CMD_E_POW_X_1 | 0x0000,
1499 CMD_SIN | 0x0000,
1500 CMD_COS | 0x0000,
1501 CMD_TAN | 0x0000,
1502 CMD_ASIN | 0x0000,
1503 CMD_ACOS | 0x0000,
1504 CMD_ATAN | 0x0000,
1505 CMD_TO_DEC | 0x0000,
1506
1507 /* 60-6F */
1508 CMD_INV | 0x0000,
1509 CMD_ABS | 0x0000,
1510 CMD_FACT | 0x0000,
1511 CMD_X_NE_0 | 0x0000,
1512 CMD_X_GT_0 | 0x0000,
1513 CMD_LN_1_X | 0x0000,
1514 CMD_X_LT_0 | 0x0000,
1515 CMD_X_EQ_0 | 0x0000,
1516 CMD_IP | 0x0000,
1517 CMD_FP | 0x0000,
1518 CMD_TO_RAD | 0x0000,
1519 CMD_TO_DEG | 0x0000,
1520 CMD_TO_HMS | 0x0000,
1521 CMD_TO_HR | 0x0000,
1522 CMD_RND | 0x0000,
1523 CMD_TO_OCT | 0x0000,
1524
1525 /* 70-7F */
1526 CMD_CLSIGMA | 0x0000,
1527 CMD_SWAP | 0x0000,
1528 CMD_PI | 0x0000,
1529 CMD_CLST | 0x0000,
1530 CMD_RUP | 0x0000,
1531 CMD_RDN | 0x0000,
1532 CMD_LASTX | 0x0000,
1533 CMD_CLX | 0x0000,
1534 CMD_X_EQ_Y | 0x0000,
1535 CMD_X_NE_Y | 0x0000,
1536 CMD_SIGN | 0x0000,
1537 CMD_X_LE_0 | 0x0000,
1538 CMD_MEAN | 0x0000,
1539 CMD_SDEV | 0x0000,
1540 CMD_AVIEW | 0x0000,
1541 CMD_CLD | 0x0000,
1542
1543 /* 80-8F */
1544 CMD_DEG | 0x0000,
1545 CMD_RAD | 0x0000,
1546 CMD_GRAD | 0x0000,
1547 CMD_ENTER | 0x0000,
1548 CMD_STOP | 0x0000,
1549 CMD_RTN | 0x0000,
1550 CMD_BEEP | 0x0000,
1551 CMD_CLA | 0x0000,
1552 CMD_ASHF | 0x0000,
1553 CMD_PSE | 0x0000,
1554 CMD_CLRG | 0x0000,
1555 CMD_AOFF | 0x0000,
1556 CMD_AON | 0x0000,
1557 CMD_OFF | 0x0000,
1558 CMD_PROMPT | 0x0000,
1559 CMD_ADV | 0x0000,
1560
1561 /* 90-9F */
1562 CMD_RCL | 0x2000,
1563 CMD_STO | 0x2000,
1564 CMD_STO_ADD | 0x2000,
1565 CMD_STO_SUB | 0x2000,
1566 CMD_STO_MUL | 0x2000,
1567 CMD_STO_DIV | 0x2000,
1568 CMD_ISG | 0x2000,
1569 CMD_DSE | 0x2000,
1570 CMD_VIEW | 0x2000,
1571 CMD_SIGMAREG | 0x2000,
1572 CMD_ASTO | 0x2000,
1573 CMD_ARCL | 0x2000,
1574 CMD_FIX | 0x2000,
1575 CMD_SCI | 0x2000,
1576 CMD_ENG | 0x2000,
1577 CMD_TONE | 0x2000,
1578
1579 /* A0-AF */
1580 /* XROM (+ 42S ext), GTO/XEQ IND, SPARE1 */
1581 CMD_NULL | 0x3000,
1582 CMD_NULL | 0x3000,
1583 CMD_NULL | 0x3000,
1584 CMD_NULL | 0x3000,
1585 CMD_NULL | 0x3000,
1586 CMD_NULL | 0x3000,
1587 CMD_NULL | 0x3000,
1588 CMD_NULL | 0x3000,
1589 CMD_SF | 0x2000,
1590 CMD_CF | 0x2000,
1591 CMD_FSC_T | 0x2000,
1592 CMD_FCC_T | 0x2000,
1593 CMD_FS_T | 0x2000,
1594 CMD_FC_T | 0x2000,
1595 CMD_NULL | 0x3000,
1596 CMD_NULL | 0x3000,
1597
1598 /* B0-BF */
1599 /* SPARE2, GTO 00-14 */
1600 CMD_NULL | 0x3000,
1601 CMD_NULL | 0x3000,
1602 CMD_NULL | 0x3000,
1603 CMD_NULL | 0x3000,
1604 CMD_NULL | 0x3000,
1605 CMD_NULL | 0x3000,
1606 CMD_NULL | 0x3000,
1607 CMD_NULL | 0x3000,
1608 CMD_NULL | 0x3000,
1609 CMD_NULL | 0x3000,
1610 CMD_NULL | 0x3000,
1611 CMD_NULL | 0x3000,
1612 CMD_NULL | 0x3000,
1613 CMD_NULL | 0x3000,
1614 CMD_NULL | 0x3000,
1615 CMD_NULL | 0x3000,
1616
1617 /* C0-CF */
1618 /* GLOBAL */
1619 CMD_NULL | 0x3000,
1620 CMD_NULL | 0x3000,
1621 CMD_NULL | 0x3000,
1622 CMD_NULL | 0x3000,
1623 CMD_NULL | 0x3000,
1624 CMD_NULL | 0x3000,
1625 CMD_NULL | 0x3000,
1626 CMD_NULL | 0x3000,
1627 CMD_NULL | 0x3000,
1628 CMD_NULL | 0x3000,
1629 CMD_NULL | 0x3000,
1630 CMD_NULL | 0x3000,
1631 CMD_NULL | 0x3000,
1632 CMD_NULL | 0x3000,
1633 CMD_X_SWAP | 0x2000,
1634 CMD_LBL | 0x2000,
1635
1636 /* D0-DF */
1637 /* 3-byte GTO */
1638 CMD_NULL | 0x3000,
1639 CMD_NULL | 0x3000,
1640 CMD_NULL | 0x3000,
1641 CMD_NULL | 0x3000,
1642 CMD_NULL | 0x3000,
1643 CMD_NULL | 0x3000,
1644 CMD_NULL | 0x3000,
1645 CMD_NULL | 0x3000,
1646 CMD_NULL | 0x3000,
1647 CMD_NULL | 0x3000,
1648 CMD_NULL | 0x3000,
1649 CMD_NULL | 0x3000,
1650 CMD_NULL | 0x3000,
1651 CMD_NULL | 0x3000,
1652 CMD_NULL | 0x3000,
1653 CMD_NULL | 0x3000,
1654
1655 /* E0-EF */
1656 /* 3-byte XEQ */
1657 CMD_NULL | 0x3000,
1658 CMD_NULL | 0x3000,
1659 CMD_NULL | 0x3000,
1660 CMD_NULL | 0x3000,
1661 CMD_NULL | 0x3000,
1662 CMD_NULL | 0x3000,
1663 CMD_NULL | 0x3000,
1664 CMD_NULL | 0x3000,
1665 CMD_NULL | 0x3000,
1666 CMD_NULL | 0x3000,
1667 CMD_NULL | 0x3000,
1668 CMD_NULL | 0x3000,
1669 CMD_NULL | 0x3000,
1670 CMD_NULL | 0x3000,
1671 CMD_NULL | 0x3000,
1672 CMD_NULL | 0x3000,
1673
1674 /* F0-FF */
1675 /* Strings + 42S ext */
1676 CMD_NOP | 0x0000,
1677 CMD_NULL | 0x3000,
1678 CMD_NULL | 0x3000,
1679 CMD_NULL | 0x3000,
1680 CMD_NULL | 0x3000,
1681 CMD_NULL | 0x3000,
1682 CMD_NULL | 0x3000,
1683 CMD_NULL | 0x3000,
1684 CMD_NULL | 0x3000,
1685 CMD_NULL | 0x3000,
1686 CMD_NULL | 0x3000,
1687 CMD_NULL | 0x3000,
1688 CMD_NULL | 0x3000,
1689 CMD_NULL | 0x3000,
1690 CMD_NULL | 0x3000,
1691 CMD_NULL | 0x3000
1692 };
1693
1694 static int hp42ext[] = {
1695 /* Flag values: 0 = string, 1 = IND string, 2 = suffix, 3 = special,
1696 * 4 = illegal
1697 * Values 80-ff are the space used on the HP-42S, that is, strings whose
1698 * first character has its high bit set. Since the gaps left in that
1699 * scheme ran out when development of Plus42 started, additional
1700 * extensions had to be defined, and they are encoded using a7 as the
1701 * first character, and the opcode in the second character. By keeping
1702 * that second-character opcode in the range 00-7f, we can still
1703 * use a single byte lookup for all these extensions.
1704 */
1705
1706 /* 00-0F */
1707 CMD_NULL | 0x4000,
1708 CMD_XASTO | 0x0000,
1709 CMD_LXASTO | 0x0000,
1710 CMD_HEAD | 0x0000,
1711 CMD_X_EQ_NN | 0x0000,
1712 CMD_X_NE_NN | 0x0000,
1713 CMD_X_LT_NN | 0x0000,
1714 CMD_X_GT_NN | 0x0000,
1715 CMD_NULL | 0x4000,
1716 CMD_XASTO | 0x1000,
1717 CMD_LXASTO | 0x1000,
1718 CMD_HEAD | 0x1000,
1719 CMD_X_EQ_NN | 0x1000,
1720 CMD_X_NE_NN | 0x1000,
1721 CMD_X_LT_NN | 0x1000,
1722 CMD_X_GT_NN | 0x1000,
1723
1724 /* 10-1F */
1725 CMD_NULL | 0x4000,
1726 CMD_XASTO | 0x2000,
1727 CMD_LXASTO | 0x2000,
1728 CMD_HEAD | 0x2000,
1729 CMD_X_EQ_NN | 0x2000,
1730 CMD_X_NE_NN | 0x2000,
1731 CMD_X_LT_NN | 0x2000,
1732 CMD_X_GT_NN | 0x2000,
1733 CMD_X_LE_NN | 0x2000,
1734 CMD_X_GE_NN | 0x2000,
1735 CMD_0_EQ_NN | 0x2000,
1736 CMD_0_NE_NN | 0x2000,
1737 CMD_0_LT_NN | 0x2000,
1738 CMD_0_GT_NN | 0x2000,
1739 CMD_0_LE_NN | 0x2000,
1740 CMD_0_GE_NN | 0x2000,
1741
1742 /* 20-2F */
1743 CMD_X_LE_NN | 0x0000,
1744 CMD_X_GE_NN | 0x0000,
1745 CMD_0_EQ_NN | 0x0000,
1746 CMD_0_NE_NN | 0x0000,
1747 CMD_0_LT_NN | 0x0000,
1748 CMD_0_GT_NN | 0x0000,
1749 CMD_0_LE_NN | 0x0000,
1750 CMD_0_GE_NN | 0x0000,
1751 CMD_X_LE_NN | 0x1000,
1752 CMD_X_GE_NN | 0x1000,
1753 CMD_0_EQ_NN | 0x1000,
1754 CMD_0_NE_NN | 0x1000,
1755 CMD_0_LT_NN | 0x1000,
1756 CMD_0_GT_NN | 0x1000,
1757 CMD_0_LE_NN | 0x1000,
1758 CMD_0_GE_NN | 0x1000,
1759
1760 /* 30-3F */
1761 CMD_PGMVAR | 0x2000,
1762 CMD_VARMNU1 | 0x2000,
1763 CMD_NULL | 0x4000,
1764 CMD_NULL | 0x4000,
1765 CMD_NULL | 0x4000,
1766 CMD_NULL | 0x4000,
1767 CMD_NULL | 0x4000,
1768 CMD_NULL | 0x4000,
1769 CMD_NULL | 0x4000,
1770 CMD_NULL | 0x4000,
1771 CMD_NULL | 0x4000,
1772 CMD_NULL | 0x4000,
1773 CMD_NULL | 0x4000,
1774 CMD_NULL | 0x4000,
1775 CMD_NULL | 0x4000,
1776 CMD_NULL | 0x4000,
1777
1778 /* 40-4F */
1779 CMD_PGMVAR | 0x0000,
1780 CMD_XSTR | 0x0000,
1781 CMD_VARMNU1 | 0x0000,
1782 CMD_NULL | 0x4000,
1783 CMD_NULL | 0x4000,
1784 CMD_NULL | 0x4000,
1785 CMD_NULL | 0x4000,
1786 CMD_NULL | 0x4000,
1787 CMD_PGMVAR | 0x1000,
1788 CMD_XSTR | 0x1000,
1789 CMD_VARMNU1 | 0x1000,
1790 CMD_NULL | 0x4000,
1791 CMD_NULL | 0x4000,
1792 CMD_NULL | 0x4000,
1793 CMD_NULL | 0x4000,
1794 CMD_NULL | 0x4000,
1795
1796 /* 50-5F */
1797 CMD_NULL | 0x4000,
1798 CMD_NULL | 0x4000,
1799 CMD_NULL | 0x4000,
1800 CMD_NULL | 0x4000,
1801 CMD_NULL | 0x4000,
1802 CMD_NULL | 0x4000,
1803 CMD_NULL | 0x4000,
1804 CMD_NULL | 0x4000,
1805 CMD_NULL | 0x4000,
1806 CMD_NULL | 0x4000,
1807 CMD_NULL | 0x4000,
1808 CMD_NULL | 0x4000,
1809 CMD_NULL | 0x4000,
1810 CMD_NULL | 0x4000,
1811 CMD_NULL | 0x4000,
1812 CMD_NULL | 0x4000,
1813
1814 /* 60-6F */
1815 CMD_NULL | 0x4000,
1816 CMD_NULL | 0x4000,
1817 CMD_NULL | 0x4000,
1818 CMD_NULL | 0x4000,
1819 CMD_LCLV | 0x2000,
1820 CMD_GETMI | 0x2000,
1821 CMD_PUTMI | 0x2000,
1822 CMD_GETLI | 0x2000,
1823 CMD_PUTLI | 0x2000,
1824 CMD_NULL | 0x4000,
1825 CMD_NULL | 0x4000,
1826 CMD_NULL | 0x4000,
1827 CMD_NULL | 0x4000,
1828 CMD_NULL | 0x4000,
1829 CMD_NULL | 0x4000,
1830 CMD_NULL | 0x4000,
1831
1832 /* 70-7F */
1833 CMD_NULL | 0x4000,
1834 CMD_LCLV | 0x0000,
1835 CMD_GETMI | 0x0000,
1836 CMD_PUTMI | 0x0000,
1837 CMD_GETLI | 0x0000,
1838 CMD_PUTLI | 0x0000,
1839 CMD_NULL | 0x4000,
1840 CMD_NULL | 0x4000,
1841 CMD_NULL | 0x4000,
1842 CMD_LCLV | 0x1000,
1843 CMD_GETMI | 0x1000,
1844 CMD_PUTMI | 0x1000,
1845 CMD_GETLI | 0x1000,
1846 CMD_PUTLI | 0x1000,
1847 CMD_NULL | 0x4000,
1848 CMD_NULL | 0x4000,
1849
1850 /* 80-8F */
1851 CMD_VIEW | 0x0000,
1852 CMD_STO | 0x0000,
1853 CMD_STO_ADD | 0x0000,
1854 CMD_STO_SUB | 0x0000,
1855 CMD_STO_MUL | 0x0000,
1856 CMD_STO_DIV | 0x0000,
1857 CMD_X_SWAP | 0x0000,
1858 CMD_INDEX | 0x0000,
1859 CMD_VIEW | 0x1000,
1860 CMD_STO | 0x1000,
1861 CMD_STO_ADD | 0x1000,
1862 CMD_STO_SUB | 0x1000,
1863 CMD_STO_MUL | 0x1000,
1864 CMD_STO_DIV | 0x1000,
1865 CMD_X_SWAP | 0x1000,
1866 CMD_INDEX | 0x1000,
1867
1868 /* 90-9F */
1869 CMD_MVAR | 0x0000,
1870 CMD_RCL | 0x0000,
1871 CMD_RCL_ADD | 0x0000,
1872 CMD_RCL_SUB | 0x0000,
1873 CMD_RCL_MUL | 0x0000,
1874 CMD_RCL_DIV | 0x0000,
1875 CMD_ISG | 0x0000,
1876 CMD_DSE | 0x0000,
1877 CMD_MVAR | 0x1000,
1878 CMD_RCL | 0x1000,
1879 CMD_RCL_ADD | 0x1000,
1880 CMD_RCL_SUB | 0x1000,
1881 CMD_RCL_MUL | 0x1000,
1882 CMD_RCL_DIV | 0x1000,
1883 CMD_ISG | 0x1000,
1884 CMD_DSE | 0x1000,
1885
1886 /* A0-AF */
1887 CMD_RTNERR | 0x2000,
1888 CMD_DROPN | 0x2000,
1889 CMD_DUPN | 0x2000,
1890 CMD_PICK | 0x2000,
1891 CMD_UNPICK | 0x2000,
1892 CMD_RDNN | 0x2000,
1893 CMD_RUPN | 0x2000,
1894 CMD_NULL | 0x3000, /* Extra extensions */
1895 CMD_SF | 0x1000,
1896 CMD_CF | 0x1000,
1897 CMD_FSC_T | 0x1000,
1898 CMD_FCC_T | 0x1000,
1899 CMD_FS_T | 0x1000,
1900 CMD_FC_T | 0x1000,
1901 CMD_GTO | 0x1000,
1902 CMD_XEQ | 0x1000,
1903
1904 /* B0-BF */
1905 CMD_CLV | 0x0000,
1906 CMD_PRV | 0x0000,
1907 CMD_ASTO | 0x0000,
1908 CMD_ARCL | 0x0000,
1909 CMD_PGMINT | 0x0000,
1910 CMD_PGMSLV | 0x0000,
1911 CMD_INTEG | 0x0000,
1912 CMD_SOLVE | 0x0000,
1913 CMD_CLV | 0x1000,
1914 CMD_PRV | 0x1000,
1915 CMD_ASTO | 0x1000,
1916 CMD_ARCL | 0x1000,
1917 CMD_PGMINT | 0x1000,
1918 CMD_PGMSLV | 0x1000,
1919 CMD_INTEG | 0x1000,
1920 CMD_SOLVE | 0x1000,
1921
1922 /* CO-CF */
1923 CMD_NULL | 0x3000, /* ASSIGN */
1924 CMD_VARMENU | 0x0000,
1925 CMD_NULL | 0x3000, /* KEYX name */
1926 CMD_NULL | 0x3000, /* KEYG name */
1927 CMD_DIM | 0x0000,
1928 CMD_INPUT | 0x0000,
1929 CMD_EDITN | 0x0000,
1930 CMD_LSTO | 0x0000,
1931 CMD_LASTO | 0x2000,
1932 CMD_VARMENU | 0x1000,
1933 CMD_NULL | 0x3000, /* KEYX IND name */
1934 CMD_NULL | 0x3000, /* KEYG IND name */
1935 CMD_DIM | 0x1000,
1936 CMD_INPUT | 0x1000,
1937 CMD_EDITN | 0x1000,
1938 CMD_LSTO | 0x1000,
1939
1940 /* DO-DF */
1941 CMD_INPUT | 0x2000,
1942 CMD_RCL_ADD | 0x2000,
1943 CMD_RCL_SUB | 0x2000,
1944 CMD_RCL_MUL | 0x2000,
1945 CMD_RCL_DIV | 0x2000,
1946 CMD_NULL | 0x4000, /* FIX 10 */
1947 CMD_NULL | 0x4000, /* SCI 10 */
1948 CMD_NULL | 0x4000, /* ENG 10 */
1949 CMD_CLV | 0x2000,
1950 CMD_PRV | 0x2000,
1951 CMD_INDEX | 0x2000,
1952 CMD_SIGMAREG | 0x1000,
1953 CMD_FIX | 0x1000,
1954 CMD_SCI | 0x1000,
1955 CMD_ENG | 0x1000,
1956 CMD_TONE | 0x1000,
1957
1958 /* E0-EF */
1959 CMD_FUNC | 0x2000,
1960 CMD_NULL | 0x4000,
1961 CMD_NULL | 0x3000, /* KEYX suffix */
1962 CMD_NULL | 0x3000, /* KEYG suffix */
1963 CMD_RTNERR | 0x1000,
1964 CMD_NULL | 0x4000, /* FIX 11 */
1965 CMD_NULL | 0x4000, /* SCI 11 */
1966 CMD_NULL | 0x4000, /* ENG 11 */
1967 CMD_PGMINT | 0x2000,
1968 CMD_PGMSLV | 0x2000,
1969 CMD_INTEG | 0x2000,
1970 CMD_SOLVE | 0x2000,
1971 CMD_DIM | 0x2000,
1972 CMD_LSTO | 0x2000,
1973 CMD_INPUT | 0x2000,
1974 CMD_EDITN | 0x2000,
1975
1976 /* F0-FF */
1977 CMD_CLP | 0x0000,
1978 CMD_NULL | 0x4000, /* XFCN */
1979 CMD_NULL | 0x4000, /* GTO . nnnn */
1980 CMD_NULL | 0x4000, /* GTO .. */
1981 CMD_NULL | 0x4000, /* GTO . "name" */
1982 CMD_LASTO | 0x0000,
1983 CMD_NULL | 0x4000, /* DEL */
1984 CMD_NULL | 0x3000, /* SIZE */
1985 CMD_VARMENU | 0x2000,
1986 CMD_DROPN | 0x1000,
1987 CMD_DUPN | 0x1000,
1988 CMD_PICK | 0x1000,
1989 CMD_UNPICK | 0x1000,
1990 CMD_LASTO | 0x1000,
1991 CMD_RDNN | 0x1000,
1992 CMD_RUPN | 0x1000
1993 };
1994
1995
1996 static bool looks_like_zero(const char *buf) {
1997 char c;
1998 while ((c = *buf++) != 0) {
1999 if (c >= '1' && c <= '9')
2000 return false;
2001 if (c == 'E')
2002 return true;
2003 }
2004 return true;
2005 }
2006
2007 static bool parse_number_line(char *buf, phloat *res) {
2008 if (buf[0] == 'E' || buf[0] == '-' && buf[1] == 'E') {
2009 char *buf2 = (char *) malloc(strlen(buf) + 2);
2010 strcpy(buf2 + 1, buf);
2011 if (buf[0] == 'E') {
2012 buf2[0] = '1';
2013 } else {
2014 buf2[0] = '-';
2015 buf2[1] = '1';
2016 }
2017 int len2 = (int) strlen(buf2);
2018 if (buf2[len2 - 1] == 'E')
2019 buf2[len2 - 1] = 0;
2020 bool success = parse_number_line(buf2, res);
2021 free(buf2);
2022 return success;
2023 }
2024
2025 /* This isn't very thorough, but the aim is simply to prevent things
2026 * that start with a valid number character but are clearly not valid
2027 * numbers from being accepted as number lines. Things like the Plus42
2028 * EQNSLV command, for instance, or numbers with attached text like
2029 * 10_ft or 20five.
2030 */
2031 bool seen_e = false;
2032 for (char *cp = buf; *cp != 0; cp++) {
2033 char c = *cp;
2034 if (seen_e && (c == 'E' || c == '.'))
2035 return false;
2036 if (c == 'E')
2037 seen_e = true;
2038 else if ((c < '0' || c > '9') && c != '.' && c != '+' && c != '-')
2039 return false;
2040 }
2041
2042 #ifdef BCD_MATH
2043 *res = Phloat(buf);
2044 #else
2045 BID_UINT128 d;
2046 bid128_from_string(&d, buf);
2047 bid128_to_binary64(res, &d);
2048 #endif
2049 if (p_isinf(*res) != 0)
2050 *res = NAN_1_PHLOAT;
2051 else if (*res == 0 && !looks_like_zero(buf))
2052 *res = NAN_2_PHLOAT;
2053 return true;
2054 }
2055
2056 static void decode_xrom(int byte1, int byte2, int *cmd, arg_struct *arg) {
2057 /* XROM & parameterless HP-42S extensions.
2058 * I don't want to build a reverse look-up table
2059 * for these, so instead I just do a linear search
2060 * on the cmd_array table.
2061 */
2062 uint4 code = (((unsigned int) byte1) << 8) | byte2;
2063 if (code >= 0x0a679 && code <= 0x0a67e) {
2064 /* HP-41CX: X=NN? etc. */
2065 switch (code & 0xf) {
2066 case 0x9: *cmd = CMD_X_EQ_NN; break;
2067 case 0xa: *cmd = CMD_X_NE_NN; break;
2068 case 0xb: *cmd = CMD_X_LT_NN; break;
2069 case 0xc: *cmd = CMD_X_LE_NN; break;
2070 case 0xd: *cmd = CMD_X_GT_NN; break;
2071 case 0xe: *cmd = CMD_X_GE_NN; break;
2072 }
2073 arg->type = ARGTYPE_IND_STK;
2074 arg->val.stk = 'Y';
2075 return;
2076 }
2077 for (int i = 0; i < CMD_SENTINEL; i++)
2078 if (cmd_array[i].code1 == byte1 && cmd_array[i].code2 == byte2) {
2079 if ((cmd_array[i].flags & FLAG_HIDDEN) != 0)
2080 break;
2081 *cmd = i;
2082 arg->type = ARGTYPE_NONE;
2083 return;
2084 }
2085 /* Not found; insert XROM instruction */
2086 *cmd = CMD_XROM;
2087 arg->type = ARGTYPE_NUM;
2088 arg->val.num = code & 0x07ff;
2089 }
2090
2091 static void decode_suffix(int cmd, int suffix, arg_struct *arg) {
2092 bool ind = (suffix & 0x80) != 0;
2093 suffix &= 0x7f;
2094 if (!ind && (cmd == CMD_LBL || cmd == CMD_GTO || cmd == CMD_XEQ
2095 || cmd >= CMD_KEY1G && cmd <= CMD_KEY9X)
2096 && suffix >= 102 && suffix <= 111) {
2097 arg->type = ARGTYPE_LCLBL;
2098 arg->val.lclbl = 'A' + (suffix - 102);
2099 } else if (!ind && (cmd == CMD_LBL || cmd == CMD_GTO || cmd == CMD_XEQ
2100 || cmd >= CMD_KEY1G && cmd <= CMD_KEY9X)
2101 && suffix >= 123) {
2102 arg->type = ARGTYPE_LCLBL;
2103 arg->val.lclbl = 'a' + (suffix - 123);
2104 } else if (suffix >= 112 && suffix <= 116) {
2105 arg->type = ind ? ARGTYPE_IND_STK : ARGTYPE_STK;
2106 switch (suffix) {
2107 case 112: arg->val.stk = 'T'; break;
2108 case 113: arg->val.stk = 'Z'; break;
2109 case 114: arg->val.stk = 'Y'; break;
2110 case 115: arg->val.stk = 'X'; break;
2111 case 116: arg->val.stk = 'L'; break;
2112 }
2113 } else {
2114 arg->type = ind ? ARGTYPE_IND_NUM : ARGTYPE_NUM;
2115 arg->val.num = suffix;
2116 }
2117 }
2118
2119 static void decode_string(unsigned char *buf, int *cmd, arg_struct *arg, char **xstr_buf, int *xstr_len) {
2120 int pos = 0;
2121 int byte1 = buf[pos++];
2122 int byte2 = buf[pos++];
2123 int str_len = 0;
2124 bool extra_extension = false;
2125 bool assign = false;
2126
2127 if ((byte2 & 0x80) == 0) {
2128 /* String */
2129 int i;
2130 *cmd = CMD_STRING;
2131 goto string_2;
2132 xrom_string:
2133 *cmd = CMD_XROM;
2134 string_2:
2135 str_len = byte1 - 0xf0;
2136 pos--;
2137 arg->type = ARGTYPE_STR;
2138 do_string:
2139 for (i = 0; i < str_len; i++)
2140 arg->val.text[i] = buf[pos++];
2141 if (extra_extension) {
2142 memmove(arg->val.text + 1, arg->val.text, str_len);
2143 arg->val.text[0] = (char) 0xa7;
2144 str_len++;
2145 }
2146 arg->length = str_len;
2147 if (assign) {
2148 assign = false;
2149 int key = buf[pos++];
2150 if (key > 17) {
2151 /* Bad assign... Fix the command to the string
2152 * it would have been if I had known this
2153 * earlier.
2154 */
2155 for (i = arg->length; i > 0; i--)
2156 arg->val.text[i] = arg->val.text[i - 1];
2157 arg->val.text[0] = (char) 0xc0;
2158 arg->val.text[arg->length + 1] = key;
2159 arg->length += 2;
2160 } else {
2161 *cmd += key;
2162 }
2163 }
2164 if (*cmd == CMD_XSTR) {
2165 // XSTR is stored as a sequence of instructions, since
2166 // it may encode a string of up to 65535 characters, while
2167 // instructions are limited to 16 bytes, giving a payload
2168 // of up to 13 characters per instruction.
2169 char *newbuf = (char *) realloc(*xstr_buf, *xstr_len + arg->length);
2170 if (newbuf == NULL && *xstr_len + arg->length != 0) {
2171 *cmd = CMD_CANCELLED;
2172 return;
2173 }
2174 *xstr_buf = newbuf;
2175 memcpy(*xstr_buf + *xstr_len, arg->val.text, arg->length);
2176 *xstr_len += arg->length;
2177 if (arg->type == ARGTYPE_IND_STR) {
2178 *cmd = CMD_NONE;
2179 return;
2180 }
2181 arg->type = ARGTYPE_XSTR;
2182 arg->length = *xstr_len;
2183 arg->val.xstr = *xstr_buf;
2184 }
2185 } else {
2186 /* Parameterized HP-42S extension */
2187 if (byte1 == 0xf1) {
2188 switch (byte2) {
2189 case 0xd5: *cmd = CMD_FIX; arg->val.num = 10; break;
2190 case 0xd6: *cmd = CMD_SCI; arg->val.num = 10; break;
2191 case 0xd7: *cmd = CMD_ENG; arg->val.num = 10; break;
2192 case 0xe5: *cmd = CMD_FIX; arg->val.num = 11; break;
2193 case 0xe6: *cmd = CMD_SCI; arg->val.num = 11; break;
2194 case 0xe7: *cmd = CMD_ENG; arg->val.num = 11; break;
2195 default: goto xrom_string;
2196 }
2197 arg->type = ARGTYPE_NUM;
2198 return;
2199 }
2200 if (byte2 == 0xa7) {
2201 byte2 = buf[pos++];
2202 byte1--;
2203 extra_extension = true;
2204 }
2205 *cmd = hp42ext[byte2];
2206 int flag = *cmd >> 12;
2207 *cmd &= 0x0fff;
2208 if (flag == 0 || flag == 1) {
2209 arg->type = flag == 0 ? ARGTYPE_STR
2210 : ARGTYPE_IND_STR;
2211 str_len = byte1 - 0xf1;
2212 extra_extension = false;
2213 goto do_string;
2214 } else if (flag == 2) {
2215 if (byte1 != 0xf2)
2216 goto xrom_string;
2217 int suffix = buf[pos++];
2218 decode_suffix(*cmd, suffix, arg);
2219 } else if (flag == 3) {
2220 int key;
2221 if (byte2 == 0xc0) {
2222 /* ASSIGN */
2223 str_len = byte1 - 0xf2;
2224 assign = 1;
2225 *cmd = CMD_ASGN01;
2226 arg->type = ARGTYPE_STR;
2227 goto do_string;
2228 } else if (byte2 == 0xc2 || byte2 == 0xc3
2229 || byte2 == 0xca || byte2 == 0xcb) {
2230 /* KEYG/KEYX name, KEYG/KEYX IND name */
2231 str_len = byte1 - 0xf2;
2232 if (str_len == 0)
2233 goto xrom_string;
2234 *cmd = byte2 == 0xc2 || byte2 == 0xca
2235 ? CMD_KEY1X : CMD_KEY1G;
2236 key = buf[pos++];
2237 if (key < 1 || key > 9) {
2238 /* Treat as plain string. Alas, it is
2239 * not safe to back up 2 positions, so
2240 * I do the whole thing here.
2241 */
2242 int i;
2243 bad_keyg_keyx:
2244 *cmd = CMD_STRING;
2245 arg->type = ARGTYPE_STR;
2246 arg->length = str_len + 2;
2247 arg->val.text[0] = byte2;
2248 arg->val.text[1] = key;
2249 for (i = 2; i < arg->length; i++)
2250 arg->val.text[i] = buf[pos++];
2251 return;
2252 }
2253 *cmd += key - 1;
2254 arg->type = byte2 == 0xc2 || byte2 == 0xc3
2255 ? ARGTYPE_STR : ARGTYPE_IND_STR;
2256 goto do_string;
2257 } else if (byte2 == 0xe2 || byte2 == 0xe3) {
2258 /* KEYG/KEYX suffix */
2259 if (byte1 != 0xf3)
2260 goto xrom_string;
2261 key = buf[pos++];
2262 if (key < 1 || key > 9)
2263 goto bad_keyg_keyx;
2264 *cmd = byte2 == 0xe2 ? CMD_KEY1X : CMD_KEY1G;
2265 *cmd += key - 1;
2266 int suffix = buf[pos++];
2267 decode_suffix(*cmd, suffix, arg);
2268 } else /* byte2 == 0xf7 */ {
2269 /* SIZE */
2270 if (byte1 != 0xf3)
2271 goto xrom_string;
2272 int hi = buf[pos++];
2273 int lo = buf[pos++];
2274 int sz = (hi << 8) | lo;
2275 *cmd = CMD_SIZE;
2276 arg->type = ARGTYPE_NUM;
2277 arg->val.num = sz;
2278 }
2279 } else /* flag == 4 */ {
2280 /* Unknown value; store as string XROM */
2281 goto xrom_string;
2282 }
2283 }
2284 }
2285
2286 void core_import_programs(int num_progs, const char *raw_file_name) {
2287 int byte1, byte2, suffix;
2288 int cmd, flag, str_len;
2289 int done_flag = 0;
2290 arg_struct arg;
2291 bool pending_end;
2292
2293 if (raw_file_name != NULL) {
2294 #ifdef IPHONE
2295 if (strncmp(raw_file_name, "mem:", 4) == 0) {
2296 char *buf;
2297 ssize_t size;
2298 memcpy(&buf, raw_file_name + 5, sizeof(char *));
2299 memcpy(&size, raw_file_name + 13, sizeof(ssize_t));
2300 gfile = fmemopen(buf, size, "rb");
2301 } else {
2302 #endif
2303 gfile = my_fopen(raw_file_name, "rb");
2304 if (gfile == NULL) {
2305 char msg[1024];
2306 int err = errno;
2307 snprintf(msg, 1024, "Could not open \"%s\" for reading: %s (%d)", raw_file_name, strerror(err), err);
2308 shell_message(msg);
2309 return;
2310 }
2311 #ifdef IPHONE
2312 }
2313 #endif
2314 }
2315
2316 set_running(false);
2317
2318 /* Set print mode to MAN during the import, to prevent store_command()
2319 * from printing programs as they load
2320 */
2321 int saved_trace = flags.f.trace_print;
2322 int saved_normal = flags.f.normal_print;
2323 flags.f.trace_print = 0;
2324 flags.f.normal_print = 0;
2325
2326 if (num_progs > 0) {
2327 // Loading state file
2328 goto_dot_dot(true);
2329 pending_end = false;
2330 } else {
2331 current_prgm = prgms_count - 1;
2332 pc = prgms[current_prgm].size - 2;
2333 // No initial END needed if last program is empty
2334 pending_end = pc > 0;
2335 }
2336
2337 char numbuf[50];
2338 char *xstr_buf = NULL;
2339 int xstr_len = 0;
2340
2341 while (!done_flag) {
2342 skip:
2343 byte1 = fgetc(gfile);
2344 if (byte1 == EOF)
2345 goto done;
2346 cmd = hp42tofree42[byte1];
2347 flag = cmd >> 12;
2348 cmd &= 0x0fff;
2349 if (flag == 0) {
2350 arg.type = ARGTYPE_NONE;
2351 } else if (flag == 1) {
2352 arg.type = ARGTYPE_NUM;
2353 arg.val.num = byte1 & 15;
2354 if (cmd == CMD_LBL)
2355 arg.val.num--;
2356 } else if (flag == 2) {
2357 suffix = fgetc(gfile);
2358 if (suffix == EOF)
2359 goto done;
2360 decode_suffix(cmd, suffix, &arg);
2361 } else /* flag == 3 */ {
2362 if (byte1 == 0x00)
2363 /* NULL */
2364 goto skip;
2365 else if (byte1 >= 0x10 && byte1 <= 0x1c) {
2366 /* Number */
2367 int numlen = 0;
2368 do {
2369 if (byte1 == 0x1a)
2370 byte1 = '.';
2371 else if (byte1 == 0x1b)
2372 byte1 = 'E';
2373 else if (byte1 == 0x1c)
2374 byte1 = '-';
2375 else
2376 byte1 += '0' - 0x10;
2377 numbuf[numlen++] = byte1;
2378 byte1 = fgetc(gfile);
2379 } while (byte1 >= 0x10 && byte1 <= 0x1c);
2380 if (byte1 == EOF)
2381 done_flag = 1;
2382 else if (byte1 != 0x00)
2383 ungetc(byte1, gfile);
2384 numbuf[numlen++] = 0;
2385 parse_number_line(numbuf, &arg.val_d);
2386 cmd = CMD_NUMBER;
2387 arg.type = ARGTYPE_DOUBLE;
2388 } else if (byte1 == 0x1d || byte1 == 0x1e) {
2389 cmd = byte1 == 0x1d ? CMD_GTO : CMD_XEQ;
2390 str_len = fgetc(gfile);
2391 if (str_len == EOF)
2392 goto done;
2393 else if (str_len < 0xf1) {
2394 ungetc(str_len, gfile);
2395 goto skip;
2396 } else
2397 str_len -= 0xf0;
2398 arg.type = ARGTYPE_STR;
2399 do_string:
2400 for (int i = 0; i < str_len; i++) {
2401 suffix = fgetc(gfile);
2402 if (suffix == EOF)
2403 goto done;
2404 arg.val.text[i] = suffix;
2405 }
2406 arg.length = str_len;
2407 } else if (byte1 == 0x1f) {
2408 /* "W" function (see HP-41C instruction table */
2409 goto skip;
2410 } else if (byte1 >= 0xa0 && byte1 <= 0xa7) {
2411 /* XROM mm,nn */
2412 byte2 = fgetc(gfile);
2413 if (byte2 == EOF)
2414 goto done;
2415 decode_xrom(byte1, byte2, &cmd, &arg);
2416 } else if (byte1 == 0xae) {
2417 /* GTO/XEQ IND */
2418 suffix = fgetc(gfile);
2419 if (suffix == EOF)
2420 goto done;
2421 if ((suffix & 0x80) != 0)
2422 cmd = CMD_XEQ;
2423 else {
2424 cmd = CMD_GTO;
2425 suffix |= 0x80;
2426 }
2427 decode_suffix(cmd, suffix, &arg);
2428 } else if (byte1 == 0xaf || byte1 == 0xb0) {
2429 /* SPARE functions (see HP-41C instruction table */
2430 goto skip;
2431 } else if (byte1 >= 0xb1 && byte1 <= 0xbf) {
2432 /* 2-byte GTO */
2433 byte2 = fgetc(gfile);
2434 if (byte2 == EOF)
2435 goto done;
2436 cmd = CMD_GTO;
2437 arg.type = ARGTYPE_NUM;
2438 arg.val.num = (byte1 & 15) - 1;
2439 } else if (byte1 >= 0xc0 && byte1 <= 0xcd) {
2440 /* GLOBAL */
2441 byte2 = fgetc(gfile);
2442 if (byte2 == EOF)
2443 goto done;
2444 str_len = fgetc(gfile);
2445 if (str_len == EOF)
2446 goto done;
2447 if (str_len < 0xf1) {
2448 /* END */
2449 cmd = CMD_END;
2450 arg.type = ARGTYPE_NONE;
2451 } else {
2452 /* LBL "" */
2453 str_len -= 0xf1;
2454 byte2 = fgetc(gfile);
2455 if (byte2 == EOF)
2456 goto done;
2457 cmd = CMD_LBL;
2458 arg.type = ARGTYPE_STR;
2459 goto do_string;
2460 }
2461 } else if (byte1 >= 0xd0 && byte1 <= 0xef) {
2462 /* 3-byte GTO & XEQ */
2463 byte2 = fgetc(gfile);
2464 if (byte2 == EOF)
2465 goto done;
2466 suffix = fgetc(gfile);
2467 if (suffix == EOF)
2468 goto done;
2469 cmd = byte1 <= 0xdf ? CMD_GTO : CMD_XEQ;
2470 suffix &= 0x7f;
2471 decode_suffix(cmd, suffix, &arg);
2472 } else /* byte1 >= 0xf1 && byte1 <= 0xff */ {
2473 /* Strings and parameterized HP-42S extensions */
2474 unsigned char buf[16];
2475 buf[0] = byte1;
2476 str_len = byte1 - 0xf0;
2477 for (int i = 0; i < str_len; i++) {
2478 int c = fgetc(gfile);
2479 if (c == EOF)
2480 goto done;
2481 buf[i + 1] = c;
2482 }
2483 decode_string(buf, &cmd, &arg, &xstr_buf, &xstr_len);
2484 if (cmd == CMD_CANCELLED)
2485 goto done;
2486 if (cmd == CMD_NONE)
2487 continue;
2488 }
2489 }
2490 if (pending_end) {
2491 goto_dot_dot(true);
2492 pending_end = false;
2493 }
2494 if (cmd == CMD_END) {
2495 if (num_progs > 0 && --num_progs == 0)
2496 break;
2497 pending_end = true;
2498 } else {
2499 store_command_after(&pc, cmd, &arg, numbuf);
2500 free(xstr_buf);
2501 xstr_buf = NULL;
2502 xstr_len = 0;
2503 }
2504 }
2505
2506 done:
2507 rebuild_label_table();
2508 if (!loading_state)
2509 update_catalog();
2510
2511 flags.f.trace_print = saved_trace;
2512 flags.f.normal_print = saved_normal;
2513
2514 if (raw_file_name != NULL) {
2515 if (ferror(gfile))
2516 shell_message("An error occurred during program import.");
2517 fclose(gfile);
2518 }
2519 free(xstr_buf);
2520 }
2521
2522 static int real2buf(char *buf, phloat x, const char *format = NULL, bool force_decimal = true) {
2523 bool saved_binsep, saved_octsep, saved_decsep, saved_hexsep;
2524 if (!force_decimal) {
2525 saved_binsep = mode_bin_sep;
2526 saved_octsep = mode_oct_sep;
2527 saved_decsep = mode_dec_sep;
2528 saved_hexsep = mode_hex_sep;
2529 mode_bin_sep = mode_oct_sep = mode_dec_sep = mode_hex_sep = false;
2530 }
2531 int bufptr = phloat2string(x, buf, 49, force_decimal ? 0 : 1, 0, 3, 0, MAX_MANT_DIGITS, format);
2532 if (!force_decimal) {
2533 mode_bin_sep = saved_binsep;
2534 mode_oct_sep = saved_octsep;
2535 mode_dec_sep = saved_decsep;
2536 mode_hex_sep = saved_hexsep;
2537 }
2538 /* Convert small-caps 'E' to regular 'e' */
2539 for (int i = 0; i < bufptr; i++)
2540 if (buf[i] == 24)
2541 buf[i] = 'e';
2542 return bufptr;
2543 }
2544
2545 static int complex2buf(char *buf, phloat re, phloat im, bool always_rect, const char *format = NULL) {
2546 bool polar = !always_rect && flags.f.polar;
2547 phloat x, y;
2548 if (polar) {
2549 generic_r2p(re, im, &x, &y);
2550 if (p_isinf(x))
2551 x = POS_HUGE_PHLOAT;
2552 } else {
2553 x = re;
2554 y = im;
2555 }
2556 int bufptr = phloat2string(x, buf, 99, 0, 0, 3, 0, MAX_MANT_DIGITS, format);
2557 if (polar) {
2558 string2buf(buf, 99, &bufptr, " \342\210\240 ", 5);
2559 } else {
2560 if (y >= 0 || p_isinf(y) != 0 || p_isnan(y))
2561 buf[bufptr++] = '+';
2562 }
2563 bufptr += phloat2string(y, buf + bufptr, 99 - bufptr, 0, 0, 3, 0, MAX_MANT_DIGITS, format);
2564 if (!polar)
2565 buf[bufptr++] = 'i';
2566 /* Convert small-caps 'E' to regular 'e' */
2567 for (int i = 0; i < bufptr; i++)
2568 if (buf[i] == 24)
2569 buf[i] = 'e';
2570 return bufptr;
2571 }
2572
2573 static void serialize_list(textbuf *tb, vartype_list *list, int indent) {
2574 char buf[50];
2575 tb_indent(tb, indent);
2576 tb_write(tb, "{\n", 2);
2577 indent += 2;
2578 tb_indent(tb, indent);
2579 int n = int2string(list->size, buf, 49);
2580 tb_write(tb, buf, n);
2581 tb_write(tb, "-Elem List\n", 11);
2582 for (int i = 0; i < list->size; i++) {
2583 vartype *elem = list->array->data[i];
2584 switch (elem->type) {
2585 case TYPE_NULL: {
2586 tb_indent(tb, indent);
2587 tb_write(tb, "null\n", 5);
2588 break;
2589 }
2590 case TYPE_REAL: {
2591 vartype_real *r = (vartype_real *) elem;
2592 tb_indent(tb, indent);
2593 n = real2buf(buf, r->x);
2594 tb_write(tb, buf, n);
2595 tb_write(tb, "\n", 1);
2596 break;
2597 }
2598 case TYPE_COMPLEX: {
2599 vartype_complex *c = (vartype_complex *) elem;
2600 tb_indent(tb, indent);
2601 n = complex2buf(buf, c->re, c->im, true);
2602 tb_write(tb, buf, n);
2603 tb_write(tb, "\n", 1);
2604 break;
2605 }
2606 case TYPE_STRING: {
2607 vartype_string *s = (vartype_string *) elem;
2608 tb_indent(tb, indent);
2609 tb_write(tb, "\"", 1);
2610 const char *txt = s->txt();
2611 char cbuf[5];
2612 for (int j = 0; j < s->length; j++) {
2613 unsigned char c = txt[j];
2614 if (c == 10)
2615 c = 138;
2616 else if (undefined_char(c))
2617 c &= 127;
2618 if (c == '"') {
2619 tb_write(tb, "\\\"", 2);
2620 } else if (c == '\\') {
2621 tb_write(tb, "\\\\", 2);
2622 } else {
2623 n = hp2ascii(cbuf, (const char *) &c, 1);
2624 tb_write(tb, cbuf, n);
2625 }
2626 }
2627 tb_write(tb, "\"\n", 2);
2628 break;
2629 }
2630 case TYPE_REALMATRIX: {
2631 vartype_realmatrix *rm = (vartype_realmatrix *) elem;
2632 tb_indent(tb, indent);
2633 tb_write(tb, "[\n", 2);
2634 indent += 2;
2635 tb_indent(tb, indent);
2636 n = int2string(rm->rows, buf, 49);
2637 tb_write(tb, buf, n);
2638 tb_write(tb, "x", 1);
2639 n = int2string(rm->columns, buf, 49);
2640 tb_write(tb, buf, n);
2641 tb_write(tb, " Matrix\n", 8);
2642 for (int j = 0; j < rm->rows * rm->columns; j++) {
2643 tb_indent(tb, indent);
2644 if (rm->array->is_string[j]) {
2645 tb_write(tb, "\"", 1);
2646 char *text;
2647 int4 len;
2648 get_matrix_string(rm, j, &text, &len);
2649 char cbuf[5];
2650 for (int k = 0; k < len; k++) {
2651 unsigned char c = text[k];
2652 if (c == 10)
2653 c = 138;
2654 else if (undefined_char(c))
2655 c &= 127;
2656 if (c == '"') {
2657 tb_write(tb, "\\\"", 2);
2658 } else if (c == '\\') {
2659 tb_write(tb, "\\\\", 2);
2660 } else {
2661 n = hp2ascii(cbuf, (const char *) &c, 1);
2662 tb_write(tb, cbuf, n);
2663 }
2664 }
2665 tb_write(tb, "\"\n", 2);
2666 } else {
2667 n = real2buf(buf, rm->array->data[j]);
2668 tb_write(tb, buf, n);
2669 tb_write(tb, "\n", 1);
2670 }
2671 }
2672 indent -= 2;
2673 tb_indent(tb, indent);
2674 tb_write(tb, "]\n", 2);
2675 break;
2676 }
2677 case TYPE_COMPLEXMATRIX: {
2678 vartype_complexmatrix *cm = (vartype_complexmatrix *) elem;
2679 tb_indent(tb, indent);
2680 tb_write(tb, "[\n", 2);
2681 indent += 2;
2682 tb_indent(tb, indent);
2683 n = int2string(cm->rows, buf, 49);
2684 tb_write(tb, buf, n);
2685 tb_write(tb, "x", 1);
2686 n = int2string(cm->columns, buf, 49);
2687 tb_write(tb, buf, n);
2688 tb_write(tb, " Cpx Matrix\n", 12);
2689 for (int j = 0; j < cm->rows * cm->columns * 2; j += 2) {
2690 tb_indent(tb, indent);
2691 n = complex2buf(buf, cm->array->data[j], cm->array->data[j + 1], true);
2692 tb_write(tb, buf, n);
2693 tb_write(tb, "\n", 1);
2694 }
2695 indent -= 2;
2696 tb_indent(tb, indent);
2697 tb_write(tb, "]\n", 2);
2698 break;
2699 }
2700 case TYPE_LIST: {
2701 serialize_list(tb, (vartype_list *) elem, indent);
2702 break;
2703 }
2704 }
2705 }
2706 indent -= 2;
2707 tb_indent(tb, indent);
2708 tb_write(tb, "}\n", 2);
2709 }
2710
2711 char *core_copy() {
2712 if (mode_interruptible != NULL)
2713 stop_interruptible();
2714 set_running(false);
2715
2716 textbuf tb;
2717 tb.buf = NULL;
2718 tb.size = 0;
2719 tb.capacity = 0;
2720 tb.fail = false;
2721
2722 if (flags.f.prgm_mode) {
2723 tb_print_current_program(&tb);
2724 textbuf_finish:
2725 tb_write_null(&tb);
2726 if (tb.fail) {
2727 free(tb.buf);
2728 display_error(ERR_INSUFFICIENT_MEMORY);
2729 redisplay();
2730 return NULL;
2731 } else
2732 return tb.buf;
2733 } else if (alpha_active()) {
2734 char *buf = (char *) malloc(5 * reg_alpha_length + 1);
2735 int bufptr = hp2ascii(buf, reg_alpha, reg_alpha_length);
2736 buf[bufptr] = 0;
2737 return buf;
2738 } else if (sp == -1) {
2739 char *buf = (char *) malloc(1);
2740 buf[0] = 0;
2741 return buf;
2742 } else if (stack[sp]->type == TYPE_REAL) {
2743 const char *format = core_settings.localized_copy_paste ? number_format() : NULL;
2744 char *buf = (char *) malloc(50);
2745 int bufptr = real2buf(buf, ((vartype_real *) stack[sp])->x, format, false);
2746 buf[bufptr] = 0;
2747 return buf;
2748 } else if (stack[sp]->type == TYPE_COMPLEX) {
2749 const char *format = core_settings.localized_copy_paste ? number_format() : NULL;
2750 char *buf = (char *) malloc(100);
2751 vartype_complex *c = (vartype_complex *) stack[sp];
2752 int bufptr = complex2buf(buf, c->re, c->im, false, format);
2753 buf[bufptr] = 0;
2754 return buf;
2755 } else if (stack[sp]->type == TYPE_STRING) {
2756 vartype_string *s = (vartype_string *) stack[sp];
2757 char *buf = (char *) malloc(5 * s->length + 1);
2758 int bufptr = hp2ascii(buf, s->txt(), s->length);
2759 buf[bufptr] = 0;
2760 return buf;
2761 } else if (stack[sp]->type == TYPE_REALMATRIX) {
2762 const char *format = core_settings.localized_copy_paste ? number_format() : NULL;
2763 vartype_realmatrix *rm = (vartype_realmatrix *) stack[sp];
2764 phloat *data = rm->array->data;
2765 char *is_string = rm->array->is_string;
2766 char buf[50];
2767 int n = 0;
2768 for (int r = 0; r < rm->rows; r++) {
2769 for (int c = 0; c < rm->columns; c++) {
2770 int bufptr;
2771 if (is_string[n] == 0) {
2772 bufptr = real2buf(buf, data[n], format);
2773 tb_write(&tb, buf, bufptr);
2774 } else {
2775 char *text;
2776 int4 len;
2777 get_matrix_string(rm, n, &text, &len);
2778 for (int4 i = 0; i < len; i += 10) {
2779 int4 seg_len = len - i;
2780 if (seg_len > 10)
2781 seg_len = 10;
2782 bufptr = hp2ascii(buf, text + i, seg_len);
2783 tb_write(&tb, buf, bufptr);
2784 }
2785 }
2786 if (c < rm->columns - 1)
2787 tb_write(&tb, "\t", 1);
2788 n++;
2789 }
2790 if (r < rm->rows - 1)
2791 tb_write(&tb, "\n", 1);
2792 }
2793 goto textbuf_finish;
2794 } else if (stack[sp]->type == TYPE_COMPLEXMATRIX) {
2795 const char *format = core_settings.localized_copy_paste ? number_format() : NULL;
2796 vartype_complexmatrix *cm = (vartype_complexmatrix *) stack[sp];
2797 phloat *data = cm->array->data;
2798 char buf[100];
2799 int n = 0;
2800 for (int r = 0; r < cm->rows; r++) {
2801 for (int c = 0; c < cm->columns; c++) {
2802 int bufptr = complex2buf(buf, data[n], data[n + 1], true, format);
2803 if (c < cm->columns - 1)
2804 buf[bufptr++] = '\t';
2805 tb_write(&tb, buf, bufptr);
2806 n += 2;
2807 }
2808 if (r < cm->rows - 1)
2809 tb_write(&tb, "\n", 1);
2810 }
2811 goto textbuf_finish;
2812 } else if (stack[sp]->type == TYPE_LIST) {
2813 serialize_list(&tb, (vartype_list *) stack[sp], 0);
2814 goto textbuf_finish;
2815 } else {
2816 // Shouldn't happen: unrecognized data type
2817 return NULL;
2818 }
2819 }
2820
2821 const char *STR_INF = "<Infinity>";
2822 const char *STR_NEG_INF = "<-Infinity>";
2823 const char *STR_NAN = "<Not a Number>";
2824
2825 static int scan_number(const char *buf, int len, int pos, const char *format, bool no_sep = false) {
2826 if (buf[pos] == '<' || len > 1 && (buf[pos] == '-' || buf[pos] == '+') && buf[pos + 1] == '<') {
2827 int off = buf[pos] == '<' ? 0 : 1;
2828 if (len >= 10 + off && strncmp(buf + pos + off, STR_INF, 10) == 0)
2829 return pos + off + 10;
2830 else if (len >= 11 + off && strncmp(buf + pos + off, STR_NEG_INF, 11) == 0)
2831 return pos + off + 11;
2832 else if (len >= 14 + off && strncmp(buf + pos + off, STR_NAN, 14) == 0)
2833 return pos + off + 14;
2834 else
2835 return pos;
2836 }
2837 // 0: before number
2838 // 1: in mantissa, before decimal
2839 // 2: in mantissa, after decimal
2840 // 3: after E
2841 // 4: in exponent
2842 int state = 0;
2843 char dec, sep;
2844 if (format == NULL) {
2845 dec = flags.f.decimal_point ? '.' : ',';
2846 sep = flags.f.decimal_point ? ',' : '.';
2847 } else {
2848 dec = format[0];
2849 sep = format[1];
2850 }
2851 for (int p = pos; p < len; p++) {
2852 char c = buf[p];
2853 switch (state) {
2854 case 0:
2855 if (c >= '0' && c <= '9' || c == '+' || c == '-')
2856 state = 1;
2857 else if (c == dec)
2858 state = 2;
2859 else if (c == 'e' || c == 'E' || c == 24)
2860 state = 3;
2861 else
2862 return p;
2863 break;
2864 case 1:
2865 if (c >= '0' && c <= '9' || !no_sep && (c == sep || c == ' '))
2866 /* state = 1 */;
2867 else if (c == dec)
2868 state = 2;
2869 else if (c == 'e' || c == 'E' || c == 24)
2870 state = 3;
2871 else
2872 return p;
2873 break;
2874 case 2:
2875 if (c >= '0' && c <= '9')
2876 /* state = 2 */;
2877 else if (c == 'e' || c == 'E' || c == 24)
2878 state = 3;
2879 else
2880 return p;
2881 break;
2882 case 3:
2883 if ((c >= '0' && c <= '9')
2884 || c == '+' || c == '-')
2885 state = 4;
2886 else
2887 return p;
2888 break;
2889 case 4:
2890 if (c >= '0' && c <= '9')
2891 /* state = 4 */;
2892 else
2893 return p;
2894 break;
2895 }
2896 }
2897 return len;
2898 }
2899
2900 static bool parse_phloat(const char *p, int len, phloat *res, const char *format) {
2901 if (p[0] == '<' || len > 1 && (p[0] == '-' || p[0] == '+') && p[1] == '<') {
2902 int off = p[0] == '<' ? 0 : 1;
2903 bool neg = p[0] == '-';
2904 if (len >= 10 + off && strncmp(p + off, STR_INF, 10) == 0) {
2905 goto return_inf;
2906 } else if (len >= 11 + off && strncmp(p + off, STR_NEG_INF, 11) == 0) {
2907 neg = !neg;
2908 return_inf:
2909 *res = (neg ? NEG_HUGE_PHLOAT : POS_HUGE_PHLOAT) * 2;
2910 return true;
2911 } else if (len >= 14 + off && strncmp(p + off, STR_NAN, 14) == 0) {
2912 *res = NAN_PHLOAT;
2913 return true;
2914 } else
2915 return false;
2916 }
2917 // We can't pass the string on to string2phloat() unchanged, because
2918 // that function is picky: it does not allow '+' signs, and it does
2919 // not allow the mantissa to be more than 34 or 16 digits long (including
2920 // leading zeroes). So, we massage the string a bit to make it
2921 // comply with those restrictions.
2922 // Note that this function does not check well-formedness;
2923 // that part should be checked beforehand using scan_number().
2924 const size_t BSIZE = 100;
2925 char buf[BSIZE];
2926 bool in_mant = true;
2927 bool leading_zero = true;
2928 int exp_offset = 0;
2929 int exp = 0;
2930 bool neg_exp = false;
2931 int mant_digits = 0;
2932 bool in_int_mant = true;
2933 bool empty_mant = true;
2934 int i = 0, j = 0;
2935 char decimal, separator;
2936 if (format == NULL) {
2937 decimal = flags.f.decimal_point ? '.' : ',';
2938 separator = flags.f.decimal_point ? ',' : '.';
2939 } else {
2940 decimal = format[0];
2941 separator = format[1];
2942 }
2943 while (i < BSIZE - 1 && j < len) {
2944 char c = p[j++];
2945 if (c == 0)
2946 break;
2947 if (c == '+' || c == ' ' || c == separator) {
2948 continue;
2949 } else if (c == 'e' || c == 'E' || c == 24) {
2950 if (!empty_mant && mant_digits == 0)
2951 buf[i++] = '0';
2952 in_mant = false;
2953 } else if (c == decimal) {
2954 in_int_mant = false;
2955 buf[i++] = flags.f.decimal_point ? '.' : ',';
2956 } else if (c >= '0' && c <= '9') {
2957 if (in_mant) {
2958 empty_mant = false;
2959 if (in_int_mant) {
2960 if (mant_digits < MAX_MANT_DIGITS) {
2961 if (c != '0' || !leading_zero) {
2962 buf[i++] = c;
2963 leading_zero = false;
2964 mant_digits++;
2965 }
2966 } else {
2967 exp_offset++;
2968 }
2969 } else {
2970 if (mant_digits < MAX_MANT_DIGITS) {
2971 if (c != '0' || !leading_zero) {
2972 buf[i++] = c;
2973 leading_zero = false;
2974 mant_digits++;
2975 } else {
2976 exp_offset--;
2977 }
2978 }
2979 }
2980 } else {
2981 exp = exp * 10 + c - '0';
2982 }
2983 } else if (c == '-') {
2984 if (in_mant)
2985 buf[i++] = c;
2986 else
2987 neg_exp = true;
2988 }
2989 }
2990 if (in_mant && empty_mant)
2991 return false;
2992 if (in_mant && mant_digits == 0 && i < BSIZE - 1)
2993 buf[i++] = '0';
2994 if (neg_exp)
2995 exp = -exp;
2996 exp += exp_offset;
2997 if (exp != 0) {
2998 i += snprintf(buf + i, BSIZE - i, "\030%d", exp);
2999 if (i > BSIZE - 1)
3000 i = BSIZE - 1;
3001 }
3002 if (i == 0)
3003 return false;
3004 int err = string2phloat(buf, i, res);
3005 if (err == 0)
3006 return true;
3007 else if (err == 1) {
3008 *res = POS_HUGE_PHLOAT;
3009 return true;
3010 } else if (err == 2) {
3011 *res = NEG_HUGE_PHLOAT;
3012 return true;
3013 } else if (err == 3 || err == 4) {
3014 *res = 0;
3015 return true;
3016 } else
3017 return false;
3018 }
3019
3020 /* NOTE: The destination buffer should be able to store dstlen + 4
3021 * characters, because of how we parse [LF] and [ESC].
3022 */
3023 static int ascii2hp(char *dst, int dstlen, const char *src, int srclen /* = -1 */) {
3024 int srcpos = 0, dstpos = 0;
3025 // state machine for detecting [LF] and [ESC]:
3026 // 0: ''
3027 // 1: '['
3028 // 2: '[L'
3029 // 3: '[LF'
3030 // 4: '[E'
3031 // 5: '[ES'
3032 // 6: '[ESC'
3033 int state = 0;
3034 bool afterCR = false;
3035 while (dstpos < dstlen + (state == 0 ? 1 : 4)) {
3036 char c = srclen == -1 || srcpos < srclen ? src[srcpos++] : 0;
3037 retry:
3038 if (c == 0)
3039 break;
3040 int code;
3041 if ((c & 0x80) == 0) {
3042 code = c;
3043 } else if ((c & 0xc0) == 0x80) {
3044 // Unexpected continuation byte
3045 continue;
3046 } else {
3047 int len;
3048 if ((c & 0xe0) == 0xc0) {
3049 len = 1;
3050 code = c & 0x1f;
3051 } else if ((c & 0xf0) == 0xe0) {
3052 len = 2;
3053 code = c & 0x0f;
3054 } else if ((c & 0xf8) == 0xf0) {
3055 len = 3;
3056 code = c & 0x07;
3057 } else {
3058 // Invalid UTF-8
3059 continue;
3060 }
3061 while (len-- > 0) {
3062 c = srclen == -1 || srcpos < srclen ? src[srcpos++] : 0;
3063 if ((c & 0xc0) != 0x80)
3064 // Unexpected non-continuation byte
3065 goto retry;
3066 code = code << 6 | c & 0x3f;
3067 }
3068 }
3069 // OK, we have a code.
3070 // Next, we translate CR to LF, but whenever that happens,
3071 // any immediately following LF should be dropped
3072 if (code == 13) {
3073 code = 10;
3074 afterCR = true;
3075 } else {
3076 bool prevAfterCR = afterCR;
3077 afterCR = false;
3078 if (prevAfterCR && code == 10)
3079 continue;
3080 }
3081 // Perform the inverse of the translation in hp2ascii()
3082 switch (code) {
3083 case 0x00f7: code = 0; break; // division sign
3084 case 0x00d7: code = 1; break; // multiplication sign
3085 case 0x221a: code = 2; break; // square root sign
3086 case 0x222b: code = 3; break; // integral sign
3087 case 0x2592: code = 4; break; // gray rectangle
3088 case 0x03a3: // Uppercase sigma
3089 case 0x2211: code = 5; break; // n-ary summation sign (i41CX)
3090 case 0x25b6: // right-pointing triangle
3091 case 0x25b8: // small right-pointing triangle
3092 case 0x25c6: code = 6; break; // black diamond (HP-41 LBL marker)
3093 case 0x03c0: code = 7; break; // lowercase pi
3094 case 0x00bf: code = 8; break; // upside-down question mark
3095 case 0x2264: code = 9; break; // less-than-or-equals sign
3096 case 0x2265: code = 11; break; // greater-than-or-equals sign
3097 case 0x2260: code = 12; break; // not-equals sign
3098 case 0x21b5: code = 13; break; // down-then-left arrow
3099 case 0x2193: code = 14; break; // downward-pointing arrow
3100 case 0x2192: code = 15; break; // right-pointing arrow
3101 case 0x2190: code = 16; break; // left-pointing arrow
3102 case 0x00b5: // micro sign
3103 case 0x03bc: code = 17; break; // lowercase mu
3104 case 0x00a3: // pound sterling sign
3105 case 0x20a4: code = 18; break; // lira sign (Emu42)
3106 case 0x00b0: code = 19; break; // degree symbol
3107 case 0x00c5: // uppercase a with ring
3108 case 0x00e5: // lowercase a with ring
3109 case 0x0226: // uppercase a with dot (i41CX)
3110 case 0x0227: code = 20; break; // lowercase a with dot (i41CX)
3111 case 0x00d1: // uppercase n with tilde
3112 case 0x00f1: code = 21; break; // lowercase n with tilde
3113 case 0x00c4: // uppercase a with umlaut
3114 case 0x00e4: code = 22; break; // lowercase a with umlaut
3115 case 0x2220: // angle symbol
3116 case 0x2221: code = 23; break; // measured angle symbol
3117 case 0x1d07: code = 24; break; // small-caps e
3118 case 0x00c6: // uppercase ae ligature
3119 case 0x00e6: // lowercase ae ligature
3120 case 0x1d01: code = 25; break; // small-caps ae ligature (i41CX)
3121 case 0x2025: // two-dot leader (Emu42)
3122 case 0x2026: code = 26; break; // ellipsis
3123 case 0x241b: code = 27; break; // ESC symbol
3124 case 0x00d6: // uppercase o with umlaut
3125 case 0x00f6: code = 28; break; // lowercase o with umlaut
3126 case 0x00dc: // uppercase u with umlaut
3127 case 0x00fc: code = 29; break; // lowercase u with umlaut
3128 case '^': code = 30; break; // caret
3129 case 0x00b7: // middle dot (Emu42)
3130 case 0x2022: code = 31; break; // bullet
3131 case 0x201c: // left curly double quote
3132 case 0x201d: code = 34; break; // right curly double quote
3133 case 0x2018: // left curly single quote
3134 case 0x2019: code = 39; break; // right curly single quote
3135 case 0x2212: code = 45; break; // minus sign
3136 case 0x2191: code = 94; break; // upward-pointing arrow
3137 case 0x22a2: // right tack sign (i41CX)
3138 case 0x22a6: // assertion sign (Emu42)
3139 case 0x251c: code = 127; break; // append sign
3140 case 0x2236: code = 128; break; // ratio sign, used for thin colon
3141 case 0x028f: code = 129; break; // small-caps y
3142 case 0x03a9: code = 130; break; // Uppercase omega
3143 case 0x1d1b: code = 131; break; // small-caps t
3144 case 0x029f: code = 132; break; // small-caps l
3145 case 0x1d00: code = 133; break; // small-caps a
3146 case 0x25b9: code = 134; break; // hollow right-pointing triangle
3147 case 0x25ec: code = 135; break; // gray right-pointing triangle
3148 case 0x00ab: code = 136; break; // opening guillemet
3149 case 0x00bb: code = 137; break; // closing guillemet
3150 case 0x240a: code = 138; break; // LF symbol
3151 // Combining accents: apply them if they fit,
3152 // otherwise ignore them
3153 case 0x0303:
3154 if (dstpos > 0 && dst[dstpos - 1] == 'N') {
3155 code = 21;
3156 dstpos--;
3157 } else {
3158 state = 0;
3159 continue;
3160 }
3161 break;
3162 case 0x0308:
3163 if (dstpos > 0) {
3164 char k = dst[dstpos - 1];
3165 if (k == 'A') {
3166 code = 22;
3167 dstpos--;
3168 } else if (k == 'O') {
3169 code = 28;
3170 dstpos--;
3171 } else if (k == 'U') {
3172 code = 29;
3173 dstpos--;
3174 } else {
3175 state = 0;
3176 continue;
3177 }
3178 } else {
3179 state = 0;
3180 continue;
3181 }
3182 break;
3183 case 0x030a:
3184 if (dstpos > 0 && dst[dstpos - 1] == 'A') {
3185 code = 20;
3186 dstpos--;
3187 } else {
3188 state = 0;
3189 continue;
3190 }
3191 break;
3192 case 0x20ac:
3193 // euro symbol; expect it to be followed by two hex digits,
3194 // encoding a character in the HP-42S character set. These
3195 // are used by the reverse translation, hp2ascii(), for HP-42S
3196 // characters that only have ambiguous translations.
3197 if (srclen == -1 ? src[srcpos] != 0 && src[srcpos + 1] != 0 : srcpos + 1 < srclen) {
3198 char c1 = src[srcpos];
3199 char c2 = src[srcpos + 1];
3200 if (c1 >= '0' && c1 <= '9')
3201 c1 = c1 - '0';
3202 else if (c1 >= 'a' && c1 <= 'f')
3203 c1 = c1 - 'a' + 10;
3204 else if (c1 >= 'A' && c1 <= 'F')
3205 c1 = c1 - 'A' + 10;
3206 else
3207 goto noescape;
3208 if (c2 >= '0' && c2 <= '9')
3209 c2 = c2 - '0';
3210 else if (c2 >= 'a' && c2 <= 'f')
3211 c2 = c2 - 'a' + 10;
3212 else if (c2 >= 'A' && c2 <= 'F')
3213 c2 = c2 - 'A' + 10;
3214 else
3215 goto noescape;
3216 code = (c1 << 4) + c2;
3217 srcpos += 2;
3218 } else {
3219 noescape:
3220 code = 31;
3221 }
3222 break;
3223 default:
3224 // Anything outside of the printable ASCII range or LF or
3225 // ESC is not representable, so we replace it with bullets,
3226 // except for combining diacritics and zero-width spaces,
3227 // which we skip, and tabs and various other whitespace
3228 // characters, which we treat as spaces.
3229 if (code >= 0x0300 && code <= 0x036f || code >= 0x200b && code <= 0x200d) {
3230 state = 0;
3231 continue;
3232 }
3233 if (code >= 9 && code <= 13 // ASCII whitespace chars
3234 || code == 0x85 || code == 0xa0 // Latin-1 line break, non-break space
3235 || code >= 0x2000 && code <= 0x200a // Unicode spaces
3236 || code == 0x2028 // Unicode line separator
3237 || code == 0x2029 // Unicode paragraph separator
3238 || code == 0x202f // Narrow no-break space
3239 )
3240 code = 32;
3241 else if (code < 32 && code != 10 && code != 27 || code > 126)
3242 code = 31;
3243 break;
3244 }
3245 switch (state) {
3246 case 0:
3247 if (code == '[')
3248 state = 1;
3249 break;
3250 case 1:
3251 if (code == 'L')
3252 state = 2;
3253 else if (code == 'E')
3254 state = 4;
3255 else
3256 state = 0;
3257 break;
3258 case 2:
3259 if (code == 'F')
3260 state = 3;
3261 else
3262 state = 0;
3263 break;
3264 case 3:
3265 if (code == ']') {
3266 code = 10;
3267 dstpos -= 3;
3268 }
3269 state = 0;
3270 break;
3271 case 4:
3272 if (code == 'S')
3273 state = 5;
3274 else
3275 state = 0;
3276 break;
3277 case 5:
3278 if (code == 'C')
3279 state = 6;
3280 else
3281 state = 0;
3282 break;
3283 case 6:
3284 if (code == ']') {
3285 code = 27;
3286 dstpos -= 4;
3287 }
3288 state = 0;
3289 break;
3290 }
3291 dst[dstpos++] = (char) code;
3292 }
3293 return dstpos > dstlen ? dstlen : dstpos;
3294 }
3295
3296 struct text_alias {
3297 char len;
3298 char equiv;
3299 char text[8];
3300 };
3301
3302 static text_alias aliases[] = {
3303 { 5, 2, "\\sqrt" },
3304 { 4, 3, "\\int" },
3305 { 6, 4, "\\gray1" },
3306 { 6, 5, "\\Sigma" },
3307 { 3, 7, "\\pi" },
3308 { 2, 9, "<=" },
3309 { 3, 10, "\\LF" },
3310 { 2, 11, ">=" },
3311 { 2, 12, "!=" },
3312 { 2, 15, "->" },
3313 { 2, 16, "<-" },
3314 { 6, 23, "\\angle" },
3315 { 4, 26, "\\esc" },
3316 { 6, 30, "\\gray2" },
3317 { 7, 31, "\\bullet" },
3318 { 2, '\\', "\\\\" },
3319 { 2, 127, "|-" },
3320 { 1, 17, "\265" },
3321 { 0, 0, "" }
3322 };
3323
3324 static int text2hp(char *buf, int len) {
3325 int srcpos = 0;
3326 int dstpos = 0;
3327 while (srcpos < len) {
3328 int al;
3329 for (int i = 0; (al = aliases[i].len) != 0; i++) {
3330 if (srcpos + al > len)
3331 continue;
3332 if (strncmp(buf + srcpos, aliases[i].text, al) == 0) {
3333 buf[dstpos++] = aliases[i].equiv;
3334 srcpos += al;
3335 break;
3336 }
3337 }
3338 if (al == 0)
3339 buf[dstpos++] = buf[srcpos++];
3340 }
3341 return dstpos;
3342 }
3343
3344 static vartype *parse_base(const char *buf, int len) {
3345 int base = get_base();
3346 if (base == 10)
3347 return NULL;
3348 int bpd = base == 2 ? 1 : base == 8 ? 3 : 4;
3349 int bits = 0;
3350 bool neg = false;
3351 int8 n = 0;
3352 int i = 0;
3353 while (i < len && buf[i] == ' ')
3354 i++;
3355 if (i < len && buf[i] == '-') {
3356 neg = true;
3357 i++;
3358 }
3359 while (i < len && bits < 64) {
3360 char c = buf[i++];
3361 if (c == ' ')
3362 continue;
3363 int d;
3364 if (base == 16) {
3365 if (c >= '0' && c <= '9')
3366 d = c - '0';
3367 else if (c >= 'A' && c <= 'F')
3368 d = c - 'A' + 10;
3369 else if (c >= 'a' && c <= 'f')
3370 d = c - 'a' + 10;
3371 else
3372 return NULL;
3373 } else {
3374 if (c >= 0 && c < '0' + base)
3375 d = c - '0';
3376 else
3377 return NULL;
3378 }
3379 n = n << bpd | d;
3380 bits += bpd;
3381 }
3382 while (i < len && buf[i] == ' ')
3383 i++;
3384 if (i < len)
3385 return NULL;
3386 if (bits == 0)
3387 return NULL;
3388 if (neg)
3389 n = -n;
3390 base_range_check(&n, true);
3391 return new_real((phloat) n);
3392 }
3393
3394 static int parse_scalar(const char *buf, int len, bool strict, phloat *re, phloat *im, int *slen, const char *format = NULL) {
3395 int i, s1, e1, s2, e2;
3396 bool polar = false;
3397 bool empty_im = false;
3398 bool no_re = false;
3399
3400 /* Try matching " %g <angle> %g " */
3401 i = 0;
3402 while (i < len && buf[i] == ' ')
3403 i++;
3404 s1 = i;
3405 i = scan_number(buf, len, i, format);
3406 e1 = i;
3407 if (e1 == s1)
3408 goto attempt_2;
3409 while (i < len && buf[i] == ' ')
3410 i++;
3411 if (i < len && buf[i] == 23)
3412 i++;
3413 else
3414 goto attempt_2;
3415 while (i < len && buf[i] == ' ')
3416 i++;
3417 s2 = i;
3418 i = scan_number(buf, len, i, format);
3419 e2 = i;
3420 if (e2 == s2)
3421 goto attempt_2;
3422 while (i < len && buf[i] == ' ')
3423 i++;
3424 if (i < len)
3425 goto attempt_2;
3426 polar = true;
3427 goto finish_complex;
3428
3429 /* Try matching " %g[+-]%g[ij] " */
3430 attempt_2:
3431 i = 0;
3432 while (i < len && buf[i] == ' ')
3433 i++;
3434 s1 = i;
3435 i = scan_number(buf, len, i, format);
3436 e1 = i;
3437 s2 = i;
3438 i = scan_number(buf, len, i, format);
3439 e2 = i;
3440 if (i < len && (buf[i] == 'i' || buf[i] == 'j'))
3441 i++;
3442 else
3443 goto attempt_3;
3444 while (i < len && buf[i] == ' ')
3445 i++;
3446 if (i < len)
3447 goto attempt_3;
3448 if (e1 == s1) {
3449 *re = 0;
3450 *im = 1;
3451 return TYPE_COMPLEX;
3452 }
3453 if (e2 == s2) {
3454 no_re = true;
3455 e2 = e1;
3456 s2 = s1;
3457 }
3458 /* Handle x+i or x-i (imaginary part consisting of just a '+' or '-' */
3459 if (e2 == s2 + 1 && (buf[s2] == '+' || buf[s2] == '-'))
3460 empty_im = true;
3461 goto finish_complex;
3462
3463 /* Try matching " ( %g , %g ) " */
3464 /* To avoid the ambiguity with the comma, a colon or semicolon is
3465 * also accepted; if those are used, you don't need to surround them
3466 * with spaces to distinguish them from 'number' chars
3467 */
3468 attempt_3:
3469 no_re = false;
3470 i = 0;
3471 while (i < len && buf[i] == ' ')
3472 i++;
3473 if (i < len && buf[i] == '(')
3474 i++;
3475 else
3476 goto attempt_4;
3477 while (i < len && buf[i] == ' ')
3478 i++;
3479 s1 = i;
3480 i = scan_number(buf, len, i, format, true);
3481 e1 = i;
3482 if (e1 == s1)
3483 goto attempt_4;
3484 while (i < len && buf[i] == ' ')
3485 i++;
3486 if (i < len || (buf[i] == ',' || buf[i] == ':' || buf[i] == ';'))
3487 i++;
3488 else
3489 goto attempt_4;
3490 while (i < len && buf[i] == ' ')
3491 i++;
3492 s2 = i;
3493 i = scan_number(buf, len, i, format, true);
3494 e2 = i;
3495 if (e2 == s2)
3496 goto attempt_4;
3497 while (i < len && buf[i] == ' ')
3498 i++;
3499 if (i < len && buf[i] == ')')
3500 i++;
3501 else
3502 goto attempt_4;
3503 while (i < len && buf[i] == ' ')
3504 i++;
3505 if (i < len)
3506 goto attempt_4;
3507
3508 finish_complex:
3509 if (no_re)
3510 *re = 0;
3511 else if (!parse_phloat(buf + s1, e1 - s1, re, format))
3512 goto attempt_4;
3513 if (empty_im)
3514 *im = buf[s2] == '+' ? 1 : -1;
3515 else if (!parse_phloat(buf + s2, e2 - s2, im, format))
3516 goto attempt_4;
3517 if (polar)
3518 generic_p2r(*re, *im, re, im);
3519 return TYPE_COMPLEX;
3520
3521 /* Try matching " %g " */
3522 attempt_4:
3523 i = 0;
3524 while (i < len && buf[i] == ' ')
3525 i++;
3526 s1 = i;
3527 i = scan_number(buf, len, i, format);
3528 e1 = i;
3529 if (e1 == s1)
3530 goto finish_string;
3531 if (strict) {
3532 while (i < len && buf[i] == ' ')
3533 i++;
3534 if (i < len)
3535 goto finish_string;
3536 }
3537 if (parse_phloat(buf + s1, e1 - s1, re, format))
3538 return TYPE_REAL;
3539
3540 finish_string:
3541 *slen = len;
3542 return TYPE_STRING;
3543 }
3544
3545 static bool nexttoken(const char *buf, int pos, int len, int *tok_start, int *tok_end) {
3546 bool have_token = false;
3547 while (pos < len) {
3548 char c = buf[pos];
3549 if (have_token) {
3550 if (c == ' ') {
3551 *tok_end = pos;
3552 return true;
3553 }
3554 } else {
3555 if (c != ' ') {
3556 *tok_start = pos;
3557 have_token = true;
3558 }
3559 }
3560 pos++;
3561 }
3562 *tok_end = pos;
3563 return have_token;
3564 }
3565
3566 static void paste_programs(const char *buf) {
3567 bool after_end = true;
3568 bool done = false;
3569 int pos = 0;
3570 char hpbuf_s[259];
3571 char *hpbuf = NULL;
3572 int cmd;
3573 arg_struct arg;
3574 char numbuf[50];
3575
3576 char *xstr_buf = NULL;
3577 int xstr_len = 0;
3578
3579 while (!done) {
3580 int end = pos;
3581 char c;
3582 while (c = buf[end], c != 0 && c != '\r' && c != '\n' && c != '\f')
3583 end++;
3584 if (c == 0)
3585 done = true;
3586 if (end == pos)
3587 goto line_done;
3588 // We now have a line between 'pos' and 'end', length 'end - pos'.
3589 // Convert to HP-42S encoding:
3590 int alen;
3591 alen = end - pos;
3592 if (alen > 255) {
3593 hpbuf = (char *) malloc(alen + 4);
3594 if (hpbuf == NULL) {
3595 display_error(ERR_INSUFFICIENT_MEMORY);
3596 redisplay();
3597 return;
3598 }
3599 } else {
3600 hpbuf = hpbuf_s;
3601 }
3602 int hpend;
3603 hpend = ascii2hp(hpbuf, alen, buf + pos, alen);
3604 // Perform additional translations, to support various 42S-to-text
3605 // and 41-to-text conversion schemes:
3606 hpend = text2hp(hpbuf, hpend);
3607
3608 // Comments: semicolons and at signs, if not preceded by a double
3609 // quote, are considered comment delimiters, and they, and everything
3610 // following until the end of the line, are ignored.
3611 // Note that any extraneous text following a syntactically correct
3612 // complete command is also considered a comment, so in most cases it
3613 // isn't necessary to use a delimiter. But sometimes it is,
3614 // specifically, unnumbered number lines followed by comments.
3615 for (int i = 0; i < hpend; i++) {
3616 c = hpbuf[i];
3617 if (c == '"')
3618 break;
3619 if (c == '@' || c == ';') {
3620 hpend = i;
3621 break;
3622 }
3623 }
3624
3625 // Skip leading whitespace and line number.
3626 int hppos;
3627 hppos = 0;
3628 while (hpbuf[hppos] == ' ')
3629 hppos++;
3630 int prev_hppos, lineno_start, lineno_end;
3631 prev_hppos = hppos;
3632 lineno_start = -1;
3633 while (hppos < hpend && (c = hpbuf[hppos], c >= '0' && c <= '9'))
3634 hppos++;
3635 if (prev_hppos != hppos) {
3636 // Number found. If this is immediately followed by a period,
3637 // comma, or E, it's not a line number but an unnumbered number
3638 // line.
3639 if (hppos < hpend && (c = hpbuf[hppos], c == '.' || c == ','
3640 || c == 'E' || c == 'e' || c == 24)) {
3641 int len = hpend - prev_hppos;
3642 if (len > 50)
3643 len = 50;
3644 int i;
3645 for (i = 0; i < len; i++) {
3646 c = hpbuf[prev_hppos + i];
3647 if (c == ' ')
3648 break;
3649 if (c == 'e' || c == 24)
3650 c = 'E';
3651 else if (c == ',')
3652 c = '.';
3653 numbuf[i] = c;
3654 }
3655 if (i == 50)
3656 // Too long
3657 goto line_done;
3658 numbuf[i] = 0;
3659 cmd = CMD_NUMBER;
3660 if (!parse_number_line(numbuf, &arg.val_d))
3661 goto line_done;
3662 arg.type = ARGTYPE_DOUBLE;
3663 goto store;
3664 } else {
3665 // Check for 1/X, 10^X, 4STK, and generalized comparisons with 0
3666 int len = hpend - prev_hppos;
3667 if ((len == 3 || len > 3 && hpbuf[prev_hppos + 3] == ' ')
3668 && strncmp(hpbuf + prev_hppos, "1/X", 3) == 0) {
3669 cmd = CMD_INV;
3670 arg.type = ARGTYPE_NONE;
3671 goto store;
3672 } else if ((len == 4 || len > 4 && hpbuf[prev_hppos + 4] == ' ')
3673 && (strncmp(hpbuf + prev_hppos, "10^X", 4) == 0
3674 || strncmp(hpbuf + prev_hppos, "10\36X", 4) == 0)) {
3675 cmd = CMD_10_POW_X;
3676 arg.type = ARGTYPE_NONE;
3677 goto store;
3678 } else if ((len == 4 || len > 4 && hpbuf[prev_hppos + 4] == ' ')
3679 && strncmp(hpbuf + prev_hppos, "4STK", 4) == 0) {
3680 cmd = CMD_4STK;
3681 arg.type = ARGTYPE_NONE;
3682 goto store;
3683 } else if (len >= 4 && hpbuf[prev_hppos] == '0'
3684 && hpbuf[prev_hppos + 2] == '?'
3685 && hpbuf[prev_hppos + 3] == ' ') {
3686 switch (hpbuf[prev_hppos + 1]) {
3687 case '=': cmd = CMD_0_EQ_NN; goto parse_arg;
3688 case '\14': cmd = CMD_0_NE_NN; goto parse_arg;
3689 case '<': cmd = CMD_0_LT_NN; goto parse_arg;
3690 case '>': cmd = CMD_0_GT_NN; goto parse_arg;
3691 case '\11': cmd = CMD_0_LE_NN; goto parse_arg;
3692 case '\13': cmd = CMD_0_GE_NN; goto parse_arg;
3693 default: goto not_zero_comp;
3694 }
3695 parse_arg:
3696 hppos = prev_hppos;
3697 goto after_line_number;
3698 not_zero_comp:;
3699 }
3700 // No decimal or exponent following the digits, and it's
3701 // not 1/X, 10^X, or 4STK; for now, assume it's a line number.
3702 lineno_start = prev_hppos;
3703 lineno_end = hppos;
3704 }
3705 }
3706 // Line number should be followed by a run of one or more characters,
3707 // which may be spaces, greater-than signs, or solid right-pointing
3708 // triangle (a.k.a. goose), but all but one of those characters must
3709 // be spaces
3710 bool goose;
3711 goose = false;
3712 prev_hppos = hppos;
3713 while (hppos < hpend) {
3714 c = hpbuf[hppos];
3715 if (c == '>' || c == 6) {
3716 if (goose)
3717 break;
3718 else
3719 goose = 1;
3720 } else if (c != ' ')
3721 break;
3722 hppos++;
3723 }
3724 // Now hppos should be pointing at the first character of the
3725 // command.
3726 after_line_number:
3727 if (hppos == hpend) {
3728 if (lineno_start == -1) {
3729 // empty line
3730 goto line_done;
3731 } else {
3732 // Nothing after the line number; treat this as a
3733 // number without a line number
3734 // Note that we could treat many more cases as unnumbered
3735 // numbers; basically, any number followed by something that
3736 // doesn't parse... but I'm not opening that can of worms until
3737 // I see a good reason to.
3738 hpbuf[lineno_end] = 0;
3739 cmd = CMD_NUMBER;
3740 strcpy(numbuf, hpbuf + lineno_start);
3741 parse_number_line(numbuf, &arg.val_d);
3742 arg.type = ARGTYPE_DOUBLE;
3743 goto store;
3744 }
3745 }
3746 if (lineno_start != -1 && hppos == prev_hppos)
3747 // No space following line number? Not acceptable.
3748 goto line_done;
3749 if (hppos < hpend - 1 && (hpbuf[hppos] == 127 || hpbuf[hppos] == '+') && hpbuf[hppos + 1] == '"') {
3750 // Appended string
3751 hpbuf[hppos + 1] = 127;
3752 goto do_string;
3753 } else if (hppos < hpend && hpbuf[hppos] == '"') {
3754 // Non-appended string
3755 do_string:
3756 hppos++;
3757 // String literals can be up to 15 characters long, and they
3758 // can contain double quotes. We scan forward for up to 15
3759 // chars, and the final double quote we find is considered the
3760 // end of the string; any intervening double quotes are considered
3761 // to be part of the string.
3762 int last_quote = -1;
3763 int i;
3764 for (i = 0; i < 16; i++) {
3765 if (hppos + i == hpend)
3766 break;
3767 c = hpbuf[hppos + i];
3768 if (c == '"')
3769 last_quote = i;
3770 }
3771 if (last_quote == -1)
3772 // No closing quote? Fishy, but let's just grab 15
3773 // characters and hope for the best.
3774 last_quote = i < 15 ? i : 15;
3775 if (last_quote == 0) {
3776 cmd = CMD_NOP;
3777 arg.type = ARGTYPE_NONE;
3778 } else {
3779 cmd = CMD_STRING;
3780 arg.type = ARGTYPE_STR;
3781 arg.length = last_quote;
3782 memcpy(arg.val.text, hpbuf + hppos, arg.length);
3783 if (arg.length > 0)
3784 arg.val.text[0] &= 127;
3785 }
3786 } else {
3787 // Not a string; try to find command
3788 int cmd_end = hppos;
3789 while (cmd_end < hpend && hpbuf[cmd_end] != ' ')
3790 cmd_end++;
3791 if (cmd_end == hppos)
3792 goto line_done;
3793 if (cmd_end - hppos == 5 && hpbuf[hppos] == 'X' && strncmp(hpbuf + hppos + 2, "NN?", 3) == 0) {
3794 // HP-41CX: X=NN? etc.
3795 switch (hpbuf[hppos + 1]) {
3796 case '=': cmd = CMD_X_EQ_NN; goto cx_comp;
3797 case 12: cmd = CMD_X_NE_NN; goto cx_comp;
3798 case '<': cmd = CMD_X_LT_NN; goto cx_comp;
3799 case '>': cmd = CMD_X_GT_NN; goto cx_comp;
3800 case 9: cmd = CMD_X_LE_NN; goto cx_comp;
3801 case 11: cmd = CMD_X_GE_NN; goto cx_comp;
3802 default: goto not_cx_comp;
3803 }
3804 cx_comp:
3805 arg.type = ARGTYPE_IND_STK;
3806 arg.val.stk = 'Y';
3807 goto store;
3808 not_cx_comp:;
3809 }
3810 cmd = find_builtin(hpbuf + hppos, cmd_end - hppos);
3811 int tok_start, tok_end;
3812 int argtype;
3813 bool stk_allowed = true;
3814 bool string_required = false;
3815 if (cmd == CMD_SIZE) {
3816 if (!nexttoken(hpbuf, cmd_end, hpend, &tok_start, &tok_end))
3817 goto line_done;
3818 if (tok_end - tok_start > 4)
3819 goto line_done;
3820 int sz = 0;
3821 for (int i = tok_start; i < tok_end; i++) {
3822 char c = hpbuf[i];
3823 if (c < '0' || c > '9')
3824 goto line_done;
3825 sz = sz * 10 + c - '0';
3826 }
3827 arg.type = ARGTYPE_NUM;
3828 arg.val.num = sz;
3829 goto store;
3830 } else if (cmd == CMD_FUNC) {
3831 if (!nexttoken(hpbuf, cmd_end, hpend, &tok_start, &tok_end))
3832 goto line_done;
3833 if (tok_end - tok_start != 2)
3834 goto line_done;
3835 int io = 0;
3836 for (int i = tok_start; i < tok_end; i++) {
3837 char c = hpbuf[i];
3838 if (c < '0' || c > '4')
3839 goto line_done;
3840 io = io * 10 + c - '0';
3841 }
3842 arg.type = ARGTYPE_NUM;
3843 arg.val.num = io;
3844 goto store;
3845 } else if (cmd == CMD_ASSIGNa) {
3846 // What we're looking for is '".*" *TO *[0-9][0-9]'
3847 tok_end = hppos;
3848 bool after_to = false;
3849 int to_start;
3850 int keynum;
3851 while (true) {
3852 if (!nexttoken(hpbuf, tok_end, hpend, &tok_start, &tok_end))
3853 goto line_done;
3854 int len = tok_end - tok_start;
3855 if (after_to) {
3856 if (len != 2 || !isdigit(hpbuf[tok_start])
3857 || !isdigit(hpbuf[tok_start + 1])) {
3858 after_to = string_equals(hpbuf + tok_start, len, "TO", 2);
3859 if (after_to)
3860 to_start = tok_start;
3861 continue;
3862 }
3863 after_to = false;
3864 sscanf(hpbuf + tok_start, "%02d", &keynum);
3865 if (keynum < 1 || keynum > 18)
3866 continue;
3867 else
3868 break;
3869 } else {
3870 after_to = string_equals(hpbuf + tok_start, len, "TO", 2);
3871 if (after_to)
3872 to_start = tok_start;
3873 }
3874 }
3875 // Between hppos (inclusive) and to_start (exclusive),
3876 // there should be a quote-delimited string...
3877 while (hppos < hpend && hpbuf[hppos] != '"')
3878 hppos++;
3879 if (hppos == hpend)
3880 goto line_done;
3881 to_start--;
3882 while (to_start > hppos && hpbuf[to_start] != '"')
3883 to_start--;
3884 if (to_start == hppos)
3885 // Only one quote sign found
3886 goto line_done;
3887 int len = to_start - hppos - 1;
3888 if (len > 7)
3889 len = 7;
3890 cmd = CMD_ASGN01 + keynum - 1;
3891 arg.type = ARGTYPE_STR;
3892 arg.length = len;
3893 memcpy(arg.val.text, hpbuf + hppos + 1, len);
3894 goto store;
3895 } else if (cmd == CMD_XSTR) {
3896 int q1 = -1, q2 = -1;
3897 for (int i = hppos; i < hpend; i++) {
3898 if (hpbuf[i] == '"') {
3899 if (q1 == -1)
3900 q1 = i;
3901 else
3902 q2 = i;
3903 }
3904 }
3905 if (q2 == -1)
3906 goto line_done;
3907 arg.type = ARGTYPE_XSTR;
3908 arg.length = q2 - q1 - 1;
3909 arg.val.xstr = hpbuf + q1 + 1;
3910 goto store;
3911 } else if (cmd != CMD_NONE) {
3912 int flags;
3913 flags = cmd_array[cmd].flags;
3914 arg.type = ARGTYPE_NONE;
3915 if ((flags & (FLAG_IMMED | FLAG_HIDDEN | FLAG_NO_PRGM)) != 0)
3916 goto line_done;
3917 argtype = cmd_array[cmd].argtype;
3918 bool ind;
3919 switch (argtype) {
3920 case ARG_NONE: {
3921 arg.type = ARGTYPE_NONE;
3922 goto store;
3923 }
3924 case ARG_VAR:
3925 case ARG_REAL:
3926 case ARG_NUM9:
3927 case ARG_NUM11:
3928 case ARG_NUM99: {
3929 string_only:
3930 ind = false;
3931 if (!nexttoken(hpbuf, cmd_end, hpend, &tok_start, &tok_end))
3932 goto line_done;
3933 if (string_equals(hpbuf + tok_start, tok_end - tok_start, "IND", 3)) {
3934 ind = true;
3935 if (cmd == CMD_CLP || cmd == CMD_MVAR)
3936 goto line_done;
3937 if (!nexttoken(hpbuf, tok_end, hpend, &tok_start, &tok_end))
3938 goto line_done;
3939 }
3940 num_or_string:
3941 if ((argtype == ARG_VAR || argtype == ARG_REAL || ind)
3942 && string_equals(hpbuf + tok_start, tok_end - tok_start, "ST", 2)) {
3943 if (!ind && (!stk_allowed || string_required))
3944 goto line_done;
3945 arg.type = ind ? ARGTYPE_IND_STK : ARGTYPE_STK;
3946 if (!nexttoken(hpbuf, tok_end, hpend, &tok_start, &tok_end))
3947 goto line_done;
3948 if (tok_end - tok_start != 1)
3949 goto line_done;
3950 char c = hpbuf[tok_start];
3951 if (c != 'X' && c != 'Y' && c != 'Z' && c != 'T'
3952 && c != 'L')
3953 goto line_done;
3954 arg.val.stk = c;
3955 goto store;
3956 }
3957 if ((argtype == ARG_VAR || argtype == ARG_REAL || ind)
3958 && tok_end - tok_start == 1) {
3959 // Accept RCL Z etc., instead of RCL ST Z, for
3960 // HP-41 compatibilitry.
3961 char c = hpbuf[tok_start];
3962 if (c == 'X' || c == 'Y' || c == 'Z' || c == 'T'
3963 || c == 'L') {
3964 if (!ind && (!stk_allowed || string_required))
3965 goto line_done;
3966 arg.type = ind ? ARGTYPE_IND_STK : ARGTYPE_STK;
3967 arg.val.stk = c;
3968 goto store;
3969 }
3970 }
3971 if (!ind && argtype == ARG_NUM9) {
3972 if (tok_end - tok_start == 1 && isdigit(hpbuf[tok_start])) {
3973 arg.type = ARGTYPE_NUM;
3974 arg.val.num = hpbuf[tok_start] - '0';
3975 if (cmd == CMD_RTNERR && arg.val.num > 8)
3976 goto line_done;
3977 goto store;
3978 }
3979 goto line_done;
3980 }
3981 if (!ind && argtype == ARG_NUM11 && tok_end - tok_start == 1
3982 && isdigit(hpbuf[tok_start])) {
3983 // Special case for FIX/SCI/ENG with 1-digit
3984 // non-indirect argument; needed for parsing
3985 // HP-41 code.
3986 arg.type = ARGTYPE_NUM;
3987 arg.val.num = hpbuf[tok_start] - '0';
3988 goto store;
3989 }
3990 if (tok_end - tok_start == 2 && isdigit(hpbuf[tok_start])
3991 && isdigit(hpbuf[tok_start + 1])) {
3992 if (!ind && (string_required || cmd == CMD_GETMI || cmd == CMD_PUTMI || cmd == CMD_GETLI || cmd == CMD_PUTLI))
3993 goto line_done;
3994 arg.type = ind ? ARGTYPE_IND_NUM : ARGTYPE_NUM;
3995 sscanf(hpbuf + tok_start, "%02d", &arg.val.num);
3996 if (!ind && argtype == ARG_NUM11 && arg.val.num > 11)
3997 goto line_done;
3998 goto store;
3999 }
4000 if ((argtype == ARG_VAR || argtype == ARG_REAL || ind)
4001 && hpbuf[tok_start] == '"') {
4002 arg.type = ind ? ARGTYPE_IND_STR : ARGTYPE_STR;
4003 handle_string_arg:
4004 hppos = tok_start + 1;
4005 // String arguments can be up to 7 characters long, and they
4006 // can contain double quotes. We scan forward for up to 7
4007 // chars, and the final double quote we find is considered the
4008 // end of the string; any intervening double quotes are considered
4009 // to be part of the string.
4010 int last_quote = -1;
4011 int i;
4012 for (i = 0; i < 8; i++) {
4013 if (hppos + i == hpend)
4014 break;
4015 c = hpbuf[hppos + i];
4016 if (c == '"')
4017 last_quote = i;
4018 }
4019 if (last_quote == -1)
4020 // No closing quote? Fishy, but let's just grab 7
4021 // characters and hope for the best.
4022 last_quote = i < 7 ? i : 7;
4023 arg.length = last_quote;
4024 memcpy(arg.val.text, hpbuf + hppos, arg.length);
4025 goto store;
4026 }
4027 goto line_done;
4028 }
4029 case ARG_PRGM:
4030 case ARG_NAMED:
4031 case ARG_MAT:
4032 case ARG_RVAR: {
4033 string_required = true;
4034 stk_allowed = false;
4035 argtype = ARG_VAR;
4036 goto string_only;
4037 }
4038 case ARG_M_STK:
4039 case ARG_L_STK: {
4040 argtype = ARG_VAR;
4041 goto string_only;
4042 }
4043 case ARG_LBL: {
4044 tok_end = cmd_end;
4045 gto_or_xeq:
4046 if (!nexttoken(hpbuf, tok_end, hpend, &tok_start, &tok_end))
4047 goto line_done;
4048 ind = false;
4049 if (string_equals(hpbuf + tok_start, tok_end - tok_start, "IND", 3)) {
4050 ind = true;
4051 if (!nexttoken(hpbuf, tok_end, hpend, &tok_start, &tok_end))
4052 goto line_done;
4053 }
4054 if (cmd == CMD_LBL && ind)
4055 goto line_done;
4056 if (tok_end - tok_start == 1) {
4057 char c = hpbuf[tok_start];
4058 if (c >= 'A' && c <= 'J' || c >= 'a' && c <= 'e') {
4059 arg.type = ARGTYPE_LCLBL;
4060 arg.val.lclbl = c;
4061 goto store;
4062 } else
4063 goto line_done;
4064 }
4065 argtype = ARG_VAR;
4066 stk_allowed = false;
4067 goto num_or_string;
4068 }
4069 case ARG_OTHER: {
4070 if (cmd == CMD_LBL) {
4071 tok_end = cmd_end;
4072 goto gto_or_xeq;
4073 }
4074 goto line_done;
4075 }
4076 default:
4077 goto line_done;
4078 }
4079 } else if (string_equals(hpbuf + hppos, cmd_end - hppos, "KEY", 3)) {
4080 // KEY GTO or KEY XEQ
4081 if (!nexttoken(hpbuf, cmd_end, hpend, &tok_start, &tok_end))
4082 goto line_done;
4083 if (tok_end - tok_start != 1)
4084 goto line_done;
4085 char c = hpbuf[tok_start];
4086 if (c < '1' || c > '9')
4087 goto line_done;
4088 if (!nexttoken(hpbuf, tok_end, hpend, &tok_start, &tok_end))
4089 goto line_done;
4090 if (string_equals(hpbuf + tok_start, tok_end - tok_start, "GTO", 3))
4091 cmd = CMD_KEY1G + c - '1';
4092 else if (string_equals(hpbuf + tok_start, tok_end - tok_start, "XEQ", 3))
4093 cmd = CMD_KEY1X + c - '1';
4094 else
4095 goto line_done;
4096 goto gto_or_xeq;
4097 } else if (string_equals(hpbuf + hppos, cmd_end - hppos, ".END.", 5)) {
4098 cmd = CMD_END;
4099 arg.type = ARGTYPE_NONE;
4100 goto store;
4101 } else if (string_equals(hpbuf + hppos, cmd_end - hppos, "XROM", 4)) {
4102 // Should handle num,num and "lbl"
4103 if (!nexttoken(hpbuf, cmd_end, hpend, &tok_start, &tok_end))
4104 goto line_done;
4105 if (hpbuf[tok_start] == '"') {
4106 arg.type = ARGTYPE_STR;
4107 cmd = CMD_XEQ;
4108 goto handle_string_arg;
4109 }
4110 int len = tok_end - tok_start;
4111 if (len >= 4 && len <= 32 && len % 2 == 0 && hpbuf[tok_start] == '0' && hpbuf[tok_start + 1] == 'x') {
4112 // XROM 0xdeadbeef: used for strings whose first character has its high
4113 // bit set, putting it in the space of HP-42S extensions, but which do
4114 // not correspond to any actual known extension.
4115 char d = 0;
4116 unsigned char buf[16];
4117 int length = 0;
4118 for (int i = 2; i < len; i++) {
4119 char c = hpbuf[tok_start + i];
4120 if (c >= '0' && c <= '9')
4121 d += c - '0';
4122 else if (c >= 'A' && c <= 'F')
4123 d += c - 'A' + 10;
4124 else if (c >= 'a' && c <= 'f')
4125 d += c - 'a' + 10;
4126 else
4127 goto line_done;
4128 if ((i & 1) != 0) {
4129 buf[++length] = d;
4130 d = 0;
4131 } else {
4132 d <<= 4;
4133 }
4134 }
4135 buf[0] = 0xf0 + length;
4136 decode_string(buf, &cmd, &arg, &xstr_buf, &xstr_len);
4137 if (cmd == CMD_CANCELLED) {
4138 display_error(ERR_INSUFFICIENT_MEMORY);
4139 redisplay();
4140 free(xstr_buf);
4141 return;
4142 }
4143 if (cmd == CMD_NONE)
4144 goto line_done;
4145 goto store;
4146 }
4147 if (len > 5)
4148 goto line_done;
4149 char xrombuf[6];
4150 memcpy(xrombuf, hpbuf + tok_start, len);
4151 xrombuf[len] = 0;
4152 int a, b;
4153 if (sscanf(xrombuf, "%d,%d", &a, &b) != 2)
4154 goto line_done;
4155 if (a < 0 || a > 31 || b < 0 || b > 63)
4156 goto line_done;
4157 int byte1 = 0xa0 | (a >> 2);
4158 int byte2 = ((a << 6) | b) & 255;
4159 decode_xrom(byte1, byte2, &cmd, &arg);
4160 goto store;
4161 } else {
4162 // Number or bust!
4163 if (nexttoken(hpbuf, hppos, hpend, &tok_start, &tok_end)) {
4164 char c = hpbuf[tok_start];
4165 bool have_exp = false;
4166 if (c >= '0' && c <= '9' || c == '-' || c == '.' || c == ','
4167 || c == 'E' || c == 'e' || c == 24) {
4168 // The first character could plausibly be part of a number;
4169 // let's run with it.
4170 int len = tok_end - tok_start;
4171 if (len > 49)
4172 len = 49;
4173 for (int i = 0; i < len; i++) {
4174 c = hpbuf[tok_start + i];
4175 if (c == 'e' || c == 24)
4176 c = 'E';
4177 else if (c == ',')
4178 c = '.';
4179 if (c == 'E')
4180 have_exp = true;
4181 numbuf[i] = c;
4182 }
4183 numbuf[len] = 0;
4184 if (!have_exp) {
4185 // In HP-41 program listings, there may be a space
4186 // before the 'E' character, e.g. "1 E3". So, if we
4187 // haven't seen an exponent yet, check if the next
4188 // token looks like an exponent, and if so, add it.
4189 if (nexttoken(hpbuf, tok_end, hpend, &tok_start, &tok_end)) {
4190 c = hpbuf[tok_start];
4191 if (c == 'E' || c == 'e' || c == 24) {
4192 int explen = tok_end - tok_start;
4193 bool is_exp = true;
4194 for (int i = 1; i < explen; i++) {
4195 c = hpbuf[tok_start + i];
4196 if (!(c == '-' && i == 1 || c >= '0' && c <= '9')) {
4197 is_exp = false;
4198 break;
4199 }
4200 }
4201 if (is_exp) {
4202 if (len + explen > 49)
4203 explen = 49 - len;
4204 char *p = numbuf + len;
4205 *p++ = 'E';
4206 for (int i = 1; i < explen; i++)
4207 *p++ = hpbuf[tok_start + i];
4208 *p = 0;
4209 }
4210 }
4211 }
4212 }
4213 cmd = CMD_NUMBER;
4214 if (!parse_number_line(numbuf, &arg.val_d))
4215 goto line_done;
4216 arg.type = ARGTYPE_DOUBLE;
4217 goto store;
4218 }
4219 }
4220 goto line_done;
4221 }
4222 }
4223
4224 store:
4225 if (after_end)
4226 goto_dot_dot(false);
4227 after_end = cmd == CMD_END;
4228 if (!after_end) {
4229 store_command_after(&pc, cmd, &arg, numbuf);
4230 free(xstr_buf);
4231 xstr_buf = NULL;
4232 xstr_len = 0;
4233 }
4234
4235 line_done:
4236 pos = end + 1;
4237 if (hpbuf != hpbuf_s) {
4238 free(hpbuf);
4239 hpbuf = NULL;
4240 }
4241 }
4242
4243 free(xstr_buf);
4244 }
4245
4246 static int get_token(const char *buf, int *pos, int *start) {
4247 char c;
4248 while (true) {
4249 c = buf[*pos];
4250 if (c == 0)
4251 return 0;
4252 if (c != ' ' && c != '\t' && c != '\n' && c != '\r' && c != '\f')
4253 break;
4254 (*pos)++;
4255 }
4256 *start = *pos;
4257 if (c == '"') {
4258 (*pos)++;
4259 while (true) {
4260 c = buf[*pos];
4261 if (c == 0)
4262 return *pos - *start;
4263 if (c == '"') {
4264 (*pos)++;
4265 return *pos - *start;
4266 }
4267 if (c == '\\') {
4268 (*pos)++;
4269 c = buf[*pos];
4270 if (c == 0)
4271 return *pos - *start;
4272 }
4273 (*pos)++;
4274 }
4275 } else {
4276 while (true) {
4277 c = buf[*pos];
4278 if (c == 0 || c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f')
4279 return *pos - *start;
4280 if (c == '<') {
4281 if (strncmp(buf + *pos, STR_INF, 10) == 0) {
4282 *pos += 10;
4283 } else if (strncmp(buf + *pos, STR_NEG_INF, 11) == 0) {
4284 *pos += 11;
4285 } else if (strncmp(buf + *pos, STR_NAN, 14) == 0) {
4286 *pos += 14;
4287 } else
4288 (*pos)++;
4289 } else
4290 (*pos)++;
4291 }
4292 }
4293 }
4294
4295 static int parse_int(const char *buf, int len) {
4296 int r = 0;
4297 for (int i = 0; i < len; i++) {
4298 char c = buf[i];
4299 if (c < '0' || c > '9')
4300 return -1;
4301 r = r * 10 + c - '0';
4302 }
4303 return r;
4304 }
4305
4306 static char *parse_string(const char *buf, int len, int *slen) {
4307 char *s = (char *) malloc(len - 2);
4308 if (s == NULL)
4309 return NULL;
4310 int sl = 0;
4311 for (int i = 1; i < len - 1; i++) {
4312 char c = buf[i];
4313 if (c == '\\')
4314 c = buf[++i];
4315 s[sl++] = c;
4316 }
4317 char *s2 = (char *) malloc(sl + 4);
4318 if (s2 == NULL) {
4319 free(s);
4320 return NULL;
4321 }
4322 sl = ascii2hp(s2, sl, s, sl);
4323 free(s);
4324 *slen = sl;
4325 return s2;
4326 }
4327
4328 static vartype *deserialize_list(const char *buf, int *pos) {
4329 int tstart;
4330 int tlen = get_token(buf, pos, &tstart);
4331 if (tlen != 1 || buf[tstart] != '{')
4332 return NULL;
4333 tlen = get_token(buf, pos, &tstart);
4334 if (tlen < 6 || strncmp(buf + tstart + tlen - 5, "-Elem", 5) != 0)
4335 return NULL;
4336 int len = parse_int(buf + tstart, tlen - 5);
4337 if (len == -1)
4338 return NULL;
4339 tlen = get_token(buf, pos, &tstart);
4340 if (tlen != 4 || strncmp(buf + tstart, "List", 4) != 0)
4341 return NULL;
4342 vartype_list *list = (vartype_list *) new_list(len);
4343 if (list == NULL)
4344 return NULL;
4345 for (int i = 0; i < len; i++) {
4346 tlen = get_token(buf, pos, &tstart);
4347 if (tlen == 0)
4348 goto failure;
4349 if (buf[tstart] == '{') {
4350 if (tlen != 1)
4351 goto failure;
4352 (*pos)--;
4353 vartype *e = deserialize_list(buf, pos);
4354 if (e == NULL)
4355 goto failure;
4356 list->array->data[i] = e;
4357 } else if (buf[tstart] == '[') {
4358 if (tlen != 1)
4359 goto failure;
4360 tlen = get_token(buf, pos, &tstart);
4361 if (tlen == 0)
4362 goto failure;
4363 int x = -1;
4364 for (int j = 0; j < tlen; j++) {
4365 if (buf[tstart + j] == 'x') {
4366 x = j;
4367 break;
4368 }
4369 }
4370 if (x == -1 || x == 0 || x == tlen - 1)
4371 goto failure;
4372 int rows = parse_int(buf + tstart, x);
4373 int cols = parse_int(buf + tstart + x + 1, tlen - x - 1);
4374 if (rows == -1 || cols == -1)
4375 goto failure;
4376 bool cpx;
4377 tlen = get_token(buf, pos, &tstart);
4378 vartype *m;
4379 if (tlen == 6 && strncmp(buf + tstart, "Matrix", 6) == 0) {
4380 m = new_realmatrix(rows, cols);
4381 if (m == NULL)
4382 goto failure;
4383 cpx = false;
4384 } else if (tlen == 3 && strncmp(buf + tstart, "Cpx", 3) == 0) {
4385 tlen = get_token(buf, pos, &tstart);
4386 if (tlen != 6 || strncmp(buf + tstart, "Matrix", 6) != 0)
4387 goto failure;
4388 m = new_complexmatrix(rows, cols);
4389 if (m == NULL)
4390 goto failure;
4391 cpx = true;
4392 } else
4393 goto failure;
4394 list->array->data[i] = m;
4395 int cells = rows * cols;
4396 for (int j = 0; j < cells; j++) {
4397 tlen = get_token(buf, pos, &tstart);
4398 if (tlen == 0)
4399 goto failure;
4400 if (buf[tstart] == '"') {
4401 if (cpx)
4402 goto failure;
4403 int slen;
4404 char *s = parse_string(buf + tstart, tlen, &slen);
4405 if (s == NULL)
4406 return NULL;
4407 bool res = put_matrix_string((vartype_realmatrix *) m, j, s, slen);
4408 free(s);
4409 if (!res)
4410 goto failure;
4411 } else {
4412 phloat re, im;
4413 int slen;
4414 int type = parse_scalar(buf + tstart, tlen, true, &re, &im, &slen);
4415 if (cpx) {
4416 if (type == TYPE_REAL)
4417 im = 0;
4418 else if (type != TYPE_COMPLEX)
4419 goto failure;
4420 vartype_complexmatrix *cm = (vartype_complexmatrix *) m;
4421 cm->array->data[j * 2] = re;
4422 cm->array->data[j * 2 + 1] = im;
4423 } else {
4424 if (type != TYPE_REAL)
4425 goto failure;
4426 vartype_realmatrix *rm = (vartype_realmatrix *) m;
4427 rm->array->data[j] = re;
4428 }
4429 }
4430 }
4431 tlen = get_token(buf, pos, &tstart);
4432 if (tlen != 1 || buf[tstart] != ']')
4433 goto failure;
4434 } else if (buf[tstart] == '"') {
4435 int slen;
4436 char *s = parse_string(buf + tstart, tlen, &slen);
4437 if (s == NULL)
4438 return NULL;
4439 vartype *str = new_string(s, slen);
4440 free(s);
4441 if (str == NULL)
4442 goto failure;
4443 list->array->data[i] = str;
4444 } else {
4445 phloat re, im;
4446 int slen;
4447 int type = parse_scalar(buf + tstart, tlen, true, &re, &im, &slen);
4448 vartype *v;
4449 if (type == TYPE_REAL)
4450 v = new_real(re);
4451 else if (type == TYPE_COMPLEX)
4452 v = new_complex(re, im);
4453 else
4454 goto failure;
4455 if (v == NULL)
4456 goto failure;
4457 list->array->data[i] = v;
4458 }
4459 }
4460 tlen = get_token(buf, pos, &tstart);
4461 if (tlen != 1 || buf[tstart] != '}') {
4462 failure:
4463 free_vartype((vartype *) list);
4464 return NULL;
4465 } else
4466 return (vartype *) list;
4467 }
4468
4469 void core_paste(const char *buf) {
4470 if (mode_interruptible != NULL)
4471 stop_interruptible();
4472 set_running(false);
4473
4474 if (mode_command_entry) {
4475 if (incomplete_alpha) {
4476 char hpbuf[26];
4477 int len = ascii2hp(hpbuf, 22, buf);
4478 int maxlen = incomplete_argtype == ARG_XSTR ? 22 : 7;
4479 maxlen -= incomplete_length;
4480 if (len > maxlen)
4481 len = maxlen;
4482 if (len == 0) {
4483 squeak();
4484 return;
4485 } else {
4486 memcpy(incomplete_str + incomplete_length, hpbuf, len);
4487 incomplete_length += len;
4488 }
4489 } else {
4490 squeak();
4491 return;
4492 }
4493 } else if (flags.f.prgm_mode) {
4494 paste_programs(buf);
4495 } else if (alpha_active()) {
4496 char hpbuf[48];
4497 int len = ascii2hp(hpbuf, 44, buf);
4498 int tlen = len + reg_alpha_length;
4499 if (tlen > 44) {
4500 int off = tlen - 44;
4501 memmove(reg_alpha, reg_alpha + off, off);
4502 reg_alpha_length -= off;
4503 }
4504 memcpy(reg_alpha + reg_alpha_length, hpbuf, len);
4505 reg_alpha_length += len;
4506 if (len > 0) {
4507 flags.f.alpha_data_input = 1;
4508 if (flags.f.trace_print && flags.f.printer_exists)
4509 docmd_pra(NULL);
4510 }
4511 } else {
4512 int rows = 0, cols = 0;
4513 int col = 1;
4514 int max_cell_size = 0;
4515 int cell_size = 0;
4516 int pos = 0;
4517 char lastchar, c = 0;
4518 vartype *v;
4519 if (buf[0] == '{') {
4520 // Try to parse a list; if unsuccessful, fall back on TSV parsing
4521 int tpos = 0;
4522 v = deserialize_list(buf, &tpos);
4523 if (v != NULL)
4524 goto parse_success;
4525 }
4526 while (true) {
4527 lastchar = c;
4528 c = buf[pos++];
4529 if (c == 0)
4530 break;
4531 if (c == '\r') {
4532 c = '\n';
4533 if (buf[pos] == '\n')
4534 pos++;
4535 }
4536 if (c == '\n') {
4537 rows++;
4538 if (cols < col)
4539 cols = col;
4540 col = 1;
4541 goto check_cell_size;
4542 } else if (c == '\t') {
4543 col++;
4544 check_cell_size:
4545 if (max_cell_size < cell_size)
4546 max_cell_size = cell_size;
4547 cell_size = 0;
4548 } else {
4549 cell_size++;
4550 }
4551 }
4552 if (lastchar != 0 && lastchar != '\n') {
4553 rows++;
4554 if (cols < col)
4555 cols = col;
4556 if (max_cell_size < cell_size)
4557 max_cell_size = cell_size;
4558 }
4559 if (rows == 0) {
4560 return;
4561 } else if (rows == 1 && cols == 1) {
4562 // Scalar
4563 int len = (int) strlen(buf);
4564 if (len > 0 && buf[len - 1] == '\n') {
4565 len--;
4566 if (len > 0 && buf[len - 1] == '\r')
4567 len--;
4568 }
4569 char *hpbuf = (char *) malloc(len + 4);
4570 if (hpbuf == NULL) {
4571 display_error(ERR_INSUFFICIENT_MEMORY);
4572 redisplay();
4573 return;
4574 }
4575 len = ascii2hp(hpbuf, len, buf, len);
4576 v = parse_base(hpbuf, len);
4577 if (v == NULL) {
4578 phloat re, im;
4579 int slen;
4580 const char *format = core_settings.localized_copy_paste ? number_format() : NULL;
4581 int type = parse_scalar(hpbuf, len, false, &re, &im, &slen, format);
4582 switch (type) {
4583 case TYPE_REAL:
4584 v = new_real(re);
4585 break;
4586 case TYPE_COMPLEX:
4587 v = new_complex(re, im);
4588 break;
4589 case TYPE_STRING:
4590 v = new_string(hpbuf, slen);
4591 break;
4592 }
4593 if (v == NULL) {
4594 display_error(ERR_INSUFFICIENT_MEMORY);
4595 redisplay();
4596 return;
4597 }
4598 }
4599 free(hpbuf);
4600 } else {
4601 // Matrix
4602 int n = rows * cols;
4603 phloat *data = (phloat *) malloc(n * sizeof(phloat));
4604 if (data == NULL) {
4605 display_error(ERR_INSUFFICIENT_MEMORY);
4606 redisplay();
4607 return;
4608 }
4609 char *is_string = (char *) malloc(n);
4610 if (is_string == NULL) {
4611 free(data);
4612 display_error(ERR_INSUFFICIENT_MEMORY);
4613 redisplay();
4614 return;
4615 }
4616 char *hpbuf = (char *) malloc(max_cell_size + 5);
4617 if (hpbuf == NULL) {
4618 free(data);
4619 free(is_string);
4620 display_error(ERR_INSUFFICIENT_MEMORY);
4621 redisplay();
4622 return;
4623 }
4624 int pos = 0;
4625 int spos = 0;
4626 int p = 0, row = 0, col = 0;
4627 const char *format = core_settings.localized_copy_paste ? number_format() : NULL;
4628 while (row < rows) {
4629 c = buf[pos++];
4630 if (c == 0 || c == '\t' || c == '\r' || c == '\n') {
4631 int cellsize = pos - spos - 1;
4632 if (c == '\r') {
4633 c = '\n';
4634 if (buf[pos] == '\n')
4635 pos++;
4636 }
4637 int hplen = ascii2hp(hpbuf, cellsize, buf + spos, cellsize);
4638 spos = pos;
4639 phloat re, im;
4640 int slen;
4641 int type = parse_scalar(hpbuf, hplen, true, &re, &im, &slen, format);
4642 if (is_string != NULL) {
4643 switch (type) {
4644 case TYPE_REAL:
4645 data[p] = re;
4646 is_string[p] = 0;
4647 break;
4648 case TYPE_COMPLEX:
4649 free_long_strings(is_string, data, p);
4650 for (int i = 0; i < p; i++)
4651 if (is_string[i] != 0)
4652 data[i] = 0;
4653 free(is_string);
4654 is_string = NULL;
4655 phloat *newdata;
4656 newdata = (phloat *) realloc((void *) data, 2 * n * sizeof(phloat));
4657 if (newdata == NULL) {
4658 nomem:
4659 free(data);
4660 free(hpbuf);
4661 display_error(ERR_INSUFFICIENT_MEMORY);
4662 redisplay();
4663 return;
4664 }
4665 data = newdata;
4666 for (int i = p - 1; i >= 0; i--) {
4667 data[i * 2] = data[i];
4668 data[i * 2 + 1] = 0;
4669 }
4670 p *= 2;
4671 data[p] = re;
4672 data[p + 1] = im;
4673 goto finish_complex_cell;
4674 case TYPE_STRING:
4675 if (slen == 0) {
4676 data[p] = 0;
4677 is_string[p] = 0;
4678 } else if (slen <= SSLENM) {
4679 char *text = (char *) &data[p];
4680 *text = slen;
4681 memcpy(text + 1, hpbuf, slen);
4682 is_string[p] = 1;
4683 } else {
4684 int4 *t = (int4 *) malloc(slen + 4);
4685 if (t == NULL) {
4686 free_long_strings(is_string, data, p);
4687 free(is_string);
4688 goto nomem;
4689 }
4690 *t = slen;
4691 memcpy(t + 1, hpbuf, slen);
4692 *(int4 **) &data[p] = t;
4693 is_string[p] = 2;
4694 }
4695 break;
4696 }
4697 p++;
4698 col++;
4699 if (c == 0 || c == '\n') {
4700 while (col++ < cols) {
4701 data[p] = 0;
4702 is_string[p] = 0;
4703 p++;
4704 }
4705 col = 0;
4706 row++;
4707 }
4708 } else {
4709 switch (type) {
4710 case TYPE_REAL:
4711 data[p] = re;
4712 data[p + 1] = 0;
4713 break;
4714 case TYPE_COMPLEX:
4715 data[p] = re;
4716 data[p + 1] = im;
4717 break;
4718 case TYPE_STRING:
4719 data[p] = 0;
4720 data[p + 1] = 0;
4721 break;
4722 }
4723 finish_complex_cell:
4724 p += 2;
4725 col++;
4726 if (c == 0 || c == '\n') {
4727 while (col++ < cols) {
4728 data[p] = 0;
4729 data[p + 1] = 0;
4730 p += 2;
4731 }
4732 col = 0;
4733 row++;
4734 }
4735 }
4736 }
4737 if (c == 0)
4738 break;
4739 }
4740
4741 free(hpbuf);
4742 if (is_string != NULL) {
4743 vartype_realmatrix *rm = (vartype_realmatrix *)
4744 malloc(sizeof(vartype_realmatrix));
4745 if (rm == NULL) {
4746 free_long_strings(is_string, data, p);
4747 free(data);
4748 free(is_string);
4749 display_error(ERR_INSUFFICIENT_MEMORY);
4750 redisplay();
4751 return;
4752 }
4753 rm->array = (realmatrix_data *)
4754 malloc(sizeof(realmatrix_data));
4755 if (rm->array == NULL) {
4756 free(rm);
4757 free_long_strings(is_string, data, p);
4758 free(data);
4759 free(is_string);
4760 display_error(ERR_INSUFFICIENT_MEMORY);
4761 redisplay();
4762 return;
4763 }
4764 rm->type = TYPE_REALMATRIX;
4765 rm->rows = rows;
4766 rm->columns = cols;
4767 rm->array->data = data;
4768 rm->array->is_string = is_string;
4769 rm->array->refcount = 1;
4770 v = (vartype *) rm;
4771 } else {
4772 vartype_complexmatrix *cm = (vartype_complexmatrix *)
4773 malloc(sizeof(vartype_complexmatrix));
4774 if (cm == NULL) {
4775 free(data);
4776 display_error(ERR_INSUFFICIENT_MEMORY);
4777 redisplay();
4778 return;
4779 }
4780 cm->array = (complexmatrix_data *)
4781 malloc(sizeof(complexmatrix_data));
4782 if (cm->array == NULL) {
4783 free(cm);
4784 free(data);
4785 display_error(ERR_INSUFFICIENT_MEMORY);
4786 redisplay();
4787 return;
4788 }
4789 cm->type = TYPE_COMPLEXMATRIX;
4790 cm->rows = rows;
4791 cm->columns = cols;
4792 cm->array->data = data;
4793 cm->array->refcount = 1;
4794 v = (vartype *) cm;
4795 }
4796 }
4797 parse_success:
4798 if (recall_result(v) != ERR_NONE) {
4799 display_error(ERR_INSUFFICIENT_MEMORY);
4800 redisplay();
4801 return;
4802 }
4803 mode_number_entry = false;
4804 mode_varmenu = false;
4805 flags.f.stack_lift_disable = 0;
4806 if (v->type == TYPE_REAL || v->type == TYPE_COMPLEX)
4807 flags.f.numeric_data_input = 1;
4808 }
4809 flags.f.message = 0;
4810 flags.f.two_line_message = 0;
4811 redisplay();
4812 }
4813
4814 #if defined(ANDROID) || defined(IPHONE)
4815
4816 void core_get_char_pixels(const char *ch, char *pixels) {
4817 char hpbuf[6];
4818 int hplen = ascii2hp(hpbuf, 1, ch);
4819 if (hplen == 0)
4820 hpbuf[0] = ' ';
4821 const unsigned char *bits = get_char(hpbuf[0]);
4822 for (int i = 0; i < 5; i++)
4823 pixels[i] = bits[i];
4824 }
4825
4826 #endif
4827
4828 void set_alpha_entry(bool state) {
4829 mode_alpha_entry = state;
4830 }
4831
4832 void set_running(bool state) {
4833 if (mode_running != state) {
4834 mode_running = state;
4835 set_annunciators(-1, -1, -1, state, -1, -1);
4836 }
4837 if (state) {
4838 /* Cancel any pending INPUT command */
4839 input_length = 0;
4840 mode_goose = -2;
4841 prgm_highlight_row = 1;
4842 }
4843 }
4844
4845 bool program_running() {
4846 return mode_running;
4847 }
4848
4849 void do_interactive(int command) {
4850 int err;
4851 if ((cmd_array[command].flags
4852 & (flags.f.prgm_mode ? FLAG_NO_PRGM : FLAG_PRGM_ONLY)) != 0) {
4853 display_error(ERR_RESTRICTED_OPERATION);
4854 redisplay();
4855 return;
4856 }
4857 if (command == CMD_GOTOROW) {
4858 if (sp != -1) {
4859 err = docmd_stoel(NULL);
4860 if (err != ERR_NONE && err != ERR_NONEXISTENT) {
4861 // Nonexistent happens with empty lists
4862 display_error(err);
4863 redisplay();
4864 return;
4865 }
4866 }
4867 } else if (command == CMD_A_THRU_F) {
4868 print_menu_trace("A...F", 5);
4869 set_base(16);
4870 set_menu(MENULEVEL_APP, MENU_BASE_A_THRU_F);
4871 redisplay();
4872 return;
4873 } else if (command == CMD_CLALLa) {
4874 mode_clall = true;
4875 set_menu(MENULEVEL_ALPHA, MENU_NONE);
4876 redisplay();
4877 return;
4878 } else if (command == CMD_CLV || command == CMD_PRV || command == CMD_LCLV) {
4879 if (!flags.f.prgm_mode && vars_count == 0) {
4880 display_error(ERR_NO_VARIABLES);
4881 redisplay();
4882 return;
4883 }
4884 } else if ((command == CMD_SST || command == CMD_SST_UP
4885 || command == CMD_SST_RT) && flags.f.prgm_mode) {
4886 sst();
4887 redisplay();
4888 repeating = 1;
4889 repeating_shift = 1;
4890 repeating_key = KEY_DOWN;
4891 return;
4892 } else if (command == CMD_BST) {
4893 bst();
4894 if (!flags.f.prgm_mode) {
4895 flags.f.prgm_mode = 1;
4896 redisplay();
4897 flags.f.prgm_mode = 0;
4898 pending_command = CMD_CANCELLED;
4899 } else
4900 redisplay();
4901 repeating = 1;
4902 repeating_shift = 1;
4903 repeating_key = KEY_UP;
4904 return;
4905 }
4906
4907 if (flags.f.prgm_mode && (cmd_array[command].flags & FLAG_IMMED) == 0) {
4908 if (command == CMD_RUN)
4909 command = CMD_STOP;
4910 if (cmd_array[command].argtype == ARG_NONE) {
4911 arg_struct arg;
4912 arg.type = ARGTYPE_NONE;
4913 store_command_after(&pc, command, &arg, NULL);
4914 if (command == CMD_END)
4915 pc = 0;
4916 prgm_highlight_row = 1;
4917 redisplay();
4918 } else {
4919 incomplete_saved_pc = pc;
4920 incomplete_saved_highlight_row = prgm_highlight_row;
4921 if (pc == -1)
4922 pc = 0;
4923 else if (!prgms[current_prgm].is_end(pc))
4924 pc += get_command_length(current_prgm, pc);
4925 prgm_highlight_row = 1;
4926 start_incomplete_command(command);
4927 }
4928 } else {
4929 if (cmd_array[command].argtype == ARG_NONE)
4930 pending_command = command;
4931 else {
4932 if (flags.f.prgm_mode) {
4933 incomplete_saved_pc = pc;
4934 incomplete_saved_highlight_row = prgm_highlight_row;
4935 }
4936 start_incomplete_command(command);
4937 }
4938 }
4939 }
4940
4941 static void continue_running() {
4942 int error;
4943 do {
4944 int cmd;
4945 arg_struct arg;
4946 oldpc = pc;
4947 if (pc == -1)
4948 pc = 0;
4949 else if (pc >= prgms[current_prgm].size) {
4950 pc = -1;
4951 set_running(false);
4952 return;
4953 }
4954 get_next_command(&pc, &cmd, &arg, 1, NULL);
4955 if (flags.f.trace_print && flags.f.printer_exists) {
4956 if (cmd == CMD_LBL)
4957 print_text(NULL, 0, true);
4958 print_program_line(current_prgm, oldpc);
4959 }
4960 mode_disable_stack_lift = false;
4961 error = handle(cmd, &arg);
4962 if (mode_pause) {
4963 shell_request_timeout3(1000);
4964 return;
4965 }
4966 if (quitting)
4967 return;
4968 if (error == ERR_INTERRUPTIBLE)
4969 return;
4970 if (!handle_error(error))
4971 return;
4972 if (mode_getkey)
4973 return;
4974 } while (!shell_wants_cpu());
4975 }
4976
4977 struct synonym_spec {
4978 char name[7];
4979 bool is_orig;
4980 int namelen;
4981 int cmd_id;
4982 };
4983
4984 static synonym_spec hp41_synonyms[] =
4985 {
4986 { "*", true, 1, CMD_MUL },
4987 { "x", false, 1, CMD_MUL },
4988 { "/", true, 1, CMD_DIV },
4989 { "CHS", true, 3, CMD_CHS },
4990 { "DEC", true, 3, CMD_TO_DEC },
4991 { "D-R", true, 3, CMD_TO_RAD },
4992 { "ENTER^", true, 6, CMD_ENTER },
4993 { "FACT", true, 4, CMD_FACT },
4994 { "FRC", true, 3, CMD_FP },
4995 { "HMS", true, 3, CMD_TO_HMS },
4996 { "HR", true, 2, CMD_TO_HR },
4997 { "INT", true, 3, CMD_IP },
4998 { "OCT", true, 3, CMD_TO_OCT },
4999 { "P-R", true, 3, CMD_TO_REC },
5000 { "R-D", true, 3, CMD_TO_DEG },
5001 { "RCL*", false, 4, CMD_RCL_MUL },
5002 { "RCLx", false, 4, CMD_RCL_MUL },
5003 { "RCL/", false, 4, CMD_RCL_DIV },
5004 { "RDN", true, 3, CMD_RDN },
5005 { "Rv", false, 2, CMD_RDN },
5006 { "R-P", true, 3, CMD_TO_POL },
5007 { "ST+", true, 3, CMD_STO_ADD },
5008 { "ST-", true, 3, CMD_STO_SUB },
5009 { "ST*", true, 3, CMD_STO_MUL },
5010 { "ST/", true, 3, CMD_STO_DIV },
5011 { "STO*", false, 4, CMD_STO_MUL },
5012 { "STOx", false, 4, CMD_STO_MUL },
5013 { "STO/", false, 4, CMD_STO_DIV },
5014 { "X<=0?", true, 5, CMD_X_LE_0 },
5015 { "X<=Y?", true, 5, CMD_X_LE_Y },
5016 { "X#0?", false, 4, CMD_X_NE_0 },
5017 { "X#Y?", false, 4, CMD_X_NE_Y },
5018 { "X<>0?", false, 5, CMD_X_NE_0 },
5019 { "X<>Y?", false, 5, CMD_X_NE_Y },
5020 { "v", false, 1, CMD_DOWN },
5021 { "SST\16", true, 4, CMD_SST },
5022 { "X>=0?", false, 5, CMD_X_GE_0 },
5023 { "X>=Y?", false, 5, CMD_X_GE_Y },
5024 { "X<>?", false, 4, CMD_X_NE_NN },
5025 { "X#?", false, 3, CMD_X_NE_NN },
5026 { "X<=?", false, 4, CMD_X_LE_NN },
5027 { "X>=?", false, 4, CMD_X_GE_NN },
5028 { "0<>?", false, 4, CMD_0_NE_NN },
5029 { "0#?", false, 3, CMD_0_NE_NN },
5030 { "0<=?", false, 4, CMD_0_LE_NN },
5031 { "0>=?", false, 4, CMD_0_GE_NN },
5032 { "", true, 0, CMD_NONE }
5033 };
5034
5035 int find_builtin(const char *name, int namelen) {
5036 for (int i = 0; hp41_synonyms[i].cmd_id != CMD_NONE; i++) {
5037 if (namelen != hp41_synonyms[i].namelen)
5038 continue;
5039 for (int j = 0; j < namelen; j++)
5040 if (name[j] != hp41_synonyms[i].name[j])
5041 goto nomatch1;
5042 return hp41_synonyms[i].cmd_id;
5043 nomatch1:;
5044 }
5045
5046 int fuzzy_match = CMD_NONE;
5047
5048 for (int i = 0; i < CMD_SENTINEL; i++) {
5049 if ((cmd_array[i].flags & FLAG_HIDDEN) != 0)
5050 continue;
5051 if (cmd_array[i].name_length != namelen)
5052 continue;
5053 bool exact = true;
5054 for (int j = 0; j < namelen; j++) {
5055 unsigned char c1, c2;
5056 c1 = name[j];
5057 if (undefined_char(c1))
5058 c1 &= 127;
5059 else if (c1 == 30)
5060 c1 = 94;
5061 c2 = cmd_array[i].name[j];
5062 if (undefined_char(c2))
5063 c2 &= 127;
5064 else if (c2 == 30)
5065 c2 = 94;
5066 if (c1 != c2)
5067 if (c1 == '-' && c2 == '\17')
5068 exact = false;
5069 else
5070 goto nomatch2;
5071 }
5072 if (exact)
5073 return i;
5074 else
5075 fuzzy_match = i;
5076 nomatch2:;
5077 }
5078 return fuzzy_match;
5079 }
5080
5081 void sst() {
5082 if (pc >= prgms[current_prgm].size - 2) {
5083 pc = -1;
5084 prgm_highlight_row = 0;
5085 } else {
5086 if (pc == -1)
5087 pc = 0;
5088 else
5089 pc += get_command_length(current_prgm, pc);
5090 prgm_highlight_row = 1;
5091 }
5092 }
5093
5094 void bst() {
5095 int4 line = pc2line(pc);
5096 if (line == 0) {
5097 pc = prgms[current_prgm].size - 2;
5098 prgm_highlight_row = 1;
5099 } else {
5100 pc = line2pc(line - 1);
5101 prgm_highlight_row = 0;
5102 }
5103 }
5104
5105 int find_menu_key(int key) {
5106 switch (key) {
5107 case KEY_SIGMA: return 0;
5108 case KEY_INV: return 1;
5109 case KEY_SQRT: return 2;
5110 case KEY_LOG: return 3;
5111 case KEY_LN: return 4;
5112 case KEY_XEQ: return 5;
5113 default: return -1;
5114 }
5115 }
5116
5117 void start_incomplete_command(int cmd_id) {
5118 int argtype = cmd_array[cmd_id].argtype;
5119 if (!flags.f.prgm_mode && (cmd_array[cmd_id].flags & FLAG_PRGM_ONLY) != 0) {
5120 display_error(ERR_RESTRICTED_OPERATION);
5121 redisplay();
5122 return;
5123 }
5124 incomplete_command = cmd_id;
5125 incomplete_ind = false;
5126 if (argtype == ARG_NAMED || argtype == ARG_PRGM
5127 || argtype == ARG_RVAR || argtype == ARG_MAT
5128 || argtype == ARG_M_STK || argtype == ARG_L_STK
5129 || argtype == ARG_XSTR)
5130 incomplete_alpha = true;
5131 else
5132 incomplete_alpha = false;
5133 incomplete_length = 0;
5134 incomplete_num = 0;
5135 if (argtype == ARG_NUM9)
5136 incomplete_maxdigits = 1;
5137 else if (argtype == ARG_COUNT)
5138 incomplete_maxdigits = cmd_id == CMD_SIMQ ? 2 : 4;
5139 else
5140 incomplete_maxdigits = 2;
5141 incomplete_argtype = argtype;
5142 mode_command_entry = true;
5143 if (incomplete_command == CMD_ASSIGNa) {
5144 set_catalog_menu(CATSECT_TOP);
5145 flags.f.local_label = 0;
5146 } else if (argtype == ARG_CKEY)
5147 set_menu(MENULEVEL_COMMAND, MENU_CUSTOM1);
5148 else if (argtype == ARG_MKEY)
5149 set_menu(MENULEVEL_COMMAND, MENU_BLANK);
5150 else if (argtype == ARG_VAR) {
5151 if (mode_alphamenu != MENU_NONE || mode_plainmenu != MENU_NONE)
5152 set_catalog_menu(CATSECT_VARS_ONLY);
5153 else if (mode_appmenu == MENU_VARMENU)
5154 mode_commandmenu = MENU_VARMENU;
5155 else if (mode_appmenu == MENU_INTEG_PARAMS)
5156 mode_commandmenu = MENU_INTEG_PARAMS;
5157 else
5158 set_catalog_menu(CATSECT_VARS_ONLY);
5159 } else if (argtype == ARG_NAMED)
5160 set_catalog_menu(CATSECT_VARS_ONLY);
5161 else if (argtype == ARG_REAL) {
5162 if (mode_alphamenu != MENU_NONE || mode_plainmenu != MENU_NONE)
5163 set_catalog_menu(CATSECT_REAL_ONLY);
5164 else if (mode_appmenu == MENU_VARMENU)
5165 mode_commandmenu = MENU_VARMENU;
5166 else if (mode_appmenu == MENU_INTEG_PARAMS)
5167 mode_commandmenu = MENU_INTEG_PARAMS;
5168 else
5169 set_catalog_menu(CATSECT_REAL_ONLY);
5170 } else if (argtype == ARG_RVAR) {
5171 if (vars_exist(CATSECT_REAL))
5172 set_catalog_menu(CATSECT_REAL_ONLY);
5173 else if (flags.f.prgm_mode) {
5174 if (incomplete_command == CMD_MVAR)
5175 mode_commandmenu = MENU_ALPHA1;
5176 } else {
5177 mode_command_entry = false;
5178 display_error(ERR_NO_REAL_VARIABLES);
5179 }
5180 } else if (argtype == ARG_MAT) {
5181 if (flags.f.prgm_mode || vars_exist(CATSECT_MAT_LIST))
5182 set_catalog_menu(CATSECT_MAT_LIST_ONLY);
5183 else if (cmd_id != CMD_DIM) {
5184 mode_command_entry = false;
5185 display_error(ERR_NO_MATRIX_VARIABLES);
5186 }
5187 } else if (argtype == ARG_M_STK) {
5188 if (flags.f.prgm_mode || vars_exist(CATSECT_MAT))
5189 set_catalog_menu(CATSECT_MAT_ONLY);
5190 } else if (argtype == ARG_L_STK) {
5191 if (flags.f.prgm_mode || vars_exist(CATSECT_LIST))
5192 set_catalog_menu(CATSECT_LIST_ONLY);
5193 } else if (argtype == ARG_LBL || argtype == ARG_PRGM)
5194 set_catalog_menu(CATSECT_PGM_ONLY);
5195 else if (cmd_id == CMD_LBL || cmd_id == CMD_XSTR)
5196 set_menu(MENULEVEL_COMMAND, MENU_ALPHA1);
5197 redisplay();
5198 }
5199
5200 void finish_command_entry(bool refresh) {
5201 if (pending_command == CMD_ASSIGNa) {
5202 pending_command = CMD_NONE;
5203 start_incomplete_command(CMD_ASSIGNb);
5204 return;
5205 }
5206 mode_command_entry = false;
5207 if (flags.f.prgm_mode) {
5208 set_menu(MENULEVEL_COMMAND, MENU_NONE);
5209 if (pending_command == CMD_NULL || pending_command == CMD_CANCELLED) {
5210 pc = incomplete_saved_pc;
5211 prgm_highlight_row = incomplete_saved_highlight_row;
5212 } else if (pending_command == CMD_SST || pending_command == CMD_SST_UP
5213 || pending_command == CMD_SST_RT || pending_command == CMD_BST) {
5214 pc = incomplete_saved_pc;
5215 prgm_highlight_row = incomplete_saved_highlight_row;
5216 if (pending_command == CMD_BST)
5217 bst();
5218 else
5219 sst();
5220 repeating = 1;
5221 repeating_shift = 1;
5222 repeating_key = pending_command == CMD_BST ? KEY_UP : KEY_DOWN;
5223 pending_command = CMD_NONE;
5224 redisplay();
5225 } else {
5226 int inserting_an_end = pending_command == CMD_END;
5227 if ((cmd_array[pending_command].flags & FLAG_IMMED) != 0) {
5228 pc = incomplete_saved_pc;
5229 prgm_highlight_row = incomplete_saved_highlight_row;
5230 goto do_it_now;
5231 }
5232 store_command(pc, pending_command, &pending_command_arg, NULL);
5233 if (inserting_an_end)
5234 /* current_prgm was already incremented by store_command() */
5235 pc = 0;
5236 prgm_highlight_row = 1;
5237 pending_command = CMD_NONE;
5238 redisplay();
5239 }
5240 } else {
5241 do_it_now:
5242 if (refresh)
5243 redisplay();
5244 if (mode_commandmenu == MENU_CATALOG
5245 && (pending_command == CMD_GTO
5246 || pending_command == CMD_XEQ)) {
5247 /* TODO: also applies to CLP, PRP, and maybe more.
5248 * Does *not* apply to the program menus displayed by VARMENU,
5249 * PGMINT, PGMSLV, and... (?)
5250 */
5251 int catsect = get_cat_section();
5252 if (catsect == CATSECT_PGM || catsect == CATSECT_PGM_ONLY) {
5253 int row = get_cat_row();
5254 set_menu(MENULEVEL_TRANSIENT, mode_commandmenu);
5255 set_cat_section(catsect);
5256 set_cat_row(row);
5257 remove_program_catalog = 1;
5258 }
5259 }
5260 if (pending_command == CMD_ASSIGNb
5261 || (pending_command >= CMD_ASGN01
5262 && pending_command <= CMD_ASGN18)) {
5263 set_menu(MENULEVEL_PLAIN, mode_commandmenu);
5264 mode_plainmenu_sticky = true;
5265 }
5266 set_menu(MENULEVEL_COMMAND, MENU_NONE);
5267 if (pending_command == CMD_BST) {
5268 bst();
5269 flags.f.prgm_mode = 1;
5270 redisplay();
5271 flags.f.prgm_mode = 0;
5272 pending_command = CMD_CANCELLED;
5273 repeating = 1;
5274 repeating_shift = 1;
5275 repeating_key = KEY_UP;
5276 }
5277 }
5278 }
5279
5280 void finish_xeq() {
5281 int prgm;
5282 int4 pc;
5283 int cmd;
5284
5285 if (find_global_label(&pending_command_arg, &prgm, &pc))
5286 cmd = CMD_NONE;
5287 else
5288 cmd = find_builtin(pending_command_arg.val.text,
5289 pending_command_arg.length);
5290
5291 if (cmd == CMD_CLALLa) {
5292 mode_clall = true;
5293 set_menu(MENULEVEL_ALPHA, MENU_NONE);
5294 mode_command_entry = false;
5295 pending_command = CMD_NONE;
5296 redisplay();
5297 return;
5298 }
5299
5300 if (cmd == CMD_NONE)
5301 finish_command_entry(true);
5302 else {
5303 /* Show the entered command in its XEQ "FOO"
5304 * form, briefly, just to confirm to the user
5305 * what they've entered; this will be replaced
5306 * by the matching built-in command after the
5307 * usual brief delay (timeout1() or the
5308 * explicit delay, below).
5309 */
5310 mode_command_entry = false;
5311 redisplay();
5312 if (cmd_array[cmd].argtype == ARG_NONE) {
5313 pending_command = cmd;
5314 pending_command_arg.type = ARGTYPE_NONE;
5315 finish_command_entry(false);
5316 return;
5317 } else {
5318 shell_delay(250);
5319 pending_command = CMD_NONE;
5320 set_menu(MENULEVEL_COMMAND, MENU_NONE);
5321 if ((cmd == CMD_CLV || cmd == CMD_PRV || cmd == CMD_LCLV)
5322 && !flags.f.prgm_mode && vars_count == 0) {
5323 display_error(ERR_NO_VARIABLES);
5324 pending_command = CMD_NONE;
5325 redisplay();
5326 } else
5327 start_incomplete_command(cmd);
5328 return;
5329 }
5330 }
5331 }
5332
5333 bool start_alpha_prgm_line() {
5334 if (flags.f.prgm_mode && prgms[current_prgm].locked)
5335 return false;
5336 incomplete_saved_pc = pc;
5337 incomplete_saved_highlight_row = prgm_highlight_row;
5338 if (pc == -1)
5339 pc = 0;
5340 else if (!prgms[current_prgm].is_end(pc))
5341 pc += get_command_length(current_prgm, pc);
5342 prgm_highlight_row = 1;
5343 if (cmdline_row == 1)
5344 display_prgm_line(0, -1);
5345 entered_string_length = 0;
5346 mode_alpha_entry = true;
5347 return true;
5348 }
5349
5350 void finish_alpha_prgm_line() {
5351 if (entered_string_length == 0) {
5352 pc = incomplete_saved_pc;
5353 prgm_highlight_row = incomplete_saved_highlight_row;
5354 } else {
5355 arg_struct arg;
5356 int i;
5357 arg.type = ARGTYPE_STR;
5358 arg.length = entered_string_length;
5359 for (i = 0; i < entered_string_length; i++)
5360 arg.val.text[i] = entered_string[i];
5361 store_command(pc, CMD_STRING, &arg, NULL);
5362 prgm_highlight_row = 1;
5363 }
5364 mode_alpha_entry = false;
5365 }
5366
5367 static void stop_interruptible() {
5368 int error = mode_interruptible(true);
5369 handle_error(error);
5370 mode_interruptible = NULL;
5371 if (mode_running)
5372 set_running(false);
5373 else
5374 set_annunciators(-1, -1, -1, false, -1, -1);
5375 pending_command = CMD_NONE;
5376 redisplay();
5377 }
5378
5379 void set_old_pc(int4 pc) {
5380 oldpc = pc;
5381 }
5382
5383 static void set_last_err(int error) {
5384 if (error <= RTNERR_MAX) {
5385 lasterr = error;
5386 } else {
5387 lasterr = -1;
5388 string_copy(lasterr_text, &lasterr_length, errors[error].text, errors[error].length);
5389 }
5390 }
5391
5392 static bool handle_error(int error) {
5393 if (mode_running) {
5394 if (error == ERR_RUN)
5395 error = ERR_NONE;
5396 if (error == ERR_NONE || error == ERR_NO || error == ERR_YES
5397 || error == ERR_STOP)
5398 flags.f.stack_lift_disable = mode_disable_stack_lift;
5399 if (error == ERR_NO) {
5400 if (!prgms[current_prgm].is_end(pc))
5401 pc += get_command_length(current_prgm, pc);
5402 } else if (error == ERR_STOP) {
5403 if (pc >= prgms[current_prgm].size)
5404 pc = -1;
5405 set_running(false);
5406 return false;
5407 } else if (error == ERR_NUMBER_TOO_LARGE
5408 || error == ERR_NUMBER_TOO_SMALL) {
5409 // Handling these separately because they shouldn't be
5410 // suppressed by flag 25, nor trapped by SOLVE
5411 goto handle_it;
5412 } else if (error != ERR_NONE && error != ERR_YES) {
5413 if (flags.f.error_ignore && error != ERR_SUSPICIOUS_OFF) {
5414 flags.f.error_ignore = 0;
5415 set_last_err(error);
5416 return true;
5417 }
5418 if (solve_active() && (error == ERR_OUT_OF_RANGE
5419 || error == ERR_DIVIDE_BY_0
5420 || error == ERR_INVALID_DATA
5421 || error == ERR_STAT_MATH_ERROR)) {
5422 bool stop = unwind_stack_until_solve();
5423 error = return_to_solve(1, stop);
5424 if (error == ERR_STOP)
5425 set_running(false);
5426 if (error == ERR_NONE || error == ERR_RUN || error == ERR_STOP)
5427 return false;
5428 }
5429 handle_it:
5430 pc = oldpc;
5431 display_error(error);
5432 set_running(false);
5433 return false;
5434 }
5435 return true;
5436 } else if (pending_command == CMD_SST || pending_command == CMD_SST_RT) {
5437 if (error == ERR_RUN)
5438 error = ERR_NONE;
5439 if (error == ERR_NONE || error == ERR_NO || error == ERR_YES
5440 || error == ERR_STOP)
5441 flags.f.stack_lift_disable = mode_disable_stack_lift;
5442 if (error == ERR_NO) {
5443 if (!prgms[current_prgm].is_end(pc))
5444 pc += get_command_length(current_prgm, pc);
5445 goto noerr;
5446 } else if (error == ERR_NONE || error == ERR_YES || error == ERR_STOP) {
5447 noerr:
5448 error = ERR_NONE;
5449 if (pc > prgms[current_prgm].size)
5450 pc = -1;
5451 } else if (error == ERR_NUMBER_TOO_LARGE
5452 || error == ERR_NUMBER_TOO_SMALL) {
5453 // Handling these separately because they shouldn't be
5454 // suppressed by flag 25, nor trapped by SOLVE
5455 goto handle_it_2;
5456 } else {
5457 if (flags.f.error_ignore) {
5458 flags.f.error_ignore = 0;
5459 set_last_err(error);
5460 goto noerr;
5461 }
5462 if (solve_active() && (error == ERR_OUT_OF_RANGE
5463 || error == ERR_DIVIDE_BY_0
5464 || error == ERR_INVALID_DATA
5465 || error == ERR_STAT_MATH_ERROR)) {
5466 bool stop = unwind_stack_until_solve();
5467 error = return_to_solve(1, stop);
5468 if (error == ERR_NONE || error == ERR_RUN || error == ERR_STOP)
5469 goto noerr;
5470 }
5471 handle_it_2:
5472 pc = oldpc;
5473 display_error(error);
5474 }
5475 return false;
5476 } else {
5477 if (error == ERR_RUN) {
5478 set_running(true);
5479 error = ERR_NONE;
5480 }
5481 if (error == ERR_NONE || error == ERR_NO || error == ERR_YES
5482 || error == ERR_STOP)
5483 flags.f.stack_lift_disable = mode_disable_stack_lift;
5484 else if (flags.f.error_ignore) {
5485 flags.f.error_ignore = 0;
5486 set_last_err(error);
5487 error = ERR_NONE;
5488 }
5489 if (error != ERR_NONE && error != ERR_STOP)
5490 display_error(error);
5491 return false;
5492 }
5493 }
5494
5495 const char *number_format() {
5496 const char *uf = shell_number_format();
5497 static char df[9];
5498 df[0] = 0;
5499 int len = ascii2hp(df, 4, uf);
5500 if (len >= 4)
5501 df[4] = 0;
5502 else
5503 df[1] = 0;
5504 // Sanity enforcement:
5505 // Decimal must be '.' or ','; default to '.'
5506 // Grouping char must be 0 (no grouping), '.', ',', '\'', or ' '; default to 0
5507 // Primary and secondary group sizes must be between 1 and 9; default to no grouping
5508 if (df[0] != ',')
5509 df[0] = '.';
5510 if (df[1] != 0 && df[1] != '.' && df[1] != ',' && df[1] != '\'' && df[1] != ' ')
5511 df[1] = 0;
5512 if (df[1] != 0 && !(df[2] >= '1' && df[2] <= '9' && df[3] >= '1' && df[3] <= '9'))
5513 df[1] = 0;
5514 return df;
5515 }