Skip to content

Commit

Permalink
printf: handle argument indices given by dollars in format strings
Browse files Browse the repository at this point in the history
  • Loading branch information
no92 committed Dec 7, 2024
1 parent 922d38d commit e277d7b
Show file tree
Hide file tree
Showing 2 changed files with 14 additions and 2 deletions.
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

0 comments on commit e277d7b

Please sign in to comment.