1 /* Copyright (c) 2014, Vsevolod Stakhov
4 * Redistribution and use in source and binary forms, with or without
5 * modification, are permitted provided that the following conditions are met:
6 * * Redistributions of source code must retain the above copyright
7 * notice, this list of conditions and the following disclaimer.
8 * * Redistributions in binary form must reproduce the above copyright
9 * notice, this list of conditions and the following disclaimer in the
10 * documentation and/or other materials provided with the distribution.
12 * THIS SOFTWARE IS PROVIDED ''AS IS'' AND ANY
13 * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
14 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
15 * DISCLAIMED. IN NO EVENT SHALL AUTHOR BE LIABLE FOR ANY
16 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
17 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
18 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
19 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
20 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
21 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
25 * @file lua ucl bindings
29 #include "ucl_internal.h"
35 * This lua module allows to parse objects from strings and to store data into
36 * ucl objects. It uses `libucl` C library to parse and manipulate with ucl objects.
38 local ucl = require("ucl")
40 local parser = ucl.parser()
41 local res,err = parser:parse_string('{key=value}')
44 print('parser error: ' .. err)
46 local obj = parser:get_object()
47 local got = ucl.to_format(obj, 'json')
59 print(ucl.to_format(table, 'ucl'))
69 #define PARSER_META "ucl.parser.meta"
70 #define EMITTER_META "ucl.emitter.meta"
71 #define NULL_META "null.emitter.meta"
73 static int ucl_object_lua_push_array (lua_State *L, const ucl_object_t *obj);
74 static int ucl_object_lua_push_scalar (lua_State *L, const ucl_object_t *obj, bool allow_array);
75 static ucl_object_t* ucl_object_lua_fromtable (lua_State *L, int idx);
76 static ucl_object_t* ucl_object_lua_fromelt (lua_State *L, int idx);
78 static void *ucl_null;
81 * Push a single element of an object to lua
87 ucl_object_lua_push_element (lua_State *L, const char *key,
88 const ucl_object_t *obj)
90 lua_pushstring (L, key);
91 ucl_object_push_lua (L, obj, true);
96 lua_ucl_userdata_dtor (void *ud)
98 struct ucl_lua_funcdata *fd = (struct ucl_lua_funcdata *)ud;
100 luaL_unref (fd->L, LUA_REGISTRYINDEX, fd->idx);
101 if (fd->ret != NULL) {
108 lua_ucl_userdata_emitter (void *ud)
110 struct ucl_lua_funcdata *fd = (struct ucl_lua_funcdata *)ud;
111 const char *out = "";
113 lua_rawgeti (fd->L, LUA_REGISTRYINDEX, fd->idx);
115 lua_pcall (fd->L, 0, 1, 0);
116 out = lua_tostring (fd->L, -1);
119 /* We need to store temporary string in a more appropriate place */
123 fd->ret = strdup (out);
126 lua_settop (fd->L, 0);
132 * Push a single object to lua
138 ucl_object_lua_push_object (lua_State *L, const ucl_object_t *obj,
141 const ucl_object_t *cur;
142 ucl_object_iter_t it = NULL;
145 if (allow_array && obj->next != NULL) {
146 /* Actually we need to push this as an array */
147 return ucl_object_lua_push_array (L, obj);
150 /* Optimize allocation by preallocation of table */
151 while (ucl_iterate_object (obj, &it, true) != NULL) {
155 lua_createtable (L, 0, nelt);
158 while ((cur = ucl_iterate_object (obj, &it, true)) != NULL) {
159 ucl_object_lua_push_element (L, ucl_object_key (cur), cur);
166 * Push an array to lua as table indexed by integers
172 ucl_object_lua_push_array (lua_State *L, const ucl_object_t *obj)
174 const ucl_object_t *cur;
177 /* Optimize allocation by preallocation of table */
178 LL_FOREACH (obj, cur) {
182 lua_createtable (L, nelt, 0);
184 LL_FOREACH (obj, cur) {
185 ucl_object_push_lua (L, cur, false);
186 lua_rawseti (L, -2, i);
194 * Push a simple object to lua depending on its actual type
197 ucl_object_lua_push_scalar (lua_State *L, const ucl_object_t *obj,
200 struct ucl_lua_funcdata *fd;
202 if (allow_array && obj->next != NULL) {
203 /* Actually we need to push this as an array */
204 return ucl_object_lua_push_array (L, obj);
209 lua_pushboolean (L, ucl_obj_toboolean (obj));
212 lua_pushstring (L, ucl_obj_tostring (obj));
215 #if LUA_VERSION_NUM >= 501
216 lua_pushinteger (L, ucl_obj_toint (obj));
218 lua_pushnumber (L, ucl_obj_toint (obj));
223 lua_pushnumber (L, ucl_obj_todouble (obj));
226 lua_getfield (L, LUA_REGISTRYINDEX, "ucl.null");
229 fd = (struct ucl_lua_funcdata *)obj->value.ud;
230 lua_rawgeti (L, LUA_REGISTRYINDEX, fd->idx);
241 * @function ucl_object_push_lua(L, obj, allow_array)
242 * This is a `C` function to push `UCL` object as lua variable. This function
243 * converts `obj` to lua representation using the following conversions:
245 * - *scalar* values are directly presented by lua objects
246 * - *userdata* values are converted to lua function objects using `LUA_REGISTRYINDEX`,
247 * this can be used to pass functions from lua to c and vice-versa
248 * - *arrays* are converted to lua tables with numeric indicies suitable for `ipairs` iterations
249 * - *objects* are converted to lua tables with string indicies
250 * @param {lua_State} L lua state pointer
251 * @param {ucl_object_t} obj object to push
252 * @param {bool} allow_array expand implicit arrays (should be true for all but partial arrays)
253 * @return {int} `1` if an object is pushed to lua
256 ucl_object_push_lua (lua_State *L, const ucl_object_t *obj, bool allow_array)
260 return ucl_object_lua_push_object (L, obj, allow_array);
262 return ucl_object_lua_push_array (L, obj->value.av);
264 return ucl_object_lua_push_scalar (L, obj, allow_array);
269 * Parse lua table into object top
274 static ucl_object_t *
275 ucl_object_lua_fromtable (lua_State *L, int idx)
277 ucl_object_t *obj, *top = NULL;
280 bool is_array = true;
284 /* For negative indicies we want to invert them */
285 idx = lua_gettop (L) + idx + 1;
287 /* Check for array */
289 while (lua_next (L, idx) != 0) {
290 if (lua_type (L, -2) == LUA_TNUMBER) {
291 double num = lua_tonumber (L, -2);
292 if (num == (int)num) {
298 /* Keys are not integer */
305 /* Keys are not numeric */
317 top = ucl_object_typed_new (UCL_ARRAY);
318 for (i = 1; i <= max; i ++) {
319 lua_pushinteger (L, i);
320 lua_gettable (L, idx);
321 obj = ucl_object_lua_fromelt (L, lua_gettop (L));
323 ucl_array_append (top, obj);
329 top = ucl_object_typed_new (UCL_OBJECT);
330 while (lua_next (L, idx) != 0) {
331 /* copy key to avoid modifications */
332 k = lua_tolstring (L, -2, &keylen);
333 obj = ucl_object_lua_fromelt (L, lua_gettop (L));
336 ucl_object_insert_key (top, obj, k, keylen, true);
346 * Get a single element from lua to object obj
351 static ucl_object_t *
352 ucl_object_lua_fromelt (lua_State *L, int idx)
356 ucl_object_t *obj = NULL;
357 struct ucl_lua_funcdata *fd;
359 type = lua_type (L, idx);
363 obj = ucl_object_fromstring_common (lua_tostring (L, idx), 0, 0);
366 num = lua_tonumber (L, idx);
367 if (num == (int64_t)num) {
368 obj = ucl_object_fromint (num);
371 obj = ucl_object_fromdouble (num);
375 obj = ucl_object_frombool (lua_toboolean (L, idx));
378 if (lua_topointer (L, idx) == ucl_null) {
379 obj = ucl_object_typed_new (UCL_NULL);
385 if (luaL_getmetafield (L, idx, "__gen_ucl")) {
386 if (lua_isfunction (L, -1)) {
387 lua_settop (L, 3); /* gen, obj, func */
388 lua_insert (L, 1); /* func, gen, obj */
389 lua_insert (L, 2); /* func, obj, gen */
391 obj = ucl_object_lua_fromelt (L, 1);
396 if (type == LUA_TTABLE) {
397 obj = ucl_object_lua_fromtable (L, idx);
399 else if (type == LUA_TFUNCTION) {
400 fd = malloc (sizeof (*fd));
402 lua_pushvalue (L, idx);
405 fd->idx = luaL_ref (L, LUA_REGISTRYINDEX);
407 obj = ucl_object_new_userdata (lua_ucl_userdata_dtor,
408 lua_ucl_userdata_emitter);
409 obj->type = UCL_USERDATA;
410 obj->value.ud = (void *)fd;
421 * @function ucl_object_lua_import(L, idx)
422 * Extracts ucl object from lua variable at `idx` position,
423 * @see ucl_object_push_lua for conversion definitions
424 * @param {lua_state} L lua state machine pointer
425 * @param {int} idx index where the source variable is placed
426 * @return {ucl_object_t} new ucl object extracted from lua variable. Reference count of this object is 1,
427 * this object thus needs to be unref'ed after usage.
430 ucl_object_lua_import (lua_State *L, int idx)
435 t = lua_type (L, idx);
438 obj = ucl_object_lua_fromtable (L, idx);
441 obj = ucl_object_lua_fromelt (L, idx);
449 lua_ucl_parser_init (lua_State *L)
451 struct ucl_parser *parser, **pparser;
454 if (lua_gettop (L) >= 1) {
455 flags = lua_tonumber (L, 1);
458 parser = ucl_parser_new (flags);
459 if (parser == NULL) {
463 pparser = lua_newuserdata (L, sizeof (parser));
465 luaL_getmetatable (L, PARSER_META);
466 lua_setmetatable (L, -2);
471 static struct ucl_parser *
472 lua_ucl_parser_get (lua_State *L, int index)
474 return *((struct ucl_parser **) luaL_checkudata(L, index, PARSER_META));
478 * @method parser:parse_file(name)
479 * Parse UCL object from file.
480 * @param {string} name filename to parse
481 * @return {bool[, string]} if res is `true` then file has been parsed successfully, otherwise an error string is also returned
483 local parser = ucl.parser()
484 local res,err = parser:parse_file('/some/file.conf')
487 print('parser error: ' .. err)
489 -- Do something with object
493 lua_ucl_parser_parse_file (lua_State *L)
495 struct ucl_parser *parser;
499 parser = lua_ucl_parser_get (L, 1);
500 file = luaL_checkstring (L, 2);
502 if (parser != NULL && file != NULL) {
503 if (ucl_parser_add_file (parser, file)) {
504 lua_pushboolean (L, true);
508 lua_pushboolean (L, false);
509 lua_pushstring (L, ucl_parser_get_error (parser));
513 lua_pushboolean (L, false);
514 lua_pushstring (L, "invalid arguments");
521 * @method parser:parse_string(input)
522 * Parse UCL object from file.
523 * @param {string} input string to parse
524 * @return {bool[, string]} if res is `true` then file has been parsed successfully, otherwise an error string is also returned
527 lua_ucl_parser_parse_string (lua_State *L)
529 struct ucl_parser *parser;
534 parser = lua_ucl_parser_get (L, 1);
535 string = luaL_checklstring (L, 2, &llen);
537 if (parser != NULL && string != NULL) {
538 if (ucl_parser_add_chunk (parser, (const unsigned char *)string, llen)) {
539 lua_pushboolean (L, true);
543 lua_pushboolean (L, false);
544 lua_pushstring (L, ucl_parser_get_error (parser));
548 lua_pushboolean (L, false);
549 lua_pushstring (L, "invalid arguments");
556 * @method parser:get_object()
557 * Get top object from parser and export it to lua representation.
558 * @return {variant or nil} ucl object as lua native variable
561 lua_ucl_parser_get_object (lua_State *L)
563 struct ucl_parser *parser;
567 parser = lua_ucl_parser_get (L, 1);
568 obj = ucl_parser_get_object (parser);
571 ret = ucl_object_push_lua (L, obj, false);
572 /* no need to keep reference */
573 ucl_object_unref (obj);
583 lua_ucl_parser_gc (lua_State *L)
585 struct ucl_parser *parser;
587 parser = lua_ucl_parser_get (L, 1);
588 ucl_parser_free (parser);
594 lua_ucl_parser_mt (lua_State *L)
596 luaL_newmetatable (L, PARSER_META);
598 lua_pushvalue(L, -1);
599 lua_setfield(L, -2, "__index");
601 lua_pushcfunction (L, lua_ucl_parser_gc);
602 lua_setfield (L, -2, "__gc");
604 lua_pushcfunction (L, lua_ucl_parser_parse_file);
605 lua_setfield (L, -2, "parse_file");
607 lua_pushcfunction (L, lua_ucl_parser_parse_string);
608 lua_setfield (L, -2, "parse_string");
610 lua_pushcfunction (L, lua_ucl_parser_get_object);
611 lua_setfield (L, -2, "get_object");
617 lua_ucl_to_string (lua_State *L, const ucl_object_t *obj, enum ucl_emitter type)
619 unsigned char *result;
621 result = ucl_object_emit (obj, type);
623 if (result != NULL) {
624 lua_pushstring (L, (const char *)result);
635 lua_ucl_to_json (lua_State *L)
638 int format = UCL_EMIT_JSON;
640 if (lua_gettop (L) > 1) {
641 if (lua_toboolean (L, 2)) {
642 format = UCL_EMIT_JSON_COMPACT;
646 obj = ucl_object_lua_import (L, 1);
648 lua_ucl_to_string (L, obj, format);
649 ucl_object_unref (obj);
659 lua_ucl_to_config (lua_State *L)
663 obj = ucl_object_lua_import (L, 1);
665 lua_ucl_to_string (L, obj, UCL_EMIT_CONFIG);
666 ucl_object_unref (obj);
676 * @function ucl.to_format(var, format)
677 * Converts lua variable `var` to the specified `format`. Formats supported are:
679 * - `json` - fine printed json
680 * - `json-compact` - compacted json
681 * - `config` - fine printed configuration
682 * - `ucl` - same as `config`
683 * - `yaml` - embedded yaml
685 * If `var` contains function, they are called during output formatting and if
686 * they return string value, then this value is used for ouptut.
687 * @param {variant} var any sort of lua variable (if userdata then metafield `__to_ucl` is searched for output)
688 * @param {string} format any available format
689 * @return {string} string representation of `var` in the specific `format`.
700 print(ucl.to_format(table, 'ucl'))
710 lua_ucl_to_format (lua_State *L)
713 int format = UCL_EMIT_JSON;
715 if (lua_gettop (L) > 1) {
716 if (lua_type (L, 2) == LUA_TNUMBER) {
717 format = lua_tonumber (L, 2);
718 if (format < 0 || format >= UCL_EMIT_YAML) {
723 else if (lua_type (L, 2) == LUA_TSTRING) {
724 const char *strtype = lua_tostring (L, 2);
726 if (strcasecmp (strtype, "json") == 0) {
727 format = UCL_EMIT_JSON;
729 else if (strcasecmp (strtype, "json-compact") == 0) {
730 format = UCL_EMIT_JSON_COMPACT;
732 else if (strcasecmp (strtype, "yaml") == 0) {
733 format = UCL_EMIT_YAML;
735 else if (strcasecmp (strtype, "config") == 0 ||
736 strcasecmp (strtype, "ucl") == 0) {
737 format = UCL_EMIT_CONFIG;
742 obj = ucl_object_lua_import (L, 1);
744 lua_ucl_to_string (L, obj, format);
745 ucl_object_unref (obj);
755 lua_ucl_null_tostring (lua_State* L)
757 lua_pushstring (L, "null");
762 lua_ucl_null_mt (lua_State *L)
764 luaL_newmetatable (L, NULL_META);
766 lua_pushcfunction (L, lua_ucl_null_tostring);
767 lua_setfield (L, -2, "__tostring");
773 luaopen_ucl (lua_State *L)
775 lua_ucl_parser_mt (L);
778 /* Create the refs weak table: */
779 lua_createtable (L, 0, 2);
780 lua_pushliteral (L, "v"); /* tbl, "v" */
781 lua_setfield (L, -2, "__mode");
782 lua_pushvalue (L, -1); /* tbl, tbl */
783 lua_setmetatable (L, -2); /* tbl */
784 lua_setfield (L, LUA_REGISTRYINDEX, "ucl.refs");
788 lua_pushcfunction (L, lua_ucl_parser_init);
789 lua_setfield (L, -2, "parser");
791 lua_pushcfunction (L, lua_ucl_to_json);
792 lua_setfield (L, -2, "to_json");
794 lua_pushcfunction (L, lua_ucl_to_config);
795 lua_setfield (L, -2, "to_config");
797 lua_pushcfunction (L, lua_ucl_to_format);
798 lua_setfield (L, -2, "to_format");
800 ucl_null = lua_newuserdata (L, 0);
801 luaL_getmetatable (L, NULL_META);
802 lua_setmetatable (L, -2);
804 lua_pushvalue (L, -1);
805 lua_setfield (L, LUA_REGISTRYINDEX, "ucl.null");
807 lua_setfield (L, -2, "null");
812 struct ucl_lua_funcdata*
813 ucl_object_toclosure (const ucl_object_t *obj)
815 if (obj == NULL || obj->type != UCL_USERDATA) {
819 return (struct ucl_lua_funcdata*)obj->value.ud;