2009-05-16 Pavel Roskin <proski@gnu.org>
[grub2/bean.git] / script / lua / grub_main.c
blob2de59205c5276b2d3d9ef625c2412e4a90acd8a1
1 /*
2 * GRUB -- GRand Unified Bootloader
3 * Copyright (C) 2009 Free Software Foundation, Inc.
5 * GRUB is free software: you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation, either version 3 of the License, or
8 * (at your option) any later version.
10 * GRUB is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License
16 * along with GRUB. If not, see <http://www.gnu.org/licenses/>.
19 #include "lua.h"
20 #include "lauxlib.h"
21 #include "lualib.h"
22 #include "grub_lib.h"
24 #include <grub/dl.h>
25 #include <grub/parser.h>
27 static lua_State *state;
29 static grub_err_t
30 grub_lua_parse_line (char *line, grub_reader_getline_t getline)
32 int r;
33 char *old_line = 0;
35 lua_settop(state, 0);
36 while (1)
38 r = luaL_loadbuffer (state, line, grub_strlen (line), "grub");
39 if (! r)
41 r = lua_pcall (state, 0, 0, 0);
42 if (r)
43 grub_error (GRUB_ERR_BAD_ARGUMENT, "lua command fails");
44 else
46 grub_free (old_line);
47 return grub_errno;
49 break;
52 if (r == LUA_ERRSYNTAX)
54 size_t lmsg;
55 const char *msg = lua_tolstring(state, -1, &lmsg);
56 const char *tp = msg + lmsg - (sizeof(LUA_QL("<eof>")) - 1);
57 if (grub_strstr(msg, LUA_QL("<eof>")) == tp)
59 char *n, *t;
60 int len;
62 lua_pop(state, 1);
63 if ((getline (&n, 1)) || (! n))
65 grub_error (GRUB_ERR_BAD_ARGUMENT, "incomplete command");
66 break;
69 len = grub_strlen (line);
70 t = grub_malloc (len + grub_strlen (n) + 2);
71 if (! t)
72 break;
74 grub_strcpy (t, line);
75 t[len] = '\n';
76 grub_strcpy (t + len + 1, n);
77 grub_free (old_line);
78 line = old_line = t;
79 continue;
83 break;
86 grub_free (old_line);
87 lua_gc (state, LUA_GCCOLLECT, 0);
89 return grub_errno;
92 static struct grub_parser grub_lua_parser =
94 .name = "lua",
95 .parse_line = grub_lua_parse_line
98 GRUB_MOD_INIT(lua)
100 (void) mod;
102 state = lua_open ();
103 if (state)
105 lua_gc(state, LUA_GCSTOP, 0);
106 luaL_openlibs(state);
107 luaL_register(state, "grub", grub_lua_lib);
108 lua_gc(state, LUA_GCRESTART, 0);
109 grub_parser_register ("lua", &grub_lua_parser);
113 GRUB_MOD_FINI(lua)
115 if (state)
117 grub_parser_unregister (&grub_lua_parser);
118 lua_close(state);