2 * This program is free software; you can redistribute it and/or modify
3 * it under the terms of the GNU General Public License as published by
4 * the Free Software Foundation; either version 2 of the License, or (at
5 * your option) any later version.
7 * This program is distributed in the hope that it will be useful, but
8 * WITHOUT ANY WARRANTY; without even the implied warranty of
9 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
10 * General Public License for more details.
12 * You should have received a copy of the GNU General Public License
13 * along with this program; if not, write to the Free Software
14 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
17 * Copyright © 2007 Pierre Habouzit
25 type 'a anchor = ('a * string * int)
29 output_string stderr (sprintf "%s:%d: %s\n" fpos lpos s);
32 let put_line = printf "#line %d \"%s\"\n"
34 let isspace = function |' '|'\t' -> true | _ -> false
37 let l = ref 0 and r = ref (String.length s) in
38 while (isspace s.[!l] && !l < !r) do incr l done;
39 while (isspace s.[!r - 1] && !l < !r) do decr r done;
40 String.sub s !l (!r - !l)
42 (* @types related {{{ *)
45 { lpos: int; fpos: string;
49 ctor : string anchor option;
50 dtor : string anchor option;
53 { lpos = 0; fpos = "";
60 let types = H.create 1031
64 List.iter (function ((s,_,_), x) -> if String.length s == 0 then
65 die t.lpos t.fpos (sprintf "type `%s' has no `%s' set" id x))
66 [(t.ctype, "ctype"); (t.check, "check"); (t.push, "push")];
70 (* @packages related {{{ *)
72 type typinst = bool * typedef
75 { typ: typinst; mname: string; init: string }
78 { rettype: typinst list; args: (typinst * string) list;
79 fname: string; body: string }
82 { line: int; file: string; name: string;
83 members: members anchor list;
84 methods: methods anchor list;
88 let newpkg lpos fpos name static =
89 { static = static; line = lpos; file = fpos; name = name; members = []; methods = []; }
91 let type_find lpos fpos t =
92 try Hashtbl.find types t
93 with Not_found -> die lpos fpos (sprintf "Unknown type `%s'" t)
95 let parse_rettype lpos fpos s =
97 match Str.split (Str.regexp "[ \t]+") t with
98 | ["const"; t] -> (true, type_find lpos fpos t)
99 | [t] -> (false, type_find lpos fpos t)
104 | s -> List.map aux (Str.split (Str.regexp "[ \t]*,[ \t]*") s)
106 let parse_args lpos fpos s =
108 match Str.split (Str.regexp "[ \t]+") t with
109 | ["const"; t; n] -> ((true, type_find lpos fpos t), n)
110 | [t; n] -> ((false, type_find lpos fpos t), n)
115 | s -> List.map aux (Str.split (Str.regexp "[ \t]*,[ \t]*") s)
118 (* parsing helpers {{{ *)
120 type stanza = Buf of string anchor | Pkg of package
123 let pos = lexbuf.L.lex_curr_p in
124 lexbuf.L.lex_curr_p <-
126 L.pos_lnum = pos.L.pos_lnum + 1;
127 L.pos_bol = pos.L.pos_cnum; };
131 let lnum lexbuf = lexbuf.L.lex_curr_p.L.pos_lnum
133 let (@.) buf s = B.add_string buf s; buf
134 let (@<) buf c = B.add_char buf c; buf
136 let getchunk lpos fpos buf lexbuf =
137 let res = B.contents buf in
141 let startchunk f fpos lexbuf =
142 f (lnum lexbuf) fpos (B.create 4096) lexbuf
144 let newchunk f lpos fpos buf lexbuf =
145 let res = getchunk lpos fpos buf lexbuf in
146 res::(f (lnum lexbuf, fpos) buf lexbuf)
148 let find_import relpath file =
149 if Filename.is_relative file then
150 match Filename.dirname relpath with
152 | s -> Filename.concat s file
159 (* regex aliases {{{ *)
161 let to_eol = [^'\n']* '\n'
162 let ident = ['a'-'z''A'-'Z''_']['a'-'z''A'-'Z''_''0'-'9']*
165 let typdecl = sp* ("const" sp+)? ident sp*
168 (* entry point {{{ *)
170 rule cLine lpos fpos buf = parse
171 | sp* "@type" sp+ (ident as id) sp* (':' sp* (ident as id0) sp*)? '{'
173 let line = lnum lexbuf in
174 let t0 = match id0 with
179 die line fpos (sprintf "Uknown type `%s'" id0)
181 let t = H.find types id in
183 (sprintf "type `%s' already defined at %s:%d"
186 (getchunk lpos fpos buf lexbuf) :: (
187 ext_type id {t0 with lpos = line; fpos = fpos}
191 | sp* "@import" sp+ '"' ([^'"''\n']* as file) '"' sp* '\n'
193 let file = find_import fpos file in
194 let _ = startchunk cLine file
195 (L.from_channel (open_in file)) in
196 cLine lpos fpos (buf @< '\n') (nextl lexbuf)
198 | sp* ("@package"|"@static_package" as kw) sp+ (ident as pkg) sp* '{'
200 let a = getchunk lpos fpos buf lexbuf in
201 let line = lnum lexbuf in
202 a::(ext_pkg (newpkg line fpos pkg
203 (kw = "@static_package")) lexbuf)
205 | sp* '@' { die (lnum lexbuf) fpos "Syntax error" }
206 | sp* '#' as s { let buf = cPP (buf @. s) lexbuf in
207 cLine lpos fpos buf lexbuf }
208 | "" { let buf = cCode buf lexbuf in
209 cLine lpos fpos buf lexbuf }
210 | eof { [getchunk lpos fpos buf lexbuf] }
213 (* cCode block parser {{{ *)
215 and cCode buf = parse
216 | '\n' as c { let _ = nextl lexbuf in buf @< c }
217 | '"' as c { let buf = cString (buf @< c) lexbuf in
219 | "/*" as s { let buf = cComment (buf @. s) lexbuf in
221 | "//" to_eol as s { cCode (buf @. s) (nextl lexbuf) }
222 | "'\"'" as s { cCode (buf @. s) lexbuf }
223 | _ as c { cCode (buf @< c) lexbuf }
226 (* helper rules: comment, string, cPP {{{ *)
228 and cComment buf = parse
229 | "*/" as s { buf @. s }
230 | '\n' as c { cComment (buf @< c) (nextl lexbuf) }
231 | _ as c { cComment (buf @< c) lexbuf }
233 and cString buf = parse
234 | '"' as c { buf @< c }
235 | "\\\"" as s { cString (buf @. s) lexbuf }
236 | "\\\n" as s { cString (buf @. s) (nextl lexbuf) }
237 | [^'\n'] as c { cString (buf @< c) lexbuf }
240 | [^'\n']* "\\\n" as s { cPP (buf @. s) (nextl lexbuf) }
241 | to_eol as s { let _ = nextl lexbuf in buf @. s }
244 (* parse @type {{{ *)
246 and ext_type id typ = parse
248 | "//" to_eol { ext_type id typ lexbuf }
249 | '\n' { ext_type id typ (nextl lexbuf) }
250 | "/*" { let _ = cComment (B.create 1024) lexbuf in
251 ext_type id typ lexbuf }
252 | '.' (ident as member) sp* '=' sp* ([^';''\n']+ as s) ';'
255 let do_anch s = s, typ.fpos, lnum lexbuf in
257 | "ctype" -> {typ with ctype = do_anch s}
258 | "check" -> {typ with check = do_anch s}
259 | "push" -> {typ with push = do_anch s}
260 | "ctor" -> {typ with ctor = Some (do_anch s)}
261 | "dtor" -> {typ with dtor = Some (do_anch s)}
263 die (lnum lexbuf) typ.fpos
264 (sprintf "Unknown directive `%s'" member)
267 | '}' sp* ';' (sp* '\n' as s)?
268 { id @:= typ; startchunk cLine typ.fpos
269 (if s = None then lexbuf else nextl lexbuf) }
270 | "" { die (lnum lexbuf) typ.fpos "Syntax error" }
273 (* parse @package {{{ *)
275 and ext_pkg pkg = parse
277 | "//" to_eol { ext_pkg pkg lexbuf }
278 | '\n' { ext_pkg pkg (nextl lexbuf) }
279 | "/*" { let _ = cComment (B.create 1024) lexbuf in
281 | ("const" sp+ as const)? (ident as typ) sp+
282 (ident as member) sp* '=' sp* ([^';''\n']* as init)';'
284 let m = { typ = const != None,
285 type_find (lnum lexbuf) pkg.file typ;
287 init = init; }, pkg.file, lnum lexbuf in
288 ext_pkg {pkg with members = m::pkg.members} lexbuf
290 | '(' ((typdecl ',')* typdecl as ret) ')' sp*
292 '('((typdecl ident sp* ',')* typdecl ident sp* as args)')' sp*
293 | (typdecl as ret) (ident as fname)
294 '('((typdecl ident sp* ',')* typdecl ident sp* as args)')' sp*
296 let rettype = parse_rettype (lnum lexbuf) pkg.file ret in
297 let args = parse_args (lnum lexbuf) pkg.file args in
298 let body = ext_body pkg (B.create 1024) lexbuf in
299 let m = { rettype = rettype;
302 body = body }, pkg.file, lnum lexbuf in
303 ext_pkg {pkg with methods = m::pkg.methods} lexbuf
305 | '}' sp* ';' (sp* '\n' as s)?
306 { Pkg({pkg with members = List.rev(pkg.members)}) :: (
307 startchunk cLine pkg.file
308 (if s = None then lexbuf else nextl lexbuf)
311 | "" { die (lnum lexbuf) pkg.file "Syntax error" }
313 and ext_body pkg buf = parse
315 | "//" to_eol as s { ext_body pkg (buf @. s) lexbuf }
316 | '\n' as c { ext_body pkg (buf @< c) lexbuf }
317 | "/*" { let buf = cComment (buf @. "/*") lexbuf in
318 ext_body pkg buf lexbuf }
319 | ';' { B.contents buf }
320 | '{' as c { let buf = ext_bodycode (buf @< c) lexbuf in
321 ext_body pkg buf lexbuf }
322 | "" { die (lnum lexbuf) pkg.file "Syntax error" }
324 and ext_bodycode buf = parse
325 | '\n' as c { ext_bodycode (buf @< c) (nextl lexbuf) }
326 | '"' as c { let buf = cString (buf @< c) lexbuf in
327 ext_bodycode buf lexbuf }
328 | "/*" as s { let buf = cComment (buf @. s) lexbuf in
329 ext_bodycode buf lexbuf }
330 | "//" to_eol as s { ext_bodycode (buf @. s) (nextl lexbuf) }
331 | "'\"'" as s { ext_bodycode (buf @. s) lexbuf }
332 | '{' as c { let buf = ext_bodycode (buf @< c) lexbuf in ext_bodycode buf lexbuf }
333 | '}' as c { buf @< c }
334 | _ as c { ext_bodycode (buf @< c) lexbuf }
339 (* templating functions {{{ *)
341 let upper = String.uppercase
343 Str.global_replace (Str.regexp_string "$L") "L" (
344 Str.global_replace (Str.regexp_string "$$") v tpl
347 let dump_struct_type begwith pkg endwith =
348 printf "%sstruct luaM_%s_t {\n" begwith pkg.name;
349 List.iter (function (m, f, l) ->
351 let ctype = t1 (snd m.typ).ctype in
353 if fst m.typ then print_string "const ";
354 let i = try String.index ctype ':' with Not_found -> String.length ctype in
355 printf "%s %s%s;\n" (Str.string_before ctype i)
356 m.mname (Str.string_after ctype i)
358 print_endline ("}" ^ endwith)
361 let do_h_aux = function
364 printf "\n#ifndef MUTT_LUA_%s_H\n" (upper pkg.name);
365 printf "#define MUTT_LUA_%s_H\n\n" (upper pkg.name);
366 if not pkg.static then (
367 dump_struct_type "" pkg ";";
368 printf "extern struct luaM_%s_t %s;\n" pkg.name pkg.name;
370 printf "\nint luaopen_%s(lua_State *L);\n\n" pkg.name;
371 printf "#endif /* MUTT_LUA_%s_H */\n" (upper pkg.name);
372 in List.iter do_h_aux
374 let do_func pkg (fn, f, l) =
375 (* return inline function *)
376 printf "\nstatic int luaM_ret_%s_%s(lua_State *L" pkg.name fn.fname;
377 let retlen = List.fold_left (fun i t ->
380 | true, typ -> printf ", const %s luaM_x%d" (t1 typ.ctype) i; i
381 | false, typ -> printf ", %s luaM_x%d" (t1 typ.ctype) i; i
384 ignore (List.fold_left (fun i (const, typ) ->
386 let (p, f, l) = typ.push in
388 printf " %s;\n" (tplize p (sprintf "luaM_x%d" i));
392 | Some(dtor, f, l) ->
394 printf " %s;\n" (tplize dtor (sprintf "&luaM_x%d" i))
397 printf " return %d;\n}\n" retlen;
400 printf "\nstatic int luaM_%s_%s(lua_State *L)\n{\n" pkg.name fn.fname;
401 ignore (List.fold_left (fun i ((const, typ), name) ->
403 let ctype = t1 typ.ctype in
405 let (c, f, l) = typ.check in
407 printf " const %s %s = %s;\n" ctype name (tplize c (string_of_int i))
411 let (c, f, l) = typ.check in
413 printf " %s %s = %s;\n" ctype name (tplize c (string_of_int i))
414 | Some (ctor, f, l) ->
416 let c, f, l = typ.check in
417 tplize (sprintf "\n#line %d \"%s\"\n %s" l f c)
421 printf " %s %s = %s;\n" ctype name (tplize ctor v)
424 printf "\n#define RAISE(s) luaL_error(L, (s))\n";
425 if fn.rettype = [] then (
426 printf "#define RETURN() return luaM_ret_%s_%s(L)\n" pkg.name fn.fname
428 printf "#define RETURN(luaM_x1";
429 for i = 2 to retlen do printf ", luaM_x%d" i done;
430 printf ") \\\n return luaM_ret_%s_%s(L" pkg.name fn.fname;
431 for i = 1 to retlen do printf ", luaM_x%d" i done;
435 printf " %s\n#undef RAISE\n#undef RETURN\n}\n" fn.body
438 let do_c_aux = function
439 | Buf (s, f, l) -> put_line l f; print_string s
441 (* dump struct const init *)
443 dump_struct_type "static " pkg (sprintf " %s = {\n" pkg.name)
445 printf "struct luaM_%s_t %s = {\n" pkg.name pkg.name
447 List.iter (function (m, f, l) ->
449 printf " %s,\n" (if fst m.typ then m.init else "0")
453 (* dump struct init func *)
454 printf "\nstatic void %s_init(void)\n{\n" pkg.name;
455 List.iter (function (m, f, l) ->
456 if not (fst m.typ) then
457 printf "#line %d \"%s\"\n %s.%s = %s;\n"
458 l f pkg.name m.mname m.init) pkg.members;
462 printf "static int luaM_%s_index(lua_State *L)\n{\n" pkg.name;
463 printf " const char *idx = luaL_checkstring(L, 2);\n\n";
464 printf " switch (mlua_which_token(idx, -1)) {\n";
465 printf " default:\n";
466 List.iter (function (m, _, _) ->
467 printf " case LTK_%s:\n" (upper m.mname);
468 let push, f, l = (snd m.typ).push in
470 printf " %s;\n" (tplize push (sprintf "%s.%s" pkg.name m.mname));
471 printf " return 1;\n"
473 printf " lua_rawget(L, lua_upvalueindex(2));\n";
474 printf " return 1;\n";
477 (* dump __newindex *)
478 printf "static int luaM_%s_newindex(lua_State *L)\n{\n" pkg.name;
479 printf " const char *idx = luaL_checkstring(L, 2);\n\n";
480 printf " switch (mlua_which_token(idx, -1)) {\n";
481 List.iter (function (m, _, _) ->
485 printf " case LTK_%s:\n" (upper m.mname);
488 | Some (dtor, f, l) ->
490 printf " %s;\n" (tplize dtor (sprintf "&%s.%s" pkg.name m.mname))
494 let (c, f, l) = t.check in
496 printf " %s.%s = %s;\n" pkg.name m.mname (tplize c "3")
497 | Some (ctor, f, l) ->
499 let c, f, l = t.check in
500 tplize (sprintf "\n#line %d \"%s\"\n %s" l f c) "3"
503 printf " %s.%s = %s;\n" pkg.name m.mname (tplize ctor v)
505 printf " return 1;\n"
507 printf " default:\n";
508 printf " return 1;\n";
512 List.iter (do_func pkg) pkg.methods;
513 printf "\nstatic const luaL_reg luaM_%s_methods[] = {\n" pkg.name;
514 List.iter (function (f, _, _) ->
515 printf " { \"%s\", luaM_%s_%s },\n" f.fname pkg.name f.fname)
517 print_string (Str.global_replace (Str.regexp "%s") pkg.name
521 int luaopen_%s(lua_State *L)
527 /* create methods table, add it the the table of globals */
528 luaL_openlib(L, \"%s\", luaM_%s_methods, 0);
529 methods = lua_gettop(L);
531 /* create metatable for %s, add it to the registry */
532 luaL_newmetatable(L, \"%s\");
535 lua_pushliteral(L, \"__index\");
536 lua_pushvalue(L, mt); /* upvalue 1 */
537 lua_pushvalue(L, methods); /* upvalue 2 */
538 lua_pushcclosure(L, &luaM_%s_index, 2);
539 lua_rawset(L, mt); /* set mt.__index */
541 lua_pushliteral(L, \"__newindex\");
542 lua_newtable(L); /* for new members */
543 lua_pushcclosure(L, &luaM_%s_newindex, 1);
544 lua_rawset(L, mt); /* set mt.__newindex */
546 lua_pushliteral(L, \"__metatable\");
547 lua_pushvalue(L, methods); /* dup methods table */
548 lua_rawset(L, mt); /* hide metatable */
550 lua_setmetatable(L, methods);
552 lua_pop(L, 2); /* drop mt + methods */
557 in List.iter do_c_aux
562 output_string stderr "usage: cpkg2c (-h | -c) file.cpkg\n";
566 let warn () = print_endline "/*** THIS FILE IS AUTOGENERATED !!! ***/" in
567 if Array.length Sys.argv <= 2 then usage();
568 let file = Sys.argv.(2) in
569 let lexbuf = L.from_channel (open_in file) in
570 let l = (startchunk cLine file lexbuf) in
571 match Sys.argv.(1) with
572 | "-h" -> warn (); do_h l
573 | "-c" -> warn (); do_c l