parse.py 1.47 KB
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12
#!   /usr/bin/env   python
#    coding: utf8

import sys
from ply import lex, yacc

tokens = (
    'NUMBER',
    'REPEAT',
    'LPAREN',
    'RPAREN',
    'DASH',
13
    'TEST',
14 15 16 17 18 19 20
)

t_NUMBER = r'[0-9]+'
t_REPEAT = r'repeat'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_DASH   = r'-'
21
t_TEST   = r'test'
22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

t_ignore = ' \t'

def t_error(t):
    print 'Illegal character [%s]' % t.value[0]
    t.lexer.skip(1)

lexer = lex.lex()

def p_battery_sequence(p):
    '''battery : batch
               | batch battery'''
    if len(p) == 2:
        p[0] = [ p[1] ]
    else:
        p[0] = [ p[1] ] + p[2]

def p_batch_single(p):
    'batch : tst'
    p[0] = p[1]

def p_batch_loop(p):
    'batch : REPEAT NUMBER LPAREN battery RPAREN'
    p[0] = [ 'loop', p[2] ] + p[4]

def p_batch_range(p):
    'batch : tst DASH tst'
    p[0] = [ 'range', p[1], p[3] ]

def p_tst(p):
52 53 54
    '''tst : NUMBER
           | TEST NUMBER'''
    p[0] = p[len(p)-1]
55 56 57 58 59 60

def p_error(p):
    print 'syntax error!'

parser = yacc.yacc()

61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82
class Sequence(object):
    pass

class Battery(Sequence, list):
    def traverse(self):
        for item in self:
            print item

class Tst(Sequence):
    def traverse(self):
        print self.tag

class Loop(Sequence):
    def traverse(self):
        for i in range(self.number):
            self.sequence.traverse()

class Range(Sequence):
    def traverse(self):
        for i in range(self.fro, self.to+1):
            print i

83 84 85 86
if __name__ == '__main__':
    result = parser.parse(sys.argv[1])
    print result