Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

printf: handle argument indices given by dollars in format strings #77

Merged
merged 1 commit into from
Dec 7, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions include/frg/formatting.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,7 @@ struct format_options {
format_conversion conversion;
int minimum_width = 0;
int arg_pos = -1;
bool dollar_arg_pos = false;
optional<int> precision;
bool left_justify = false;
bool always_sign = false;
Expand Down
15 changes: 13 additions & 2 deletions include/frg/printf.hpp
Original file line number Diff line number Diff line change
Expand Up @@ -62,9 +62,16 @@ T pop_arg(va_struct *vsp, format_options *opts) {
if (opts->arg_pos == -1)
return pop_va_arg();

FRG_ASSERT(opts->arg_pos <= vsp->num_args);
if (opts->arg_pos < vsp->num_args)
if(opts->dollar_arg_pos) {
// we copy out all previous and the requested argument into our vsp->arg_list
for(int i = vsp->num_args; i <= opts->arg_pos; i++) {
auto arg = pop_va_arg();
*get_union_member(i) = arg;
}

vsp->num_args = opts->arg_pos + 1;
return *get_union_member(opts->arg_pos);
}

auto arg = pop_va_arg();
*get_union_member(vsp->num_args++) = arg;
Expand All @@ -74,6 +81,7 @@ T pop_arg(va_struct *vsp, format_options *opts) {
template<typename A>
frg::expected<format_error> printf_format(A agent, const char *s, va_struct *vsp) {
FRG_ASSERT(s != nullptr);
bool dollar_arg_pos = false;

while(*s) {
if(*s != '%') {
Expand All @@ -100,9 +108,12 @@ frg::expected<format_error> printf_format(A agent, const char *s, va_struct *vsp


format_options opts;
opts.dollar_arg_pos = dollar_arg_pos;
while(true) {
if (*s >= '0' && *s <= '9' && s[1] && s[1] == '$') {
opts.arg_pos = *s - '0' - 1; // args are 1-indexed
opts.dollar_arg_pos = true;
dollar_arg_pos = true;
s += 2;
FRG_ASSERT(*s);
} else if(*s == '-') {
Expand Down
2 changes: 2 additions & 0 deletions tests/tests.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -428,6 +428,8 @@ TEST(formatting, printf) {
do_test("hello", "%.5s", "hello world");
do_test("hello", "%.*s", 5, "hello world");
do_test("hello", "%.10s", "hello\0!!!!");

do_test("55 33", "%2$d %1$d", 33, 55);
}

#include <frg/bitset.hpp>
Expand Down