6dcd13b5c9ad3a1d20b54352e47aa50f7699c224
[xboard.git] / parser.l
1 %a 10000
2 %o 10000
3 %e 2000
4 %k 2500
5 %p 7000
6 %n 1000
7 %{
8 /*
9  * parser.l -- lex parser of algebraic chess moves for XBoard
10  *
11  * Copyright 1991 by Digital Equipment Corporation, Maynard,
12  * Massachusetts.
13  *
14  * Enhancements Copyright 1992-2001, 2002, 2003, 2004, 2005,
15  * 2006, 2007, 2008, 2009 Free Software Foundation, Inc.
16  *
17  * The following terms apply to Digital Equipment Corporation's copyright
18  * interest in XBoard:
19  * ------------------------------------------------------------------------
20  * All Rights Reserved
21  *
22  * Permission to use, copy, modify, and distribute this software and its
23  * documentation for any purpose and without fee is hereby granted,
24  * provided that the above copyright notice appear in all copies and that
25  * both that copyright notice and this permission notice appear in
26  * supporting documentation, and that the name of Digital not be
27  * used in advertising or publicity pertaining to distribution of the
28  * software without specific, written prior permission.
29  *
30  * DIGITAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS SOFTWARE, INCLUDING
31  * ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS, IN NO EVENT SHALL
32  * DIGITAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR
33  * ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS,
34  * WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION,
35  * ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS
36  * SOFTWARE.
37  * ------------------------------------------------------------------------
38  *
39  * The following terms apply to the enhanced version of XBoard
40  * distributed by the Free Software Foundation:
41  * ------------------------------------------------------------------------
42  *
43  * GNU XBoard is free software: you can redistribute it and/or modify
44  * it under the terms of the GNU General Public License as published by
45  * the Free Software Foundation, either version 3 of the License, or (at
46  * your option) any later version.
47  *
48  * GNU XBoard is distributed in the hope that it will be useful, but
49  * WITHOUT ANY WARRANTY; without even the implied warranty of
50  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
51  * General Public License for more details.
52  *
53  * You should have received a copy of the GNU General Public License
54  * along with this program. If not, see http://www.gnu.org/licenses/.  
55  *
56  *------------------------------------------------------------------------
57  ** See the file ChangeLog for a revision history.  */
58
59 /* This parser handles all forms of promotion.
60  * The parser resolves ambiguous moves by searching and check-testing.
61  * It also parses comments of the form [anything] or (anything).
62  *
63  * [HGM] Parser extensively modified for bigger boards, Shogi-like syntax,
64  * and unknow pieces. All pieces are now mandatory upper case, but can be
65  * any letter A-Z. Files must be lower case (as before), but can run upto 'l'.
66  * Ranks can be 0-9. The parser returns 0 for off-board files and ranks.
67  * For an unknown piece (as mover or promotion piece) it returns
68  * IllegalMove, like it does when the piece doesn't match.
69  * Promotions can now also be appended Shogi-style, a bare '=' or '+',
70  * and this is then returned as promotion character. The piece indicator
71  * can be prefixed by a '+' to indicate it is a promoted piece.
72  */
73
74 #include "config.h"
75
76 #define NO_CONSTRAINT   -1
77 #undef YYLMAX
78 #define YYLMAX                  4096
79 #define UNPUT_BUF_SIZE          YYLMAX
80
81 #ifdef FLEX_SCANNER
82 /* yytext is probably a char*, but could be a char[].  yy_text is set
83    in YY_DECL below, because if yytext is a char*, its value is not
84    constant. */
85 char *yy_text;
86 #else /*!FLEX_SCANNER*/
87 /* yytext is definitely a char[], so yy_text can be set here, statically. */
88 char *yy_text = (char *) yytext;
89 #endif
90
91 #ifdef FLEX_SCANNER
92 /* This is flex */
93 /* [AP] use prototypes in function declarations */
94 #define YY_USE_PROTOS
95
96 #ifdef YY_USE_PROTOS
97 #define YY_PROTO(proto) proto
98 #else
99 #define YY_PROTO(proto) ()
100 #endif
101 /* end of [AP] fix */
102
103 #undef YY_INPUT
104 #define YY_INPUT(buf, result, max_size) my_yy_input(buf, &result, max_size)
105 #undef YY_DECL
106 #define YY_DECL                     \
107     int _yylex YY_PROTO((void));    \
108     int yylex YY_PROTO((void))      \
109     {                               \
110         int result = _yylex();      \
111         yy_text = (char *) yytext;  \
112         return(result);             \
113     }                               \
114     int _yylex YY_PROTO((void))
115 #else
116 /* This is lex */
117 #undef input
118 #undef output
119 #undef unput
120 #endif
121
122 /* The includes must be here, below the #undef input */
123
124 #include <ctype.h>
125
126 #if STDC_HEADERS
127 # include <stdlib.h>
128 # include <string.h>
129 #else /* not STDC_HEADERS */
130 # if HAVE_STRING_H
131 #  include <string.h>
132 # else /* not HAVE_STRING_H */
133 #  include <strings.h>
134 # endif /* not HAVE_STRING_H */
135 #endif /* not STDC_HEADERS */
136
137 #if HAVE_UNISTD_H
138 # include <unistd.h>
139 #endif
140
141 #if defined(_amigados)
142 # include <errno.h>
143 # if HAVE_FCNTL_H
144 #  include <fcntl.h>    /*  isatty() prototype  */
145 # endif /*  HAVE_FCNTL_H        */
146 #endif  /*  defined(_amigados)  */
147
148 #include "common.h"
149 #include "backend.h"
150 #include "frontend.h"
151 #include "parser.h"
152 #include "moves.h"
153
154 extern int PosFlags P((int));
155
156 extern Board    boards[MAX_MOVES];
157 int             yyboardindex;
158 int             yyskipmoves = FALSE;
159 char            currentMoveString[YYLMAX];
160 #ifndef FLEX_SCANNER
161 char            unputBuffer[UNPUT_BUF_SIZE];
162 int             unputCount = 0;
163 #endif
164
165 #ifdef FLEX_SCANNER
166 void my_yy_input P((char *buf, int *result, int max_size));
167 #else /*!FLEX_SCANNER*/
168 static int input P((void));
169 static void output P((int ch));
170 static void unput P((int ch));
171 int yylook P((void));
172 int yyback P((int *, int));
173 #endif
174 #undef yywrap
175 int yywrap P((void));
176 extern void CopyBoard P((Board to, Board from));
177
178 %}
179 %%
180
181 "+"?[A-Z][/]?[a-l][0-9][xX:-]?[a-l][0-9]((=?\(?[A-Z]\)?)|[=+])? {
182     /*
183      * Fully-qualified algebraic move, possibly with promotion
184      */
185     int skip1 = 0, skip2 = 0, skip3 = 0, promoted = 0;
186     ChessSquare piece;
187     ChessMove result;
188     char c;
189     
190     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
191
192     if (yytext[0] == '+') skip1 = skip3 = promoted = 1; /* [HGM] Shogi promoted */
193
194     /* remove the / */
195     if (yytext[1+skip1] == '/')  skip1++; 
196     
197     /* remove the [xX:-] */
198     if ((yytext[3+skip1] == 'x') || (yytext[3+skip1] == 'X') ||
199         (yytext[3+skip1] == '-') || (yytext[3+skip1] == ':')) skip2 = 1;
200     
201     currentMoveString[0] = yytext[1+skip1];
202     currentMoveString[1] = yytext[2+skip1];
203     currentMoveString[2] = yytext[3+skip1+skip2];
204     currentMoveString[3] = yytext[4+skip1+skip2];
205     currentMoveString[4] = NULLCHAR;
206     
207     if (appData.debugMode) {
208         fprintf(debugFP, "Parser Qa1b2: yyleng=%d\n",
209         yyleng);
210     }
211
212     if (yyleng-skip1-skip2 > 5) { char c;
213         if (yytext[yyleng-1] == ')') {
214             c = currentMoveString[4] = ToLower(yytext[yyleng-2]);
215         } else {
216             c = currentMoveString[4] = ToLower(yytext[yyleng-1]);
217         }
218         if(c == '+' && gameInfo.variant != VariantShogi) c = currentMoveString[4] = NULLCHAR; // + means check outside Shogi
219         currentMoveString[5] = NULLCHAR;
220     }
221
222     if (appData.debugMode) {
223         fprintf(debugFP, "parser: %s\n", currentMoveString);
224     }
225     /* [HGM] do not allow values beyond board size */
226     if(currentMoveString[1] - ONE >= BOARD_HEIGHT ||
227        currentMoveString[1] - ONE <  0            ||
228        currentMoveString[0] - AAA >= BOARD_RGHT   ||
229        currentMoveString[3] - ONE >= BOARD_HEIGHT ||
230        currentMoveString[3] - ONE <  0            ||
231        currentMoveString[2] - AAA >= BOARD_RGHT   ||
232        currentMoveString[0] - AAA <  BOARD_LEFT   ||
233        currentMoveString[2] - AAA <  BOARD_LEFT     )
234       return ImpossibleMove;
235
236     piece = boards[yyboardindex]
237       [currentMoveString[1] - ONE][currentMoveString[0] - AAA];
238     if(PieceToChar(piece) == '+' && appData.icsActive) promoted = 1, yytext[skip3] = PieceToChar(DEMOTED piece); // trust ICS
239     if(promoted) piece = (ChessSquare) (DEMOTED piece);
240     c = PieceToChar(piece);
241     if(c == '~') c = PieceToChar((ChessSquare) (DEMOTED piece));
242     if (ToLower(yytext[skip3]) != ToLower(c))
243       return (int) IllegalMove;
244
245     result = LegalityTest(boards[yyboardindex],
246                           PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: might think we can e.p.!
247                           currentMoveString[1] - ONE,
248                           currentMoveString[0] - AAA,
249                           currentMoveString[3] - ONE,
250                           currentMoveString[2] - AAA,
251                           currentMoveString[4]);
252
253     if (currentMoveString[4] == NULLCHAR) {
254       if(result == WhitePromotion  || result == BlackPromotion) {
255         if(gameInfo.variant == VariantCourier || gameInfo.variant == VariantShatranj)
256             currentMoveString[4] = PieceToChar(BlackFerz);
257         else if(gameInfo.variant == VariantGreat)
258             currentMoveString[4] = PieceToChar(BlackMan);
259         else if(gameInfo.variant == VariantShogi)
260             currentMoveString[4] = '+';
261         else
262             currentMoveString[4] = PieceToChar(BlackQueen);
263       } else if(result == WhiteNonPromotion  || result == BlackNonPromotion)
264             currentMoveString[4] = '=';
265       currentMoveString[5] = NULLCHAR;
266     }
267
268     return (int) result;
269 }
270
271 [a-l][0-9][xX:-]?[a-l][0-9]((=?\(?[A-Za-z]\)?)|[=+])?      {
272     /*
273      * Simple algebraic move, possibly with promotion
274      * [HGM] Engine moves are received in this format, with lower-case promoChar!
275      */
276     int skip = 0;
277     ChessMove result;
278
279     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
280
281     /* remove the [xX:-] */
282     if ((yytext[2] == 'x') || (yytext[2] == 'X') ||
283         (yytext[2] == '-') || (yytext[2] == ':')) skip = 1;
284
285     currentMoveString[0] = yytext[0];
286     currentMoveString[1] = yytext[1];
287     currentMoveString[2] = yytext[2+skip];
288     currentMoveString[3] = yytext[3+skip];
289     currentMoveString[4] = NULLCHAR;
290
291     if (yyleng-skip > 4) { char c;
292         if (yytext[yyleng-1] == ')') {
293             c = currentMoveString[4] = ToLower(yytext[yyleng-2]);
294         } else {
295             c = currentMoveString[4] = ToLower(yytext[yyleng-1]);
296         }
297         if(c == '+' && gameInfo.variant != VariantShogi) c = currentMoveString[4] = NULLCHAR; // + means check outside Shogi
298         currentMoveString[5] = NULLCHAR;
299     }
300
301     /* [HGM] do not allow values beyond board size */
302     if(currentMoveString[1] - ONE >= BOARD_HEIGHT ||
303        currentMoveString[1] - ONE <  0            ||
304        currentMoveString[0] - AAA >= BOARD_RGHT   ||
305        currentMoveString[3] - ONE >= BOARD_HEIGHT ||
306        currentMoveString[3] - ONE <  0            ||
307        currentMoveString[2] - AAA >= BOARD_RGHT   ||
308        currentMoveString[0] - AAA <  BOARD_LEFT   ||
309        currentMoveString[2] - AAA <  BOARD_LEFT     )
310       return ImpossibleMove;
311
312     result = LegalityTest(boards[yyboardindex],
313                           PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: might think we can e.p.!
314                           currentMoveString[1] - ONE,
315                           currentMoveString[0] - AAA,
316                           currentMoveString[3] - ONE,
317                           currentMoveString[2] - AAA,
318                           currentMoveString[4]);
319
320     if (currentMoveString[4] == NULLCHAR) {
321       if(result == WhitePromotion  || result == BlackPromotion) {
322         if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
323             currentMoveString[4] = PieceToChar(BlackFerz);
324         else if(gameInfo.variant == VariantGreat)
325             currentMoveString[4] = PieceToChar(BlackMan);
326         else if(gameInfo.variant == VariantShogi)
327             currentMoveString[4] = '+'; // Queen might not be defined in mini variants!
328         else
329             currentMoveString[4] = PieceToChar(BlackQueen);
330       } else if(result == WhiteNonPromotion  || result == BlackNonPromotion)
331             currentMoveString[4] = '=';
332       currentMoveString[5] = NULLCHAR;
333     } else if(appData.testLegality && // strip off unnecessary and false promo characters
334        !(result == WhitePromotion  || result == BlackPromotion ||
335          result == WhiteNonPromotion || result == BlackNonPromotion)) currentMoveString[4] = NULLCHAR;
336
337     return (int) result;
338 }
339
340 [A-L][0-9][xX:-]?[A-L][0-9]      {
341     /*
342      * Simple algebraic move, in capitals
343      * [HGM] Some Xiangqi engines use this format ('ICCS notation'). So no promotions!
344      */
345     int skip = 0;
346     ChessMove result;
347
348     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
349
350     /* remove the [xX:-] */
351     if ((yytext[2] == 'x') || (yytext[2] == 'X') ||
352         (yytext[2] == '-') || (yytext[2] == ':')) skip = 1;
353
354     currentMoveString[0] = yytext[0]+32;
355     currentMoveString[1] = yytext[1];
356     currentMoveString[2] = yytext[2+skip]+32;
357     currentMoveString[3] = yytext[3+skip];
358     currentMoveString[4] = NULLCHAR;
359
360     /* [HGM] do not allow values beyond board size */
361     if(currentMoveString[1] - ONE >= BOARD_HEIGHT ||
362        currentMoveString[1] - ONE <  0            ||
363        currentMoveString[0] - AAA >= BOARD_RGHT   ||
364        currentMoveString[3] - ONE >= BOARD_HEIGHT ||
365        currentMoveString[3] - ONE <  0            ||
366        currentMoveString[2] - AAA >= BOARD_RGHT   ||
367        currentMoveString[0] - AAA <  BOARD_LEFT   ||
368        currentMoveString[2] - AAA <  BOARD_LEFT     )
369       return ImpossibleMove;
370
371     result = LegalityTest(boards[yyboardindex],
372                           PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: might think we can e.p.!
373                           currentMoveString[1] - ONE,
374                           currentMoveString[0] - AAA,
375                           currentMoveString[3] - ONE,
376                           currentMoveString[2] - AAA,
377                           currentMoveString[4]);
378
379     return (int) result;
380 }
381
382 [a-l][0-9]((=?\(?[A-Za-z]\)?)|[=+])?       {
383     /*
384      * Pawn move, possibly with promotion
385      */
386     DisambiguateClosure cl;
387     int skip = 0; char c;
388
389     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
390
391     /* remove the =() */
392     if (yytext[2] == '=' && yytext[3] != NULLCHAR) skip++;
393     if (yytext[2+skip] == '(') skip++;
394
395     cl.pieceIn = WhiteOnMove(yyboardindex) ? WhitePawn : BlackPawn;
396     cl.rfIn = -1;
397     cl.ffIn = yytext[0] - AAA;
398     cl.rtIn = yytext[1] - ONE;
399     cl.ftIn = yytext[0] - AAA;
400     cl.promoCharIn = ToLower(yytext[2+skip]);
401     if(cl.promoCharIn == '+' && gameInfo.variant != VariantShogi) cl.promoCharIn = NULLCHAR; // + means check outside Shogi
402
403     /* [HGM] do not allow values beyond board size */
404     if(cl.rtIn >= BOARD_HEIGHT ||
405        cl.rtIn <  0            ||
406        cl.ffIn >= BOARD_RGHT   ||
407        cl.ftIn <  BOARD_LEFT     )
408       return ImpossibleMove;
409
410     Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
411
412     currentMoveString[0] = cl.ff + AAA;
413     currentMoveString[1] = cl.rf + ONE;
414     currentMoveString[2] = cl.ft + AAA;
415     currentMoveString[3] = cl.rt + ONE;
416     currentMoveString[4] = cl.promoChar;
417     currentMoveString[5] = NULLCHAR;
418
419     return (int) cl.kind;
420 }
421
422
423 (ab|bc|cd|de|ef|fg|gh|hi|ij|jk|kl|lk|kj|ji|ih|hg|gf|fe|ed|dc|cb|ba|aa|bb|cc|dd|ee|ff|gg|hh|ii|jj|kk|ll|([a-l][xX:-][a-l]))((=?\(?[A-Z]\)?)|ep|"e.p."|=)? {
424     /*
425      * Pawn capture, possibly with promotion, possibly ambiguous
426      */
427     DisambiguateClosure cl;
428     int skip1 = 0, skip2 = 0; char c;
429
430     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
431
432     /* remove trailing ep or e.p. (nonstandard PGN) */
433     if (yytext[yyleng-1] == 'p') {
434       yyleng -= 2;
435       yytext[yyleng] = NULLCHAR;
436     } else if (yytext[yyleng-1] == '.') {
437       yyleng -= 4;
438       yytext[yyleng] = NULLCHAR;
439     }
440
441     /* remove the [xX:-] and =() */
442     if ((yytext[1] == 'x') || (yytext[1] == 'X')
443         || (yytext[1] == ':') || (yytext[1] == '-')) skip1 = 1;
444     if (yytext[2+skip1] == '=' && yytext[3+skip1] != NULLCHAR) skip2++;
445     if (yytext[2+skip1+skip2] == '(') skip2++;
446
447     cl.pieceIn = WhiteOnMove(yyboardindex) ? WhitePawn : BlackPawn;
448     cl.rfIn = -1;
449     cl.ffIn = yytext[0] - AAA;
450     cl.rtIn = -1;
451     cl.ftIn = yytext[1+skip1] - AAA;
452     cl.promoCharIn = yytext[2+skip1+skip2];
453     if(cl.promoCharIn == '+' && gameInfo.variant != VariantShogi) cl.promoCharIn = NULLCHAR; // + means check outside Shogi
454
455     /* [HGM] do not allow values beyond board size */
456     if(cl.ffIn >= BOARD_RGHT  ||
457        cl.ffIn <  BOARD_LEFT  ||
458        cl.ftIn >= BOARD_RGHT  ||
459        cl.ftIn <  BOARD_LEFT     )
460       return ImpossibleMove;
461
462     Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
463
464     currentMoveString[0] = cl.ff + AAA;
465     currentMoveString[1] = cl.rf + ONE;
466     currentMoveString[2] = cl.ft + AAA;
467     currentMoveString[3] = cl.rt + ONE;
468     currentMoveString[4] = cl.promoChar;
469     currentMoveString[5] = NULLCHAR;
470
471     return (int) cl.kind;
472 }
473
474 [a-l][xX:]?[a-l][0-9]((=?\(?[A-Z]\)?)|ep|"e.p."|[=+])? {
475     /*
476      * unambiguously abbreviated Pawn capture, possibly with promotion
477      */
478     int skip = 0;
479     ChessMove result; char c;
480
481     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
482
483     /* remove trailing ep or e.p. (nonstandard PGN) */
484     if (yytext[yyleng-1] == 'p') {
485       yyleng -= 2;
486       yytext[yyleng] = NULLCHAR;
487     } else if (yytext[yyleng-1] == '.') {
488       yyleng -= 4;
489       yytext[yyleng] = NULLCHAR;
490     }
491
492     /* remove the [xX:-] */
493     if ((yytext[1] == 'x') || (yytext[1] == 'X')
494         || (yytext[1] == ':') || (yytext[1] == '-')) skip = 1;
495
496     currentMoveString[0] = yytext[0];
497     currentMoveString[2] = yytext[1+skip];
498     currentMoveString[3] = yytext[2+skip];
499
500     /* [HGM] do not allow values beyond board size */
501     if(currentMoveString[0] - AAA >= BOARD_RGHT   ||
502        currentMoveString[3] - ONE >= BOARD_HEIGHT ||
503        currentMoveString[3] - ONE <  0            ||
504        currentMoveString[2] - AAA >= BOARD_RGHT   ||
505        currentMoveString[0] - AAA <  BOARD_LEFT   ||
506        currentMoveString[2] - AAA <  BOARD_LEFT     )
507       return ImpossibleMove;
508
509     if (gameInfo.variant == VariantXiangqi && /* [HGM] In Xiangqi rank stays same */
510          currentMoveString[0] != currentMoveString[2] ) {
511         currentMoveString[1] = yytext[2+skip];
512     } else 
513     if (WhiteOnMove(yyboardindex)) {
514         if (yytext[2+skip] == ONE) return (int) ImpossibleMove;
515         currentMoveString[1] = yytext[2+skip] - 1;
516         if(boards[yyboardindex][currentMoveString[1]-ONE][currentMoveString[0]-AAA] != WhitePawn) 
517                 return ImpossibleMove;
518     } else {
519         currentMoveString[1] = currentMoveString[3] + 1;
520         if (currentMoveString[3] == ONE+BOARD_HEIGHT-1) return (int) ImpossibleMove;
521         if(boards[yyboardindex][currentMoveString[1]-ONE][currentMoveString[0]-AAA] != BlackPawn) 
522                 return ImpossibleMove;
523     }
524     if (yyleng-skip > 3) {
525         if (yytext[yyleng-1] == ')')
526           c = currentMoveString[4] = ToLower(yytext[yyleng-2]);
527         else
528           c = currentMoveString[4] = ToLower(yytext[yyleng-1]);
529         currentMoveString[5] = NULLCHAR;
530         if(c == '+' && gameInfo.variant != VariantShogi) c = currentMoveString[4] = NULLCHAR; // + means check outside Shogi
531     } else {
532         currentMoveString[4] = NULLCHAR;
533     }
534
535     result = LegalityTest(boards[yyboardindex],
536                           PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: might think we can e.p.!
537                           currentMoveString[1] - ONE,
538                           currentMoveString[0] - AAA,
539                           currentMoveString[3] - ONE,
540                           currentMoveString[2] - AAA,
541                           currentMoveString[4]);
542
543     if (currentMoveString[4] == NULLCHAR) {
544       if(result == WhitePromotion  || result == BlackPromotion) {
545         currentMoveString[4] = PieceToChar(BlackQueen);
546         // [HGM] shatranj: take care of variants without Queen
547         if(gameInfo.variant == VariantShatranj || gameInfo.variant == VariantCourier || gameInfo.variant == VariantMakruk)
548             currentMoveString[4] = PieceToChar(BlackFerz);
549         if(gameInfo.variant == VariantGreat)
550             currentMoveString[4] = PieceToChar(BlackMan);
551         if(gameInfo.variant == VariantShogi)
552             currentMoveString[4] = '+';
553       } else if(result == WhiteNonPromotion  || result == BlackNonPromotion)
554             currentMoveString[4] = '=';
555       currentMoveString[5] = NULLCHAR;
556     }
557
558     if (result != IllegalMove) return (int) result;
559
560     /* Special case: improperly written en passant capture */
561     if (WhiteOnMove(yyboardindex)) {
562         if (currentMoveString[3] == '5') {
563             currentMoveString[1] = '5';
564             currentMoveString[3] = '6';
565         } else {
566             return (int) IllegalMove;
567         }
568     } else {
569         if (currentMoveString[3] == '4') {
570             currentMoveString[1] = '4';
571             currentMoveString[3] = '3';
572         } else {
573             return (int) IllegalMove;
574         }
575     }
576
577     result = LegalityTest(boards[yyboardindex],
578                           PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: might think we can e.p.!
579                           currentMoveString[1] - ONE,
580                           currentMoveString[0] - AAA,
581                           currentMoveString[3] - ONE,
582                           currentMoveString[2] - AAA,
583                           currentMoveString[4]);
584
585     if (result == WhiteCapturesEnPassant || result == BlackCapturesEnPassant)
586       return (int) result;
587     else
588       return (int) IllegalMove;
589 }
590
591 "+"?[A-Z][xX:-]?[a-l][0-9]((=?\(?[A-Z]\)?)|[=+])?  {
592     /*
593      * piece move, possibly ambiguous
594      */
595     DisambiguateClosure cl;
596     int skip = 0, skip2 = 0, promoted = 0;
597
598     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
599
600     if(yytext[0] == '+') promoted = skip = skip2 = 1;
601
602     /* remove the [xX:-] */
603     if ((yytext[1+skip] == 'x') || (yytext[1+skip] == 'X')
604         || (yytext[1+skip] == ':') || (yytext[1+skip] == '-')) skip++;
605
606     if (WhiteOnMove(yyboardindex)) {
607         cl.pieceIn = CharToPiece(ToUpper(yytext[skip2]));
608     } else {
609         cl.pieceIn = CharToPiece(ToLower(yytext[skip2]));
610     }
611     if(promoted) cl.pieceIn = (ChessSquare) (PROMOTED cl.pieceIn);
612
613     cl.rfIn = -1;
614     cl.ffIn = -1;
615     cl.rtIn = yytext[2+skip] - ONE;
616     cl.ftIn = yytext[1+skip] - AAA;
617     cl.promoCharIn = NULLCHAR;
618
619     if(yyleng-skip > 3 && gameInfo.variant == VariantShogi) /* [HGM] can have Shogi-style promotion */
620         cl.promoCharIn = yytext[yyleng-1-(yytext[yyleng-1]==')')];
621     if(cl.promoCharIn == '+' && gameInfo.variant != VariantShogi) cl.promoCharIn = NULLCHAR; // + means check outside Shogi
622
623     if (appData.debugMode) {
624         fprintf(debugFP, "Parser Qa1: yyleng=%d,  %d(%d,%d)-(%d,%d) = %d (%c)\n",
625         yyleng,
626         cl.pieceIn,cl.ffIn,cl.rfIn,cl.ftIn,cl.rtIn,cl.promoCharIn,cl.promoCharIn?cl.promoCharIn:' ');
627     }
628
629     /* [HGM] but do not allow values beyond board size */
630     if(cl.rtIn >= BOARD_HEIGHT ||
631        cl.rtIn <  0            ||
632        cl.ftIn >= BOARD_RGHT   ||
633        cl.ftIn <  BOARD_LEFT     )
634       return ImpossibleMove;
635
636     Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
637
638     currentMoveString[0] = cl.ff + AAA;
639     currentMoveString[1] = cl.rf + ONE;
640     currentMoveString[2] = cl.ft + AAA;
641     currentMoveString[3] = cl.rt + ONE;
642     currentMoveString[4] = cl.promoChar;
643     currentMoveString[5] = NULLCHAR;
644
645     return (int) cl.kind;
646 }
647
648 "+"?[A-Z][a-l0-9][xX:-]?[a-l][0-9]((=?\(?[A-Z]\)?)|[=+])?   {
649     /*
650      * piece move with rank or file disambiguator
651      */
652     DisambiguateClosure cl;
653     int skip = 0, skip2 = 0; int promoted=0;
654
655     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
656
657     if(yytext[0]=='+') promoted = skip = skip2 = 1;
658
659     /* remove the [xX:-] */
660     if ((yytext[2+skip] == 'x') || (yytext[2+skip] == 'X')
661         || (yytext[2+skip] == ':') || (yytext[2+skip] == '-')) skip++;
662
663     if (WhiteOnMove(yyboardindex)) {
664         cl.pieceIn = CharToPiece(ToUpper(yytext[skip2]));
665     } else {
666         cl.pieceIn = CharToPiece(ToLower(yytext[skip2]));
667     }
668     if(promoted) cl.pieceIn = (ChessSquare) (PROMOTED cl.pieceIn);
669
670     if (isalpha(yytext[1+skip2])) {
671         cl.rfIn = -1;
672         cl.ffIn = yytext[1+skip2] - AAA;
673        
674         if(cl.ffIn >= BOARD_RGHT ||
675            cl.ffIn <  BOARD_LEFT   ) return 0;
676     } else {
677         cl.rfIn = yytext[1+skip2] - ONE;
678         cl.ffIn = -1;
679         if(cl.rfIn >= BOARD_HEIGHT ||
680            cl.rfIn <  0) return 0;
681     }
682     cl.rtIn = yytext[3+skip] - ONE;
683     cl.ftIn = yytext[2+skip] - AAA;
684     cl.promoCharIn = NULLCHAR;
685
686     if(yyleng-skip > 4) /* [HGM] can have Shogi-style promotion */
687         cl.promoCharIn = yytext[yyleng-1-(yytext[yyleng-1]==')')];
688     if(cl.promoCharIn == '+' && gameInfo.variant != VariantShogi) cl.promoCharIn = NULLCHAR; // + means check outside Shogi
689
690     /* [HGM] do not allow values beyond board size */
691     if(cl.rtIn >= BOARD_HEIGHT ||
692        cl.rtIn <  0            ||
693        cl.ftIn >= BOARD_RGHT   ||
694        cl.ftIn <  BOARD_LEFT     )
695       return ImpossibleMove;
696
697     Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
698
699     currentMoveString[0] = cl.ff + AAA;
700     currentMoveString[1] = cl.rf + ONE;
701     currentMoveString[2] = cl.ft + AAA;
702     currentMoveString[3] = cl.rt + ONE;
703     currentMoveString[4] = cl.promoChar;
704     currentMoveString[5] = NULLCHAR;
705
706     return (int) cl.kind;
707 }
708
709 000|0-0-0|ooo|OOO|o-o-o|O-O-O   {
710     int rf, ff, rt, ft;
711
712     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
713
714     /* [HGM] all squares referenced to board edges in stead of absolute */
715     if (WhiteOnMove(yyboardindex)) {
716         if (boards[yyboardindex][0][(BOARD_WIDTH-1)>>1] == WhiteKing) {
717             /* ICS wild castling */
718             rf = 0;
719             ff = (BOARD_WIDTH-1)>>1;
720             rt = 0;
721             ft = BOARD_RGHT-3;
722         } else {
723             rf = 0;
724             ff = BOARD_WIDTH>>1;
725             rt = 0;
726             ft = BOARD_LEFT+2;
727         }
728     } else{ 
729         if (boards[yyboardindex][BOARD_HEIGHT-1][(BOARD_WIDTH-1)>>1] == BlackKing) {
730             /* ICS wild castling */
731             rf = BOARD_HEIGHT-1;
732             ff = (BOARD_WIDTH-1)>>1;
733             rt = BOARD_HEIGHT-1;
734             ft = BOARD_RGHT-3;
735         } else {
736             rf = BOARD_HEIGHT-1;
737             ff = BOARD_WIDTH>>1;
738             rt = BOARD_HEIGHT-1;
739             ft = BOARD_LEFT+2;
740         }
741     }
742     if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
743
744         if (WhiteOnMove(yyboardindex)) {
745             ff = initialRights[2];
746             ft = initialRights[1];
747         } else {
748             ff = initialRights[5];
749             ft = initialRights[4];
750         }
751         if (appData.debugMode) 
752         {
753           fprintf(debugFP, "Parser FRC long %d %d\n", ff, ft);
754         };
755         if(ff < 0 || ft < 0) return 0;
756     }
757     sprintf(currentMoveString, "%c%c%c%c",ff+AAA,rf+ONE,ft+AAA,rt+ONE);
758     if (appData.debugMode) {
759         fprintf(debugFP, "long castling %d %d\n", ff, ft);
760     }
761     return (int) LegalityTest(boards[yyboardindex],
762                               PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: e.p.!
763                               rf, ff, rt, ft, NULLCHAR);
764 }
765
766 00|0-0|oo|OO|o-o|O-O    {
767     int rf, ff, rt, ft;
768
769     if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
770
771     if (WhiteOnMove(yyboardindex)) {
772         if (boards[yyboardindex][0][(BOARD_WIDTH-1)>>1] == WhiteKing) {
773             /* ICS wild castling */
774             rf = 0;
775             ff = (BOARD_WIDTH-1)>>1;
776             rt = 0;
777             ft = BOARD_LEFT+1;
778         } else {
779             rf = 0;
780             ff = BOARD_WIDTH>>1;
781             rt = 0;
782             ft = BOARD_RGHT-2;
783         }
784     } else {
785         if (boards[yyboardindex][BOARD_HEIGHT-1][(BOARD_WIDTH-1)>>1] == BlackKing) {
786             /* ICS wild castling */
787             rf = BOARD_HEIGHT-1;
788             ff = (BOARD_WIDTH-1)>>1;
789             rt = BOARD_HEIGHT-1;
790             ft = BOARD_LEFT+1;
791         } else {
792             rf = BOARD_HEIGHT-1;
793             ff = BOARD_WIDTH>>1;
794             rt = BOARD_HEIGHT-1;
795             ft = BOARD_RGHT-2;
796         }
797     }
798     if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
799         if (WhiteOnMove(yyboardindex)) {
800             ff = initialRights[2];
801             ft = initialRights[0];
802         } else {
803             ff = initialRights[5];
804             ft = initialRights[3];
805         }
806     if (appData.debugMode) {
807         fprintf(debugFP, "Parser FRC short %d %d\n", ff, ft);
808     }
809         if(ff < 0 || ft < 0) return 0;
810     }
811     sprintf(currentMoveString, "%c%c%c%c",ff+AAA,rf+ONE,ft+AAA,rt+ONE);
812     if (appData.debugMode) {
813         fprintf(debugFP, "short castling %d %d\n", ff, ft);
814     }
815
816     return (int) LegalityTest(boards[yyboardindex],
817                               PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: e.p.!
818                               rf, ff, rt, ft, NULLCHAR);
819 }
820
821 [A-Za-z][@*][a-l][0-9] {
822     /* Bughouse piece drop. */
823     currentMoveString[1] = '@';
824     currentMoveString[2] = yytext[2];
825     currentMoveString[3] = yytext[3];
826     currentMoveString[4] = NULLCHAR;
827
828     if (appData.debugMode) {
829         fprintf(debugFP, "Drop: %s\n", currentMoveString);
830     }
831     /* [HGM] do not allow values beyond board size */
832     if(currentMoveString[3] - ONE >= BOARD_HEIGHT ||
833        currentMoveString[2] - AAA >= BOARD_WIDTH     )
834       return ImpossibleMove;
835
836     if (WhiteOnMove(yyboardindex)) {
837         currentMoveString[0] = ToUpper(yytext[0]);
838     } else {
839         currentMoveString[0] = ToLower(yytext[0]);
840     }
841     return LegalityTest(boards[yyboardindex], PosFlags(yyboardindex), DROP_RANK, // [HGM] does drops now too
842                         CharToPiece(currentMoveString[0]), currentMoveString[3] - ONE, currentMoveString[2] - AAA, NULLCHAR);
843 }
844
845 [Rr]esign(s|ed)?  {
846     if (WhiteOnMove(yyboardindex))
847       return (int) BlackWins;
848     else
849       return (int) WhiteWins;
850 }
851
852 (([Ww](hite)?)|([Bb](lack)?))" "(([Rr]esign)|([Ff]orfeit))(s|ed)?  {
853     return (int) (ToUpper(yytext[0]) == 'W' ? BlackWins : WhiteWins);
854 }
855
856 (([Ww](hite)?)|([Bb](lack)?))" "[Dd]isconnect(s|ed)  {
857     return (int) GameUnfinished;
858 }
859
860 [Ss]talemate  {
861     return (int) GameIsDrawn;
862 }
863
864 "+-+"  {
865     return (int) GameIsDrawn;
866 }
867
868 ([Cc]heck)?[Mm]ate {
869     if (WhiteOnMove(yyboardindex))
870       return (int) BlackWins;
871     else
872       return (int) WhiteWins;
873 }
874
875 "++"  {
876     if (WhiteOnMove(yyboardindex))
877       return (int) BlackWins;
878     else
879       return (int) WhiteWins;
880 }
881
882 [Dd]raw(n)?(" "by)?(" "[Rr]epetition)|(" "[Aa]gree(d|ment))  {
883     return (int) GameIsDrawn;
884 }
885
886 [Dd]raw(n)?(" (".*")")?  {
887     return (int) GameIsDrawn;
888 }
889
890 (([Ww](hite)?)|([Bb](lack)?))" "(([Mm]ates)|([Ww][io]n(s)?)) { 
891     return (int) (ToUpper(yytext[0]) == 'W' ? WhiteWins : BlackWins);
892 }
893
894 (([Ww](hite)?)|([Bb](lack)?))" "(([Mm]ated)|([Ll]os[tes]+)) { 
895     return (int) (ToUpper(yytext[0]) == 'W' ? BlackWins : WhiteWins);
896 }
897
898 ("{"[^\}\n]*"} ")?(1-0|"1 - 0"|"1/0"|"1 / 0"|"1:0"|"1 : 0")(" (".*")"|" {".*"}")? { 
899     return (int) WhiteWins;
900 }
901
902 ("{"[^\}\n]*"} ")?(0-1|"0 - 1"|"0/1"|"0 / 1"|"0:1"|"0 : 1")(" (".*")"|" {".*"}")? { 
903     return (int) BlackWins;
904 }
905
906 ("{"[^\}\n]*"} ")?("1/2"|"1 / 2")(" "?[-:]" "?("1/2"|"1 / 2"))?(" (".*")"|" {".*"}")? {
907     return (int) GameIsDrawn;
908 }
909
910 ("{"[^\}\n]*"} ")?"*"(" (".*")"|" {".*"}")? {
911     return (int) GameUnfinished;
912 }
913
914 [1-9][0-9]*/"."?[ \t\n]*[a-lNnPpRrBQqKACFEWDGHOo]    {
915     /* move numbers */
916     if ((yyleng == 1) && (yytext[0] == '1'))
917       return (int) MoveNumberOne;
918 }
919
920 \([0-9]+:[0-9][0-9](\.[0-9]+)?\)|\{[0-9]+:[0-9][0-9](\.[0-9]+)?\} {
921     /* elapsed time indication, e.g. (0:12) or {10:21.071} */ 
922     return (int) ElapsedTime;
923 }
924
925 "[--"[^\]]*"--]" {
926     /* position diagram enclosed in [-- --] */
927     return (int) PositionDiagram;
928 }
929
930 ^"{--------------"\n[^\}]*\n"--------------}"$ {
931     /* position diagram enclosed in {-- --} */
932     return (int) PositionDiagram;
933 }
934
935 \[[ \t\n]*[A-Za-z0-9][A-Za-z0-9_+#=-]*[ \t\n]*\"[^"]*\"[ \t\n]*\] {
936     return (int) PGNTag;
937 }    
938
939 [Gg](nu|NU)" "?[Cc](hess|HESS).*[Gg](ame|AME) {
940     return (int) GNUChessGame;
941 }
942
943 ^[#;%]" "[^ ]*(" game file"|" position file").*$ {
944     return (int) XBoardGame;
945 }
946
947 \$[0-9]+        {                               /* numeric annotation glyph */
948     return (int) NAG;
949 }
950
951 \{[^\}]*\}      {                               /* anything in {} */
952     return (int) Comment; 
953 }
954
955 ;.*$ {                                          /* ; to end of line */
956     return (int) Comment;
957 }
958
959 \[[^\]]*\]      {                               /* anything in [] */
960     return (int) Comment; 
961 }
962
963 \([^()]*(\([^()]*(\([^()]*(\([^()]*\)[^()]*)*\)[^()]*)*\)[^()]*)+[^()]*\)  { /* very nested () */
964     return (int) Comment; 
965 }
966
967 \([^)][^)]+\)   {                               /* >=2 chars in () */
968     return (int) Comment; 
969 }       
970
971 ^[-a-zA-Z0-9]+:" ".*(\n[ \t]+.*)*  {
972         /* Skip mail headers */
973 }
974
975 [a-zA-Z0-9'-]+                  {
976         /* Skip random words */
977 }
978
979 .|\n                            {
980         /* Skip everything else */
981 }
982
983 %%
984
985
986 static char *StringToLex;
987
988 #ifndef FLEX_SCANNER
989 static FILE *lexFP;
990
991 static int input()
992 {
993     int ret;
994     
995     if (StringToLex != NULL) {
996         ret = *StringToLex;
997         if (ret == NULLCHAR)
998           ret = EOF;
999         else
1000           StringToLex++;
1001     } else if (unputCount > 0) {
1002         ret = unputBuffer[--unputCount];
1003     } else {
1004         ret = fgetc(lexFP);
1005     }    
1006
1007     if (ret == EOF) 
1008       return 0;
1009     else
1010       return ret;
1011 }
1012
1013 /*
1014  * Return offset of next pattern within current file
1015  */
1016 int yyoffset()
1017 {
1018     int offset = ftell(lexFP) - unputCount;
1019
1020     if (offset < 0) {
1021         offset = 0;
1022     }
1023     return(offset);
1024 }
1025  
1026 static void output(ch)
1027      int ch;
1028 {
1029     if(appData.debugMode) fprintf(debugFP, "PARSER BUG: unmatched character '%c' (0%o)\n",
1030             ch, ch);
1031 }
1032
1033 static void unput(ch)
1034      int ch;
1035 {
1036     if (ch == 0) return;
1037     if (StringToLex != NULL) {
1038         StringToLex--;
1039     } else {
1040         if (unputCount >= UNPUT_BUF_SIZE)
1041           if(appData.debugMode) fprintf(debugFP, "PARSER BUG: unput buffer overflow '%c' (0%o)\n",
1042                   ch, ch);
1043         unputBuffer[unputCount++] = ch;
1044     }
1045 }
1046
1047 /* Get ready to lex from a new file.  Kludge below sticks
1048    an artificial newline at the front of the file, which the
1049    above grammar ignores, but which makes ^ at start of pattern
1050    match at the real start of the file.
1051 */
1052 void yynewfile(f)
1053      FILE *f;
1054 {
1055     lexFP = f;
1056     StringToLex = NULL;
1057     unputCount = 0;
1058     unput('\n'); /* kludge */
1059 }
1060
1061 /* Get ready to lex from a string.  ^ at start of pattern WON'T
1062    match at the start of the string!
1063 */
1064 void yynewstr(s)
1065      char *s;
1066 {
1067     lexFP = NULL;
1068     StringToLex = s;
1069     unputCount = 0;
1070 }
1071 #endif /*!FLEX_SCANNER*/
1072
1073 #ifdef FLEX_SCANNER
1074 void my_yy_input(buf, result, max_size)
1075      char *buf;
1076      int *result;
1077      int max_size;
1078 {
1079     int count;
1080
1081     if (StringToLex != NULL) {
1082         count = 0;
1083         while (*StringToLex != NULLCHAR) {
1084             *buf++ = *StringToLex++;
1085             count++;
1086         }
1087         *result = count;
1088         return;
1089     } else {
1090         count = fread(buf, 1, max_size, yyin);
1091         if (count == 0) {
1092             *result = YY_NULL;
1093         } else {
1094             *result = count;
1095         }
1096         return;
1097     }    
1098 }
1099
1100 static YY_BUFFER_STATE my_file_buffer = NULL;
1101
1102 /*
1103     Return offset of next pattern in the current file.
1104 */
1105 int yyoffset()
1106 {
1107     int pos = yy_c_buf_p - YY_CURRENT_BUFFER->yy_ch_buf;
1108
1109     return(ftell(YY_CURRENT_BUFFER->yy_input_file) -
1110          yy_n_chars + pos);
1111 }
1112
1113
1114 void yynewstr(s)
1115      char *s;
1116 {
1117     if (my_file_buffer != NULL)
1118       yy_delete_buffer(my_file_buffer);
1119     StringToLex = s;
1120     my_file_buffer = yy_create_buffer(stdin, YY_BUF_SIZE);
1121     yy_switch_to_buffer(my_file_buffer);
1122 }
1123
1124 void yynewfile(f)
1125      FILE *f;
1126 {
1127     if (my_file_buffer != NULL)
1128       yy_delete_buffer(my_file_buffer);
1129     StringToLex = NULL;
1130     my_file_buffer = yy_create_buffer(f, YY_BUF_SIZE);
1131     yy_switch_to_buffer(my_file_buffer);
1132 }
1133 #endif /*FLEX_SCANNER*/
1134
1135 int yywrap()
1136 {
1137     return TRUE;
1138 }
1139
1140 /* Parse a move from the given string s */
1141 /* ^ at start of pattern WON'T work here unless using flex */
1142 ChessMove yylexstr(boardIndex, s, text, len)
1143      int boardIndex, len;
1144      char *s, *text;
1145 {
1146     ChessMove ret;
1147     char *oldStringToLex;
1148 #ifdef FLEX_SCANNER
1149     YY_BUFFER_STATE buffer, oldBuffer;
1150 #endif
1151     
1152     yyboardindex = boardIndex;
1153     oldStringToLex = StringToLex;
1154     StringToLex = s;
1155 #ifdef FLEX_SCANNER
1156     buffer = yy_create_buffer(stdin, YY_BUF_SIZE);
1157     oldBuffer = YY_CURRENT_BUFFER;
1158     yy_switch_to_buffer(buffer);
1159 #endif /*FLEX_SCANNER*/
1160
1161     ret = (ChessMove) yylex();
1162      strncpy(text, yy_text, len-1); // [HGM] vari: yy_text is not available to caller after buffer switch ?!?
1163      text[len-1] = NULLCHAR;
1164
1165 #ifdef FLEX_SCANNER
1166     if (oldBuffer != NULL) 
1167       yy_switch_to_buffer(oldBuffer);
1168     yy_delete_buffer(buffer);
1169 #endif /*FLEX_SCANNER*/
1170     StringToLex = oldStringToLex;
1171
1172     return ret;
1173 }