blob: 19ca649c9fe5a024434942240d583e1040a261db [file] [log] [blame]
Dave Hylands117c46d2014-05-07 07:15:00 -07001/*
2 * This file is part of the Micro Python project, http://micropython.org/
3 *
4 * The MIT License (MIT)
5 *
6 * Copyright (c) 2013, 2014 Damien P. George
7 *
8 * Permission is hereby granted, free of charge, to any person obtaining a copy
9 * of this software and associated documentation files (the "Software"), to deal
10 * in the Software without restriction, including without limitation the rights
11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12 * copies of the Software, and to permit persons to whom the Software is
13 * furnished to do so, subject to the following conditions:
14 *
15 * The above copyright notice and this permission notice shall be included in
16 * all copies or substantial portions of the Software.
17 *
18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24 * THE SOFTWARE.
25 */
26
Damien George7c6c8432014-05-07 15:33:15 +010027#include <stdio.h>
Dave Hylands117c46d2014-05-07 07:15:00 -070028#include <stdint.h>
29#include <stdlib.h>
30#include <string.h>
31
32#include "mpconfig.h"
33#include "nlr.h"
34#include "misc.h"
35#include "qstr.h"
36#include "obj.h"
37#include "input.h"
38
39#if MICROPY_USE_READLINE
40#include <readline/readline.h>
41#include <readline/history.h>
42#endif
43
Dave Hylands117c46d2014-05-07 07:15:00 -070044char *prompt(char *p) {
45#if MICROPY_USE_READLINE
46 char *line = readline(p);
47 if (line) {
48 add_history(line);
49 }
50#else
51 static char buf[256];
52 fputs(p, stdout);
53 char *s = fgets(buf, sizeof(buf), stdin);
54 if (!s) {
55 return NULL;
56 }
57 int l = strlen(buf);
58 if (buf[l - 1] == '\n') {
59 buf[l - 1] = 0;
60 } else {
61 l++;
62 }
63 char *line = malloc(l);
64 memcpy(line, buf, l);
65#endif
66 return line;
67}
68
69STATIC mp_obj_t mp_builtin_input(uint n_args, const mp_obj_t *args) {
70 if (n_args == 1) {
71 mp_obj_print(args[0], PRINT_STR);
72 }
73
74 char *line = prompt("");
75 if (line == NULL) {
76 nlr_raise(mp_obj_new_exception(&mp_type_EOFError));
77 }
Damien George2617eeb2014-05-25 22:27:57 +010078 mp_obj_t o = mp_obj_new_str(line, strlen(line), false);
Dave Hylands117c46d2014-05-07 07:15:00 -070079 free(line);
80 return o;
81}
82
83MP_DEFINE_CONST_FUN_OBJ_VAR_BETWEEN(mp_builtin_input_obj, 0, 1, mp_builtin_input);