Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JEP-16 Arithmetic Expressions #294

Open
wants to merge 3 commits into
base: develop
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 1 commit
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
Prev Previous commit
JEP-16 Evaluates arithmetic expressions
  • Loading branch information
springcomp committed Oct 22, 2022
commit a99a6d88bb9c8052124af003a3a1ac280548800d
25 changes: 25 additions & 0 deletions jmespath/visitor.py
Original file line number Diff line number Diff line change
Expand Up @@ -107,6 +107,18 @@ class TreeInterpreter(Visitor):
'gte': operator.ge
}
_EQUALITY_OPS = ['eq', 'ne']
_ARITHMETIC_UNARY_FUNC = {
'minus': operator.neg,
'plus': lambda x: x
}
_ARITHMETIC_FUNC = {
'div': operator.floordiv,
'divide': operator.truediv,
'minus': operator.sub,
'modulo': operator.mod,
'multiply': operator.mul,
'plus': operator.add,
}
MAP_TYPE = dict

def __init__(self, options=None):
Expand Down Expand Up @@ -157,6 +169,19 @@ def visit_comparator(self, node, value):
return None
return comparator_func(left, right)

def visit_arithmetic_unary(self, node, value):
operation = self._ARITHMETIC_UNARY_FUNC[node['value']]
return operation(
self.visit(node['children'][0], value)
)

def visit_arithmetic(self, node, value):
operation = self._ARITHMETIC_FUNC[node['value']]
return operation(
self.visit(node['children'][0], value),
self.visit(node['children'][1], value)
)

def visit_current(self, node, value):
return value

Expand Down
62 changes: 62 additions & 0 deletions tests/compliance/arithmetic.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,62 @@
[
{
"given": {
"a": {
"b": 1
},
"c": {
"d": 2
}
},
"cases": [
{
"expression": "`1` + `2`",
"result": 3.0
},
{
"expression": "`1` - `2`",
"result": -1.0
},
{
"expression": "`2` * `4`",
"result": 8.0
},
{
"expression": "`2` × `4`",
"result": 8.0
},
{
"expression": "`2` / `3`",
"result": 0.6666666666666666
},
{
"expression": "`2` ÷ `3`",
"result": 0.6666666666666666
},
{
"expression": "`10` % `3`",
"result": 1.0
},
{
"expression": "`10` // `3`",
"result": 3.0
},
{
"expression": "-`1` - + `2`",
"result": -3.0
},
{
"expression": "{ ab: a.b, cd: c.d } | ab + cd",
"result": 3.0
},
{
"expression": "{ ab: a.b, cd: c.d } | ab + cd × cd",
"result": 5.0
},
{
"expression": "{ ab: a.b, cd: c.d } | (ab + cd) × cd",
"result": 6.0
}
]
}
]