from simpleparse.parser import Parser
from simpleparse import dispatchprocessor
from simpleparse.common import numbers, chartypes
import time

definition = r"""
file  := (comment_line/command_line)+

<comment_line> := '**', -[\n]*, '\n'?,ws
command_line   := '*', name, ws, parameter_list?,ws, EOL?, (data/comment_line)*
data           := [0-9,-eE. \t\n]+

>parameter_list< := ',',ws, (parameter, ','?, ws)+

parameter := name, ws, '=', ws, (number/name), ws

name    := [a-zA-Z0-9-]+
<ws>    := [ \t]*
<EOL>   := '\n'
"""
p = Parser( definition, 'file')

class Handler( dispatchprocessor.DispatchProcessor ):
	def _m_float( self, taglist, text, left, right, subtags ):
		taglist.append( float( text[left:right]))
	def _m_parameter( self, taglist, text, left, right, subtags ):
		name, value = subtags
		taglist.append( (name,value))
	def _m_name( self, taglist, text, left, right, subtags ):
		taglist.append( text[left:right] )
	_m_command = _m_name
	def _m_command_line( self, taglist, text, left, right, subtags ):
		print 'command', left, left/float(len(text))#, len(text)
		del subtags[:]
	def _m_data_line( self, taglist, text, left, right, subtags ):
		taglist.extend( subtags )
		
##import psyco
##psyco.bind( Handler )
def gen_file(filename):
	fa=open(filename,'w')
	for i in range(400):
		fa.write('*LINE, Color =red, Thickness=3.1,\n')
		for j in range(500):
			fa.write('3.0000000,  2.0000000,  7.000000000\n')
			fa.write('13.0000000,  97.0000000,  -127.000000000,\n')
		for j in range(15):
			fa.write('** This is a comment\n')
			fa.write('     *** This is a comment, with a comma\n')
	fa.close()

def test( ):
	filename = "test.data"
	gen_file( filename )
	t = time.clock()
	data = open( filename ).read()
	success, results, current = p.parse(
		data,
		processor=Handler(),
##		production = 'file'
	)
	t = time.clock() - t
	print 'success', success, current#, results
	print 't=', t
	print 'speed=', current/t
	if current != len(data):
		print 'FAILED to parse whole stream'

if __name__ == "__main__":
	test()
	