Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-bin-mirb/tools/mirb/mirb.c

raw
1 /*
2 ** mirb - Embeddable Interactive Ruby Shell
3 **
4 ** This program takes code from the user in
5 ** an interactive way and executes it
6 ** immediately. It's a REPL...
7 */
8
9 #include <mruby.h>
10
11 #ifdef MRB_NO_STDIO
12 # error mruby-bin-mirb conflicts 'MRB_NO_STDIO' in your build configuration
13 #endif
14
15 #include <mruby/array.h>
16 #include <mruby/proc.h>
17 #include <mruby/compile.h>
18 #include <mruby/dump.h>
19 #include <mruby/string.h>
20 #include <mruby/variable.h>
21 #include <mruby/error.h>
22 #include <mruby/presym.h>
23 #include <mruby/internal.h>
24
25 #include <stdlib.h>
26 #include <string.h>
27 #include <ctype.h>
28
29 #include <signal.h>
30 #include <setjmp.h>
31
32 /* obsolete configuration */
33 #ifdef ENABLE_READLINE
34 # define MRB_USE_READLINE
35 #endif
36 #ifdef ENABLE_LINENOISE
37 # define MRB_USE_LINENOISE
38 #endif
39 #ifdef DISABLE_MIRB_UNDERSCORE
40 # define MRB_NO_MIRB_UNDERSCORE
41 #endif
42
43 #ifdef MRB_USE_READLINE
44 #include MRB_READLINE_HEADER
45 #include MRB_READLINE_HISTORY
46 #define MIRB_ADD_HISTORY(line) add_history(line)
47 #define MIRB_READLINE(ch) readline(ch)
48 #if !defined(RL_READLINE_VERSION) || RL_READLINE_VERSION < 0x600
49 /* libedit & older readline do not have rl_free() */
50 #define MIRB_LINE_FREE(line) free(line)
51 #else
52 #define MIRB_LINE_FREE(line) rl_free(line)
53 #endif
54 #define MIRB_WRITE_HISTORY(path) write_history(path)
55 #define MIRB_READ_HISTORY(path) read_history(path)
56 #define MIRB_USING_HISTORY() using_history()
57 #elif defined(MRB_USE_LINENOISE)
58 #define MRB_USE_READLINE
59 #include <linenoise.h>
60 #define MIRB_ADD_HISTORY(line) linenoiseHistoryAdd(line)
61 #define MIRB_READLINE(ch) linenoise(ch)
62 #define MIRB_LINE_FREE(line) linenoiseFree(line)
63 #define MIRB_WRITE_HISTORY(path) linenoiseHistorySave(path)
64 #define MIRB_READ_HISTORY(path) linenoiseHistoryLoad(history_path)
65 #define MIRB_USING_HISTORY()
66 #endif
67
68 #if !defined(_WIN32) && defined(_POSIX_C_SOURCE)
69 #define MIRB_SIGSETJMP(env) sigsetjmp(env, 1)
70 #define MIRB_SIGLONGJMP(env, val) siglongjmp(env, val)
71 #define SIGJMP_BUF sigjmp_buf
72 #else
73 #define MIRB_SIGSETJMP(env) setjmp(env)
74 #define MIRB_SIGLONGJMP(env, val) longjmp(env, val)
75 #define SIGJMP_BUF jmp_buf
76 #endif
77
78 #ifdef MRB_USE_READLINE
79
80 static const char history_file_name[] = ".mirb_history";
81
82 static char *
83 get_history_path(mrb_state *mrb)
84 {
85 char *path = NULL;
86 const char *home = getenv("HOME");
87
88 #ifdef _WIN32
89 if (home != NULL) {
90 home = getenv("USERPROFILE");
91 }
92 #endif
93
94 if (home != NULL) {
95 int len = snprintf(NULL, 0, "%s/%s", home, history_file_name);
96 if (len >= 0) {
97 size_t size = len + 1;
98 path = (char*)mrb_malloc_simple(mrb, size);
99 if (path != NULL) {
100 int n = snprintf(path, size, "%s/%s", home, history_file_name);
101 if (n != len) {
102 mrb_free(mrb, path);
103 path = NULL;
104 }
105 }
106 }
107 }
108
109 return path;
110 }
111
112 #endif
113
114 static void
115 p(mrb_state *mrb, mrb_value obj, int prompt)
116 {
117 mrb_value val;
118 char* msg;
119
120 val = mrb_funcall_argv(mrb, obj, MRB_SYM(inspect), 0, NULL);
121 if (prompt) {
122 if (!mrb->exc) {
123 fputs(" => ", stdout);
124 }
125 else {
126 val = mrb_funcall_id(mrb, mrb_obj_value(mrb->exc), MRB_SYM(inspect), 0);
127 }
128 }
129 if (!mrb_string_p(val)) {
130 val = mrb_obj_as_string(mrb, obj);
131 }
132 msg = mrb_locale_from_utf8(RSTRING_PTR(val), (int)RSTRING_LEN(val));
133 fwrite(msg, strlen(msg), 1, stdout);
134 mrb_locale_free(msg);
135 putc('\n', stdout);
136 }
137
138 /* Guess if the user might want to enter more
139 * or if they wants an evaluation of their code now */
140 static mrb_bool
141 is_code_block_open(struct mrb_parser_state *parser)
142 {
143 mrb_bool code_block_open = FALSE;
144
145 /* check for heredoc */
146 if (parser->parsing_heredoc != NULL) return TRUE;
147
148 /* check for unterminated string */
149 if (parser->lex_strterm) return TRUE;
150
151 /* check if parser error are available */
152 if (0 < parser->nerr) {
153 const char unexpected_end[] = "syntax error, unexpected end of file";
154 const char *message = parser->error_buffer[0].message;
155
156 /* a parser error occur, we have to check if */
157 /* we need to read one more line or if there is */
158 /* a different issue which we have to show to */
159 /* the user */
160
161 if (strncmp(message, unexpected_end, sizeof(unexpected_end) - 1) == 0) {
162 code_block_open = TRUE;
163 }
164 else if (strcmp(message, "syntax error, unexpected keyword_end") == 0) {
165 code_block_open = FALSE;
166 }
167 else if (strcmp(message, "syntax error, unexpected tREGEXP_BEG") == 0) {
168 code_block_open = FALSE;
169 }
170 return code_block_open;
171 }
172
173 switch (parser->lstate) {
174
175 /* all states which need more code */
176
177 case EXPR_BEG:
178 /* beginning of a statement, */
179 /* that means previous line ended */
180 code_block_open = FALSE;
181 break;
182 case EXPR_DOT:
183 /* a message dot was the last token, */
184 /* there has to come more */
185 code_block_open = TRUE;
186 break;
187 case EXPR_CLASS:
188 /* a class keyword is not enough! */
189 /* we need also a name of the class */
190 code_block_open = TRUE;
191 break;
192 case EXPR_FNAME:
193 /* a method name is necessary */
194 code_block_open = TRUE;
195 break;
196 case EXPR_VALUE:
197 /* if, elsif, etc. without condition */
198 code_block_open = TRUE;
199 break;
200
201 /* now all the states which are closed */
202
203 case EXPR_ARG:
204 /* an argument is the last token */
205 code_block_open = FALSE;
206 break;
207
208 /* all states which are unsure */
209
210 case EXPR_CMDARG:
211 break;
212 case EXPR_END:
213 /* an expression was ended */
214 break;
215 case EXPR_ENDARG:
216 /* closing parenthesis */
217 break;
218 case EXPR_ENDFN:
219 /* definition end */
220 break;
221 case EXPR_MID:
222 /* jump keyword like break, return, ... */
223 break;
224 case EXPR_MAX_STATE:
225 /* don't know what to do with this token */
226 break;
227 default:
228 /* this state is unexpected! */
229 break;
230 }
231
232 return code_block_open;
233 }
234
235 struct _args {
236 FILE *rfp;
237 mrb_bool verbose : 1;
238 mrb_bool debug : 1;
239 int argc;
240 char** argv;
241 int libc;
242 char **libv;
243 };
244
245 static void
246 usage(const char *name)
247 {
248 static const char *const usage_msg[] = {
249 "switches:",
250 "-d set $DEBUG to true (same as `mruby -d`)",
251 "-r library same as `mruby -r`",
252 "-v print version number, then run in verbose mode",
253 "--verbose run in verbose mode",
254 "--version print the version",
255 "--copyright print the copyright",
256 NULL
257 };
258 const char *const *p = usage_msg;
259
260 printf("Usage: %s [switches] [programfile] [arguments]\n", name);
261 while (*p)
262 printf(" %s\n", *p++);
263 }
264
265 static char *
266 dup_arg_item(mrb_state *mrb, const char *item)
267 {
268 size_t buflen = strlen(item) + 1;
269 char *buf = (char*)mrb_malloc(mrb, buflen);
270 memcpy(buf, item, buflen);
271 return buf;
272 }
273
274 static int
275 parse_args(mrb_state *mrb, int argc, char **argv, struct _args *args)
276 {
277 char **origargv = argv;
278 static const struct _args args_zero = { 0 };
279
280 *args = args_zero;
281
282 for (argc--,argv++; argc > 0; argc--,argv++) {
283 char *item;
284 if (argv[0][0] != '-') break;
285
286 item = argv[0] + 1;
287 switch (*item++) {
288 case 'd':
289 args->debug = TRUE;
290 break;
291 case 'r':
292 if (!item[0]) {
293 if (argc <= 1) {
294 printf("%s: No library specified for -r\n", *origargv);
295 return EXIT_FAILURE;
296 }
297 argc--; argv++;
298 item = argv[0];
299 }
300 if (args->libc == 0) {
301 args->libv = (char**)mrb_malloc(mrb, sizeof(char*));
302 }
303 else {
304 args->libv = (char**)mrb_realloc(mrb, args->libv, sizeof(char*) * (args->libc + 1));
305 }
306 args->libv[args->libc++] = dup_arg_item(mrb, item);
307 break;
308 case 'v':
309 if (!args->verbose) mrb_show_version(mrb);
310 args->verbose = TRUE;
311 break;
312 case '-':
313 if (strcmp((*argv) + 2, "version") == 0) {
314 mrb_show_version(mrb);
315 exit(EXIT_SUCCESS);
316 }
317 else if (strcmp((*argv) + 2, "verbose") == 0) {
318 args->verbose = TRUE;
319 break;
320 }
321 else if (strcmp((*argv) + 2, "copyright") == 0) {
322 mrb_show_copyright(mrb);
323 exit(EXIT_SUCCESS);
324 }
325 default:
326 return EXIT_FAILURE;
327 }
328 }
329
330 if (args->rfp == NULL) {
331 if (*argv != NULL) {
332 args->rfp = fopen(argv[0], "r");
333 if (args->rfp == NULL) {
334 printf("Cannot open program file. (%s)\n", *argv);
335 return EXIT_FAILURE;
336 }
337 argc--; argv++;
338 }
339 }
340 args->argv = (char **)mrb_realloc(mrb, args->argv, sizeof(char*) * (argc + 1));
341 memcpy(args->argv, argv, (argc+1) * sizeof(char*));
342 args->argc = argc;
343
344 return EXIT_SUCCESS;
345 }
346
347 static void
348 cleanup(mrb_state *mrb, struct _args *args)
349 {
350 if (args->rfp)
351 fclose(args->rfp);
352 mrb_free(mrb, args->argv);
353 if (args->libc) {
354 while (args->libc--) {
355 mrb_free(mrb, args->libv[args->libc]);
356 }
357 mrb_free(mrb, args->libv);
358 }
359 mrb_close(mrb);
360 }
361
362 /* Print a short remark for the user */
363 static void
364 print_hint(void)
365 {
366 printf("mirb - Embeddable Interactive Ruby Shell\n\n");
367 }
368
369 #ifndef MRB_USE_READLINE
370 /* Print the command line prompt of the REPL */
371 static void
372 print_cmdline(int code_block_open)
373 {
374 if (code_block_open) {
375 printf("* ");
376 }
377 else {
378 printf("> ");
379 }
380 fflush(stdout);
381 }
382 #endif
383
384 static int
385 check_keyword(const char *buf, const char *word)
386 {
387 const char *p = buf;
388 size_t len = strlen(word);
389
390 /* skip preceding spaces */
391 while (*p && ISSPACE(*p)) {
392 p++;
393 }
394 /* check keyword */
395 if (strncmp(p, word, len) != 0) {
396 return 0;
397 }
398 p += len;
399 /* skip trailing spaces */
400 while (*p) {
401 if (!ISSPACE(*p)) return 0;
402 p++;
403 }
404 return 1;
405 }
406
407
408 #ifndef MRB_USE_READLINE
409 volatile sig_atomic_t input_canceled = 0;
410 void
411 ctrl_c_handler(int signo)
412 {
413 input_canceled = 1;
414 }
415 #else
416 SIGJMP_BUF ctrl_c_buf;
417 void
418 ctrl_c_handler(int signo)
419 {
420 MIRB_SIGLONGJMP(ctrl_c_buf, 1);
421 }
422 #endif
423
424 #ifndef MRB_NO_MIRB_UNDERSCORE
425 void decl_lv_underscore(mrb_state *mrb, mrbc_context *cxt)
426 {
427 struct RProc *proc;
428 struct mrb_parser_state *parser;
429
430 parser = mrb_parse_string(mrb, "_=nil", cxt);
431 if (parser == NULL) {
432 fputs("create parser state error\n", stderr);
433 mrb_close(mrb);
434 exit(EXIT_FAILURE);
435 }
436
437 proc = mrb_generate_code(mrb, parser);
438 mrb_vm_run(mrb, proc, mrb_top_self(mrb), 0);
439
440 mrb_parser_free(parser);
441 }
442 #endif
443
444 int
445 main(int argc, char **argv)
446 {
447 char ruby_code[4096] = { 0 };
448 char last_code_line[1024] = { 0 };
449 #ifndef MRB_USE_READLINE
450 int last_char;
451 size_t char_index;
452 #else
453 char *history_path;
454 char* line;
455 #endif
456 mrbc_context *cxt;
457 struct mrb_parser_state *parser;
458 mrb_state *mrb;
459 mrb_value result;
460 struct _args args;
461 mrb_value ARGV;
462 int n;
463 int i;
464 mrb_bool code_block_open = FALSE;
465 int ai;
466 unsigned int stack_keep = 0;
467
468 /* new interpreter instance */
469 mrb = mrb_open();
470 if (mrb == NULL) {
471 fputs("Invalid mrb interpreter, exiting mirb\n", stderr);
472 return EXIT_FAILURE;
473 }
474
475 n = parse_args(mrb, argc, argv, &args);
476 if (n == EXIT_FAILURE) {
477 cleanup(mrb, &args);
478 usage(argv[0]);
479 return n;
480 }
481
482 ARGV = mrb_ary_new_capa(mrb, args.argc);
483 for (i = 0; i < args.argc; i++) {
484 char* utf8 = mrb_utf8_from_locale(args.argv[i], -1);
485 if (utf8) {
486 mrb_ary_push(mrb, ARGV, mrb_str_new_cstr(mrb, utf8));
487 mrb_utf8_free(utf8);
488 }
489 }
490 mrb_define_global_const(mrb, "ARGV", ARGV);
491 mrb_gv_set(mrb, mrb_intern_lit(mrb, "$DEBUG"), mrb_bool_value(args.debug));
492
493 #ifdef MRB_USE_READLINE
494 history_path = get_history_path(mrb);
495 if (history_path == NULL) {
496 fputs("failed to get history path\n", stderr);
497 mrb_close(mrb);
498 return EXIT_FAILURE;
499 }
500
501 MIRB_USING_HISTORY();
502 MIRB_READ_HISTORY(history_path);
503 #endif
504
505 print_hint();
506
507 cxt = mrbc_context_new(mrb);
508
509 /* Load libraries */
510 for (i = 0; i < args.libc; i++) {
511 FILE *lfp = fopen(args.libv[i], "r");
512 if (lfp == NULL) {
513 printf("Cannot open library file. (%s)\n", args.libv[i]);
514 cleanup(mrb, &args);
515 return EXIT_FAILURE;
516 }
517 mrb_load_file_cxt(mrb, lfp, cxt);
518 fclose(lfp);
519 mrb_vm_ci_env_clear(mrb, mrb->c->cibase);
520 mrbc_cleanup_local_variables(mrb, cxt);
521 }
522
523 #ifndef MRB_NO_MIRB_UNDERSCORE
524 decl_lv_underscore(mrb, cxt);
525 #endif
526
527 cxt->capture_errors = TRUE;
528 cxt->lineno = 1;
529 mrbc_filename(mrb, cxt, "(mirb)");
530 if (args.verbose) cxt->dump_result = TRUE;
531
532 ai = mrb_gc_arena_save(mrb);
533
534 while (TRUE) {
535 char *utf8;
536
537 if (args.rfp) {
538 if (fgets(last_code_line, sizeof(last_code_line)-1, args.rfp) != NULL)
539 goto done;
540 break;
541 }
542
543 #ifndef MRB_USE_READLINE
544 print_cmdline(code_block_open);
545
546 signal(SIGINT, ctrl_c_handler);
547 char_index = 0;
548 while ((last_char = getchar()) != '\n') {
549 if (last_char == EOF) break;
550 if (char_index >= sizeof(last_code_line)-2) {
551 fputs("input string too long\n", stderr);
552 continue;
553 }
554 last_code_line[char_index++] = last_char;
555 }
556 signal(SIGINT, SIG_DFL);
557 if (input_canceled) {
558 ruby_code[0] = '\0';
559 last_code_line[0] = '\0';
560 code_block_open = FALSE;
561 puts("^C");
562 input_canceled = 0;
563 continue;
564 }
565 if (last_char == EOF) {
566 fputs("\n", stdout);
567 break;
568 }
569
570 last_code_line[char_index++] = '\n';
571 last_code_line[char_index] = '\0';
572 #else
573 if (MIRB_SIGSETJMP(ctrl_c_buf) == 0) {
574 ;
575 }
576 else {
577 ruby_code[0] = '\0';
578 last_code_line[0] = '\0';
579 code_block_open = FALSE;
580 puts("^C");
581 }
582 signal(SIGINT, ctrl_c_handler);
583 line = MIRB_READLINE(code_block_open ? "* " : "> ");
584 signal(SIGINT, SIG_DFL);
585
586 if (line == NULL) {
587 printf("\n");
588 break;
589 }
590 if (strlen(line) > sizeof(last_code_line)-2) {
591 fputs("input string too long\n", stderr);
592 continue;
593 }
594 strcpy(last_code_line, line);
595 strcat(last_code_line, "\n");
596 MIRB_ADD_HISTORY(line);
597 MIRB_LINE_FREE(line);
598 #endif
599
600 done:
601 if (code_block_open) {
602 if (strlen(ruby_code)+strlen(last_code_line) > sizeof(ruby_code)-1) {
603 fputs("concatenated input string too long\n", stderr);
604 continue;
605 }
606 strcat(ruby_code, last_code_line);
607 }
608 else {
609 if (check_keyword(last_code_line, "quit") || check_keyword(last_code_line, "exit")) {
610 break;
611 }
612 strcpy(ruby_code, last_code_line);
613 }
614
615 utf8 = mrb_utf8_from_locale(ruby_code, -1);
616 if (!utf8) abort();
617
618 /* parse code */
619 parser = mrb_parser_new(mrb);
620 if (parser == NULL) {
621 fputs("create parser state error\n", stderr);
622 break;
623 }
624 parser->s = utf8;
625 parser->send = utf8 + strlen(utf8);
626 parser->lineno = cxt->lineno;
627 mrb_parser_parse(parser, cxt);
628 code_block_open = is_code_block_open(parser);
629 mrb_utf8_free(utf8);
630
631 if (code_block_open) {
632 /* no evaluation of code */
633 }
634 else {
635 if (0 < parser->nwarn) {
636 /* warning */
637 char* msg = mrb_locale_from_utf8(parser->warn_buffer[0].message, -1);
638 printf("line %d: %s\n", parser->warn_buffer[0].lineno, msg);
639 mrb_locale_free(msg);
640 }
641 if (0 < parser->nerr) {
642 /* syntax error */
643 char* msg = mrb_locale_from_utf8(parser->error_buffer[0].message, -1);
644 printf("line %d: %s\n", parser->error_buffer[0].lineno, msg);
645 mrb_locale_free(msg);
646 }
647 else {
648 /* generate bytecode */
649 struct RProc *proc = mrb_generate_code(mrb, parser);
650 if (proc == NULL) {
651 mrb_parser_free(parser);
652 continue;
653 }
654
655 if (args.verbose) {
656 mrb_codedump_all(mrb, proc);
657 }
658 /* adjust stack length of toplevel environment */
659 if (mrb->c->cibase->u.env) {
660 struct REnv *e = mrb_vm_ci_env(mrb->c->cibase);
661 if (e && MRB_ENV_LEN(e) < proc->body.irep->nlocals) {
662 MRB_ENV_SET_LEN(e, proc->body.irep->nlocals);
663 }
664 }
665 /* pass a proc for evaluation */
666 /* evaluate the bytecode */
667 result = mrb_vm_run(mrb,
668 proc,
669 mrb_top_self(mrb),
670 stack_keep);
671 stack_keep = proc->body.irep->nlocals;
672 /* did an exception occur? */
673 if (mrb->exc) {
674 MRB_EXC_CHECK_EXIT(mrb, mrb->exc);
675 p(mrb, mrb_obj_value(mrb->exc), 0);
676 mrb->exc = 0;
677 }
678 else {
679 /* no */
680 if (!mrb_respond_to(mrb, result, MRB_SYM(inspect))){
681 result = mrb_any_to_s(mrb, result);
682 }
683 p(mrb, result, 1);
684 #ifndef MRB_NO_MIRB_UNDERSCORE
685 *(mrb->c->ci->stack + 1) = result;
686 #endif
687 }
688 }
689 ruby_code[0] = '\0';
690 last_code_line[0] = '\0';
691 mrb_gc_arena_restore(mrb, ai);
692 }
693 mrb_parser_free(parser);
694 cxt->lineno++;
695 }
696
697 #ifdef MRB_USE_READLINE
698 MIRB_WRITE_HISTORY(history_path);
699 mrb_free(mrb, history_path);
700 #endif
701
702 if (args.rfp) fclose(args.rfp);
703 mrb_free(mrb, args.argv);
704 if (args.libv) {
705 for (i = 0; i < args.libc; i++) {
706 mrb_free(mrb, args.libv[i]);
707 }
708 mrb_free(mrb, args.libv);
709 }
710 mrbc_context_free(mrb, cxt);
711 mrb_close(mrb);
712
713 return 0;
714 }