[racket] parser-tools help
-----BEGIN PGP SIGNED MESSAGE-----
Hash: SHA1
On 30-11-11 14:33, Marijn wrote:
> Hi,
>
> I'm trying to use the parser-tools to parse the startup info for
> the Google AI Challenge, but I am not sure what I'm doing wrong.
I managed to get my code working, see below. (BTW parser gives a
really silly error-message when you have an end-clause like (end 'ready).)
> As a secondary question, given the repetitive nature of the code,
> how would one use macros to make it better?
I'd still be interested in how to do this.
Marijn
#lang racket
(require parser-tools/lex
(prefix-in re: parser-tools/lex-sre)
parser-tools/yacc)
(define-tokens number-group (number))
(define-tokens turn0-data-group
(turn
loadtime
turntime
rows
cols
turns
viewradius2
attackradius2
spawnradius2
player_seed))
(define-empty-tokens turn0-end-group (ready))
(define (turn0-lexer port)
((lexer
("turn" 'turn)
("loadtime" 'loadtime)
("turntime" 'turntime)
("rows" 'rows)
("cols" 'cols)
("turns" 'turns)
("viewradius2" 'viewradius2)
("attackradius2" 'attackradius2)
("spawnradius2" 'spawnradius2)
("player_seed" 'player_seed)
("ready" 'ready)
((re:+ (char-set "1234567890")) (token-number lexeme))
((re:+ whitespace) (turn0-lexer port))
)
port) )
(define turn0-parser
(let ((ret (hash)))
(parser
(tokens number-group turn0-data-group turn0-end-group)
(start data)
(end ready)
(grammar
(data ((datum) (hash (token-name $1) (token-value $1)))
((datum data) (hash-set $2 (token-name $1) (token-value $1)))
)
(datum ((turn number) (token-turn $2))
((loadtime number) (token-loadtime $2))
((turntime number) (token-turntime $2))
((rows number) (token-rows $2))
((cols number) (token-cols $2))
((turns number) (token-turns $2))
((viewradius2 number) (token-viewradius2 $2))
((attackradius2 number) (token-attackradius2 $2))
((spawnradius2 number) (token-spawnradius2 $2))
((player_seed number) (token-player_seed $2))
)
)
(error (lambda args (map displayln args))) )) )
(define (main port)
(write (turn0-parser (lambda () (turn0-lexer port)))))
(define input
(string-append
"turn 0 "
"loadtime 3000"
"turntime 1000"
"rows 20 "
"cols 20 "
"turns 500 "
"viewradius2 55 "
"attackradius2 5 "
"spawnradius2 1 "
"player_seed 42"
"ready") )
(main (open-input-string input))
-----BEGIN PGP SIGNATURE-----
Version: GnuPG v2.0.18 (GNU/Linux)
Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org/
iEYEARECAAYFAk7WS+QACgkQp/VmCx0OL2yTiwCbBa8h6aRAYGms+WtvGglntEc0
sKkAnizOfr61cvw1LQFY+VCgKhqXjxtq
=xqSK
-----END PGP SIGNATURE-----