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