Implement printf, dprintf, string.format

This commit is contained in:
2026-02-17 19:57:58 -05:00
parent a987754b38
commit ff81d79b4a
7 changed files with 363 additions and 121 deletions

View File

@@ -5,6 +5,7 @@
#include "table.hpp"
#include <cmath>
#include <cinttypes>
class PrintMachine {
public:
@@ -185,24 +186,21 @@ public:
}
}
// If it's an array of atomic values, without a visible metatable,
// we're going to print it without newlines. Scan the table to see if
// it's possible to print it array-style.
bool array_style = false;
if (!print_meta) {
array_style = true;
for (int i = 1; i <= nkeys; i++) {
LS.rawget(val, value, i);
if (LS.isnil(val) || (LS.type(val) == LUA_TTABLE)) {
array_style = false;
break;
}
}
// Count the number of array-style keys.
// Also, check if there are any tables in the array keys.
int narray_keys = 0;
bool array_contains_table = false;
for (int i = 1; i <= nkeys; i++) {
LS.rawget(val, value, i);
if (LS.isnil(val)) break;
narray_keys = i;
if (LS.type(val) == LUA_TTABLE) array_contains_table = true;
}
// Print it array-style. This code is simple because
// Maybe print it array-style. This code is simple because
// we don't do indentation, and we don't handle any values
// that aren't atomic.
bool array_style = (narray_keys == nkeys) && (!array_contains_table);
if (array_style) {
(*output_) << "{";
for (int i = 1; i <= nkeys; i++) {
@@ -310,61 +308,231 @@ void pprint(LuaCoreStack &LS, LuaSlot val, const PrettyPrintOptions &opts, std::
PrintMachine pm(LS, val, opts.indent, opts.level, opts.expand, os);
}
LuaDefine(string_pprint, "obj1, obj2, ...",
"|Pretty-print the specified objects into a string."
"|"
"|See also: string.pprintx, which has a lot more options."
"|This function uses the default options: pretty print indented,"
"|start at indentation level zero, and always expand the"
"|top-level table."
"|") {
LuaRet result;
LuaExtraArgs extra;
LuaDefStack LS(L, result, extra);
util::ostringstream oss;
for (int i = 0; i < extra.size(); i++) {
pprint(LS, extra[i], PrettyPrintOptions(), &oss);
oss << "\n";
//////////////////////////////////////////////////////////////////////////////////
//
// Format
//
// Printf-style formatting that consumes arguments from LuaExtraArgs.
//
//////////////////////////////////////////////////////////////////////////////////
class FormatDirective
{
// Given a string_view that starts with '%', count the number of characters
// in the format parameters: the '%', flags, width, and precision. Does NOT
// include the conversion character.
//
// For example, given "%8.2d %2.7d", returns 4 (the length of "%8.2").
//
static int format_parameters_length(std::string_view fmt) {
assert ((fmt.size() >= 1) && (fmt[0] == '%'));
size_t i = 1;
// Flags
while (i < fmt.size() && (fmt[i] == '-' || fmt[i] == '+' || fmt[i] == ' ' || fmt[i] == '#' || fmt[i] == '0'))
i++;
// Width
while (i < fmt.size() && fmt[i] >= '0' && fmt[i] <= '9')
i++;
// Precision
if (i < fmt.size() && fmt[i] == '.') {
i++;
while (i < fmt.size() && fmt[i] >= '0' && fmt[i] <= '9')
i++;
}
return (int)i;
}
public:
std::string_view precedingliteral;
std::string_view parameters;
std::string_view modifiers;
char directive;
char rebuilt[100];
const int PARAMETERS_TOO_LONG = 50;
// Return an error message declaring this format specifier to be invalid.
//
eng::string invalid()
{
return util::ss("Invalid format specifier: '", parameters, modifiers, directive, "'");
}
// Rebuild the format directive, using the specified suffix
// instead of the stored modifiers and directive.
//
const char *rebuild(std::string_view suffix)
{
std::string_view params = parameters;
if (int(params.size()) > PARAMETERS_TOO_LONG) params = "%";
memcpy(rebuilt, params.data(), params.size());
memcpy(rebuilt + params.size(), suffix.data(), suffix.size());
rebuilt[params.size() + suffix.size()] = 0;
return rebuilt;
}
// Read one directive from fmt, advancing fmt past everything consumed.
//
// On return:
// directive != 0, parameters non-empty — normal format directive
// directive != 0, parameters empty — not possible
// directive == 0, parameters empty — end of string (may have precedingliteral)
// directive == 0, parameters non-empty — truncated format (missing conversion char)
//
void read(std::string_view &fmt)
{
// Find the preceding literal (everything before the first '%').
size_t pct = fmt.find('%');
if (pct == std::string_view::npos) {
precedingliteral = fmt;
parameters = {};
modifiers = {};
directive = 0;
fmt = {};
return;
}
precedingliteral = fmt.substr(0, pct);
fmt.remove_prefix(pct);
// Measure format parameters (%, flags, width, precision).
int plen = format_parameters_length(fmt);
parameters = fmt.substr(0, plen);
fmt.remove_prefix(plen);
// Read 'l' modifiers.
int modcount = 0;
while ((modcount < int(fmt.size())) && (fmt[modcount] == 'l'))
modcount++;
modifiers = fmt.substr(0, modcount);
fmt.remove_prefix(modcount);
// Read conversion character.
if (fmt.empty()) { directive = 0; return; }
directive = fmt[0];
fmt.remove_prefix(1);
}
};
static void format_signed(LuaCoreStack &LS, LuaSlot arg, const char *format, std::ostream *os) {
auto ni = LS.tryinteger(arg);
if (ni) {
char buf[64];
snprintf(buf, sizeof(buf), format, *ni);
(*os) << buf;
}
LS.set(result, oss.view());
return LS.result();
}
LuaDefine(string_pprintx, "options",
"|Pretty-print the specified object into a string, with options"
"|"
"|Options is a table with these fields:"
"|"
"| value - the object to pretty-print"
"| indent - if false, suppress newlines and indentation (default: true)"
"| level - base level of indentation (default: zero)"
"| expand - if true, force expansion of top-level table (default: false)"
"|"
"|About the expand flag: normally, when you print a class, it just "
"|prints '<class name>', and when you print a tangible, it just"
"|prints '<tangible id>'. But sometimes, you want to see the details."
"|The expand flag forces it to expand the top-level table, even if the"
"|top-level table is a tangible or class."
"|") {
LuaArg loptions;
LuaRet result;
LuaVar value;
LuaDefStack LS(L, loptions, result, value);
PrettyPrintOptions options;
LuaKeywordParser kp(LS, loptions);
options.parse(kp);
if (!kp.optional(value, "value")) {
LS.set(value, LuaNil);
static void format_unsigned(LuaCoreStack &LS, LuaSlot arg, const char *format, std::ostream *os) {
auto ni = LS.tryinteger(arg);
if (ni) {
char buf[64];
snprintf(buf, sizeof(buf), format, (uint64_t)(*ni));
(*os) << buf;
}
kp.final_check_throw();
util::ostringstream oss;
pprint(LS, value, options, &oss);
LS.set(result, oss.view());
return LS.result();
}
LuaDefine(string_print, "obj",
static void format_double(LuaCoreStack &LS, LuaSlot arg, const char *format, std::ostream *os) {
auto ni = LS.trynumber(arg);
if (ni) {
char buf[64];
snprintf(buf, sizeof(buf), format, *ni);
(*os) << buf;
}
}
eng::string format(LuaCoreStack &LS, std::string_view fmt, LuaExtraArgs args, std::ostream *os) {
FormatDirective fd;
// First pass: validate the format string and the argument types.
std::string_view fmtcopy = fmt;
int nargs = 0;
while (!fmtcopy.empty()) {
fd.read(fmtcopy);
if (int(fd.parameters.size()) > fd.PARAMETERS_TOO_LONG) return fd.invalid();
if (fd.directive == 0 && !fd.parameters.empty()) return fd.invalid();
if (fd.directive == '%') {
if ((fd.parameters.size() != 1)||(fd.modifiers.size() != 0))
return fd.invalid();
} else if (fd.directive != 0) {
if (nargs >= args.size())
return util::ss("expected more than ", args.size(), " arguments");
LuaSpecial arg = args[nargs++];
switch (fd.directive) {
case 'd': case 'i': case 'o': case 'u': case 'x': case 'X':
case 'c':
if (!LS.isinteger(arg))
return util::ss("bad argument #", nargs, " (integer expected, got ", LS.typestr(arg), ")");
break;
case 'e': case 'E': case 'f': case 'g': case 'G':
if (!LS.isnumber(arg))
return util::ss("bad argument #", nargs, " (number expected, got ", LS.typestr(arg), ")");
break;
case 's': case 'q': case 'p': case 'P':
break;
default:
return fd.invalid();
}
}
}
if (nargs != args.size())
return util::ss("expected ", nargs, " arguments, got ", args.size());
// Second pass: produce output.
int argidx = 0;
while (!fmt.empty()) {
fd.read(fmt);
if (!fd.precedingliteral.empty())
os->write(fd.precedingliteral.data(), fd.precedingliteral.size());
if (fd.directive == 0) break;
if (fd.directive == '%') { os->put('%'); continue; }
LuaSpecial arg = args[argidx++];
switch (fd.directive) {
case 'd': format_signed(LS, arg, fd.rebuild(PRId64), os); break;
case 'i': format_signed(LS, arg, fd.rebuild(PRId64), os); break;
case 'o': format_unsigned(LS, arg, fd.rebuild(PRIo64), os); break;
case 'u': format_unsigned(LS, arg, fd.rebuild(PRIu64), os); break;
case 'x': format_unsigned(LS, arg, fd.rebuild(PRIx64), os); break;
case 'X': format_unsigned(LS, arg, fd.rebuild(PRIX64), os); break;
case 'e': format_double(LS, arg, fd.rebuild("e"), os); break;
case 'E': format_double(LS, arg, fd.rebuild("E"), os); break;
case 'f': format_double(LS, arg, fd.rebuild("f"), os); break;
case 'g': format_double(LS, arg, fd.rebuild("g"), os); break;
case 'G': format_double(LS, arg, fd.rebuild("G"), os); break;
case 'c': format_signed(LS, arg, fd.rebuild("c"), os); break;
case 's': atomic_print(LS, arg, false, os); break;
case 'q': atomic_print(LS, arg, true, os); break;
case 'p': pprint(LS, arg, PrettyPrintOptions(fd.modifiers.empty(), false), os); break;
case 'P': pprint(LS, arg, PrettyPrintOptions(fd.modifiers.empty(), true), os); break;
default: break;
}
}
return {};
}
//////////////////////////////////////////////////////////////////////////////////
//
// Lua Interfaces to the Various Printing Routines
//
// Note: there are more functions like this in world-accessor.
//
//////////////////////////////////////////////////////////////////////////////////
LuaDefine(tostring, "obj",
"|Concise print the specified object into a string"
"|"
"|This prints a concise representation of obj into a string. Tables"
@@ -381,9 +549,9 @@ LuaDefine(string_print, "obj",
return LS.result();
}
LuaDefineAlias(tostring, string_print);
LuaDefine(string_isidentifier, "str", "return true if the string is a valid lua identifier") {
LuaDefine(string_isidentifier, "str",
"return true if the string is a valid lua identifier") {
LuaArg str;
LuaRet result;
LuaDefStack LS(L, str, result);
@@ -396,5 +564,3 @@ LuaDefine(string_isidentifier, "str", "return true if the string is a valid lua
return LS.result();
}