Skip to content

Commit

Permalink
binops
Browse files Browse the repository at this point in the history
  • Loading branch information
spyoungtech committed Mar 1, 2022
1 parent 39a3426 commit 8a1f66d
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 2 deletions.
2 changes: 2 additions & 0 deletions ahk_ast/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,8 @@ class BinOp(Expression):
def __init__(self, op: str, left: Expression, right: Expression):
assert isinstance(op, str)
assert op in (
'**',
'//',
'+',
'-',
'*',
Expand Down
12 changes: 10 additions & 2 deletions ahk_ast/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,9 +71,9 @@ def seen_ASSIGN(self, p: YaccProduction) -> Any:
def assignment_statement(self, p: YaccProduction) -> Assignment:
return Assignment(location=p.location, value=p.expression)

@_('literal', 'location')
@_('literal', 'location', 'bin_op')
def expression(self, p: YaccProduction) -> Any:
self.expecting.pop()
# self.expecting.pop()
return p[0]

@_('INTEGER')
Expand Down Expand Up @@ -145,6 +145,14 @@ def function_call(self, p: YaccProduction) -> FunctionCall:
else None,
)

@_('PLUS', 'MINUS', 'TIMES', 'DIVIDE', 'INT_DIVIDE', 'EXP')
def bin_operator(self, p: YaccProduction) -> Any:
return p[0]

@_('expression [ WHITESPACE ] bin_operator [ WHITESPACE ] expression')
def bin_op(self, p: YaccProduction) -> BinOp:
return BinOp(op=p.bin_operator, left=p.expression0, right=p.expression1)

def error(self, token: Union[AHKToken, None]) -> NoReturn:
if token:
if self.expecting:
Expand Down
34 changes: 34 additions & 0 deletions tests/test_bin_op.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
import json
import os
import sys
from importlib.machinery import SourceFileLoader
from importlib.util import module_from_spec
from importlib.util import spec_from_file_location
from textwrap import dedent

import pytest

sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), '../')))
from ahk_ast import parser
from ahk_ast.model import *
from ahk_ast.tokenizer import tokenize

tests_path = os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(__file__)), 'examples'))


@pytest.mark.parametrize('op', argvalues=[('+',), ('-',), ('*',), ('/',), ('//',), ('**',)])
def test_math_binop(op):
op = op[0]
script = dedent(
f"""\
a := 1 {op} 1
"""
)
expected = Program(
Assignment(
location=Identifier(name='a'),
value=BinOp(left=Integer(value=1), right=Integer(value=1), op=op),
)
)
model = parser.parse(script)
assert model == expected

0 comments on commit 8a1f66d

Please sign in to comment.