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