Implement C++ pretty-printer

This commit is contained in:
2021-09-08 01:32:08 -04:00
parent 67b309a0b7
commit bac1a7b876
9 changed files with 322 additions and 454 deletions

View File

@@ -1,5 +1,6 @@
#include "print.hpp"
#include "util.hpp"
#include "table.hpp"
#include <ostream>
#include <iostream>
@@ -25,8 +26,243 @@ LuaDefine(string_isidentifier, "c") {
return LS.result();
}
void pprint(LuaStack &LS0, LuaSlot val, int indent, int maxlen, std::ostream *os) {
bool string_quote(LuaStack &LS, LuaSlot val, std::ostream *os) {
switch (LS.type(val)) {
case LUA_TNIL:
(*os) << "nil";
return true;
case LUA_TSTRING:
util::quote_string(LS.ckstring(val), os);
return true;
case LUA_TNUMBER:
(*os) << LS.ckinteger(val);
return true;
case LUA_TBOOLEAN:
(*os) << (LS.ckboolean(val) ? "true" : "false");
return true;
default:
return false;
}
}
LuaDefine(string_quote, "c") {
LuaArg val;
LuaRet result;
LuaStack LS(L, val, result);
std::ostringstream oss;
string_quote(LS, val, &oss);
LS.set(result, oss.str());
return LS.result();
}
// Find tables recursively.
//
// Builds a table (tabcount) whose keys are tables. If a table
// is visited exactly once, then tabcount[t]=0. If a table is
// visited more than once, then tabcount[t]=-1.
//
static void findtables(LuaStack &LS0, LuaSlot root, LuaSlot tabcount) {
lua_State *L = LS0.state();
LuaVar key, val, tab, count;
LuaStack LS(L, key, val, tab, count);
LS.newtable(tabcount);
int top = lua_gettop(L);
if (LS.istable(root)) {
lua_pushvalue(L, root.index());
}
while (lua_gettop(L) > top) {
lua_checkstack(L, 10);
lua_replace(L, tab.index());
LS.rawget(count, tabcount, tab);
if (LS.isnil(count)) {
LS.rawset(tabcount, tab, 0);
LS.set(key, LuaNil);
while (LS.next(tab, key, val)) {
if (LS.istable(key)) {
lua_pushvalue(L, key.index());
}
if (LS.istable(val)) {
lua_pushvalue(L, val.index());
}
}
LS.getmetatable(val, tab);
if (LS.istable(val)) {
lua_pushvalue(L, val.index());
}
} else {
LS.rawset(tabcount, tab, -1);
}
}
LS.result();
}
LuaDefine(table_findtables, "c") {
LuaArg root;
LuaRet tabcount;
LuaStack LS(L, root, tabcount);
findtables(LS, root, tabcount);
return LS.result();
}
struct Inspector {
lua_State *L;
LuaVar ids;
int nextid;
bool indent;
int maxlen;
bool anyindent;
std::ostream *stream;
};
static void tabify(Inspector &insp, int level) {
if (insp.indent) {
(*insp.stream) << std::endl;
for (int i = 0; i < level; i++) {
(*insp.stream) << " ";
}
insp.anyindent = true;
} else {
(*insp.stream) << " ";
}
}
static void pprint_r(Inspector &insp, int level, LuaSlot root) {
LuaVar idv, pairs, key, val;
LuaStack LS(insp.L, idv, pairs, key, val);
// If it's a simple type, print it quoted.
if (string_quote(LS, root, insp.stream)) {
LS.result();
return;
}
// If it's not a table, just print the typename.
int t = LS.type(root);
if (t != LUA_TTABLE) {
(*insp.stream) << "<" << lua_typename(insp.L, t) << ">";
LS.result();
return;
}
// If the table ID is greater than zero, then we've already
// printed it. Just print the table ID.
LS.rawget(idv, insp.ids, root);
int id = LS.ckint(idv);
if (id > 0) {
if (lua_nkeys(insp.L, root.index())==0) {
(*insp.stream) << "<table " << id << ">{}";
} else {
(*insp.stream) << "<table " << id << ">{...}";
}
LS.result();
return;
}
// Allocate an ID for the table, if necessary.
if (id < 0) {
id = insp.nextid++;
LS.rawset(insp.ids, root, id);
}
// Print the table ID if greater than zero.
if (id > 0) {
(*insp.stream) << "<table " << id << ">";
}
// State variables.
int nextseq = 1;
bool needcomma = false;
bool multiline = false;
// Open the brackets.
(*insp.stream) << "{";
// Output the table keys.
table_getpairs(LS, root, pairs, true);
for (int i = 2; ; i+=2) {
LS.rawgeti(key, pairs, i);
if (LS.isnil(key)) break;
LS.rawgeti(val, pairs, i+1);
if (needcomma) (*insp.stream) << ",";
needcomma = true;
if (LS.isnumber(key) && (LS.ckint(key) == nextseq)) {
(*insp.stream) << " ";
pprint_r(insp, level + 1, val);
nextseq = nextseq + 1;
} else {
multiline = true;
tabify(insp, level + 1);
if (LS.isstring(key) && util::is_identifier(LS.ckstring(key))) {
(*insp.stream) << LS.ckstring(key);
} else {
(*insp.stream) << "[";
pprint_r(insp, level + 1, key);
(*insp.stream) << "]";
}
(*insp.stream) << " = ";
pprint_r(insp, level + 1, val);
}
}
// Output the metatable.
LS.getmetatable(val, root);
if (LS.istable(val)) {
multiline = true;
if (needcomma) (*insp.stream) << ",";
needcomma = true;
tabify(insp, level + 1);
(*insp.stream) << "<meta> = ";
// if isclass(mt) then
// self:puts('<class ')
// self:puts(rawget(mt, "__class"))
// self:puts('>')
// end
pprint_r(insp, level + 1, val);
}
// Close the brackets.
if (multiline) {
tabify(insp, level);
} else if (nextseq > 1) {
(*insp.stream) << " ";
}
(*insp.stream) << "}";
LS.result();
}
void pprint(LuaStack &LS0, LuaSlot root, bool indent, std::ostream *os) {
Inspector insp;
LuaStack LS(LS0.state(), insp.ids);
findtables(LS, root, insp.ids);
insp.L = LS0.state();
insp.nextid = 1;
insp.indent = indent;
insp.anyindent = false;
insp.stream = os;
pprint_r(insp, 0, root);
LS.result();
}
LuaDefine(pprint_pprint, "f") {
LuaStack LS(L);
for (int i = 1; i <= lua_gettop(L); i++) {
LuaSpecial root(i);
pprint(LS, root, true, &std::cout);
std::cout << std::endl;
}
return LS.result();
}
LuaDefine(string_pprint, "c") {
LuaArg root, indent;
LuaRet result;
LuaStack LS(L, root, indent, result);
bool ind = LS.ckboolean(indent);
std::ostringstream oss;
pprint(LS, root, ind, &oss);
LS.set(result, oss.str());
return LS.result();
}

View File

@@ -20,6 +20,15 @@ void luai_writestring(const char *s, size_t len);
void luai_writeline();
}
// Output a simple value to a stream.
//
// If the value is a string, number, boolean, or nil, it is
// quoted and output to the stream, and this function returns
// true. Otherwise, this function returns false and nothing
// is sent to the stream.
//
bool string_quote(LuaStack &LS, LuaSlot val, std::ostream *os);
// Pretty print to a stream.
//
// If indent is >=0, the output is indented. If indent<0, then
@@ -32,15 +41,15 @@ void pprint(LuaStack &LS, LuaSlot val, int indent, int maxlen, std::ostream *os)
// The following lua interfaces to this code are included:
//
// pprint(expr)
// pprint(expr, expr, expr...)
//
// - pretty print the specified expression to stdout.
//
// string.pprint(expr, indent, maxlen)
// string.pprint(expr, indent)
//
// - pretty print the specified expression, return the result as a string.
//
void pprint_pprint(lua_State *L);
void string_pprint(lua_State *L);
int lfn_pprint_pprint(lua_State *L);
int lfn_string_pprint(lua_State *L);
#endif // PRINT_HPP

