cosmopolitan/third_party/lua/luaencodejsondata.c

173 lines
6.8 KiB
C
Raw Normal View History

/*-*- mode:c;indent-tabs-mode:nil;c-basic-offset:2;tab-width:8;coding:utf-8 -*-│
vi: set net ft=c ts=2 sts=2 sw=2 fenc=utf-8 :vi
Copyright 2022 Justine Alexandra Roberts Tunney
Permission to use, copy, modify, and/or distribute this software for
any purpose with or without fee is hereby granted, provided that the
above copyright notice and this permission notice appear in all copies.
THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL
WARRANTIES WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE
AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL
DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR
PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER
TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
PERFORMANCE OF THIS SOFTWARE.
*/
2022-04-29 13:06:23 +00:00
#include "libc/assert.h"
#include "libc/bits/bits.h"
#include "libc/fmt/itoa.h"
2022-07-12 06:06:49 +00:00
#include "libc/intrin/kprintf.h"
#include "libc/log/log.h"
#include "libc/log/rop.h"
2022-04-29 13:06:23 +00:00
#include "libc/mem/mem.h"
#include "libc/runtime/gc.internal.h"
#include "libc/stdio/append.internal.h"
#include "libc/stdio/strlist.internal.h"
2022-07-09 18:44:19 +00:00
#include "libc/str/str.h"
#include "net/http/escape.h"
2022-07-09 18:44:19 +00:00
#include "third_party/double-conversion/wrapper.h"
#include "third_party/lua/cosmo.h"
#include "third_party/lua/lauxlib.h"
#include "third_party/lua/lua.h"
2022-04-29 13:06:23 +00:00
#include "third_party/lua/visitor.h"
static int LuaEncodeJsonDataImpl(lua_State *L, char **buf, int level,
2022-04-29 13:06:23 +00:00
char *numformat, int idx,
2022-07-12 06:06:49 +00:00
struct LuaVisited *visited,
const char **reason) {
char *s;
int sli, rc;
bool isarray;
2022-07-12 06:06:49 +00:00
char ibuf[128];
2022-04-29 13:06:23 +00:00
size_t tbllen, i, z;
struct StrList sl = {0};
if (level > 0) {
switch (lua_type(L, idx)) {
2022-04-29 13:06:23 +00:00
case LUA_TNIL:
RETURN_ON_ERROR(appendw(buf, READ32LE("null")));
2022-04-29 13:06:23 +00:00
return 0;
case LUA_TBOOLEAN:
RETURN_ON_ERROR(appendw(buf, lua_toboolean(L, idx)
? READ32LE("true")
: READ64LE("false\0\0")));
2022-04-29 13:06:23 +00:00
return 0;
case LUA_TSTRING:
s = lua_tolstring(L, idx, &z);
2022-07-12 06:06:49 +00:00
if (!(s = EscapeJsStringLiteral(s, z, &z))) {
goto OnError;
}
RETURN_ON_ERROR(appendw(buf, '"'));
RETURN_ON_ERROR(appendd(buf, s, z));
RETURN_ON_ERROR(appendw(buf, '"'));
free(s);
return 0;
2022-04-29 13:06:23 +00:00
case LUA_TNUMBER:
if (lua_isinteger(L, idx)) {
RETURN_ON_ERROR(appendd(
buf, ibuf, FormatInt64(ibuf, luaL_checkinteger(L, idx)) - ibuf));
} else {
2022-07-09 18:44:19 +00:00
RETURN_ON_ERROR(
2022-07-12 19:30:42 +00:00
appends(buf, DoubleToJson(ibuf, lua_tonumber(L, idx))));
}
return 0;
2022-04-29 13:06:23 +00:00
case LUA_TTABLE:
RETURN_ON_ERROR(rc = LuaPushVisit(visited, lua_topointer(L, idx)));
if (!rc) {
2022-07-12 06:06:49 +00:00
// create nearby reference to table at idx
lua_pushvalue(L, idx);
// fast way to tell if table is an array or object
if ((tbllen = lua_rawlen(L, -1)) > 0) {
isarray = true;
} else {
// the json parser inserts `[0]=false` in empty arrays
// so we can tell them apart from empty objects, which
// is needed in order to have `[]` roundtrip the parse
isarray = (lua_rawgeti(L, -1, 0) == LUA_TBOOLEAN &&
!lua_toboolean(L, -1));
lua_pop(L, 1);
}
// now serialize the table
2022-04-29 13:06:23 +00:00
if (isarray) {
for (i = 1; i <= tbllen; i++) {
RETURN_ON_ERROR(sli = AppendStrList(&sl));
2022-04-29 13:06:23 +00:00
lua_rawgeti(L, -1, i); // table/-2, value/-1
2022-07-12 06:06:49 +00:00
RETURN_ON_ERROR(LuaEncodeJsonDataImpl(
L, &sl.p[sli], level - 1, numformat, -1, visited, reason));
2022-04-29 13:06:23 +00:00
lua_pop(L, 1);
}
2022-04-29 13:06:23 +00:00
} else {
i = 1;
lua_pushnil(L); // push the first key
while (lua_next(L, -2)) {
2022-04-29 13:35:27 +00:00
if (lua_type(L, -2) != LUA_TSTRING) {
2022-07-12 06:06:49 +00:00
*reason = "json objects must only use string keys";
goto OnError;
2022-04-29 13:06:23 +00:00
}
2022-07-12 06:06:49 +00:00
RETURN_ON_ERROR(sli = AppendStrList(&sl));
RETURN_ON_ERROR(LuaEncodeJsonDataImpl(
L, &sl.p[sli], level - 1, numformat, -2, visited, reason));
RETURN_ON_ERROR(appendw(&sl.p[sli], ':'));
RETURN_ON_ERROR(LuaEncodeJsonDataImpl(
L, &sl.p[sli], level - 1, numformat, -1, visited, reason));
2022-04-29 13:06:23 +00:00
lua_pop(L, 1); // table/-2, key/-1
}
2022-04-29 13:06:23 +00:00
// stack: table/-1, as the key was popped by lua_next
SortStrList(&sl);
}
RETURN_ON_ERROR(appendw(buf, isarray ? '[' : '{'));
RETURN_ON_ERROR(JoinStrList(&sl, buf, ','));
FreeStrList(&sl);
RETURN_ON_ERROR(appendw(buf, isarray ? ']' : '}'));
2022-04-29 13:06:23 +00:00
LuaPopVisit(visited);
2022-04-29 13:35:27 +00:00
lua_pop(L, 1); // table ref
2022-07-12 06:06:49 +00:00
2022-04-29 13:06:23 +00:00
return 0;
} else {
2022-07-12 06:06:49 +00:00
*reason = "won't serialize cyclic lua table";
goto OnError;
}
default:
2022-07-12 06:06:49 +00:00
*reason = "unsupported lua type";
goto OnError;
}
} else {
2022-07-12 06:06:49 +00:00
*reason = "table has great depth";
goto OnError;
}
OnError:
FreeStrList(&sl);
return -1;
}
/**
* Encodes Lua data structure as JSON.
*
* @param L is Lua interpreter state
* @param buf receives encoded output string
* @param numformat controls double formatting
* @param idx is index of item on Lua stack
* @return 0 on success, or -1 on error
*/
int LuaEncodeJsonData(lua_State *L, char **buf, char *numformat, int idx) {
int rc;
2022-04-29 13:06:23 +00:00
struct LuaVisited visited = {0};
2022-07-12 06:06:49 +00:00
const char *reason = "out of memory";
rc = LuaEncodeJsonDataImpl(L, buf, 64, numformat, idx, &visited, &reason);
2022-04-29 13:06:23 +00:00
free(visited.p);
2022-07-12 06:06:49 +00:00
if (rc == -1) {
lua_pushnil(L);
lua_pushstring(L, reason);
}
return rc;
}