Skip to content
Open
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
27 changes: 27 additions & 0 deletions fire/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,11 +105,16 @@ def _LiteralEval(value):
for index, subchild in enumerate(child):
if isinstance(subchild, ast.Name):
child[index] = _Replacement(subchild)
elif _IsNegativeBareword(subchild):
child[index] = _StrNode('-' + subchild.operand.id)

elif isinstance(child, ast.Name):
replacement = _Replacement(child)
setattr(node, field, replacement)

elif _IsNegativeBareword(child):
setattr(node, field, _StrNode('-' + child.operand.id))

# ast.literal_eval supports the following types:
# strings, bytes, numbers, tuples, lists, dicts, sets, booleans, and None
# (bytes and set literals only starting with Python 3.2)
Expand All @@ -130,3 +135,25 @@ def _Replacement(node):
if value in ('True', 'False', 'None'):
return node
return _StrNode(value)


def _IsNegativeBareword(node):
"""Returns whether node is a unary minus applied to a bare identifier.

For example, the token '-b' in '[a,-b,c]' parses as
ast.UnaryOp(op=USub, operand=ast.Name('b')). Since ast.literal_eval
can't negate a string, this can't simply be handled by replacing the
inner Name node with a string Constant (as _Replacement does) -- the
whole UnaryOp node needs to be replaced with a single string Constant
of '-' + the identifier's name.

Args:
node: An AST node.
Returns:
True if node is ast.UnaryOp(ast.USub, ast.Name) where the Name isn't
one of the builtin constants supported by literal_eval.
"""
return (isinstance(node, ast.UnaryOp)
and isinstance(node.op, ast.USub)
and isinstance(node.operand, ast.Name)
and node.operand.id not in ('True', 'False', 'None'))
6 changes: 6 additions & 0 deletions fire/parser_test.py
Original file line number Diff line number Diff line change
Expand Up @@ -96,6 +96,12 @@ def testDefaultParseValueLists(self):
def testDefaultParseValueBareWordsLists(self):
self.assertEqual(parser.DefaultParseValue('[one, 2, "3"]'), ['one', 2, '3'])

def testDefaultParseValueBareWordsListsWithLeadingHyphen(self):
self.assertEqual(parser.DefaultParseValue('[a,-b,c]'), ['a', '-b', 'c'])
self.assertEqual(parser.DefaultParseValue('[1,-2,3]'), [1, -2, 3])
self.assertIsInstance(parser.DefaultParseValue('[1,-2,3]')[1], int)
self.assertEqual(parser.DefaultParseValue('-b'), '-b')

def testDefaultParseValueDict(self):
self.assertEqual(
parser.DefaultParseValue('{"abc": 5, "123": 1}'), {'abc': 5, '123': 1})
Expand Down