Skip to content

Commit

Permalink
Parsing a + b to hold_keys(a, b) (#392)
Browse files Browse the repository at this point in the history
  • Loading branch information
sezanzeb committed May 7, 2022
1 parent de22c5d commit 1782b3c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 26 deletions.
24 changes: 8 additions & 16 deletions inputremapper/injection/macros/parse.py
Original file line number Diff line number Diff line change
Expand Up @@ -328,28 +328,20 @@ def _parse_recurse(code, context, macro_instance=None, depth=0):


def handle_plus_syntax(macro):
"""transform a + b + c to modify(a,modify(b,modify(c,hold())))"""
"""transform a + b + c to hold_keys(a,b,c)"""
if "+" not in macro:
return macro

if "(" in macro or ")" in macro:
raise ValueError(
f'Mixing "+" and macros is unsupported: "{ macro}"'
) # TODO: MacroParsingError
# TODO: MacroParsingError
raise ValueError(f'Mixing "+" and macros is unsupported: "{ macro}"')

chunks = [chunk.strip() for chunk in macro.split("+")]
output = ""
depth = 0
for chunk in chunks:
if chunk == "":
# invalid syntax
raise ValueError(f'Invalid syntax for "{macro}"')

depth += 1
output += f"modify({chunk},"

output += "hold()"
output += depth * ")"

if "" in chunks:
raise ValueError(f'Invalid syntax for "{macro}"')

output = f"hold_keys({','.join(chunks)})"

logger.debug('Transformed "%s" to "%s"', macro, output)
return output
Expand Down
17 changes: 7 additions & 10 deletions tests/unit/test_macros.py
Original file line number Diff line number Diff line change
Expand Up @@ -266,16 +266,13 @@ def test_is_this_a_macro(self):
self.assertTrue(is_this_a_macro("a + b + c"))

def test_handle_plus_syntax(self):
self.assertEqual(handle_plus_syntax("a + b"), "modify(a,modify(b,hold()))")
self.assertEqual(
handle_plus_syntax("a + b + c"), "modify(a,modify(b,modify(c,hold())))"
)
self.assertEqual(
handle_plus_syntax(" a+b+c "), "modify(a,modify(b,modify(c,hold())))"
)
self.assertEqual(handle_plus_syntax("a + b"), "hold_keys(a,b)")
self.assertEqual(handle_plus_syntax("a + b + c"), "hold_keys(a,b,c)")
self.assertEqual(handle_plus_syntax(" a+b+c "), "hold_keys(a,b,c)")

# invalid
strings = ["+", "a+", "+b", "key(a + b)"]
# invalid. The last one with `key` should not have been a parameter
# of this function to begin with.
strings = ["+", "a+", "+b", "a\n+\n+\nb", "key(a + b)"]
for string in strings:
with self.assertRaises(ValueError):
logger.info(f'testing "%s"', string)
Expand All @@ -287,7 +284,7 @@ def test_handle_plus_syntax(self):

def test_parse_plus_syntax(self):
macro = parse("a + b")
self.assertEqual(macro.code, "modify(a,modify(b,hold()))")
self.assertEqual(macro.code, "hold_keys(a,b)")

# this is not erroneously recognized as "plus" syntax
macro = parse("key(a) # a + b")
Expand Down

0 comments on commit 1782b3c

Please sign in to comment.