Alexandru
Alexandru

Reputation: 25800

Grammar to parse a chess move using PEG

What is the correct grammar to parse a move in SAN format using PEG?

The solution I come up is

MOVE <- [NBRQK]? [a-h]? [1-8]? [-x]? [a-h] [1-8] [NBRQ]?

However, this seems wrong as it doesn't parse Nh4 because h matches the first optional file [a-h]? and the parser doesn't backtrack.

Other moves that should be correctly parsed are: a4, a3a4, xa4, a8Q, xa8Q, Nh4, Nxh4, Ngxh4, Ng3h4,Ngh4, N3h4, Ng3-h4, Ng3xh4, but (optionally) not -a4, N-h4.

Upvotes: 0

Views: 227

Answers (1)

Ira Baxter
Ira Baxter

Reputation: 95306

I've built algebraic notation parsers before.

Frankly, the grammar is pretty simple (as you show, didn't check details).

More importantly, I don't recall any need to backtrack, which is the point of using PEG. So you don't need a mechanism this complex.

In fact, "parsing" this is so simple that building a real parser seems like overkill; you can build an FSA to recognize it without much trouble.

Upvotes: -2

Related Questions