Updated copyright notice to 2012
[xboard.git] / parser.c
1 /*
2  * parser.c --
3  *
4  * Copyright 2011, 2012 Free Software Foundation, Inc.
5  * ------------------------------------------------------------------------
6  *
7  * GNU XBoard is free software: you can redistribute it and/or modify
8  * it under the terms of the GNU General Public License as published by
9  * the Free Software Foundation, either version 3 of the License, or (at
10  * your option) any later version.
11  *
12  * GNU XBoard is distributed in the hope that it will be useful, but
13  * WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15  * General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program. If not, see http://www.gnu.org/licenses/.  *
19  *
20  *------------------------------------------------------------------------
21  ** See the file ChangeLog for a revision history.  */
22
23 #include "config.h"
24 #include <stdio.h>
25 #include <ctype.h>
26 #include <string.h>
27 #include "common.h"
28 #include "backend.h"
29 #include "frontend.h"
30 #include "parser.h"
31 #include "moves.h"
32
33
34 extern Board    boards[MAX_MOVES];
35 extern int      PosFlags(int nr);
36 int             yyboardindex;
37 int             yyskipmoves = FALSE;
38 char            currentMoveString[4096]; // a bit ridiculous size?
39 char *yy_text;
40
41 #define PARSEBUFSIZE 10000
42
43 static FILE *inputFile;
44 static char *inPtr, *parsePtr, *parseStart;
45 static char inputBuf[PARSEBUFSIZE];
46 static char yytext[PARSEBUFSIZE];
47 static char fromString = 0, lastChar = '\n';
48
49 #define NOTHING 0
50 #define NUMERIC 1
51 #define ALPHABETIC 2
52 #define BADNUMBER (-2000000000)
53
54 int ReadLine()
55 {   // Read one line from the input file, and append to the buffer
56     char c, *start = inPtr;
57     if(fromString) return 0; // parsing string, so the end is a hard end
58     if(!inputFile) return 0;
59     while((c = fgetc(inputFile)) != EOF) {
60         *inPtr++ = c;
61         if(c == '\n') { *inPtr = NULLCHAR; return 1; }
62         if(inPtr - inputBuf > PARSEBUFSIZE-2) inPtr--; //prevent crash on overflow
63     }
64     if(inPtr == start) return 0;
65     *inPtr++ = '\n', *inPtr = NULLCHAR; // repair missing linefeed at EOF
66     return 1;
67 }
68
69 int Scan(char c, char **p)
70 {   // line-spanning skip to mentioned character or EOF
71     do {
72         while(**p) if(*(*p)++ == c) return 0;
73     } while(ReadLine());
74     // no closing bracket; force match for entire rest of file.
75     return 1;
76 }
77
78 int SkipWhite(char **p)
79 {   // skip spaces tabs and newlines; return 1 if anything was skipped
80     char *start = *p;
81     do{
82         while(**p == ' ' || **p == '\t' || **p == '\n' || **p == '\r') (*p)++;
83     } while(**p == NULLCHAR && ReadLine()); // continue as long as ReadLine reads something
84     return *p != start;
85 }
86
87 inline int Match(char *pattern, char **ptr)
88 {
89     char *p = pattern, *s = *ptr;
90     while(*p && (*p == *s++ || s[-1] == '\r' && *p--)) p++;
91     if(*p == 0) {
92         *ptr = s;
93         return 1;
94     }
95     return 0; // no match, no ptr update
96 }
97
98 inline int Word(char *pattern, char **p)
99 {
100     if(Match(pattern, p)) return 1;
101     if(*pattern >= 'a' && *pattern <= 'z' && *pattern - **p == 'a' - 'A') { // capitalized
102         (*p)++;
103         if(Match(pattern + 1, p)) return 1;
104         (*p)--;
105     }
106     return 0;
107 }
108
109 int Verb(char *pattern, char **p)
110 {
111     int res = Word(pattern, p);
112     if(res && !Match("s", p)) Match("ed", p); // eat conjugation suffix, if any
113     return res;
114 }
115
116
117 int Number(char **p)
118 {
119     int val = 0;
120     if(**p < '0' || **p > '9') return BADNUMBER;
121     while(**p >= '0' && **p <= '9') {
122         val = 10*val + *(*p)++ - '0';
123     }
124     return val;
125 }
126
127 int RdTime(char c, char **p)
128 {
129     char *start = ++(*p), *sec; // increment *p, as it was pointing to the opening ( or {
130     if(Number(p) == BADNUMBER) return 0;
131     sec = *p;
132     if(Match(":", p) && Number(p) != BADNUMBER && *p - sec == 3) { // well formed
133         sec = *p;
134         if(Match(".", p) && Number(p) != BADNUMBER && *(*p)++ == c) return 1; // well-formed fraction
135         *p = sec;
136         if(*(*p)++ == c) return 1; // matching bracket without fraction
137     }
138     *p = start; // failure
139     return 0;
140 }
141
142 char PromoSuffix(char **p)
143 {
144     char *start = *p;
145     if(**p == 'e' && (Match("ep", p) || Match("e.p.", p))) { *p = start; return NULLCHAR; } // non-compliant e.p. suffix is no promoChar!
146     if(**p == '+' && gameInfo.variant == VariantShogi) { (*p)++; return '+'; } 
147     if(**p == '=' || (gameInfo.variant == VariantSChess) && **p == '/') (*p)++; // optional = (or / for Seirawan gating)
148     if(**p == '(' && (*p)[2] == ')' && isalpha( (*p)[1] )) { (*p) += 3; return (*p)[-2]; }
149     if(isalpha(**p)) return *(*p)++;
150     if(*p != start) return '='; // must be the optional =
151     return NULLCHAR; // no suffix detected
152 }
153
154 int NextUnit(char **p)
155 {       // Main parser routine
156         int coord[4], n, result, piece, i;
157         char type[4], promoted, separator, slash, *oldp, *commentEnd, c;
158         int wom = quickFlag ? quickFlag&1 : WhiteOnMove(yyboardindex);
159
160         // ********* try white first, because it is so common **************************
161         if(**p == ' ' || **p == '\n' || **p == '\t') { parseStart = (*p)++; return Nothing; }
162
163
164         if(**p == NULLCHAR) { // make sure there is something to parse
165             if(fromString) return 0; // we are parsing string, so the end is really the end
166             *p = inPtr = inputBuf;
167             if(!ReadLine()) return 0; // EOF
168         }
169         parseStart = oldp = *p; // remember where we begin
170
171
172         // ********* attempt to recognize a SAN move in the leading non-blank text *****
173         piece = separator = promoted = slash = n = 0;
174         for(i=0; i<4; i++) coord[i] = -1, type[i] = NOTHING;
175         if(**p == '+') (*p)++, promoted++;
176         if(**p >= 'a' && **p <= 'z' && (*p)[1]== '@') piece =*(*p)++ + 'A' - 'a'; else
177         if(**p >= 'A' && **p <= 'Z') {
178              piece = *(*p)++; // Note we could test for 2-byte non-ascii names here
179              if(**p == '/') slash = *(*p)++;
180         }
181         while(n < 4) {
182             if(**p >= 'a' && **p < 'x') coord[n] = *(*p)++ - 'a', type[n++] = ALPHABETIC;
183             else if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
184             else break;
185             if(n == 2 && type[0] == type[1]) { // if two identical types, the opposite type in between must have been missing
186                 type[2] = type[1]; coord[2] = coord[1];
187                 type[1] = NOTHING; coord[1] = -1; n++;
188             }
189         }
190         // we always get here, and might have read a +, a piece, and upto 4 potential coordinates
191         if(n <= 2) { // could be from-square or disambiguator, when -:xX follow, or drop with @ directly after piece, but also to-square
192              if(**p == '-' || **p == ':' || **p == 'x' || **p == 'X' || // these cannot be move suffix, so to-square must follow
193                  (**p == '@' || **p == '*') && n == 0 && !promoted && piece) { // P@ must also be followed by to-square
194                 separator = *(*p)++;
195                 if(n == 1) coord[1] = coord[0]; // must be disambiguator, but we do not know which yet
196                 n = 2;
197                 while(n < 4) { // attempt to read to-square
198                     if(**p >= 'a' && **p < 'x') coord[n] = *(*p)++ - 'a', type[n++] = ALPHABETIC;
199                     else if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
200                     else break;
201                 }
202             } else if((**p == '+' || **p == '=') && n == 1 && piece && type[0] == NUMERIC) { // can be traditional Xiangqi notation
203                 separator = *(*p)++;
204                 n = 2;
205                 if((i = Number(p)) != BADNUMBER) coord[n] = i, type[n++] = NUMERIC;
206             } else if(n == 2) { // only one square mentioned, must be to-square
207                 while(n < 4) { coord[n] = coord[n-2], type[n] = type[n-2], coord[n-2] = -1, type[n-2] = NOTHING; n++; }
208             }
209         } else if(n == 3 && type[1] != NOTHING) { // must be hyphenless disambiguator + to-square
210             for(i=3; i>0; i--) coord[i] = coord[i-1], type[i] = type[i-1]; // move to-square to where it belongs
211             type[1] = NOTHING; // disambiguator goes in first two positions
212             n = 4;
213         }
214 if(appData.debugMode)fprintf(debugFP, "trial %d,%d,%d,%d  type %d%d%d%d\n", coord[0], coord[1], coord[2], coord[3], type[0], type[1], type[2], type[3]);
215         // we always get here; move must be completely read now, with to-square coord(s) at end
216         if(n == 3) { // incomplete to-square. Could be Xiangqi traditional, or stuff like fxg
217             if(piece && type[1] == NOTHING && type[0] == NUMERIC && type[2] == NUMERIC && 
218                 (separator == '+' || separator == '=' || separator == '-')) {
219                      // Xiangqi traditional
220
221                 return ImpossibleMove; // for now treat as invalid
222             }
223             // fxg stuff, but also things like 0-0, 0-1 and 1-0
224             if(!piece && type[1] == NOTHING && type[0] == ALPHABETIC && type[2] == ALPHABETIC
225                  && (coord[0] != 14 || coord[2] != 14) /* reserve oo for castling! */ ) {
226                 piece = 'P'; n = 4; // kludge alert: fake full to-square
227             }
228         } else if(n == 1 && type[0] == NUMERIC && coord[0] > 1) { while(**p == '.') (*p)++; return Nothing; } // fast exit for move numbers
229         if(n == 4 && type[2] != type[3] && // we have a valid to-square (kludge: type[3] can be NOTHING on fxg type move)
230                      (piece || !promoted) && // promoted indicator only valid on named piece type
231                      (type[2] == ALPHABETIC || gameInfo.variant == VariantShogi)) { // in Shogi also allow alphabetic rank
232             DisambiguateClosure cl;
233             int fromX, fromY, toX, toY;
234
235             if(slash && (!piece || type[1] == NOTHING)) goto badMove; // slash after piece only in ICS long format
236             if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
237
238             if(type[2] == NUMERIC) { // alpha-rank
239                 coord[2] = BOARD_RGHT - BOARD_LEFT - coord[2];
240                 coord[3] = BOARD_HEIGHT - coord[3];
241                 if(coord[0] >= 0) coord[0] = BOARD_RGHT - BOARD_LEFT - coord[0];
242                 if(coord[1] >= 0) coord[1] = BOARD_HEIGHT - coord[1];
243             }
244             toX = cl.ftIn = (currentMoveString[2] = coord[2] + 'a') - AAA;
245             toY = cl.rtIn = (currentMoveString[3] = coord[3] + '0') - ONE;
246             if(type[3] == NOTHING) cl.rtIn = -1; // for fxg type moves ask for toY disambiguation
247             else if(toY >= BOARD_HEIGHT || toY < 0)   return ImpossibleMove; // vert off-board to-square
248             if(toX < BOARD_LEFT || toX >= BOARD_RGHT) return ImpossibleMove;
249             if(piece) {
250                 cl.pieceIn = CharToPiece(wom ? piece : ToLower(piece));
251                 if(cl.pieceIn == EmptySquare) return ImpossibleMove; // non-existent piece
252                 if(promoted) cl.pieceIn = (ChessSquare) (PROMOTED cl.pieceIn);
253             } else cl.pieceIn = EmptySquare;
254             if(separator == '@' || separator == '*') { // drop move. We only get here without from-square or promoted piece
255                 fromY = DROP_RANK; fromX = cl.pieceIn;
256                 currentMoveString[0] = piece;
257                 currentMoveString[1] = '@';
258                 return LegalityTest(boards[yyboardindex], PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, fromY, fromX, toY, toX, NULLCHAR);
259             }
260             if(type[1] == NOTHING && type[0] != NOTHING) { // there is a disambiguator
261                 if(type[0] != type[2]) coord[0] = -1, type[1] = type[0], type[0] = NOTHING; // it was a rank-disambiguator
262             }
263             if(  type[1] != type[2] && // means fromY is of opposite type as ToX, or NOTHING
264                 (type[0] == NOTHING || type[0] == type[2]) ) { // well formed
265
266                 fromX = (currentMoveString[0] = coord[0] + 'a') - AAA;
267                 fromY = (currentMoveString[1] = coord[1] + '0') - ONE;
268                 currentMoveString[4] = cl.promoCharIn = PromoSuffix(p);
269                 currentMoveString[5] = NULLCHAR;
270                 if(type[0] != NOTHING && type[1] != NOTHING && type[3] != NOTHING) { // fully specified.
271                     // Note that Disambiguate does not work for illegal moves, but flags them as impossible
272                     if(piece) { // check if correct piece indicated
273                         ChessSquare realPiece = boards[yyboardindex][fromY][fromX];
274                         if(PieceToChar(realPiece) == '~') realPiece = (ChessSquare) (DEMOTED realPiece);
275                         if(!(appData.icsActive && PieceToChar(realPiece) == '+') && // trust ICS if it moves promoted pieces
276                            piece && realPiece != cl.pieceIn) return ImpossibleMove;
277                     }
278                     result = LegalityTest(boards[yyboardindex], PosFlags(yyboardindex), fromY, fromX, toY, toX, cl.promoCharIn);
279                     if (currentMoveString[4] == NULLCHAR) { // suppy missing mandatory promotion character
280                       if(result == WhitePromotion  || result == BlackPromotion) {
281                         switch(gameInfo.variant) {
282                           case VariantCourier:
283                           case VariantShatranj: currentMoveString[4] = PieceToChar(BlackFerz); break;
284                           case VariantGreat:    currentMoveString[4] = PieceToChar(BlackMan); break;
285                           case VariantShogi:    currentMoveString[4] = '+'; break;
286                           default:              currentMoveString[4] = PieceToChar(BlackQueen);
287                         }
288                       } else if(result == WhiteNonPromotion  || result == BlackNonPromotion) {
289                                                 currentMoveString[4] = '=';
290                       }
291                     } else if(appData.testLegality && gameInfo.variant != VariantSChess && // strip off unnecessary and false promo characters
292                        !(result == WhitePromotion  || result == BlackPromotion ||
293                          result == WhiteNonPromotion || result == BlackNonPromotion)) currentMoveString[4] = NULLCHAR;
294                     return result;
295                 } else if(cl.pieceIn == EmptySquare) cl.pieceIn = wom ? WhitePawn : BlackPawn;
296                 cl.ffIn = type[0] == NOTHING ? -1 : coord[0] + 'a' - AAA;
297                 cl.rfIn = type[1] == NOTHING ? -1 : coord[1] + '0' - ONE;
298
299                 Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
300
301                 if(cl.kind == ImpossibleMove && !piece && type[1] == NOTHING // fxg5 type
302                         && toY == (wom ? 4 : 3)) { // could be improperly written e.p.
303                     cl.rtIn += wom ? 1 : -1; // shift target square to e.p. square
304                     Disambiguate(boards[yyboardindex], PosFlags(yyboardindex), &cl);
305                     if((cl.kind != WhiteCapturesEnPassant && cl.kind != BlackCapturesEnPassant))
306                         return ImpossibleMove; // nice try, but no cigar
307                 }
308
309                 currentMoveString[0] = cl.ff + AAA;
310                 currentMoveString[1] = cl.rf + ONE;
311                 currentMoveString[3] = cl.rt + ONE;
312                 currentMoveString[4] = cl.promoChar;
313
314                 if((cl.kind == WhiteCapturesEnPassant || cl.kind == BlackCapturesEnPassant) && (Match("ep", p) || Match("e.p.", p)));
315
316                 return (int) cl.kind;
317             }
318         }
319 badMove:// we failed to find algebraic move
320         *p = oldp;
321
322
323         // Next we do some common symbols where the first character commits us to things that cannot possibly be a move
324
325         // ********* PGN tags ******************************************
326         if(**p == '[') {
327             oldp = ++(*p);
328             if(Match("--", p)) { // "[--" could be start of position diagram
329                 if(!Scan(']', p) && (*p)[-3] == '-' && (*p)[-2] == '-') return PositionDiagram; 
330                 *p = oldp;
331             }
332             SkipWhite(p);
333             if(isdigit(**p) || isalpha(**p)) {
334                 do (*p)++; while(isdigit(**p) || isalpha(**p) || **p == '+' ||
335                                 **p == '-' || **p == '=' || **p == '_' || **p == '#');
336                 SkipWhite(p);
337                 if(**p == '"') {
338                     (*p)++;
339                     while(**p != '\n' && (*(*p)++ != '"'|| (*p)[-2] == '\\')); // look for unescaped quote
340                     if((*p)[-1] !='"') { *p = oldp; Scan(']', p); return Comment; } // string closing delimiter missing
341                     SkipWhite(p); if(*(*p)++ == ']') return PGNTag;
342                 }
343             }
344             Scan(']', p); return Comment;
345         }
346
347         // ********* SAN Castings *************************************
348         if(**p == 'O' || **p == 'o' || **p == '0') {
349             int castlingType = 0;
350             if(Match("O-O-O", p) || Match("o-o-o", p) || Match("0-0-0", p) || 
351                Match("OOO", p) || Match("ooo", p) || Match("000", p)) castlingType = 2;
352             else if(Match("O-O", p) || Match("o-o", p) || Match("0-0", p) ||
353                     Match("OO", p) || Match("oo", p) || Match("00", p)) castlingType = 1;
354             if(castlingType) { //code from old parser, collapsed for both castling types, and streamlined a bit
355                 int rf, ff, rt, ft; ChessSquare king;
356                 char promo=NULLCHAR;
357
358                 if(gameInfo.variant == VariantSChess) promo = PromoSuffix(p);
359
360                 if (yyskipmoves) return (int) AmbiguousMove; /* not disambiguated */
361
362                 if (wom) {
363                     rf = 0;
364                     rt = 0;
365                     king = WhiteKing;
366                 } else {
367                     rf = BOARD_HEIGHT-1;
368                     rt = BOARD_HEIGHT-1;
369                     king = BlackKing;
370                 }
371                 ff = (BOARD_WIDTH-1)>>1; // this would be d-file
372                 if (boards[yyboardindex][rf][ff] == king) {
373                     /* ICS wild castling */
374                     ft = castlingType == 1 ? BOARD_LEFT+1 : (gameInfo.variant == VariantJanus ? BOARD_RGHT-2 : BOARD_RGHT-3);
375                 } else {
376                     ff = BOARD_WIDTH>>1; // e-file
377                     ft = castlingType == 1 ? BOARD_RGHT-2 : BOARD_LEFT+2;
378                 }
379                 if(PosFlags(0) & F_FRC_TYPE_CASTLING) {
380                     if (wom) {
381                         ff = initialRights[2];
382                         ft = initialRights[castlingType-1];
383                     } else {
384                         ff = initialRights[5];
385                         ft = initialRights[castlingType+2];
386                     }
387                     if (appData.debugMode) fprintf(debugFP, "Parser FRC (type=%d) %d %d\n", castlingType, ff, ft);
388                     if(ff == NoRights || ft == NoRights) return ImpossibleMove;
389                 }
390                 sprintf(currentMoveString, "%c%c%c%c%c",ff+AAA,rf+ONE,ft+AAA,rt+ONE,promo);
391                 if (appData.debugMode) fprintf(debugFP, "(%d-type) castling %d %d\n", castlingType, ff, ft);
392
393                 return (int) LegalityTest(boards[yyboardindex],
394                               PosFlags(yyboardindex)&~F_MANDATORY_CAPTURE, // [HGM] losers: e.p.!
395                               rf, ff, rt, ft, promo);
396             }
397         }
398
399
400         // ********* variations (nesting) ******************************
401         if(**p =='(') {
402             if(RdTime(')', p)) return ElapsedTime;
403             return Open;
404         }
405         if(**p ==')') { (*p)++; return Close; }
406         if(**p == ';') { while(**p != '\n') (*p)++; return Comment; }
407
408
409         // ********* Comments and result messages **********************
410         *p = oldp; commentEnd = NULL; result = 0;
411         if(**p == '{') {
412             if(RdTime('}', p)) return ElapsedTime;
413             if(lastChar == '\n' && Match("--------------\n", p)) {
414                 char *q;
415                 i = Scan ('}', p); q = *p - 16;
416                 if(Match("\n--------------}\n", &q)) return PositionDiagram;
417             } else i = Scan('}', p);
418             commentEnd = *p; if(i) return Comment; // return comment that runs to EOF immediately
419         }
420         if(commentEnd) SkipWhite(p);
421         if(Match("*", p)) result = GameUnfinished;
422         else if(**p == '0') {
423             if( Match("0-1", p) || Match("0/1", p) || Match("0:1", p) ||
424                 Match("0 - 1", p) || Match("0 / 1", p) || Match("0 : 1", p)) result = BlackWins;
425         } else if(**p == '1') {
426             if( Match("1-0", p) || Match("1/0", p) || Match("1:0", p) ||
427                 Match("1 - 0", p) || Match("1 / 0", p) || Match("1 : 0", p)) result = WhiteWins;
428             else if(Match("1/2 - 1/2", p) || Match("1/2:1/2", p) || Match("1/2 : 1/2", p) || Match("1 / 2 - 1 / 2", p) ||
429                     Match("1 / 2 : 1 / 2", p) || Match("1/2", p) || Match("1 / 2", p)) result = GameIsDrawn;
430         }
431         if(result) {
432             if(Match(" (", p) && !Scan(')', p) || Match(" {", p) && !Scan('}', p)) { // there is a comment after the PGN result!
433                 if(commentEnd) { *p = commentEnd; return Comment; } // so comment before it is normal comment; return that first
434             }
435             return result; // this returns a possible preceeding comment as result details
436         }
437         if(commentEnd) { *p = commentEnd; return Comment; } // there was no PGN result following, so return as normal comment
438
439
440         // ********* Move numbers (after castlings or PGN results!) ***********
441         if((i = Number(p)) != BADNUMBER) { // a single number was read as part of our attempt to read a move
442             char *numEnd = *p;
443             if(**p == '.') (*p)++; SkipWhite(p);
444             if(**p == '+' || isalpha(**p) || gameInfo.variant == VariantShogi && *p != numEnd && isdigit(**p)) {
445                 *p = numEnd;
446                 return i == 1 ? MoveNumberOne : Nothing;
447             }
448             *p = numEnd; return Nothing;
449         }
450
451
452         // ********* non-compliant game-result indicators *********************
453         if(Match("+-+", p) || Word("stalemate", p)) return GameIsDrawn;
454         if(Match("++", p) || Verb("resign", p) || (Word("check", p) || 1) && Word("mate", p) )
455             return (wom ? BlackWins : WhiteWins);
456         c = ToUpper(**p);
457         if(Word("w", p) && (Match("hite", p) || 1) || Word("b", p) && (Match("lack", p) || 1) ) {
458             if(**p != ' ') return Nothing;
459             ++*p;
460             if(Verb("disconnect", p)) return GameUnfinished;
461             if(Verb("resign", p) || Verb("forfeit", p) || Word("mated", p) || Word("lost", p) || Word("loses", p))
462                 return (c == 'W' ? BlackWins : WhiteWins);
463             if(Word("mates", p) || Word("wins", p) || Word("won", p))
464                 return (c != 'W' ? BlackWins : WhiteWins);
465             return Nothing;
466         }
467         if(Word("draw", p)) {
468             if(**p == 'n') (*p)++;
469             if(**p != ' ') return GameIsDrawn;
470             oldp = ++*p;
471             if(Word("agreed", p)) return GameIsDrawn;
472             if(Match("by ", p) && (Word("repetition", p) || Word("agreement", p)) ) return GameIsDrawn;
473             *p = oldp;
474             if(*(*p)++ == '(') {
475                 while(**p != '\n') if(*(*p)++ == ')') break;
476                 if((*p)[-1] == ')')  return GameIsDrawn;
477             }
478             *p = oldp - 1; return GameIsDrawn;
479         }
480
481
482         // ********* Numeric annotation glyph **********************************
483         if(**p == '$') { (*p)++; if(Number(p) != BADNUMBER) return NAG; return Nothing; }
484
485
486         // ********** by now we are getting down to the silly stuff ************
487         if(Word("gnu", p) || Match("GNU", p)) {
488             if(**p == ' ') (*p)++;
489             if(Word("chess", p) || Match("CHESS", p)) {
490                 char *q;
491                 if((q = strstr(*p, "game")) || (q = strstr(*p, "GAME")) || (q = strstr(*p, "Game"))) {
492                     (*p) = q + 4; return GNUChessGame;
493                 }
494             }
495             return Nothing;
496         }
497         if(lastChar == '\n' && (Match("# ", p) || Match("; ", p) || Match("% ", p))) {
498             while(**p != '\n' && **p != ' ') (*p)++;
499             if(**p == ' ' && (Match(" game file", p) || Match(" position file", p))) {
500                 while(**p != '\n') (*p)++; // skip to EOLN
501                 return XBoardGame;
502             }
503             *p = oldp; // we might need to re-match the skipped stuff
504         }
505
506         if(Match("@@@@", p) || Match("--", p) || Match("Z0", p) || Match("pass", p) || Match("null", p)) {
507             strncpy(currentMoveString, "@@@@", 5);
508             return yyboardindex & F_WHITE_ON_MOVE ? WhiteDrop : BlackDrop;
509         }
510
511         // ********* Efficient skipping of (mostly) alphabetic chatter **********
512         while(isdigit(**p) || isalpha(**p) || **p == '-') (*p)++;
513         if(*p != oldp) {
514             if(**p == '\'') {
515                 while(isdigit(**p) || isalpha(**p) || **p == '-' || **p == '\'') (*p)++;
516                 return Nothing; // random word
517             }
518             if(lastChar == '\n' && Match(": ", p)) { // mail header, skip indented lines
519                 do {
520                     while(**p != '\n') (*p)++;
521                     if(!ReadLine()) return Nothing; // append next line if not EOF
522                 } while(Match("\n ", p) || Match("\n\t", p));
523             }
524             return Nothing;
525         }
526
527
528         // ********* Could not match to anything. Return offending character ****
529         (*p)++;
530         return Nothing;
531 }
532
533 /*
534     Return offset of next pattern in the current file.
535 */
536 int yyoffset()
537 {
538     return ftell(inputFile) - (inPtr - parsePtr); // subtract what is read but not yet parsed
539 }
540
541 void yynewfile (FILE *f)
542 {   // prepare parse buffer for reading file
543     inputFile = f;
544     inPtr = parsePtr = inputBuf;
545     fromString = 0;
546     lastChar = '\n';
547     *inPtr = NULLCHAR; // make sure we will start by reading a line
548 }
549
550 void yynewstr P((char *s))
551 {
552     parsePtr = s;
553     inputFile = NULL;
554     fromString = 1;
555 }
556
557 int yylex()
558 {   // this replaces the flex-generated parser
559     int result = NextUnit(&parsePtr);
560     char *p = parseStart, *q = yytext;
561     while(p < parsePtr) *q++ = *p++; // copy the matched text to yytext[]
562     *q = NULLCHAR;
563     lastChar = q[-1];
564     return result;
565 }
566
567 int Myylex()
568 {   // [HGM] wrapper for yylex, which treats nesting of parentheses
569     int symbol, nestingLevel = 0, i=0;
570     char *p;
571     static char buf[256*MSG_SIZ];
572     buf[0] = NULLCHAR;
573     do { // eat away anything not at level 0
574         symbol = yylex();
575         if(symbol == Open) nestingLevel++;
576         if(nestingLevel) { // save all parsed text between (and including) the ()
577             for(p=yytext; *p && i<256*MSG_SIZ-2;) buf[i++] = *p++;
578             buf[i] = NULLCHAR;
579         }
580         if(symbol == 0) break; // ran into EOF
581         if(symbol == Close) symbol = Comment, nestingLevel--;
582     } while(nestingLevel || symbol == Nothing);
583     yy_text = buf[0] ? buf : (char*)yytext;
584     return symbol;
585 }
586
587 ChessMove yylexstr(int boardIndex, char *s, char *buf, int buflen)
588 {
589     ChessMove ret;
590     char *savPP = parsePtr;
591     fromString = 1;
592     yyboardindex = boardIndex;
593     parsePtr = s;
594     ret = (ChessMove) Myylex();
595     strncpy(buf, yy_text, buflen-1);
596     buf[buflen-1] = NULLCHAR;
597     parsePtr = savPP;
598     fromString = 0;
599     return ret;
600 }
601