Merge remote-tracking branch 'gerrit/release-4-6'
[alexxy/gromacs.git] / src / gromacs / selection / scanner_internal.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief Helper functions for the selection tokenizer.
33  *
34  * This file implements the functions in the headers scanner.h and
35  * scanner_internal.h.
36  *
37  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
38  * \ingroup module_selection
39  */
40 /*! \cond
41  * \internal \file scanner_flex.h
42  * \brief Generated (from scanner.l) header file by Flex.
43  *
44  * This file contains definitions of functions that are needed in
45  * scanner_internal.cpp.
46  *
47  * \ingroup module_selection
48  * \endcond
49  */
50 #ifdef HAVE_CONFIG_H
51 #include <config.h>
52 #endif
53
54 #include <stdlib.h>
55 #include <string.h>
56
57 #include "typedefs.h"
58 #include "smalloc.h"
59 #include "string2.h"
60
61 #include "gromacs/utility/errorcodes.h"
62 #include "gromacs/utility/exceptions.h"
63 #include "gromacs/utility/gmxassert.h"
64 #include "gromacs/utility/messagestringcollector.h"
65
66 #include "parsetree.h"
67 #include "selectioncollection-impl.h"
68 #include "selelem.h"
69 #include "selmethod.h"
70 #include "symrec.h"
71
72 #include "parser.h"
73 #include "scanner.h"
74 #include "scanner_internal.h"
75
76 //! Step in which the allocated memory for pretty-printed input is incremented.
77 #define STRSTORE_ALLOCSTEP 1000
78
79 /* These are defined as macros in the generated scanner_flex.h.
80  * We undefine them here to have them as variable names in the subroutines.
81  * There are other ways of doing this, but this is probably the easiest. */
82 #undef yylval
83 #undef yytext
84 #undef yyleng
85
86 /*! \brief
87  * Handles initialization of method parameter token.
88  */
89 static int
90 init_param_token(YYSTYPE *yylval, gmx_ana_selparam_t *param, bool bBoolNo)
91 {
92     if (bBoolNo)
93     {
94         GMX_RELEASE_ASSERT(param->name != NULL,
95                 "bBoolNo should only be set for a parameters with a name");
96         snew(yylval->str, strlen(param->name) + 3);
97         yylval->str[0] = 'n';
98         yylval->str[1] = 'o';
99         strcpy(yylval->str+2, param->name);
100     }
101     else
102     {
103         yylval->str = param->name ? strdup(param->name) : NULL;
104     }
105     return PARAM;
106 }
107
108 /*! \brief
109  * Processes a selection method token.
110  */
111 static int
112 init_method_token(YYSTYPE *yylval, gmx_ana_selmethod_t *method, bool bPosMod,
113                   gmx_sel_lexer_t *state)
114 {
115     /* If the previous token was not KEYWORD_POS, return EMPTY_POSMOD
116      * before the actual method to work around a limitation in Bison. */
117     if (!bPosMod && method->type != POS_VALUE)
118     {
119         state->nextmethod = method;
120         return EMPTY_POSMOD;
121     }
122     yylval->meth = method;
123     if (!(method->flags & SMETH_MODIFIER) && method->nparams == 0)
124     {
125         /* Keyword */
126         switch (method->type)
127         {
128             case INT_VALUE:   return KEYWORD_NUMERIC;
129             case REAL_VALUE:  return KEYWORD_NUMERIC;
130             case STR_VALUE:   return KEYWORD_STR;
131             case GROUP_VALUE: return KEYWORD_GROUP;
132             default:
133                 GMX_ERROR_NORET(gmx::eeInternalError, "Unsupported keyword type");
134                 return INVALID;
135         }
136     }
137     else
138     {
139         /* Method with parameters or a modifier */
140         if (method->flags & SMETH_MODIFIER)
141         {
142             /* Remove all methods from the stack */
143             state->msp = -1;
144             if (method->param[1].name == NULL)
145             {
146                 state->nextparam = &method->param[1];
147             }
148         }
149         else
150         {
151             if (method->param[0].name == NULL)
152             {
153                 state->nextparam = &method->param[0];
154             }
155         }
156         ++state->msp;
157         if (state->msp >= state->mstack_alloc)
158         {
159             state->mstack_alloc += 10;
160             srenew(state->mstack, state->mstack_alloc);
161         }
162         state->mstack[state->msp] = method;
163         if (method->flags & SMETH_MODIFIER)
164         {
165             return MODIFIER;
166         }
167         switch (method->type)
168         {
169             case INT_VALUE:   return METHOD_NUMERIC;
170             case REAL_VALUE:  return METHOD_NUMERIC;
171             case POS_VALUE:   return METHOD_POS;
172             case GROUP_VALUE: return METHOD_GROUP;
173             default:
174                 --state->msp;
175                 GMX_ERROR_NORET(gmx::eeInternalError, "Unsupported method type");
176                 return INVALID;
177         }
178     }
179     return INVALID; /* Should not be reached */
180 }
181
182 int
183 _gmx_sel_lexer_process_pending(YYSTYPE *yylval, gmx_sel_lexer_t *state)
184 {
185     if (state->nextparam)
186     {
187         gmx_ana_selparam_t *param = state->nextparam;
188         bool                bBoolNo = state->bBoolNo;
189
190         if (state->neom > 0)
191         {
192             --state->neom;
193             return END_OF_METHOD;
194         }
195         state->nextparam = NULL;
196         state->bBoolNo   = false;
197         _gmx_sel_lexer_add_token(param->name, -1, state);
198         return init_param_token(yylval, param, bBoolNo);
199     }
200     if (state->prev_pos_kw > 0)
201     {
202         --state->prev_pos_kw;
203     }
204     if (state->nextmethod)
205     {
206         gmx_ana_selmethod_t *method = state->nextmethod;
207
208         state->nextmethod = NULL;
209         return init_method_token(yylval, method, true, state);
210     }
211     return 0;
212 }
213
214 int
215 _gmx_sel_lexer_process_identifier(YYSTYPE *yylval, char *yytext, size_t yyleng,
216                                   gmx_sel_lexer_t *state)
217 {
218     gmx_sel_symrec_t *symbol;
219     e_symbol_t        symtype;
220
221     /* Check if the identifier matches with a parameter name */
222     if (state->msp >= 0)
223     {
224         gmx_ana_selparam_t *param = NULL;
225         bool                bBoolNo = false;
226         int                 sp = state->msp;
227         while (!param && sp >= 0)
228         {
229             int             i;
230             for (i = 0; i < state->mstack[sp]->nparams; ++i)
231             {
232                 /* Skip NULL parameters and too long parameters */
233                 if (state->mstack[sp]->param[i].name == NULL
234                     || strlen(state->mstack[sp]->param[i].name) > yyleng)
235                 {
236                     continue;
237                 }
238                 if (!strncmp(state->mstack[sp]->param[i].name, yytext, yyleng))
239                 {
240                     param = &state->mstack[sp]->param[i];
241                     break;
242                 }
243                 /* Check separately for a 'no' prefix on boolean parameters */
244                 if (state->mstack[sp]->param[i].val.type == NO_VALUE
245                     && yyleng > 2 && yytext[0] == 'n' && yytext[1] == 'o'
246                     && !strncmp(state->mstack[sp]->param[i].name, yytext+2, yyleng-2))
247                 {
248                     param = &state->mstack[sp]->param[i];
249                     bBoolNo = true;
250                     break;
251                 }
252             }
253             if (!param)
254             {
255                 --sp;
256             }
257         }
258         if (param)
259         {
260             if (param->val.type == NO_VALUE && !bBoolNo)
261             {
262                 state->bMatchBool = true;
263             }
264             if (sp < state->msp)
265             {
266                 state->neom = state->msp - sp - 1;
267                 state->nextparam = param;
268                 state->bBoolNo   = bBoolNo;
269                 return END_OF_METHOD;
270             }
271             _gmx_sel_lexer_add_token(param->name, -1, state);
272             return init_param_token(yylval, param, bBoolNo);
273         }
274     }
275
276     /* Check if the identifier matches with a symbol */
277     symbol = _gmx_sel_find_symbol_len(state->sc->symtab, yytext, yyleng, false);
278     /* If there is no match, return the token as a string */
279     if (!symbol)
280     {
281         yylval->str = gmx_strndup(yytext, yyleng);
282         _gmx_sel_lexer_add_token(yytext, yyleng, state);
283         return IDENTIFIER;
284     }
285     _gmx_sel_lexer_add_token(_gmx_sel_sym_name(symbol), -1, state);
286     symtype = _gmx_sel_sym_type(symbol);
287     /* Reserved symbols should have been caught earlier */
288     if (symtype == SYMBOL_RESERVED)
289     {
290         GMX_ERROR_NORET(gmx::eeInternalError,
291                         "Mismatch between tokenizer and reserved symbol table");
292         return INVALID;
293     }
294     /* For variable symbols, return the type of the variable value */
295     if (symtype == SYMBOL_VARIABLE)
296     {
297         t_selelem *var;
298
299         var = _gmx_sel_sym_value_var(symbol);
300         /* Return simple tokens for constant variables */
301         if (var->type == SEL_CONST)
302         {
303             switch (var->v.type)
304             {
305                 case INT_VALUE:
306                     yylval->i = var->v.u.i[0];
307                     return TOK_INT;
308                 case REAL_VALUE:
309                     yylval->r = var->v.u.r[0];
310                     return TOK_REAL;
311                 case POS_VALUE:
312                     break;
313                 default:
314                     GMX_ERROR_NORET(gmx::eeInternalError,
315                                     "Unsupported variable type");
316                     return INVALID;
317             }
318         }
319         yylval->sel = var;
320         switch (var->v.type)
321         {
322             case INT_VALUE:   return VARIABLE_NUMERIC;
323             case REAL_VALUE:  return VARIABLE_NUMERIC;
324             case POS_VALUE:   return VARIABLE_POS;
325             case GROUP_VALUE: return VARIABLE_GROUP;
326             default:
327                 GMX_ERROR_NORET(gmx::eeInternalError,
328                                 "Unsupported variable type");
329                 return INVALID;
330         }
331         return INVALID; /* Should not be reached. */
332     }
333     /* For method symbols, return the correct type */
334     if (symtype == SYMBOL_METHOD)
335     {
336         gmx_ana_selmethod_t *method;
337
338         method = _gmx_sel_sym_value_method(symbol);
339         return init_method_token(yylval, method, state->prev_pos_kw > 0, state);
340     }
341     /* For position symbols, we need to return KEYWORD_POS, but we also need
342      * some additional handling. */
343     if (symtype == SYMBOL_POS)
344     {
345         state->bMatchOf = true;
346         yylval->str = _gmx_sel_sym_name(symbol);
347         state->prev_pos_kw = 2;
348         return KEYWORD_POS;
349     }
350     /* Should not be reached */
351     return INVALID;
352 }
353
354 void
355 _gmx_sel_lexer_add_token(const char *str, int len, gmx_sel_lexer_t *state)
356 {
357     /* Do nothing if the string is empty, or if it is a space and there is
358      * no other text yet, or if there already is a space. */
359     if (!str || len == 0 || strlen(str) == 0
360         || (str[0] == ' ' && str[1] == 0
361             && (state->pslen == 0 || state->pselstr[state->pslen - 1] == ' ')))
362     {
363         return;
364     }
365     if (len < 0)
366     {
367         len = strlen(str);
368     }
369     /* Allocate more memory if necessary */
370     if (state->nalloc_psel - state->pslen < len)
371     {
372         int incr = STRSTORE_ALLOCSTEP < len ? len : STRSTORE_ALLOCSTEP;
373         state->nalloc_psel += incr;
374         srenew(state->pselstr, state->nalloc_psel);
375     }
376     /* Append the token to the stored string */
377     strncpy(state->pselstr + state->pslen, str, len);
378     state->pslen += len;
379     state->pselstr[state->pslen] = 0;
380 }
381
382 void
383 _gmx_sel_init_lexer(yyscan_t *scannerp, struct gmx_ana_selcollection_t *sc,
384                     bool bInteractive, int maxnr, bool bGroups,
385                     struct gmx_ana_indexgrps_t *grps)
386 {
387     int rc = _gmx_sel_yylex_init(scannerp);
388     if (rc != 0)
389     {
390         // TODO: Throw a more representative exception.
391         GMX_THROW(gmx::InternalError("Lexer initialization failed"));
392     }
393
394     gmx_sel_lexer_t *state = new gmx_sel_lexer_t;
395
396     state->sc        = sc;
397     state->errors    = NULL;
398     state->bGroups   = bGroups;
399     state->grps      = grps;
400     state->nexpsel   = (maxnr > 0 ? static_cast<int>(sc->sel.size()) + maxnr : -1);
401
402     state->bInteractive = bInteractive;
403
404     snew(state->pselstr, STRSTORE_ALLOCSTEP);
405     state->pselstr[0]   = 0;
406     state->pslen        = 0;
407     state->nalloc_psel  = STRSTORE_ALLOCSTEP;
408
409     snew(state->mstack, 20);
410     state->mstack_alloc = 20;
411     state->msp          = -1;
412     state->neom         = 0;
413     state->nextparam    = NULL;
414     state->nextmethod   = NULL;
415     state->prev_pos_kw  = 0;
416     state->bBoolNo      = false;
417     state->bMatchOf     = false;
418     state->bMatchBool   = false;
419     state->bCmdStart    = true;
420     state->bBuffer      = false;
421
422     _gmx_sel_yyset_extra(state, *scannerp);
423 }
424
425 void
426 _gmx_sel_free_lexer(yyscan_t scanner)
427 {
428     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
429
430     sfree(state->pselstr);
431     sfree(state->mstack);
432     if (state->bBuffer)
433     {
434         _gmx_sel_yy_delete_buffer(state->buffer, scanner);
435     }
436     delete state;
437     _gmx_sel_yylex_destroy(scanner);
438 }
439
440 void
441 _gmx_sel_set_lexer_error_reporter(yyscan_t scanner,
442                                   gmx::MessageStringCollector *errors)
443 {
444     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
445     state->errors = errors;
446 }
447
448 void
449 _gmx_sel_lexer_set_exception(yyscan_t scanner,
450                              const boost::exception_ptr &ex)
451 {
452     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
453     state->exception = ex;
454 }
455
456 void
457 _gmx_sel_lexer_rethrow_exception_if_occurred(yyscan_t scanner)
458 {
459     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
460     if (state->exception)
461     {
462         boost::exception_ptr ex = state->exception;
463         state->exception = boost::exception_ptr();
464         rethrow_exception(ex);
465     }
466 }
467
468 bool
469 _gmx_sel_is_lexer_interactive(yyscan_t scanner)
470 {
471     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
472     return state->bInteractive;
473 }
474
475 struct gmx_ana_selcollection_t *
476 _gmx_sel_lexer_selcollection(yyscan_t scanner)
477 {
478     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
479     return state->sc;
480 }
481
482 gmx::MessageStringCollector *
483 _gmx_sel_lexer_error_reporter(yyscan_t scanner)
484 {
485     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
486     GMX_RELEASE_ASSERT(state->errors != NULL, "Error reporter not set");
487     return state->errors;
488 }
489
490 bool
491 _gmx_sel_lexer_has_groups_set(yyscan_t scanner)
492 {
493     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
494     return state->bGroups;
495 }
496
497 struct gmx_ana_indexgrps_t *
498 _gmx_sel_lexer_indexgrps(yyscan_t scanner)
499 {
500     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
501     return state->grps;
502 }
503
504 int
505 _gmx_sel_lexer_exp_selcount(yyscan_t scanner)
506 {
507     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
508     return state->nexpsel;
509 }
510
511 const char *
512 _gmx_sel_lexer_pselstr(yyscan_t scanner)
513 {
514     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
515     return state->pselstr;
516 }
517
518 void
519 _gmx_sel_lexer_clear_pselstr(yyscan_t scanner)
520 {
521     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
522     state->pselstr[0] = 0;
523     state->pslen      = 0;
524 }
525
526 void
527 _gmx_sel_lexer_clear_method_stack(yyscan_t scanner)
528 {
529     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
530
531     state->msp = -1;
532 }
533
534 void
535 _gmx_sel_finish_method(yyscan_t scanner)
536 {
537     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
538
539     if (state->msp >= 0)
540     {
541         --state->msp;
542     }
543 }
544
545 void
546 _gmx_sel_set_lex_input_file(yyscan_t scanner, FILE *fp)
547 {
548     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
549
550     state->bBuffer = true;
551     state->buffer  = _gmx_sel_yy_create_buffer(fp, YY_BUF_SIZE, scanner);
552     _gmx_sel_yy_switch_to_buffer(state->buffer, scanner);
553 }
554
555 void
556 _gmx_sel_set_lex_input_str(yyscan_t scanner, const char *str)
557 {
558     gmx_sel_lexer_t *state = _gmx_sel_yyget_extra(scanner);
559
560     if (state->bBuffer)
561     {
562         _gmx_sel_yy_delete_buffer(state->buffer, scanner);
563     }
564     state->bBuffer = true;
565     state->buffer  = _gmx_sel_yy_scan_string(str, scanner);
566 }