View File

@@ -1,50 +1,6 @@
#include "table.hpp"
#include "source.hpp"
void table_findtables_i(LuaStack &LS0, LuaSlot root, LuaSlot tabcount) {
lua_State *L = LS0.state();
LuaVar key, val, tab, count;
LuaStack LS(L, key, val, tab, count);
LS.newtable(tabcount);
int top = lua_gettop(L);
if (LS.istable(root)) {
lua_pushvalue(L, root.index());
}
while (lua_gettop(L) > top) {
lua_checkstack(L, 10);
lua_replace(L, tab.index());
LS.rawget(count, tabcount, tab);
if (LS.isnil(count)) {
LS.rawset(tabcount, tab, 1);
LS.set(key, LuaNil);
while (LS.next(tab, key, val)) {
if (LS.istable(key)) {
lua_pushvalue(L, key.index());
}
if (LS.istable(val)) {
lua_pushvalue(L, val.index());
}
}
LS.getmetatable(val, tab);
if (LS.istable(val)) {
lua_pushvalue(L, val.index());
}
} else {
LS.rawset(tabcount, tab, LS.ckint(count) + 1);
}
}
LS.result();
}
LuaDefine(table_findtables, "c") {
LuaArg root;
LuaRet tabcount;
LuaStack LS(L, root, tabcount);
table_findtables_i(LS, root, tabcount);
return LS.result();
}
LuaDefine(table_getregistry, "f") {
LuaArg key;
LuaRet result;
@@ -575,28 +531,13 @@ static void auxsort (lua_State *L, int tab, int l, int u) {
} /* repeat the routine for the larger one */
}
static int table_getpairs(lua_State *L, bool sort, bool *unsortable) {
lua_checkstack(L, 40);
LuaArg tab;
bool table_getpairs(LuaStack &LS0, LuaSlot tab, LuaSlot pairs, bool sort) {
lua_State *L = LS0.state();
LuaVar key, value;
LuaRet pairs;
LuaStack LS(L, tab, key, value, pairs);
if (unsortable != nullptr) {
*unsortable = false;
}
LS.checktable(tab);
// Count the total number of pairs.
// TODO: add lua_npairs to make this faster.
lua_pushnil(L);
int total = 0;
while (lua_next(L, tab.index()) != 0) {
int ktype = lua_type(L, -2);
if (ktype == LUA_TNUMBER || ktype == LUA_TSTRING || ktype == LUA_TBOOLEAN) {
total += 1;
}
lua_pop(L, 1);
}
LuaStack LS(L, key, value);
bool sorted = true;
// Create the table, store the initial 1.
int total = lua_nkeys(L, tab.index());
LS.createtable(pairs, total * 2 + 1, 0);
LS.rawseti(pairs, 1, 1);
// Transfer the pairs into the sequence.
@@ -604,21 +545,18 @@ static int table_getpairs(lua_State *L, bool sort, bool *unsortable) {
int offset = 2;
while (lua_next(L, tab.index()) != 0) {
int ktype = lua_type(L, -2);
if (ktype == LUA_TNUMBER || ktype == LUA_TSTRING || ktype == LUA_TBOOLEAN) {
lua_pushvalue(L, -2); // K V K
lua_rawseti(L, pairs.index(), offset++);
lua_rawseti(L, pairs.index(), offset++);
} else {
if (unsortable != nullptr) {
*unsortable = true;
}
lua_pop(L, 1);
if (ktype != LUA_TNUMBER && ktype != LUA_TSTRING && ktype != LUA_TBOOLEAN) {
sorted = false;
}
lua_pushvalue(L, -2); // K V K
lua_rawseti(L, pairs.index(), offset++);
lua_rawseti(L, pairs.index(), offset++);
}
if (sort) {
auxsort(L, pairs.index(), 1, total);
}
return LS.result();
LS.result();
return sorted;
}
/////////////////////////////////////////////////////////////
@@ -652,13 +590,20 @@ LuaDefine(table_sortedpairs, "c") {
LuaArg tab;
LuaRet closure, rtab, key;
LuaStack LS(L, tab, closure, rtab, key);
lua_pushvalue(L, tab.index());
bool unsortable;
table_getpairs(L, true, &unsortable);
if (unsortable) {
bool sorted = table_getpairs(LS, tab, rtab, true);
if (!sorted) {
luaL_error(L, "Cannot iterate over a table with unsortable keys");
}
lua_replace(L, rtab.index());
LS.set(closure, lfn_table_nextsortedpair);
LS.set(key, LuaNil);
return LS.result();
}
LuaDefine(table_semisortedpairs, "c") {
LuaArg tab;
LuaRet closure, rtab, key;
LuaStack LS(L, tab, closure, rtab, key);
table_getpairs(LS, tab, rtab, true);
LS.set(closure, lfn_table_nextsortedpair);
LS.set(key, LuaNil);
return LS.result();

View File

@@ -12,14 +12,6 @@
#include "luastack.hpp"
// Starting at the specified root, find tables recursively.
//
// Returns a table containing every table found, in tabcount.
// The value associated with the table is the number of times the
// table was found.
//
void table_findtables(LuaStack &LS0, LuaSlot root, LuaSlot tabcount);
// table_clear
//
// Remove all key/value pairs from the table. Does not remove
@@ -33,6 +25,13 @@ void table_clear(LuaStack &LS0, LuaSlot tab);
//
bool table_equal(LuaStack &LS0, LuaSlot tab1, LuaSlot tab2);
// table_getpairs
//
// Get a table containing the key-value pairs in tab. Optionally sort
// the pairs. Return true if all keys were sortable.
//
bool table_getpairs(LuaStack &LS0, LuaSlot tab, LuaSlot pairs, bool sort);
// table_findremove
//
// Given a vector and a value, remove the specified value from

View File

@@ -14,6 +14,7 @@
#include "traceback.hpp"
#include "textgame.hpp"
#include "luaconsole.hpp"
#include "print.hpp"
// Add another error status.
@@ -54,17 +55,8 @@ void TextGame::do_lua(const std::string &exp) {
signal(SIGINT, SIG_DFL);
if (status == LUA_OK) {
if (lua_gettop(L) > 0) {
lua_getglobal(L, "pprint");
if (lua_isnil(L, -1)) {
lua_pop(L, 1);
lua_getglobal(L, "print");
}
lua_insert(L, 1);
if (lua_pcall(L, lua_gettop(L) - 1, 0, 0) != 0) {
l_message(
lua_pushfstring(L, "error calling 'print' (%s)",
lua_tostring(L, -1)));
}
lfn_pprint_pprint(L);
lua_settop(L, 0);
}
} else {
const char *msg = lua_tostring(L, -1);

View File

@@ -35,6 +35,38 @@ bool is_identifier(const std::string &str) {
return true;
}
void quote_string(const std::string &s, std::ostream *os) {
bool usesinglequote = false;
for (char c : s) {
if (c == '"') {
usesinglequote = true;
break;
}
}
(*os) << (usesinglequote ? '\'' : '"');
for (char c : s) {
if (c >= 32) {
if (c == '"') {
(*os) << (usesinglequote ? "\"" : "\\\"");
} else if (c == '\'') {
(*os) << (usesinglequote ? "\\'" : "'");
} else {
(*os) << c;
}
} else {
switch (c) {
case '\n': (*os) << "\\n"; break;
case '\t': (*os) << "\\t"; break;
case '\r': (*os) << "\\r"; break;
default:
(*os) << "\\" << std::setw(3) << int(c);
break;
}
}
}
(*os) << (usesinglequote ? '\'' : '"');
}
IdVector id_vector_create(int64_t id1, int64_t id2, int64_t id3, int64_t id4) {
IdVector result;
if (id1 >= 0) result.push_back(id1);

View File

@@ -27,6 +27,9 @@ using IdVector = std::vector<int64_t>;
// Return true if the string is a valid lua identifier.
bool is_identifier(const std::string &str);
// Output a string to a stream using Lua string escaping and quoting.
void quote_string(const std::string &str, std::ostream *os);
// ID vector quick create.
IdVector id_vector_create(int64_t id1=-1, int64_t id2=-1, int64_t id3=-1, int64_t id4=-1);