xref: /freebsd/contrib/libucl/lua/lua_ucl.c (revision f4b37ed0f8b307b1f3f0f630ca725d68f1dff30d)
1 /* Copyright (c) 2014, Vsevolod Stakhov
2  * All rights reserved.
3  *
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.
11  *
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.
22  */
23 
24 /**
25  * @file lua ucl bindings
26  */
27 
28 #include "ucl.h"
29 #include "ucl_internal.h"
30 #include "lua_ucl.h"
31 #include <strings.h>
32 
33 /***
34  * @module ucl
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.
37  * @example
38 local ucl = require("ucl")
39 
40 local parser = ucl.parser()
41 local res,err = parser:parse_string('{key=value}')
42 
43 if not res then
44 	print('parser error: ' .. err)
45 else
46 	local obj = parser:get_object()
47 	local got = ucl.to_format(obj, 'json')
48 endif
49 
50 local table = {
51   str = 'value',
52   num = 100500,
53   null = ucl.null,
54   func = function ()
55     return 'huh'
56   end
57 }
58 
59 print(ucl.to_format(table, 'ucl'))
60 -- Output:
61 --[[
62 num = 100500;
63 str = "value";
64 null = null;
65 func = "huh";
66 --]]
67  */
68 
69 #define PARSER_META "ucl.parser.meta"
70 #define EMITTER_META "ucl.emitter.meta"
71 #define NULL_META "null.emitter.meta"
72 
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);
77 
78 static void *ucl_null;
79 
80 /**
81  * Push a single element of an object to lua
82  * @param L
83  * @param key
84  * @param obj
85  */
86 static void
87 ucl_object_lua_push_element (lua_State *L, const char *key,
88 		const ucl_object_t *obj)
89 {
90 	lua_pushstring (L, key);
91 	ucl_object_push_lua (L, obj, true);
92 	lua_settable (L, -3);
93 }
94 
95 static void
96 lua_ucl_userdata_dtor (void *ud)
97 {
98 	struct ucl_lua_funcdata *fd = (struct ucl_lua_funcdata *)ud;
99 
100 	luaL_unref (fd->L, LUA_REGISTRYINDEX, fd->idx);
101 	if (fd->ret != NULL) {
102 		free (fd->ret);
103 	}
104 	free (fd);
105 }
106 
107 static const char *
108 lua_ucl_userdata_emitter (void *ud)
109 {
110 	struct ucl_lua_funcdata *fd = (struct ucl_lua_funcdata *)ud;
111 	const char *out = "";
112 
113 	lua_rawgeti (fd->L, LUA_REGISTRYINDEX, fd->idx);
114 
115 	lua_pcall (fd->L, 0, 1, 0);
116 	out = lua_tostring (fd->L, -1);
117 
118 	if (out != NULL) {
119 		/* We need to store temporary string in a more appropriate place */
120 		if (fd->ret) {
121 			free (fd->ret);
122 		}
123 		fd->ret = strdup (out);
124 	}
125 
126 	lua_settop (fd->L, 0);
127 
128 	return fd->ret;
129 }
130 
131 /**
132  * Push a single object to lua
133  * @param L
134  * @param obj
135  * @return
136  */
137 static int
138 ucl_object_lua_push_object (lua_State *L, const ucl_object_t *obj,
139 		bool allow_array)
140 {
141 	const ucl_object_t *cur;
142 	ucl_object_iter_t it = NULL;
143 	int nelt = 0;
144 
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);
148 	}
149 
150 	/* Optimize allocation by preallocation of table */
151 	while (ucl_iterate_object (obj, &it, true) != NULL) {
152 		nelt ++;
153 	}
154 
155 	lua_createtable (L, 0, nelt);
156 	it = NULL;
157 
158 	while ((cur = ucl_iterate_object (obj, &it, true)) != NULL) {
159 		ucl_object_lua_push_element (L, ucl_object_key (cur), cur);
160 	}
161 
162 	return 1;
163 }
164 
165 /**
166  * Push an array to lua as table indexed by integers
167  * @param L
168  * @param obj
169  * @return
170  */
171 static int
172 ucl_object_lua_push_array (lua_State *L, const ucl_object_t *obj)
173 {
174 	const ucl_object_t *cur;
175 	int i = 1, nelt = 0;
176 
177 	/* Optimize allocation by preallocation of table */
178 	LL_FOREACH (obj, cur) {
179 		nelt ++;
180 	}
181 
182 	lua_createtable (L, nelt, 0);
183 
184 	LL_FOREACH (obj, cur) {
185 		ucl_object_push_lua (L, cur, false);
186 		lua_rawseti (L, -2, i);
187 		i ++;
188 	}
189 
190 	return 1;
191 }
192 
193 /**
194  * Push a simple object to lua depending on its actual type
195  */
196 static int
197 ucl_object_lua_push_scalar (lua_State *L, const ucl_object_t *obj,
198 		bool allow_array)
199 {
200 	struct ucl_lua_funcdata *fd;
201 
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);
205 	}
206 
207 	switch (obj->type) {
208 	case UCL_BOOLEAN:
209 		lua_pushboolean (L, ucl_obj_toboolean (obj));
210 		break;
211 	case UCL_STRING:
212 		lua_pushstring (L, ucl_obj_tostring (obj));
213 		break;
214 	case UCL_INT:
215 #if LUA_VERSION_NUM >= 501
216 		lua_pushinteger (L, ucl_obj_toint (obj));
217 #else
218 		lua_pushnumber (L, ucl_obj_toint (obj));
219 #endif
220 		break;
221 	case UCL_FLOAT:
222 	case UCL_TIME:
223 		lua_pushnumber (L, ucl_obj_todouble (obj));
224 		break;
225 	case UCL_NULL:
226 		lua_getfield (L, LUA_REGISTRYINDEX, "ucl.null");
227 		break;
228 	case UCL_USERDATA:
229 		fd = (struct ucl_lua_funcdata *)obj->value.ud;
230 		lua_rawgeti (L, LUA_REGISTRYINDEX, fd->idx);
231 		break;
232 	default:
233 		lua_pushnil (L);
234 		break;
235 	}
236 
237 	return 1;
238 }
239 
240 /***
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:
244  *
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
254  */
255 int
256 ucl_object_push_lua (lua_State *L, const ucl_object_t *obj, bool allow_array)
257 {
258 	switch (obj->type) {
259 	case UCL_OBJECT:
260 		return ucl_object_lua_push_object (L, obj, allow_array);
261 	case UCL_ARRAY:
262 		return ucl_object_lua_push_array (L, obj->value.av);
263 	default:
264 		return ucl_object_lua_push_scalar (L, obj, allow_array);
265 	}
266 }
267 
268 /**
269  * Parse lua table into object top
270  * @param L
271  * @param top
272  * @param idx
273  */
274 static ucl_object_t *
275 ucl_object_lua_fromtable (lua_State *L, int idx)
276 {
277 	ucl_object_t *obj, *top = NULL;
278 	size_t keylen;
279 	const char *k;
280 	bool is_array = true;
281 	int max = INT_MIN;
282 
283 	if (idx < 0) {
284 		/* For negative indicies we want to invert them */
285 		idx = lua_gettop (L) + idx + 1;
286 	}
287 	/* Check for array */
288 	lua_pushnil (L);
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) {
293 				if (num > max) {
294 					max = num;
295 				}
296 			}
297 			else {
298 				/* Keys are not integer */
299 				lua_pop (L, 2);
300 				is_array = false;
301 				break;
302 			}
303 		}
304 		else {
305 			/* Keys are not numeric */
306 			lua_pop (L, 2);
307 			is_array = false;
308 			break;
309 		}
310 		lua_pop (L, 1);
311 	}
312 
313 	/* Table iterate */
314 	if (is_array) {
315 		int i;
316 
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));
322 			if (obj != NULL) {
323 				ucl_array_append (top, obj);
324 			}
325 		}
326 	}
327 	else {
328 		lua_pushnil (L);
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));
334 
335 			if (obj != NULL) {
336 				ucl_object_insert_key (top, obj, k, keylen, true);
337 			}
338 			lua_pop (L, 1);
339 		}
340 	}
341 
342 	return top;
343 }
344 
345 /**
346  * Get a single element from lua to object obj
347  * @param L
348  * @param obj
349  * @param idx
350  */
351 static ucl_object_t *
352 ucl_object_lua_fromelt (lua_State *L, int idx)
353 {
354 	int type;
355 	double num;
356 	ucl_object_t *obj = NULL;
357 	struct ucl_lua_funcdata *fd;
358 
359 	type = lua_type (L, idx);
360 
361 	switch (type) {
362 	case LUA_TSTRING:
363 		obj = ucl_object_fromstring_common (lua_tostring (L, idx), 0, 0);
364 		break;
365 	case LUA_TNUMBER:
366 		num = lua_tonumber (L, idx);
367 		if (num == (int64_t)num) {
368 			obj = ucl_object_fromint (num);
369 		}
370 		else {
371 			obj = ucl_object_fromdouble (num);
372 		}
373 		break;
374 	case LUA_TBOOLEAN:
375 		obj = ucl_object_frombool (lua_toboolean (L, idx));
376 		break;
377 	case LUA_TUSERDATA:
378 		if (lua_topointer (L, idx) == ucl_null) {
379 			obj = ucl_object_typed_new (UCL_NULL);
380 		}
381 		break;
382 	case LUA_TTABLE:
383 	case LUA_TFUNCTION:
384 	case LUA_TTHREAD:
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 */
390 				lua_call(L, 2, 1);
391 				obj = ucl_object_lua_fromelt (L, 1);
392 			}
393 			lua_pop (L, 2);
394 		}
395 		else {
396 			if (type == LUA_TTABLE) {
397 				obj = ucl_object_lua_fromtable (L, idx);
398 			}
399 			else if (type == LUA_TFUNCTION) {
400 				fd = malloc (sizeof (*fd));
401 				if (fd != NULL) {
402 					lua_pushvalue (L, idx);
403 					fd->L = L;
404 					fd->ret = NULL;
405 					fd->idx = luaL_ref (L, LUA_REGISTRYINDEX);
406 
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;
411 				}
412 			}
413 		}
414 		break;
415 	}
416 
417 	return obj;
418 }
419 
420 /**
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.
428  */
429 ucl_object_t *
430 ucl_object_lua_import (lua_State *L, int idx)
431 {
432 	ucl_object_t *obj;
433 	int t;
434 
435 	t = lua_type (L, idx);
436 	switch (t) {
437 	case LUA_TTABLE:
438 		obj = ucl_object_lua_fromtable (L, idx);
439 		break;
440 	default:
441 		obj = ucl_object_lua_fromelt (L, idx);
442 		break;
443 	}
444 
445 	return obj;
446 }
447 
448 static int
449 lua_ucl_parser_init (lua_State *L)
450 {
451 	struct ucl_parser *parser, **pparser;
452 	int flags = 0;
453 
454 	if (lua_gettop (L) >= 1) {
455 		flags = lua_tonumber (L, 1);
456 	}
457 
458 	parser = ucl_parser_new (flags);
459 	if (parser == NULL) {
460 		lua_pushnil (L);
461 	}
462 
463 	pparser = lua_newuserdata (L, sizeof (parser));
464 	*pparser = parser;
465 	luaL_getmetatable (L, PARSER_META);
466 	lua_setmetatable (L, -2);
467 
468 	return 1;
469 }
470 
471 static struct ucl_parser *
472 lua_ucl_parser_get (lua_State *L, int index)
473 {
474 	return *((struct ucl_parser **) luaL_checkudata(L, index, PARSER_META));
475 }
476 
477 /***
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
482 @example
483 local parser = ucl.parser()
484 local res,err = parser:parse_file('/some/file.conf')
485 
486 if not res then
487 	print('parser error: ' .. err)
488 else
489 	-- Do something with object
490 end
491  */
492 static int
493 lua_ucl_parser_parse_file (lua_State *L)
494 {
495 	struct ucl_parser *parser;
496 	const char *file;
497 	int ret = 2;
498 
499 	parser = lua_ucl_parser_get (L, 1);
500 	file = luaL_checkstring (L, 2);
501 
502 	if (parser != NULL && file != NULL) {
503 		if (ucl_parser_add_file (parser, file)) {
504 			lua_pushboolean (L, true);
505 			ret = 1;
506 		}
507 		else {
508 			lua_pushboolean (L, false);
509 			lua_pushstring (L, ucl_parser_get_error (parser));
510 		}
511 	}
512 	else {
513 		lua_pushboolean (L, false);
514 		lua_pushstring (L, "invalid arguments");
515 	}
516 
517 	return ret;
518 }
519 
520 /***
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
525  */
526 static int
527 lua_ucl_parser_parse_string (lua_State *L)
528 {
529 	struct ucl_parser *parser;
530 	const char *string;
531 	size_t llen;
532 	int ret = 2;
533 
534 	parser = lua_ucl_parser_get (L, 1);
535 	string = luaL_checklstring (L, 2, &llen);
536 
537 	if (parser != NULL && string != NULL) {
538 		if (ucl_parser_add_chunk (parser, (const unsigned char *)string, llen)) {
539 			lua_pushboolean (L, true);
540 			ret = 1;
541 		}
542 		else {
543 			lua_pushboolean (L, false);
544 			lua_pushstring (L, ucl_parser_get_error (parser));
545 		}
546 	}
547 	else {
548 		lua_pushboolean (L, false);
549 		lua_pushstring (L, "invalid arguments");
550 	}
551 
552 	return ret;
553 }
554 
555 /***
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
559  */
560 static int
561 lua_ucl_parser_get_object (lua_State *L)
562 {
563 	struct ucl_parser *parser;
564 	ucl_object_t *obj;
565 	int ret = 1;
566 
567 	parser = lua_ucl_parser_get (L, 1);
568 	obj = ucl_parser_get_object (parser);
569 
570 	if (obj != NULL) {
571 		ret = ucl_object_push_lua (L, obj, false);
572 		/* no need to keep reference */
573 		ucl_object_unref (obj);
574 	}
575 	else {
576 		lua_pushnil (L);
577 	}
578 
579 	return ret;
580 }
581 
582 static int
583 lua_ucl_parser_gc (lua_State *L)
584 {
585 	struct ucl_parser *parser;
586 
587 	parser = lua_ucl_parser_get (L, 1);
588 	ucl_parser_free (parser);
589 
590 	return 0;
591 }
592 
593 static void
594 lua_ucl_parser_mt (lua_State *L)
595 {
596 	luaL_newmetatable (L, PARSER_META);
597 
598 	lua_pushvalue(L, -1);
599 	lua_setfield(L, -2, "__index");
600 
601 	lua_pushcfunction (L, lua_ucl_parser_gc);
602 	lua_setfield (L, -2, "__gc");
603 
604 	lua_pushcfunction (L, lua_ucl_parser_parse_file);
605 	lua_setfield (L, -2, "parse_file");
606 
607 	lua_pushcfunction (L, lua_ucl_parser_parse_string);
608 	lua_setfield (L, -2, "parse_string");
609 
610 	lua_pushcfunction (L, lua_ucl_parser_get_object);
611 	lua_setfield (L, -2, "get_object");
612 
613 	lua_pop (L, 1);
614 }
615 
616 static int
617 lua_ucl_to_string (lua_State *L, const ucl_object_t *obj, enum ucl_emitter type)
618 {
619 	unsigned char *result;
620 
621 	result = ucl_object_emit (obj, type);
622 
623 	if (result != NULL) {
624 		lua_pushstring (L, (const char *)result);
625 		free (result);
626 	}
627 	else {
628 		lua_pushnil (L);
629 	}
630 
631 	return 1;
632 }
633 
634 static int
635 lua_ucl_to_json (lua_State *L)
636 {
637 	ucl_object_t *obj;
638 	int format = UCL_EMIT_JSON;
639 
640 	if (lua_gettop (L) > 1) {
641 		if (lua_toboolean (L, 2)) {
642 			format = UCL_EMIT_JSON_COMPACT;
643 		}
644 	}
645 
646 	obj = ucl_object_lua_import (L, 1);
647 	if (obj != NULL) {
648 		lua_ucl_to_string (L, obj, format);
649 		ucl_object_unref (obj);
650 	}
651 	else {
652 		lua_pushnil (L);
653 	}
654 
655 	return 1;
656 }
657 
658 static int
659 lua_ucl_to_config (lua_State *L)
660 {
661 	ucl_object_t *obj;
662 
663 	obj = ucl_object_lua_import (L, 1);
664 	if (obj != NULL) {
665 		lua_ucl_to_string (L, obj, UCL_EMIT_CONFIG);
666 		ucl_object_unref (obj);
667 	}
668 	else {
669 		lua_pushnil (L);
670 	}
671 
672 	return 1;
673 }
674 
675 /***
676  * @function ucl.to_format(var, format)
677  * Converts lua variable `var` to the specified `format`. Formats supported are:
678  *
679  * - `json` - fine printed json
680  * - `json-compact` - compacted json
681  * - `config` - fine printed configuration
682  * - `ucl` - same as `config`
683  * - `yaml` - embedded yaml
684  *
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`.
690  * @example
691 local table = {
692   str = 'value',
693   num = 100500,
694   null = ucl.null,
695   func = function ()
696     return 'huh'
697   end
698 }
699 
700 print(ucl.to_format(table, 'ucl'))
701 -- Output:
702 --[[
703 num = 100500;
704 str = "value";
705 null = null;
706 func = "huh";
707 --]]
708  */
709 static int
710 lua_ucl_to_format (lua_State *L)
711 {
712 	ucl_object_t *obj;
713 	int format = UCL_EMIT_JSON;
714 
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) {
719 				lua_pushnil (L);
720 				return 1;
721 			}
722 		}
723 		else if (lua_type (L, 2) == LUA_TSTRING) {
724 			const char *strtype = lua_tostring (L, 2);
725 
726 			if (strcasecmp (strtype, "json") == 0) {
727 				format = UCL_EMIT_JSON;
728 			}
729 			else if (strcasecmp (strtype, "json-compact") == 0) {
730 				format = UCL_EMIT_JSON_COMPACT;
731 			}
732 			else if (strcasecmp (strtype, "yaml") == 0) {
733 				format = UCL_EMIT_YAML;
734 			}
735 			else if (strcasecmp (strtype, "config") == 0 ||
736 				strcasecmp (strtype, "ucl") == 0) {
737 				format = UCL_EMIT_CONFIG;
738 			}
739 		}
740 	}
741 
742 	obj = ucl_object_lua_import (L, 1);
743 	if (obj != NULL) {
744 		lua_ucl_to_string (L, obj, format);
745 		ucl_object_unref (obj);
746 	}
747 	else {
748 		lua_pushnil (L);
749 	}
750 
751 	return 1;
752 }
753 
754 static int
755 lua_ucl_null_tostring (lua_State* L)
756 {
757 	lua_pushstring (L, "null");
758 	return 1;
759 }
760 
761 static void
762 lua_ucl_null_mt (lua_State *L)
763 {
764 	luaL_newmetatable (L, NULL_META);
765 
766 	lua_pushcfunction (L, lua_ucl_null_tostring);
767 	lua_setfield (L, -2, "__tostring");
768 
769 	lua_pop (L, 1);
770 }
771 
772 int
773 luaopen_ucl (lua_State *L)
774 {
775 	lua_ucl_parser_mt (L);
776 	lua_ucl_null_mt (L);
777 
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");
785 
786 	lua_newtable (L);
787 
788 	lua_pushcfunction (L, lua_ucl_parser_init);
789 	lua_setfield (L, -2, "parser");
790 
791 	lua_pushcfunction (L, lua_ucl_to_json);
792 	lua_setfield (L, -2, "to_json");
793 
794 	lua_pushcfunction (L, lua_ucl_to_config);
795 	lua_setfield (L, -2, "to_config");
796 
797 	lua_pushcfunction (L, lua_ucl_to_format);
798 	lua_setfield (L, -2, "to_format");
799 
800 	ucl_null = lua_newuserdata (L, 0);
801 	luaL_getmetatable (L, NULL_META);
802 	lua_setmetatable (L, -2);
803 
804 	lua_pushvalue (L, -1);
805 	lua_setfield (L, LUA_REGISTRYINDEX, "ucl.null");
806 
807 	lua_setfield (L, -2, "null");
808 
809 	return 1;
810 }
811 
812 struct ucl_lua_funcdata*
813 ucl_object_toclosure (const ucl_object_t *obj)
814 {
815 	if (obj == NULL || obj->type != UCL_USERDATA) {
816 		return NULL;
817 	}
818 
819 	return (struct ucl_lua_funcdata*)obj->value.ud;
820 }
821