2 ** mirb - Embeddable Interactive Ruby Shell
4 ** This program takes code from the user in
5 ** an interactive way and executes it
6 ** immediately. It's a REPL...
10 #include <mruby/array.h>
11 #include <mruby/proc.h>
12 #include <mruby/compile.h>
13 #include <mruby/dump.h>
14 #include <mruby/string.h>
15 #include <mruby/variable.h>
16 #include <mruby/throw.h>
26 #ifdef ENABLE_READLINE
27 #include <readline/readline.h>
28 #include <readline/history.h>
29 #define MIRB_ADD_HISTORY(line) add_history(line)
30 #define MIRB_READLINE(ch) readline(ch)
31 #if !defined(RL_READLINE_VERSION) || RL_READLINE_VERSION < 0x600
32 /* libedit & older readline do not have rl_free() */
33 #define MIRB_LINE_FREE(line) free(line)
35 #define MIRB_LINE_FREE(line) rl_free(line)
37 #define MIRB_WRITE_HISTORY(path) write_history(path)
38 #define MIRB_READ_HISTORY(path) read_history(path)
39 #define MIRB_USING_HISTORY() using_history()
40 #elif defined(ENABLE_LINENOISE)
41 #define ENABLE_READLINE
42 #include <linenoise.h>
43 #define MIRB_ADD_HISTORY(line) linenoiseHistoryAdd(line)
44 #define MIRB_READLINE(ch) linenoise(ch)
45 #define MIRB_LINE_FREE(line) linenoiseFree(line)
46 #define MIRB_WRITE_HISTORY(path) linenoiseHistorySave(path)
47 #define MIRB_READ_HISTORY(path) linenoiseHistoryLoad(history_path)
48 #define MIRB_USING_HISTORY()
52 #define MIRB_SIGSETJMP(env) sigsetjmp(env, 1)
53 #define MIRB_SIGLONGJMP(env, val) siglongjmp(env, val)
54 #define SIGJMP_BUF sigjmp_buf
56 #define MIRB_SIGSETJMP(env) setjmp(env)
57 #define MIRB_SIGLONGJMP(env, val) longjmp(env, val)
58 #define SIGJMP_BUF jmp_buf
61 #ifdef ENABLE_READLINE
63 static const char history_file_name[] = ".mirb_history";
66 get_history_path(mrb_state *mrb)
69 const char *home = getenv("HOME");
73 home = getenv("USERPROFILE");
78 int len = snprintf(NULL, 0, "%s/%s", home, history_file_name);
80 size_t size = len + 1;
81 path = (char *)mrb_malloc_simple(mrb, size);
83 int n = snprintf(path, size, "%s/%s", home, history_file_name);
98 p(mrb_state *mrb, mrb_value obj, int prompt)
103 val = mrb_funcall(mrb, obj, "inspect", 0);
106 fputs(" => ", stdout);
109 val = mrb_funcall(mrb, mrb_obj_value(mrb->exc), "inspect", 0);
112 if (!mrb_string_p(val)) {
113 val = mrb_obj_as_string(mrb, obj);
115 msg = mrb_locale_from_utf8(RSTRING_PTR(val), (int)RSTRING_LEN(val));
116 fwrite(msg, strlen(msg), 1, stdout);
117 mrb_locale_free(msg);
121 /* Guess if the user might want to enter more
122 * or if he wants an evaluation of his code now */
124 is_code_block_open(struct mrb_parser_state *parser)
126 mrb_bool code_block_open = FALSE;
128 /* check for heredoc */
129 if (parser->parsing_heredoc != NULL) return TRUE;
131 /* check for unterminated string */
132 if (parser->lex_strterm) return TRUE;
134 /* check if parser error are available */
135 if (0 < parser->nerr) {
136 const char unexpected_end[] = "syntax error, unexpected $end";
137 const char *message = parser->error_buffer[0].message;
139 /* a parser error occur, we have to check if */
140 /* we need to read one more line or if there is */
141 /* a different issue which we have to show to */
144 if (strncmp(message, unexpected_end, sizeof(unexpected_end) - 1) == 0) {
145 code_block_open = TRUE;
147 else if (strcmp(message, "syntax error, unexpected keyword_end") == 0) {
148 code_block_open = FALSE;
150 else if (strcmp(message, "syntax error, unexpected tREGEXP_BEG") == 0) {
151 code_block_open = FALSE;
153 return code_block_open;
156 switch (parser->lstate) {
158 /* all states which need more code */
161 /* beginning of a statement, */
162 /* that means previous line ended */
163 code_block_open = FALSE;
166 /* a message dot was the last token, */
167 /* there has to come more */
168 code_block_open = TRUE;
171 /* a class keyword is not enough! */
172 /* we need also a name of the class */
173 code_block_open = TRUE;
176 /* a method name is necessary */
177 code_block_open = TRUE;
180 /* if, elsif, etc. without condition */
181 code_block_open = TRUE;
184 /* now all the states which are closed */
187 /* an argument is the last token */
188 code_block_open = FALSE;
191 /* all states which are unsure */
196 /* an expression was ended */
199 /* closing parenthese */
205 /* jump keyword like break, return, ... */
208 /* don't know what to do with this token */
211 /* this state is unexpected! */
215 return code_block_open;
220 mrb_bool verbose : 1;
229 usage(const char *name)
231 static const char *const usage_msg[] = {
233 "-d set $DEBUG to true (same as `mruby -d`)",
234 "-r library same as `mruby -r`",
235 "-v print version number, then run in verbose mode",
236 "--verbose run in verbose mode",
237 "--version print the version",
238 "--copyright print the copyright",
241 const char *const *p = usage_msg;
243 printf("Usage: %s [switches]\n", name);
245 printf(" %s\n", *p++);
249 dup_arg_item(mrb_state *mrb, const char *item)
251 size_t buflen = strlen(item) + 1;
252 char *buf = (char*)mrb_malloc(mrb, buflen);
253 memcpy(buf, item, buflen);
258 parse_args(mrb_state *mrb, int argc, char **argv, struct _args *args)
260 char **origargv = argv;
261 static const struct _args args_zero = { 0 };
265 for (argc--,argv++; argc > 0; argc--,argv++) {
267 if (argv[0][0] != '-') break;
277 printf("%s: No library specified for -r\n", *origargv);
283 if (args->libc == 0) {
284 args->libv = (char**)mrb_malloc(mrb, sizeof(char*));
287 args->libv = (char**)mrb_realloc(mrb, args->libv, sizeof(char*) * (args->libc + 1));
289 args->libv[args->libc++] = dup_arg_item(mrb, item);
292 if (!args->verbose) mrb_show_version(mrb);
293 args->verbose = TRUE;
296 if (strcmp((*argv) + 2, "version") == 0) {
297 mrb_show_version(mrb);
300 else if (strcmp((*argv) + 2, "verbose") == 0) {
301 args->verbose = TRUE;
304 else if (strcmp((*argv) + 2, "copyright") == 0) {
305 mrb_show_copyright(mrb);
313 if (args->rfp == NULL) {
315 args->rfp = fopen(argv[0], "r");
316 if (args->rfp == NULL) {
317 printf("Cannot open program file. (%s)\n", *argv);
323 args->argv = (char **)mrb_realloc(mrb, args->argv, sizeof(char*) * (argc + 1));
324 memcpy(args->argv, argv, (argc+1) * sizeof(char*));
331 cleanup(mrb_state *mrb, struct _args *args)
335 mrb_free(mrb, args->argv);
337 while (args->libc--) {
338 mrb_free(mrb, args->libv[args->libc]);
340 mrb_free(mrb, args->libv);
345 /* Print a short remark for the user */
349 printf("mirb - Embeddable Interactive Ruby Shell\n\n");
352 #ifndef ENABLE_READLINE
353 /* Print the command line prompt of the REPL */
355 print_cmdline(int code_block_open)
357 if (code_block_open) {
367 void mrb_codedump_all(mrb_state*, struct RProc*);
370 check_keyword(const char *buf, const char *word)
373 size_t len = strlen(word);
375 /* skip preceding spaces */
376 while (*p && ISSPACE(*p)) {
380 if (strncmp(p, word, len) != 0) {
384 /* skip trailing spaces */
386 if (!ISSPACE(*p)) return 0;
393 #ifndef ENABLE_READLINE
394 volatile sig_atomic_t input_canceled = 0;
396 ctrl_c_handler(int signo)
401 SIGJMP_BUF ctrl_c_buf;
403 ctrl_c_handler(int signo)
405 MIRB_SIGLONGJMP(ctrl_c_buf, 1);
410 main(int argc, char **argv)
412 char ruby_code[4096] = { 0 };
413 char last_code_line[1024] = { 0 };
414 #ifndef ENABLE_READLINE
422 struct mrb_parser_state *parser;
429 mrb_bool code_block_open = FALSE;
431 unsigned int stack_keep = 0;
433 /* new interpreter instance */
436 fputs("Invalid mrb interpreter, exiting mirb\n", stderr);
440 n = parse_args(mrb, argc, argv, &args);
441 if (n == EXIT_FAILURE) {
447 ARGV = mrb_ary_new_capa(mrb, args.argc);
448 for (i = 0; i < args.argc; i++) {
449 char* utf8 = mrb_utf8_from_locale(args.argv[i], -1);
451 mrb_ary_push(mrb, ARGV, mrb_str_new_cstr(mrb, utf8));
455 mrb_define_global_const(mrb, "ARGV", ARGV);
456 mrb_gv_set(mrb, mrb_intern_lit(mrb, "$DEBUG"), mrb_bool_value(args.debug));
458 #ifdef ENABLE_READLINE
459 history_path = get_history_path(mrb);
460 if (history_path == NULL) {
461 fputs("failed to get history path\n", stderr);
466 MIRB_USING_HISTORY();
467 MIRB_READ_HISTORY(history_path);
472 cxt = mrbc_context_new(mrb);
475 for (i = 0; i < args.libc; i++) {
476 FILE *lfp = fopen(args.libv[i], "r");
478 printf("Cannot open library file. (%s)\n", args.libv[i]);
482 mrb_load_file_cxt(mrb, lfp, cxt);
486 cxt->capture_errors = TRUE;
488 mrbc_filename(mrb, cxt, "(mirb)");
489 if (args.verbose) cxt->dump_result = TRUE;
491 ai = mrb_gc_arena_save(mrb);
495 struct mrb_jmpbuf c_jmp;
500 if (fgets(last_code_line, sizeof(last_code_line)-1, args.rfp) != NULL)
505 #ifndef ENABLE_READLINE
506 print_cmdline(code_block_open);
508 signal(SIGINT, ctrl_c_handler);
510 while ((last_char = getchar()) != '\n') {
511 if (last_char == EOF) break;
512 if (char_index >= sizeof(last_code_line)-2) {
513 fputs("input string too long\n", stderr);
516 last_code_line[char_index++] = last_char;
518 signal(SIGINT, SIG_DFL);
519 if (input_canceled) {
521 last_code_line[0] = '\0';
522 code_block_open = FALSE;
527 if (last_char == EOF) {
532 last_code_line[char_index++] = '\n';
533 last_code_line[char_index] = '\0';
535 if (MIRB_SIGSETJMP(ctrl_c_buf) == 0) {
540 last_code_line[0] = '\0';
541 code_block_open = FALSE;
544 signal(SIGINT, ctrl_c_handler);
545 line = MIRB_READLINE(code_block_open ? "* " : "> ");
546 signal(SIGINT, SIG_DFL);
552 if (strlen(line) > sizeof(last_code_line)-2) {
553 fputs("input string too long\n", stderr);
556 strcpy(last_code_line, line);
557 strcat(last_code_line, "\n");
558 MIRB_ADD_HISTORY(line);
559 MIRB_LINE_FREE(line);
563 if (code_block_open) {
564 if (strlen(ruby_code)+strlen(last_code_line) > sizeof(ruby_code)-1) {
565 fputs("concatenated input string too long\n", stderr);
568 strcat(ruby_code, last_code_line);
571 if (check_keyword(last_code_line, "quit") || check_keyword(last_code_line, "exit")) {
574 strcpy(ruby_code, last_code_line);
577 utf8 = mrb_utf8_from_locale(ruby_code, -1);
581 parser = mrb_parser_new(mrb);
582 if (parser == NULL) {
583 fputs("create parser state error\n", stderr);
587 parser->send = utf8 + strlen(utf8);
588 parser->lineno = cxt->lineno;
589 mrb_parser_parse(parser, cxt);
590 code_block_open = is_code_block_open(parser);
593 if (code_block_open) {
594 /* no evaluation of code */
597 if (0 < parser->nwarn) {
599 char* msg = mrb_locale_from_utf8(parser->warn_buffer[0].message, -1);
600 printf("line %d: %s\n", parser->warn_buffer[0].lineno, msg);
601 mrb_locale_free(msg);
603 if (0 < parser->nerr) {
605 char* msg = mrb_locale_from_utf8(parser->error_buffer[0].message, -1);
606 printf("line %d: %s\n", parser->error_buffer[0].lineno, msg);
607 mrb_locale_free(msg);
610 /* generate bytecode */
611 struct RProc *proc = mrb_generate_code(mrb, parser);
613 fputs("codegen error\n", stderr);
614 mrb_parser_free(parser);
619 mrb_codedump_all(mrb, proc);
621 /* adjust stack length of toplevel environment */
622 if (mrb->c->cibase->env) {
623 struct REnv *e = mrb->c->cibase->env;
624 if (e && MRB_ENV_STACK_LEN(e) < proc->body.irep->nlocals) {
625 MRB_ENV_SET_STACK_LEN(e, proc->body.irep->nlocals);
628 /* pass a proc for evaluation */
629 /* evaluate the bytecode */
630 result = mrb_vm_run(mrb,
634 stack_keep = proc->body.irep->nlocals;
635 /* did an exception occur? */
637 p(mrb, mrb_obj_value(mrb->exc), 0);
642 if (!mrb_respond_to(mrb, result, mrb_intern_lit(mrb, "inspect"))){
643 result = mrb_any_to_s(mrb, result);
649 last_code_line[0] = '\0';
650 mrb_gc_arena_restore(mrb, ai);
652 mrb_parser_free(parser);
655 p(mrb, mrb_obj_value(mrb->exc), 0);
661 #ifdef ENABLE_READLINE
662 MIRB_WRITE_HISTORY(history_path);
663 mrb_free(mrb, history_path);
666 if (args.rfp) fclose(args.rfp);
667 mrb_free(mrb, args.argv);
669 for (i = 0; i < args.libc; ++i) {
670 mrb_free(mrb, args.libv[i]);
672 mrb_free(mrb, args.libv);
674 mrbc_context_free(mrb, cxt);