You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

lua_ucl.c 26KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215
  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. * @file lua ucl bindings
  25. */
  26. #include "ucl.h"
  27. #include "ucl_internal.h"
  28. #include "lua_ucl.h"
  29. #include <strings.h>
  30. #include <zconf.h>
  31. /***
  32. * @module ucl
  33. * This lua module allows to parse objects from strings and to store data into
  34. * ucl objects. It uses `libucl` C library to parse and manipulate with ucl objects.
  35. * @example
  36. local ucl = require("ucl")
  37. local parser = ucl.parser()
  38. local res,err = parser:parse_string('{key=value}')
  39. if not res then
  40. print('parser error: ' .. err)
  41. else
  42. local obj = parser:get_object()
  43. local got = ucl.to_format(obj, 'json')
  44. endif
  45. local table = {
  46. str = 'value',
  47. num = 100500,
  48. null = ucl.null,
  49. func = function ()
  50. return 'huh'
  51. end
  52. }
  53. print(ucl.to_format(table, 'ucl'))
  54. -- Output:
  55. --[[
  56. num = 100500;
  57. str = "value";
  58. null = null;
  59. func = "huh";
  60. --]]
  61. */
  62. #define PARSER_META "ucl.parser.meta"
  63. #define EMITTER_META "ucl.emitter.meta"
  64. #define NULL_META "null.emitter.meta"
  65. #define OBJECT_META "ucl.object.meta"
  66. static int ucl_object_lua_push_array (lua_State *L, const ucl_object_t *obj);
  67. static int ucl_object_lua_push_scalar (lua_State *L, const ucl_object_t *obj, bool allow_array);
  68. static ucl_object_t* ucl_object_lua_fromtable (lua_State *L, int idx);
  69. static ucl_object_t* ucl_object_lua_fromelt (lua_State *L, int idx);
  70. static void *ucl_null;
  71. /**
  72. * Push a single element of an object to lua
  73. * @param L
  74. * @param key
  75. * @param obj
  76. */
  77. static void
  78. ucl_object_lua_push_element (lua_State *L, const char *key,
  79. const ucl_object_t *obj)
  80. {
  81. lua_pushstring (L, key);
  82. ucl_object_push_lua (L, obj, true);
  83. lua_settable (L, -3);
  84. }
  85. static void
  86. lua_ucl_userdata_dtor (void *ud)
  87. {
  88. struct ucl_lua_funcdata *fd = (struct ucl_lua_funcdata *)ud;
  89. luaL_unref (fd->L, LUA_REGISTRYINDEX, fd->idx);
  90. if (fd->ret != NULL) {
  91. free (fd->ret);
  92. }
  93. free (fd);
  94. }
  95. static const char *
  96. lua_ucl_userdata_emitter (void *ud)
  97. {
  98. struct ucl_lua_funcdata *fd = (struct ucl_lua_funcdata *)ud;
  99. const char *out = "";
  100. lua_rawgeti (fd->L, LUA_REGISTRYINDEX, fd->idx);
  101. lua_pcall (fd->L, 0, 1, 0);
  102. out = lua_tostring (fd->L, -1);
  103. if (out != NULL) {
  104. /* We need to store temporary string in a more appropriate place */
  105. if (fd->ret) {
  106. free (fd->ret);
  107. }
  108. fd->ret = strdup (out);
  109. }
  110. lua_settop (fd->L, 0);
  111. return fd->ret;
  112. }
  113. /**
  114. * Push a single object to lua
  115. * @param L
  116. * @param obj
  117. * @return
  118. */
  119. static int
  120. ucl_object_lua_push_object (lua_State *L, const ucl_object_t *obj,
  121. bool allow_array)
  122. {
  123. const ucl_object_t *cur;
  124. ucl_object_iter_t it = NULL;
  125. int nelt = 0;
  126. if (allow_array && obj->next != NULL) {
  127. /* Actually we need to push this as an array */
  128. return ucl_object_lua_push_array (L, obj);
  129. }
  130. /* Optimize allocation by preallocation of table */
  131. while (ucl_object_iterate (obj, &it, true) != NULL) {
  132. nelt ++;
  133. }
  134. lua_createtable (L, 0, nelt);
  135. it = NULL;
  136. while ((cur = ucl_object_iterate (obj, &it, true)) != NULL) {
  137. ucl_object_lua_push_element (L, ucl_object_key (cur), cur);
  138. }
  139. return 1;
  140. }
  141. /**
  142. * Push an array to lua as table indexed by integers
  143. * @param L
  144. * @param obj
  145. * @return
  146. */
  147. static int
  148. ucl_object_lua_push_array (lua_State *L, const ucl_object_t *obj)
  149. {
  150. const ucl_object_t *cur;
  151. ucl_object_iter_t it;
  152. int i = 1, nelt = 0;
  153. if (obj->type == UCL_ARRAY) {
  154. nelt = obj->len;
  155. it = ucl_object_iterate_new (obj);
  156. lua_createtable (L, nelt, 0);
  157. while ((cur = ucl_object_iterate_safe (it, true))) {
  158. ucl_object_push_lua (L, cur, false);
  159. lua_rawseti (L, -2, i);
  160. i ++;
  161. }
  162. ucl_object_iterate_free (it);
  163. }
  164. else {
  165. /* Optimize allocation by preallocation of table */
  166. LL_FOREACH (obj, cur) {
  167. nelt ++;
  168. }
  169. lua_createtable (L, nelt, 0);
  170. LL_FOREACH (obj, cur) {
  171. ucl_object_push_lua (L, cur, false);
  172. lua_rawseti (L, -2, i);
  173. i ++;
  174. }
  175. }
  176. return 1;
  177. }
  178. /**
  179. * Push a simple object to lua depending on its actual type
  180. */
  181. static int
  182. ucl_object_lua_push_scalar (lua_State *L, const ucl_object_t *obj,
  183. bool allow_array)
  184. {
  185. struct ucl_lua_funcdata *fd;
  186. if (allow_array && obj->next != NULL) {
  187. /* Actually we need to push this as an array */
  188. return ucl_object_lua_push_array (L, obj);
  189. }
  190. switch (obj->type) {
  191. case UCL_BOOLEAN:
  192. lua_pushboolean (L, ucl_obj_toboolean (obj));
  193. break;
  194. case UCL_STRING:
  195. lua_pushstring (L, ucl_obj_tostring (obj));
  196. break;
  197. case UCL_INT:
  198. #if LUA_VERSION_NUM >= 501
  199. lua_pushinteger (L, ucl_obj_toint (obj));
  200. #else
  201. lua_pushnumber (L, ucl_obj_toint (obj));
  202. #endif
  203. break;
  204. case UCL_FLOAT:
  205. case UCL_TIME:
  206. lua_pushnumber (L, ucl_obj_todouble (obj));
  207. break;
  208. case UCL_NULL:
  209. lua_getfield (L, LUA_REGISTRYINDEX, "ucl.null");
  210. break;
  211. case UCL_USERDATA:
  212. fd = (struct ucl_lua_funcdata *)obj->value.ud;
  213. lua_rawgeti (L, LUA_REGISTRYINDEX, fd->idx);
  214. break;
  215. default:
  216. lua_pushnil (L);
  217. break;
  218. }
  219. return 1;
  220. }
  221. /***
  222. * @function ucl_object_push_lua(L, obj, allow_array)
  223. * This is a `C` function to push `UCL` object as lua variable. This function
  224. * converts `obj` to lua representation using the following conversions:
  225. *
  226. * - *scalar* values are directly presented by lua objects
  227. * - *userdata* values are converted to lua function objects using `LUA_REGISTRYINDEX`,
  228. * this can be used to pass functions from lua to c and vice-versa
  229. * - *arrays* are converted to lua tables with numeric indicies suitable for `ipairs` iterations
  230. * - *objects* are converted to lua tables with string indicies
  231. * @param {lua_State} L lua state pointer
  232. * @param {ucl_object_t} obj object to push
  233. * @param {bool} allow_array expand implicit arrays (should be true for all but partial arrays)
  234. * @return {int} `1` if an object is pushed to lua
  235. */
  236. int
  237. ucl_object_push_lua (lua_State *L, const ucl_object_t *obj, bool allow_array)
  238. {
  239. switch (obj->type) {
  240. case UCL_OBJECT:
  241. return ucl_object_lua_push_object (L, obj, allow_array);
  242. case UCL_ARRAY:
  243. return ucl_object_lua_push_array (L, obj);
  244. default:
  245. return ucl_object_lua_push_scalar (L, obj, allow_array);
  246. }
  247. }
  248. /**
  249. * Parse lua table into object top
  250. * @param L
  251. * @param top
  252. * @param idx
  253. */
  254. static ucl_object_t *
  255. ucl_object_lua_fromtable (lua_State *L, int idx)
  256. {
  257. ucl_object_t *obj, *top = NULL;
  258. size_t keylen;
  259. const char *k;
  260. bool is_array = true;
  261. int max = INT_MIN;
  262. if (idx < 0) {
  263. /* For negative indicies we want to invert them */
  264. idx = lua_gettop (L) + idx + 1;
  265. }
  266. /* Check for array */
  267. lua_pushnil (L);
  268. while (lua_next (L, idx) != 0) {
  269. if (lua_type (L, -2) == LUA_TNUMBER) {
  270. double num = lua_tonumber (L, -2);
  271. if (num == (int)num) {
  272. if (num > max) {
  273. max = num;
  274. }
  275. }
  276. else {
  277. /* Keys are not integer */
  278. lua_pop (L, 2);
  279. is_array = false;
  280. break;
  281. }
  282. }
  283. else {
  284. /* Keys are not numeric */
  285. lua_pop (L, 2);
  286. is_array = false;
  287. break;
  288. }
  289. lua_pop (L, 1);
  290. }
  291. /* Table iterate */
  292. if (is_array) {
  293. int i;
  294. top = ucl_object_typed_new (UCL_ARRAY);
  295. for (i = 1; i <= max; i ++) {
  296. lua_pushinteger (L, i);
  297. lua_gettable (L, idx);
  298. obj = ucl_object_lua_fromelt (L, lua_gettop (L));
  299. if (obj != NULL) {
  300. ucl_array_append (top, obj);
  301. }
  302. lua_pop (L, 1);
  303. }
  304. }
  305. else {
  306. lua_pushnil (L);
  307. top = ucl_object_typed_new (UCL_OBJECT);
  308. while (lua_next (L, idx) != 0) {
  309. /* copy key to avoid modifications */
  310. k = lua_tolstring (L, -2, &keylen);
  311. obj = ucl_object_lua_fromelt (L, lua_gettop (L));
  312. if (obj != NULL) {
  313. ucl_object_insert_key (top, obj, k, keylen, true);
  314. }
  315. lua_pop (L, 1);
  316. }
  317. }
  318. return top;
  319. }
  320. /**
  321. * Get a single element from lua to object obj
  322. * @param L
  323. * @param obj
  324. * @param idx
  325. */
  326. static ucl_object_t *
  327. ucl_object_lua_fromelt (lua_State *L, int idx)
  328. {
  329. int type;
  330. double num;
  331. ucl_object_t *obj = NULL;
  332. struct ucl_lua_funcdata *fd;
  333. type = lua_type (L, idx);
  334. switch (type) {
  335. case LUA_TSTRING:
  336. obj = ucl_object_fromstring_common (lua_tostring (L, idx), 0, 0);
  337. break;
  338. case LUA_TNUMBER:
  339. num = lua_tonumber (L, idx);
  340. if (num == (int64_t)num) {
  341. obj = ucl_object_fromint (num);
  342. }
  343. else {
  344. obj = ucl_object_fromdouble (num);
  345. }
  346. break;
  347. case LUA_TBOOLEAN:
  348. obj = ucl_object_frombool (lua_toboolean (L, idx));
  349. break;
  350. case LUA_TUSERDATA:
  351. if (lua_topointer (L, idx) == ucl_null) {
  352. obj = ucl_object_typed_new (UCL_NULL);
  353. }
  354. break;
  355. case LUA_TTABLE:
  356. case LUA_TFUNCTION:
  357. case LUA_TTHREAD:
  358. if (luaL_getmetafield (L, idx, "__gen_ucl")) {
  359. if (lua_isfunction (L, -1)) {
  360. lua_settop (L, 3); /* gen, obj, func */
  361. lua_insert (L, 1); /* func, gen, obj */
  362. lua_insert (L, 2); /* func, obj, gen */
  363. lua_call(L, 2, 1);
  364. obj = ucl_object_lua_fromelt (L, 1);
  365. }
  366. lua_pop (L, 2);
  367. }
  368. else {
  369. if (type == LUA_TTABLE) {
  370. obj = ucl_object_lua_fromtable (L, idx);
  371. }
  372. else if (type == LUA_TFUNCTION) {
  373. fd = malloc (sizeof (*fd));
  374. if (fd != NULL) {
  375. lua_pushvalue (L, idx);
  376. fd->L = L;
  377. fd->ret = NULL;
  378. fd->idx = luaL_ref (L, LUA_REGISTRYINDEX);
  379. obj = ucl_object_new_userdata (lua_ucl_userdata_dtor,
  380. lua_ucl_userdata_emitter, (void *)fd);
  381. }
  382. }
  383. }
  384. break;
  385. }
  386. return obj;
  387. }
  388. /**
  389. * @function ucl_object_lua_import(L, idx)
  390. * Extracts ucl object from lua variable at `idx` position,
  391. * @see ucl_object_push_lua for conversion definitions
  392. * @param {lua_state} L lua state machine pointer
  393. * @param {int} idx index where the source variable is placed
  394. * @return {ucl_object_t} new ucl object extracted from lua variable. Reference count of this object is 1,
  395. * this object thus needs to be unref'ed after usage.
  396. */
  397. ucl_object_t *
  398. ucl_object_lua_import (lua_State *L, int idx)
  399. {
  400. ucl_object_t *obj;
  401. int t;
  402. t = lua_type (L, idx);
  403. switch (t) {
  404. case LUA_TTABLE:
  405. obj = ucl_object_lua_fromtable (L, idx);
  406. break;
  407. default:
  408. obj = ucl_object_lua_fromelt (L, idx);
  409. break;
  410. }
  411. return obj;
  412. }
  413. static int
  414. lua_ucl_to_string (lua_State *L, const ucl_object_t *obj, enum ucl_emitter type)
  415. {
  416. unsigned char *result;
  417. result = ucl_object_emit (obj, type);
  418. if (result != NULL) {
  419. lua_pushstring (L, (const char *)result);
  420. free (result);
  421. }
  422. else {
  423. lua_pushnil (L);
  424. }
  425. return 1;
  426. }
  427. static int
  428. lua_ucl_parser_init (lua_State *L)
  429. {
  430. struct ucl_parser *parser, **pparser;
  431. int flags = 0;
  432. if (lua_gettop (L) >= 1) {
  433. flags = lua_tonumber (L, 1);
  434. }
  435. parser = ucl_parser_new (flags);
  436. if (parser == NULL) {
  437. lua_pushnil (L);
  438. }
  439. pparser = lua_newuserdata (L, sizeof (parser));
  440. *pparser = parser;
  441. luaL_getmetatable (L, PARSER_META);
  442. lua_setmetatable (L, -2);
  443. return 1;
  444. }
  445. static struct ucl_parser *
  446. lua_ucl_parser_get (lua_State *L, int index)
  447. {
  448. return *((struct ucl_parser **) luaL_checkudata(L, index, PARSER_META));
  449. }
  450. static ucl_object_t *
  451. lua_ucl_object_get (lua_State *L, int index)
  452. {
  453. return *((ucl_object_t **) luaL_checkudata(L, index, OBJECT_META));
  454. }
  455. static void
  456. lua_ucl_push_opaque (lua_State *L, ucl_object_t *obj)
  457. {
  458. ucl_object_t **pobj;
  459. pobj = lua_newuserdata (L, sizeof (*pobj));
  460. *pobj = obj;
  461. luaL_getmetatable (L, OBJECT_META);
  462. lua_setmetatable (L, -2);
  463. }
  464. static inline enum ucl_parse_type
  465. lua_ucl_str_to_parse_type (const char *str)
  466. {
  467. enum ucl_parse_type type = UCL_PARSE_UCL;
  468. if (str != NULL) {
  469. if (strcasecmp (str, "msgpack") == 0) {
  470. type = UCL_PARSE_MSGPACK;
  471. }
  472. else if (strcasecmp (str, "sexp") == 0 ||
  473. strcasecmp (str, "csexp") == 0) {
  474. type = UCL_PARSE_CSEXP;
  475. }
  476. else if (strcasecmp (str, "auto") == 0) {
  477. type = UCL_PARSE_AUTO;
  478. }
  479. }
  480. return type;
  481. }
  482. /***
  483. * @method parser:parse_file(name)
  484. * Parse UCL object from file.
  485. * @param {string} name filename to parse
  486. * @return {bool[, string]} if res is `true` then file has been parsed successfully, otherwise an error string is also returned
  487. @example
  488. local parser = ucl.parser()
  489. local res,err = parser:parse_file('/some/file.conf')
  490. if not res then
  491. print('parser error: ' .. err)
  492. else
  493. -- Do something with object
  494. end
  495. */
  496. static int
  497. lua_ucl_parser_parse_file (lua_State *L)
  498. {
  499. struct ucl_parser *parser;
  500. const char *file;
  501. int ret = 2;
  502. parser = lua_ucl_parser_get (L, 1);
  503. file = luaL_checkstring (L, 2);
  504. if (parser != NULL && file != NULL) {
  505. if (ucl_parser_add_file (parser, file)) {
  506. lua_pushboolean (L, true);
  507. ret = 1;
  508. }
  509. else {
  510. lua_pushboolean (L, false);
  511. lua_pushstring (L, ucl_parser_get_error (parser));
  512. }
  513. }
  514. else {
  515. lua_pushboolean (L, false);
  516. lua_pushstring (L, "invalid arguments");
  517. }
  518. return ret;
  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. enum ucl_parse_type type = UCL_PARSE_UCL;
  533. int ret = 2;
  534. parser = lua_ucl_parser_get (L, 1);
  535. string = luaL_checklstring (L, 2, &llen);
  536. if (lua_type (L, 3) == LUA_TSTRING) {
  537. type = lua_ucl_str_to_parse_type (lua_tostring (L, 3));
  538. }
  539. if (parser != NULL && string != NULL) {
  540. if (ucl_parser_add_chunk_full (parser, (const unsigned char *)string,
  541. llen, 0, UCL_DUPLICATE_APPEND, type)) {
  542. lua_pushboolean (L, true);
  543. ret = 1;
  544. }
  545. else {
  546. lua_pushboolean (L, false);
  547. lua_pushstring (L, ucl_parser_get_error (parser));
  548. }
  549. }
  550. else {
  551. lua_pushboolean (L, false);
  552. lua_pushstring (L, "invalid arguments");
  553. }
  554. return ret;
  555. }
  556. /***
  557. * @method parser:get_object()
  558. * Get top object from parser and export it to lua representation.
  559. * @return {variant or nil} ucl object as lua native variable
  560. */
  561. static int
  562. lua_ucl_parser_get_object (lua_State *L)
  563. {
  564. struct ucl_parser *parser;
  565. ucl_object_t *obj;
  566. int ret = 1;
  567. parser = lua_ucl_parser_get (L, 1);
  568. obj = ucl_parser_get_object (parser);
  569. if (obj != NULL) {
  570. ret = ucl_object_push_lua (L, obj, false);
  571. /* no need to keep reference */
  572. ucl_object_unref (obj);
  573. }
  574. else {
  575. lua_pushnil (L);
  576. }
  577. return ret;
  578. }
  579. /***
  580. * @method parser:get_object_wrapped()
  581. * Get top object from parser and export it to userdata object without
  582. * unwrapping to lua.
  583. * @return {ucl.object or nil} ucl object wrapped variable
  584. */
  585. static int
  586. lua_ucl_parser_get_object_wrapped (lua_State *L)
  587. {
  588. struct ucl_parser *parser;
  589. ucl_object_t *obj;
  590. int ret = 1;
  591. parser = lua_ucl_parser_get (L, 1);
  592. obj = ucl_parser_get_object (parser);
  593. if (obj != NULL) {
  594. lua_ucl_push_opaque (L, obj);
  595. }
  596. else {
  597. lua_pushnil (L);
  598. }
  599. return ret;
  600. }
  601. /***
  602. * @method parser:validate(schema)
  603. * Validates the top object in the parser against schema. Schema might be
  604. * another object or a string that represents file to load schema from.
  605. *
  606. * @param {string/table} schema input schema
  607. * @return {result,err} two values: boolean result and the corresponding error
  608. *
  609. */
  610. static int
  611. lua_ucl_parser_validate (lua_State *L)
  612. {
  613. struct ucl_parser *parser, *schema_parser;
  614. ucl_object_t *schema;
  615. const char *schema_file;
  616. struct ucl_schema_error err;
  617. parser = lua_ucl_parser_get (L, 1);
  618. if (parser && parser->top_obj) {
  619. if (lua_type (L, 2) == LUA_TTABLE) {
  620. schema = ucl_object_lua_import (L, 2);
  621. if (schema == NULL) {
  622. lua_pushboolean (L, false);
  623. lua_pushstring (L, "cannot load schema from lua table");
  624. return 2;
  625. }
  626. }
  627. else if (lua_type (L, 2) == LUA_TSTRING) {
  628. schema_parser = ucl_parser_new (0);
  629. schema_file = luaL_checkstring (L, 2);
  630. if (!ucl_parser_add_file (schema_parser, schema_file)) {
  631. lua_pushboolean (L, false);
  632. lua_pushfstring (L, "cannot parse schema file \"%s\": "
  633. "%s", schema_file, ucl_parser_get_error (parser));
  634. ucl_parser_free (schema_parser);
  635. return 2;
  636. }
  637. schema = ucl_parser_get_object (schema_parser);
  638. ucl_parser_free (schema_parser);
  639. }
  640. else {
  641. lua_pushboolean (L, false);
  642. lua_pushstring (L, "invalid schema argument");
  643. return 2;
  644. }
  645. if (!ucl_object_validate (schema, parser->top_obj, &err)) {
  646. lua_pushboolean (L, false);
  647. lua_pushfstring (L, "validation error: "
  648. "%s", err.msg);
  649. }
  650. else {
  651. lua_pushboolean (L, true);
  652. lua_pushnil (L);
  653. }
  654. ucl_object_unref (schema);
  655. }
  656. else {
  657. lua_pushboolean (L, false);
  658. lua_pushstring (L, "invalid parser or empty top object");
  659. }
  660. return 2;
  661. }
  662. static int
  663. lua_ucl_parser_gc (lua_State *L)
  664. {
  665. struct ucl_parser *parser;
  666. parser = lua_ucl_parser_get (L, 1);
  667. ucl_parser_free (parser);
  668. return 0;
  669. }
  670. /***
  671. * @method object:unwrap()
  672. * Unwraps opaque ucl object to the native lua object (performing copying)
  673. * @return {variant} any lua object
  674. */
  675. static int
  676. lua_ucl_object_unwrap (lua_State *L)
  677. {
  678. ucl_object_t *obj;
  679. obj = lua_ucl_object_get (L, 1);
  680. if (obj) {
  681. ucl_object_push_lua (L, obj, true);
  682. }
  683. else {
  684. lua_pushnil (L);
  685. }
  686. return 1;
  687. }
  688. static inline enum ucl_emitter
  689. lua_ucl_str_to_emit_type (const char *strtype)
  690. {
  691. enum ucl_emitter format = UCL_EMIT_JSON_COMPACT;
  692. if (strcasecmp (strtype, "json") == 0) {
  693. format = UCL_EMIT_JSON;
  694. }
  695. else if (strcasecmp (strtype, "json-compact") == 0) {
  696. format = UCL_EMIT_JSON_COMPACT;
  697. }
  698. else if (strcasecmp (strtype, "yaml") == 0) {
  699. format = UCL_EMIT_YAML;
  700. }
  701. else if (strcasecmp (strtype, "config") == 0 ||
  702. strcasecmp (strtype, "ucl") == 0) {
  703. format = UCL_EMIT_CONFIG;
  704. }
  705. return format;
  706. }
  707. /***
  708. * @method object:tostring(type)
  709. * Unwraps opaque ucl object to string (json by default). Optionally you can
  710. * specify output format:
  711. *
  712. * - `json` - fine printed json
  713. * - `json-compact` - compacted json
  714. * - `config` - fine printed configuration
  715. * - `ucl` - same as `config`
  716. * - `yaml` - embedded yaml
  717. * @param {string} type optional
  718. * @return {string} string representation of the opaque ucl object
  719. */
  720. static int
  721. lua_ucl_object_tostring (lua_State *L)
  722. {
  723. ucl_object_t *obj;
  724. enum ucl_emitter format = UCL_EMIT_JSON_COMPACT;
  725. obj = lua_ucl_object_get (L, 1);
  726. if (obj) {
  727. if (lua_gettop (L) > 1) {
  728. if (lua_type (L, 2) == LUA_TSTRING) {
  729. const char *strtype = lua_tostring (L, 2);
  730. format = lua_ucl_str_to_emit_type (strtype);
  731. }
  732. }
  733. return lua_ucl_to_string (L, obj, format);
  734. }
  735. else {
  736. lua_pushnil (L);
  737. }
  738. return 1;
  739. }
  740. /***
  741. * @method object:validate(schema[, path[, ext_refs]])
  742. * Validates the given ucl object using schema object represented as another
  743. * opaque ucl object. You can also specify path in the form `#/path/def` to
  744. * specify the specific schema element to perform validation.
  745. *
  746. * @param {ucl.object} schema schema object
  747. * @param {string} path optional path for validation procedure
  748. * @return {result,err} two values: boolean result and the corresponding
  749. * error, if `ext_refs` are also specified, then they are returned as opaque
  750. * ucl object as {result,err,ext_refs}
  751. */
  752. static int
  753. lua_ucl_object_validate (lua_State *L)
  754. {
  755. ucl_object_t *obj, *schema, *ext_refs = NULL;
  756. const ucl_object_t *schema_elt;
  757. bool res = false;
  758. struct ucl_schema_error err;
  759. const char *path = NULL;
  760. obj = lua_ucl_object_get (L, 1);
  761. schema = lua_ucl_object_get (L, 2);
  762. if (schema && obj && ucl_object_type (schema) == UCL_OBJECT) {
  763. if (lua_gettop (L) > 2) {
  764. if (lua_type (L, 3) == LUA_TSTRING) {
  765. path = lua_tostring (L, 3);
  766. if (path[0] == '#') {
  767. path++;
  768. }
  769. }
  770. else if (lua_type (L, 3) == LUA_TUSERDATA || lua_type (L, 3) ==
  771. LUA_TTABLE) {
  772. /* External refs */
  773. ext_refs = lua_ucl_object_get (L, 3);
  774. }
  775. if (lua_gettop (L) > 3) {
  776. if (lua_type (L, 4) == LUA_TUSERDATA || lua_type (L, 4) ==
  777. LUA_TTABLE) {
  778. /* External refs */
  779. ext_refs = lua_ucl_object_get (L, 4);
  780. }
  781. }
  782. }
  783. if (path) {
  784. schema_elt = ucl_object_lookup_path_char (schema, path, '/');
  785. }
  786. else {
  787. /* Use the top object */
  788. schema_elt = schema;
  789. }
  790. if (schema_elt) {
  791. res = ucl_object_validate_root_ext (schema_elt, obj, schema,
  792. ext_refs, &err);
  793. if (res) {
  794. lua_pushboolean (L, res);
  795. lua_pushnil (L);
  796. if (ext_refs) {
  797. lua_ucl_push_opaque (L, ext_refs);
  798. }
  799. }
  800. else {
  801. lua_pushboolean (L, res);
  802. lua_pushfstring (L, "validation error: %s", err.msg);
  803. if (ext_refs) {
  804. lua_ucl_push_opaque (L, ext_refs);
  805. }
  806. }
  807. }
  808. else {
  809. lua_pushboolean (L, res);
  810. lua_pushfstring (L, "cannot find the requested path: %s", path);
  811. if (ext_refs) {
  812. lua_ucl_push_opaque (L, ext_refs);
  813. }
  814. }
  815. }
  816. else {
  817. lua_pushboolean (L, res);
  818. lua_pushstring (L, "invalid object or schema");
  819. }
  820. if (ext_refs) {
  821. return 3;
  822. }
  823. return 2;
  824. }
  825. static int
  826. lua_ucl_object_gc (lua_State *L)
  827. {
  828. ucl_object_t *obj;
  829. obj = lua_ucl_object_get (L, 1);
  830. ucl_object_unref (obj);
  831. return 0;
  832. }
  833. static void
  834. lua_ucl_parser_mt (lua_State *L)
  835. {
  836. luaL_newmetatable (L, PARSER_META);
  837. lua_pushvalue(L, -1);
  838. lua_setfield(L, -2, "__index");
  839. lua_pushcfunction (L, lua_ucl_parser_gc);
  840. lua_setfield (L, -2, "__gc");
  841. lua_pushcfunction (L, lua_ucl_parser_parse_file);
  842. lua_setfield (L, -2, "parse_file");
  843. lua_pushcfunction (L, lua_ucl_parser_parse_string);
  844. lua_setfield (L, -2, "parse_string");
  845. lua_pushcfunction (L, lua_ucl_parser_get_object);
  846. lua_setfield (L, -2, "get_object");
  847. lua_pushcfunction (L, lua_ucl_parser_get_object_wrapped);
  848. lua_setfield (L, -2, "get_object_wrapped");
  849. lua_pushcfunction (L, lua_ucl_parser_validate);
  850. lua_setfield (L, -2, "validate");
  851. lua_pop (L, 1);
  852. }
  853. static void
  854. lua_ucl_object_mt (lua_State *L)
  855. {
  856. luaL_newmetatable (L, OBJECT_META);
  857. lua_pushvalue(L, -1);
  858. lua_setfield(L, -2, "__index");
  859. lua_pushcfunction (L, lua_ucl_object_gc);
  860. lua_setfield (L, -2, "__gc");
  861. lua_pushcfunction (L, lua_ucl_object_tostring);
  862. lua_setfield (L, -2, "__tostring");
  863. lua_pushcfunction (L, lua_ucl_object_tostring);
  864. lua_setfield (L, -2, "tostring");
  865. lua_pushcfunction (L, lua_ucl_object_unwrap);
  866. lua_setfield (L, -2, "unwrap");
  867. lua_pushcfunction (L, lua_ucl_object_unwrap);
  868. lua_setfield (L, -2, "tolua");
  869. lua_pushcfunction (L, lua_ucl_object_validate);
  870. lua_setfield (L, -2, "validate");
  871. lua_pushstring (L, OBJECT_META);
  872. lua_setfield (L, -2, "class");
  873. lua_pop (L, 1);
  874. }
  875. static int
  876. lua_ucl_to_json (lua_State *L)
  877. {
  878. ucl_object_t *obj;
  879. int format = UCL_EMIT_JSON;
  880. if (lua_gettop (L) > 1) {
  881. if (lua_toboolean (L, 2)) {
  882. format = UCL_EMIT_JSON_COMPACT;
  883. }
  884. }
  885. obj = ucl_object_lua_import (L, 1);
  886. if (obj != NULL) {
  887. lua_ucl_to_string (L, obj, format);
  888. ucl_object_unref (obj);
  889. }
  890. else {
  891. lua_pushnil (L);
  892. }
  893. return 1;
  894. }
  895. static int
  896. lua_ucl_to_config (lua_State *L)
  897. {
  898. ucl_object_t *obj;
  899. obj = ucl_object_lua_import (L, 1);
  900. if (obj != NULL) {
  901. lua_ucl_to_string (L, obj, UCL_EMIT_CONFIG);
  902. ucl_object_unref (obj);
  903. }
  904. else {
  905. lua_pushnil (L);
  906. }
  907. return 1;
  908. }
  909. /***
  910. * @function ucl.to_format(var, format)
  911. * Converts lua variable `var` to the specified `format`. Formats supported are:
  912. *
  913. * - `json` - fine printed json
  914. * - `json-compact` - compacted json
  915. * - `config` - fine printed configuration
  916. * - `ucl` - same as `config`
  917. * - `yaml` - embedded yaml
  918. *
  919. * If `var` contains function, they are called during output formatting and if
  920. * they return string value, then this value is used for ouptut.
  921. * @param {variant} var any sort of lua variable (if userdata then metafield `__to_ucl` is searched for output)
  922. * @param {string} format any available format
  923. * @return {string} string representation of `var` in the specific `format`.
  924. * @example
  925. local table = {
  926. str = 'value',
  927. num = 100500,
  928. null = ucl.null,
  929. func = function ()
  930. return 'huh'
  931. end
  932. }
  933. print(ucl.to_format(table, 'ucl'))
  934. -- Output:
  935. --[[
  936. num = 100500;
  937. str = "value";
  938. null = null;
  939. func = "huh";
  940. --]]
  941. */
  942. static int
  943. lua_ucl_to_format (lua_State *L)
  944. {
  945. ucl_object_t *obj;
  946. int format = UCL_EMIT_JSON;
  947. if (lua_gettop (L) > 1) {
  948. if (lua_type (L, 2) == LUA_TNUMBER) {
  949. format = lua_tonumber (L, 2);
  950. if (format < 0 || format >= UCL_EMIT_YAML) {
  951. lua_pushnil (L);
  952. return 1;
  953. }
  954. }
  955. else if (lua_type (L, 2) == LUA_TSTRING) {
  956. const char *strtype = lua_tostring (L, 2);
  957. if (strcasecmp (strtype, "json") == 0) {
  958. format = UCL_EMIT_JSON;
  959. }
  960. else if (strcasecmp (strtype, "json-compact") == 0) {
  961. format = UCL_EMIT_JSON_COMPACT;
  962. }
  963. else if (strcasecmp (strtype, "yaml") == 0) {
  964. format = UCL_EMIT_YAML;
  965. }
  966. else if (strcasecmp (strtype, "config") == 0 ||
  967. strcasecmp (strtype, "ucl") == 0) {
  968. format = UCL_EMIT_CONFIG;
  969. }
  970. else if (strcasecmp (strtype, "msgpack") == 0) {
  971. format = UCL_EMIT_MSGPACK;
  972. }
  973. }
  974. }
  975. obj = ucl_object_lua_import (L, 1);
  976. if (obj != NULL) {
  977. lua_ucl_to_string (L, obj, format);
  978. ucl_object_unref (obj);
  979. }
  980. else {
  981. lua_pushnil (L);
  982. }
  983. return 1;
  984. }
  985. static int
  986. lua_ucl_null_tostring (lua_State* L)
  987. {
  988. lua_pushstring (L, "null");
  989. return 1;
  990. }
  991. static void
  992. lua_ucl_null_mt (lua_State *L)
  993. {
  994. luaL_newmetatable (L, NULL_META);
  995. lua_pushcfunction (L, lua_ucl_null_tostring);
  996. lua_setfield (L, -2, "__tostring");
  997. lua_pop (L, 1);
  998. }
  999. int
  1000. luaopen_ucl (lua_State *L)
  1001. {
  1002. lua_ucl_parser_mt (L);
  1003. lua_ucl_null_mt (L);
  1004. lua_ucl_object_mt (L);
  1005. /* Create the refs weak table: */
  1006. lua_createtable (L, 0, 2);
  1007. lua_pushliteral (L, "v"); /* tbl, "v" */
  1008. lua_setfield (L, -2, "__mode");
  1009. lua_pushvalue (L, -1); /* tbl, tbl */
  1010. lua_setmetatable (L, -2); /* tbl */
  1011. lua_setfield (L, LUA_REGISTRYINDEX, "ucl.refs");
  1012. lua_newtable (L);
  1013. lua_pushcfunction (L, lua_ucl_parser_init);
  1014. lua_setfield (L, -2, "parser");
  1015. lua_pushcfunction (L, lua_ucl_to_json);
  1016. lua_setfield (L, -2, "to_json");
  1017. lua_pushcfunction (L, lua_ucl_to_config);
  1018. lua_setfield (L, -2, "to_config");
  1019. lua_pushcfunction (L, lua_ucl_to_format);
  1020. lua_setfield (L, -2, "to_format");
  1021. ucl_null = lua_newuserdata (L, 0);
  1022. luaL_getmetatable (L, NULL_META);
  1023. lua_setmetatable (L, -2);
  1024. lua_pushvalue (L, -1);
  1025. lua_setfield (L, LUA_REGISTRYINDEX, "ucl.null");
  1026. lua_setfield (L, -2, "null");
  1027. return 1;
  1028. }
  1029. struct ucl_lua_funcdata*
  1030. ucl_object_toclosure (const ucl_object_t *obj)
  1031. {
  1032. if (obj == NULL || obj->type != UCL_USERDATA) {
  1033. return NULL;
  1034. }
  1035. return (struct ucl_lua_funcdata*)obj->value.ud;
  1036. }