#!/usr/bin/env python3

# To get your _virtual environment_ setup, make sure you have Python 3
# installed and then run the following on a Linux/Mac/Unix system:
#
#   $ python3 -m venv env-playground
#   $ source env-playground/bin/activate
#   $ python3 -m pip install -U pip wheel ply
#

import sys

import ply.lex as lex

# Adapted from https://www.dabeaz.com/ply/ply.html#ply_nn4

tokens = (
        'ID',
        'NUM',
        'PLUS',
        'MINUS',
        'STAR',
        'SLASH',
        'LPAREN',
        'RPAREN',
        )

t_PLUS      = r'\+'
t_MINUS     = r'-'
t_STAR      = r'\*'
t_SLASH     = r'/'
t_LPAREN    = r'\('
t_RPAREN    = r'\)'

def t_ID(t):
    r'[_a-zA-Z][_a-zA-Z0-9]*'
    return t

def t_NUM(t):
    r'\d+'
    t.value = int(t.value)
    return t

def t_newline(t):
    r'\n+'
    t.lexer.lineno += len(t.value)

t_ignore  = ' \t'

def t_error(t):
    print(f"Illegal character '{t.value[0]}'")
    t.lexer.skip(1)

###########

lexer = lex.lex()

def process(data):
    lexer.input(data)

    while True:
        tok = lexer.token()
        if not tok:
            # Reached end-of-input
            break

        print(f'\t{tok}')

if __name__ == '__main__':
    if len(sys.argv) > 1:
        for data in sys.argv[1:]:
            print(f'Input: {data}')
            process(data)
    else:
        while True:
            try:
                data = input('lexer> ')
            except (EOFError, KeyboardInterrupt):
                break

            if not data:
                continue

            process(data)
