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