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 34KB

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