add BSD license
[philodendron.git] / lang_ext / lua / bc_read_stream.c
blobdb8ec3459532acadbf6b549542d0f508c065d8a1
1 /*********************************************************************
3 Gazelle: a system for building fast, reusable grammars
5 bc_read_stream.c
7 These are Lua wrappers for bc_read_stream.
9 Copyright (c) 2007 Joshua Haberman. See LICENSE for details.
11 *********************************************************************/
13 #include "bc_read_stream_lua.h"
15 #include "lua.h"
16 #include "lualib.h"
17 #include "lauxlib.h"
19 static int bc_read_stream_lua_open(lua_State *L)
21 const char *filename = luaL_checkstring(L, 1);
22 struct bc_read_stream_lua *s = lua_newuserdata(L, sizeof(*s));
23 luaL_getmetatable(L, "bc_read_stream");
24 lua_setmetatable(L, -2);
25 s->s = bc_rs_open_file(filename);
26 if(!s->s)
27 return luaL_error(L, "Couldn't open bitcode file %s", filename);
28 else
29 return 1;
32 static int bc_read_stream_lua_next_record(lua_State *L)
34 struct bc_read_stream_lua *s = luaL_checkudata(L, 1, "bc_read_stream");
35 struct record_info ri = bc_rs_next_data_record(s->s);
37 if(ri.record_type == Eof)
39 lua_pushnil(L);
40 return 1;
42 else if(ri.record_type == DataRecord)
44 lua_pushstring(L, "data");
45 lua_pushnumber(L, ri.id);
46 for(int i = 0; i < bc_rs_get_record_size(s->s); i++)
47 lua_pushnumber(L, bc_rs_read_64(s->s, i));
48 return bc_rs_get_record_size(s->s) + 2;
50 else if(ri.record_type == StartBlock)
52 lua_pushstring(L, "startblock");
53 lua_pushnumber(L, ri.id);
54 return 2;
56 else if(ri.record_type == EndBlock)
58 lua_pushstring(L, "endblock");
59 return 1;
62 /* compiler too stupid to realize that this is unreachable */
63 return 0;
66 static const luaL_reg global_functions[] =
68 {"open", bc_read_stream_lua_open},
69 {NULL, NULL}
72 static const luaL_reg read_stream_methods[] =
74 {"next_record", bc_read_stream_lua_next_record},
75 {NULL, NULL}
78 int luaopen_bc_read_stream(lua_State *L)
80 luaL_newmetatable(L, "bc_read_stream");
82 /* metatable.__index = metatable */
83 lua_pushvalue(L, -1); /* duplicates the metatable */
84 lua_setfield(L, -2, "__index");
86 luaL_register(L, NULL, read_stream_methods);
87 luaL_register(L, "bc_read_stream", global_functions);
88 return 1;
91 /* Local Variables:
92 * c-set-style: "bsd"
93 * c-basic-offset: 2
94 * indent-tabs-mode: nil
95 * End:
96 * vim: et sts=2 sw=2