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

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