Skip to content

Commit

Permalink
Special case string handling for operator
Browse files Browse the repository at this point in the history
- First implemented for BinOp such that the original strings are
  preserved with quotes intact if they were part of a bianry operator
  expression, to present a more natural appearance for the final string.
  • Loading branch information
metatoaster committed Oct 8, 2021
1 parent 6c0ebbd commit 0097595
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 3 deletions.
2 changes: 1 addition & 1 deletion src/calmjs/parse/tests/test_unparsers_extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -601,7 +601,7 @@ def test_basic_operator_str(self):
a = 'hello' + ' ' + 'world';
""")
self.assertEqual(dict(unparser(ast)), {
'a': 'hello + + world',
'a': "'hello' + ' ' + 'world'",
})

def test_ternary_assignment(self):
Expand Down
21 changes: 19 additions & 2 deletions src/calmjs/parse/unparsers/extractor.py
Original file line number Diff line number Diff line change
Expand Up @@ -727,6 +727,23 @@ def __call__(self, walk, dispatcher, node):
yield next(dispatcher.token(None, node, self.value, None))


class OpString(Token):
"""
Special case for the BinOp/UnaryExpr, to ensure that the raw value
that was parsed into the ast node is returned instead of being
treated, such that the original expression have their quotes
preserved.
"""

def __call__(self, walk, dispatcher, node):
value = getattr(node, self.attr)
if isinstance(value, String):
yield next(dispatcher.token(None, node, value.value, None))
else:
for chunk in walk(dispatcher, value, token=self):
yield chunk


class RawBoolean(Attr):
"""
Simple yield the raw boolean value from the attribute.
Expand Down Expand Up @@ -890,9 +907,9 @@ def __call__(self, walk, dispatcher, node):
),),
),
'BinOp': (GroupAsStr((
Attr('left'), Text(value=' '),
OpString('left'), Text(value=' '),
Operator(attr='op'),
Text(value=' '), Attr('right'),
Text(value=' '), OpString('right'),
),),),
'UnaryExpr': (
# the default grouping required to ensure positive/negative
Expand Down

0 comments on commit 0097595

Please sign in to comment.