Skip to content

Commit

Permalink
[builtin/printf] Support multiple flags
Browse files Browse the repository at this point in the history
  • Loading branch information
akinomyoga committed Mar 19, 2020
1 parent cb08494 commit 88360e5
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 11 deletions.
2 changes: 1 addition & 1 deletion frontend/syntax.asdl
Original file line number Diff line number Diff line change
Expand Up @@ -349,7 +349,7 @@ module syntax
Literal(Token token)
-- flags are 0 hyphen space + #
-- type is 's' for %s, etc.
| Percent(Token? flag, Token? width, Token? precision, Token type)
| Percent(Token* flags, Token? width, Token? precision, Token type)

--
-- OIL LANGUAGE
Expand Down
25 changes: 15 additions & 10 deletions osh/builtin_printf.py
Original file line number Diff line number Diff line change
Expand Up @@ -75,14 +75,14 @@ def _ParseFormatStr(self):
self._Next(lex_mode_e.PrintfPercent) # move past %

part = printf_part.Percent()
if self.token_type in (Id.Format_Flag, Id.Format_Zero):
part.flag = self.cur_token
self._Next(lex_mode_e.PrintfPercent)

while self.token_type in (Id.Format_Flag, Id.Format_Zero):
# space and + could be implemented
flag = part.flag.val
flag = self.cur_token.val
if flag in '# +':
p_die("osh printf doesn't support the %r flag", flag, token=part.flag)
p_die("osh printf doesn't support the %r flag", flag, token=self.cur_token)

part.flags.append(self.cur_token)
self._Next(lex_mode_e.PrintfPercent)

if self.token_type in (Id.Format_Num, Id.Format_Star):
part.width = self.cur_token
Expand Down Expand Up @@ -212,6 +212,12 @@ def Run(self, cmd_val):
out.append(s)

elif isinstance(part, printf_part.Percent):
flags = None
if len(part.flags) > 0:
flags = ''
for flag_token in part.flags:
flags += flag_token.val

width = None
if part.width:
if part.width.id in (Id.Format_Num, Id.Format_Zero):
Expand Down Expand Up @@ -356,11 +362,10 @@ def Run(self, cmd_val):
raise AssertionError()

if width is not None:
if part.flag:
flag = part.flag.val
if flag == '-':
if flags:
if '-' in flags:
s = s.ljust(width, ' ')
elif flag == '0':
elif '0' in flags:
s = s.rjust(width, '0')
else:
pass
Expand Down

0 comments on commit 88360e5

Please sign in to comment.