Skip to content

Instantly share code, notes, and snippets.

@mtomwing
Created July 22, 2014 07:23
Show Gist options
  • Save mtomwing/ff7d297e381749d0c0df to your computer and use it in GitHub Desktop.
Save mtomwing/ff7d297e381749d0c0df to your computer and use it in GitHub Desktop.
import operator
from purplex import Lexer, Parser, TokenDef, attach
class RPNLexer(Lexer):
INTEGER = TokenDef(r'\d+')
MULTIPLY = TokenDef(r'\*')
DIVIDE = TokenDef(r'/')
PLUS = TokenDef(r'\+')
MINUS = TokenDef(r'-')
WHITESPACE = TokenDef(r'[\s\n]+', ignore=True)
def on_token(self, token):
if token.value.strip():
print('parsed token:', token.value)
class RPNParser(Parser):
LEXER = RPNLexer
START = 'e'
PRECEDENCE = (
('left', 'INTEGER'),
)
OPERATORS = {
'*': operator.mul,
'/': operator.ifloordiv,
'+': operator.add,
'-': operator.sub,
}
@attach('e : e e MULTIPLY')
@attach('e : e e DIVIDE')
@attach('e : e e PLUS')
@attach('e : e e MINUS')
def binop(self, *args):
return self.OPERATORS[args[2]](args[0], args[1])
@attach('e : INTEGER')
def integer(self, number):
return int(number)
if __name__ == '__main__':
line = input('>> ')
print('input is', line)
print(RPNParser().parse(line))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment