Merge branch release-5-0
[alexxy/gromacs.git] / src / gromacs / selection / parsetree.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009,2010,2011,2012,2013,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
37  * Implements functions in parsetree.h.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_selection
41  */
42 /*! \internal
43  * \page page_module_selection_parser Selection parsing
44  *
45  * The selection parser is implemented in the following files:
46  *  - scanner.l:
47  *    Tokenizer implemented using Flex, splits the input into tokens
48  *    (scanner.c and scanner_flex.h are generated from this file).
49  *  - scanner.h, scanner_internal.h, scanner_internal.cpp:
50  *    Helper functions for scanner.l and for interfacing between
51  *    scanner.l and parser.y. Functions in scanner_internal.h are only
52  *    used from scanner.l, while scanner.h is used from the parser.
53  *  - symrec.h, symrec.cpp:
54  *    Functions used by the tokenizer to handle the symbol table, i.e.,
55  *    the recognized keywords. Some basic keywords are hardcoded into
56  *    scanner.l, but all method and variable references go through the
57  *    symbol table, as do position evaluation keywords.
58  *  - parser.y:
59  *    Semantic rules for parsing the grammar
60  *    (parser.cpp and parser.h are generated from this file by Bison).
61  *  - parsetree.h, parsetree.cpp:
62  *    Functions called from actions in parser.y to construct the
63  *    evaluation elements corresponding to different grammar elements.
64  *  - params.c:
65  *    Defines a function that processes the parameters of selection
66  *    methods and initializes the children of the method element.
67  *  - selectioncollection.h, selectioncollection.cpp:
68  *    These files define the high-level public interface to the parser
69  *    through SelectionCollection::parseFromStdin(),
70  *    SelectionCollection::parseFromFile() and
71  *    SelectionCollection::parseFromString().
72  *
73  * The basic control flow in the parser is as follows: when a parser function
74  * in SelectionCollection gets called, it performs some
75  * initialization, and then calls the _gmx_sel_yyparse() function generated
76  * by Bison. This function then calls _gmx_sel_yylex() to repeatedly read
77  * tokens from the input (more complex tasks related to token recognition
78  * and bookkeeping are done by functions in scanner_internal.cpp) and uses the
79  * grammar rules to decide what to do with them. Whenever a grammar rule
80  * matches, a corresponding function in parsetree.cpp is called to construct
81  * either a temporary representation for the object or a
82  * gmx::SelectionTreeElement object
83  * (some simple rules are handled internally in parser.y).
84  * When a complete selection has been parsed, the functions in parsetree.cpp
85  * also take care of updating the ::gmx_ana_selcollection_t structure
86  * appropriately.
87  *
88  * The rest of this page describes the resulting gmx::SelectionTreeElement
89  * object tree.
90  * Before the selections can be evaluated, this tree needs to be passed to
91  * the selection compiler, which is described on a separate page:
92  * \ref page_module_selection_compiler
93  *
94  *
95  * \section selparser_tree Element tree constructed by the parser
96  *
97  * The parser initializes the following fields in all selection elements:
98  * gmx::SelectionTreeElement::name, gmx::SelectionTreeElement::type,
99  * gmx::SelectionTreeElement::v\c .type,
100  * gmx::SelectionTreeElement::flags, gmx::SelectionTreeElement::child, and
101  * gmx::SelectionTreeElement::next.
102  * Some other fields are also initialized for particular element types as
103  * discussed below.
104  * Fields that are not initialized are set to zero, NULL, or other similar
105  * value.
106  *
107  *
108  * \subsection selparser_tree_root Root elements
109  *
110  * The parser creates a \ref SEL_ROOT selection element for each variable
111  * assignment and each selection. However, there are two exceptions that do
112  * not result in a \ref SEL_ROOT element (in these cases, only the symbol
113  * table is modified):
114  *  - Variable assignments that assign a variable to another variable.
115  *  - Variable assignments that assign a non-group constant.
116  *  .
117  * The \ref SEL_ROOT elements are linked together in a chain in the same order
118  * as in the input.
119  *
120  * The children of the \ref SEL_ROOT elements can be used to distinguish
121  * the two types of root elements from each other:
122  *  - For variable assignments, the first and only child is always
123  *    a \ref SEL_SUBEXPR element.
124  *  - For selections, the first child is a \ref SEL_EXPRESSION or a
125  *    \ref SEL_MODIFIER element that evaluates the final positions (if the
126  *    selection defines a constant position, the child is a \ref SEL_CONST).
127  *    The rest of the children are \ref SEL_MODIFIER elements with
128  *    \ref NO_VALUE, in the order given by the user.
129  *  .
130  * The name of the selection/variable is stored in
131  * gmx::SelectionTreeElement::cgrp\c .name.
132  * It is set to either the name provided by the user or the selection string
133  * for selections not explicitly named by the user.
134  * \ref SEL_ROOT or \ref SEL_SUBEXPR elements do not appear anywhere else.
135  *
136  *
137  * \subsection selparser_tree_const Constant elements
138  *
139  * \ref SEL_CONST elements are created for every constant that is required
140  * for later evaluation.
141  * Currently, \ref SEL_CONST elements can be present for
142  *  - selections that consist of a constant position,
143  *  - \ref GROUP_VALUE method parameters if provided using external index
144  *    groups,
145  *  .
146  * For group-valued elements, the value is stored in
147  * gmx::SelectionTreeElement::cgrp; other types of values are stored in
148  * gmx::SelectionTreeElement::v.
149  * Constants that appear as parameters for selection methods are not present
150  * in the selection tree unless they have \ref GROUP_VALUE.
151  * \ref SEL_CONST elements have no children.
152  *
153  *
154  * \subsection selparser_tree_method Method evaluation elements
155  *
156  * \ref SEL_EXPRESSION and \ref SEL_MODIFIER elements are treated very
157  * similarly. The \c gmx_ana_selmethod_t structure corresponding to the
158  * evaluation method is in gmx::SelectionTreeElement::method, and the method
159  * data in gmx::SelectionTreeElement::mdata has been allocated using
160  * sel_datafunc().
161  * If a non-standard reference position type was set,
162  * gmx::SelectionTreeElement::pc has also been created, but only the type has
163  * been set.
164  * All children of these elements are of the type \ref SEL_SUBEXPRREF, and
165  * each describes a selection that needs to be evaluated to obtain a value
166  * for one parameter of the method.
167  * No children are present for parameters that were given a constant
168  * non-\ref GROUP_VALUE value.
169  * The children are sorted in the order in which the parameters appear in the
170  * \ref gmx_ana_selmethod_t structure.
171  *
172  * In addition to actual selection keywords, \ref SEL_EXPRESSION elements
173  * are used internally to implement numerical comparisons (e.g., "x < 5")
174  * and keyword matching (e.g., "resnr 1 to 3" or "name CA").
175  *
176  *
177  * \subsection selparser_tree_subexpr Subexpression elements
178  *
179  * \ref SEL_SUBEXPR elements only appear for variables, as described above.
180  * gmx::SelectionTreeElement::name points to the name of the variable (from the
181  * \ref SEL_ROOT element).
182  * The element always has exactly one child, which represents the value of
183  * the variable.
184  *
185  * \ref SEL_SUBEXPRREF elements are used for two purposes:
186  *  - Variable references that need to be evaluated (i.e., there is a
187  *    \ref SEL_SUBEXPR element for the variable) are represented using
188  *    \ref SEL_SUBEXPRREF elements.
189  *    In this case, gmx::SelectionTreeElement::param is NULL, and the first and
190  *    only child of the element is the \ref SEL_SUBEXPR element of the
191  *    variable.
192  *    Such references can appear anywhere where the variable value
193  *    (the child of the \ref SEL_SUBEXPR element) would be valid.
194  *  - Children of \ref SEL_EXPRESSION and \ref SEL_MODIFIER elements are
195  *    always of this type. For these elements, gmx::SelectionTreeElement::param
196  *    is initialized to point to the parameter that receives the value from
197  *    the expression.
198  *    Each such element has exactly one child, which can be of any type;
199  *    the \ref SEL_SUBEXPR element of a variable is used if the value comes
200  *    from a variable, otherwise the child type is not \ref SEL_SUBEXPR.
201  *
202  *
203  * \subsection selparser_tree_bool Boolean elements
204  *
205  * One \ref SEL_BOOLEAN element is created for each boolean keyword in the
206  * input, and the tree structure represents the evaluation order.
207  * The gmx::SelectionTreeElement::boolt type gives the type of the operation.
208  * Each element has exactly two children (one for \ref BOOL_NOT elements),
209  * which are in the order given in the input.
210  * The children always have \ref GROUP_VALUE, but different element types
211  * are possible.
212  *
213  *
214  * \subsection selparser_tree_arith Arithmetic elements
215  *
216  * One \ref SEL_ARITHMETIC element is created for each arithmetic operation in
217  * the input, and the tree structure represents the evaluation order.
218  * The gmx::SelectionTreeElement::optype type gives the name of the operation.
219  * Each element has exactly two children (one for unary negation elements),
220  * which are in the order given in the input.
221  */
222 #include "gmxpre.h"
223
224 #include "parsetree.h"
225
226 #include <stdarg.h>
227 #include <stdio.h>
228
229 #include <boost/exception_ptr.hpp>
230 #include <boost/shared_ptr.hpp>
231
232 #include "gromacs/selection/selection.h"
233 #include "gromacs/utility/cstringutil.h"
234 #include "gromacs/utility/exceptions.h"
235 #include "gromacs/utility/file.h"
236 #include "gromacs/utility/messagestringcollector.h"
237 #include "gromacs/utility/smalloc.h"
238 #include "gromacs/utility/stringutil.h"
239
240 #include "keywords.h"
241 #include "poscalc.h"
242 #include "scanner.h"
243 #include "selectioncollection-impl.h"
244 #include "selelem.h"
245 #include "selmethod.h"
246 #include "symrec.h"
247
248 using gmx::SelectionLocation;
249 using gmx::SelectionParserValue;
250 using gmx::SelectionParserValueList;
251 using gmx::SelectionParserValueListPointer;
252 using gmx::SelectionParserParameter;
253 using gmx::SelectionParserParameterList;
254 using gmx::SelectionParserParameterListPointer;
255 using gmx::SelectionParserValue;
256 using gmx::SelectionTreeElement;
257 using gmx::SelectionTreeElementPointer;
258
259 namespace
260 {
261
262 /*! \brief
263  * Formats context string for errors.
264  *
265  * The returned string is used as the context for errors reported during
266  * parsing.
267  */
268 std::string
269 formatCurrentErrorContext(yyscan_t scanner)
270 {
271     return gmx::formatString(
272             "While parsing '%s'",
273             _gmx_sel_lexer_get_current_text(scanner).c_str());
274 }
275
276 } // namespace
277
278 void
279 _gmx_selparser_error(yyscan_t scanner, const char *fmt, ...)
280 {
281     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
282     // FIXME: Use an arbitrary length buffer.
283     char    buf[1024];
284     va_list ap;
285     va_start(ap, fmt);
286     vsnprintf(buf, 1024, fmt, ap);
287     va_end(ap);
288     errors->append(buf);
289 }
290
291 bool
292 _gmx_selparser_handle_exception(yyscan_t scanner, std::exception *ex)
293 {
294     try
295     {
296         bool                   canContinue = false;
297         gmx::GromacsException *gromacsException
298             = dynamic_cast<gmx::GromacsException *>(ex);
299         if (gromacsException != NULL)
300         {
301             gromacsException->prependContext(formatCurrentErrorContext(scanner));
302             canContinue = (dynamic_cast<gmx::UserInputError *>(ex) != NULL);
303         }
304         _gmx_sel_lexer_set_exception(scanner, boost::current_exception());
305         return canContinue;
306     }
307     catch (const std::exception &)
308     {
309         _gmx_sel_lexer_set_exception(scanner, boost::current_exception());
310         return false;
311     }
312 }
313
314 bool
315 _gmx_selparser_handle_error(yyscan_t scanner)
316 {
317     std::string context(gmx::formatString("In selection '%s'",
318                                           _gmx_sel_lexer_pselstr(scanner)));
319     // The only way to prepend context to the exception is to rethrow it.
320     try
321     {
322         _gmx_sel_lexer_rethrow_exception_if_occurred(scanner);
323     }
324     catch (gmx::UserInputError &ex)
325     {
326         ex.prependContext(context);
327         if (_gmx_sel_is_lexer_interactive(scanner))
328         {
329             gmx::formatExceptionMessageToFile(stderr, ex);
330             return true;
331         }
332         throw;
333     }
334     catch (gmx::GromacsException &ex)
335     {
336         ex.prependContext(context);
337         throw;
338     }
339     // Do legacy processing for non-exception cases.
340     // This is only reached if there was no active exception.
341     _gmx_selparser_error(scanner, "Invalid selection '%s'",
342                          _gmx_sel_lexer_pselstr(scanner));
343     return _gmx_sel_is_lexer_interactive(scanner);
344 }
345
346 namespace gmx
347 {
348
349 /********************************************************************
350  * SelectionParserValue
351  */
352
353 SelectionParserValue::SelectionParserValue(
354         e_selvalue_t type, const SelectionLocation &location)
355     : type(type), location_(location)
356 {
357     memset(&u, 0, sizeof(u));
358 }
359
360 SelectionParserValue::SelectionParserValue(
361         const SelectionTreeElementPointer &expr)
362     : type(expr->v.type), expr(expr), location_(expr->location())
363 {
364     memset(&u, 0, sizeof(u));
365 }
366
367 /********************************************************************
368  * SelectionParserParameter
369  */
370
371 SelectionParserParameter::SelectionParserParameter(
372         const char                      *name,
373         SelectionParserValueListPointer  values,
374         const SelectionLocation         &location)
375     : name_(name != NULL ? name : ""), location_(location),
376       values_(values ? move(values)
377               : SelectionParserValueListPointer(new SelectionParserValueList))
378 {
379 }
380
381 } // namespace gmx
382
383 /*!
384  * \param[in,out] sel  Root of the selection element tree to initialize.
385  *
386  * Propagates the \ref SEL_DYNAMIC flag from the children of \p sel to \p sel
387  * (if any child of \p sel is dynamic, \p sel is also marked as such).
388  * The \ref SEL_DYNAMIC flag is also set for \ref SEL_EXPRESSION elements with
389  * a dynamic method.
390  * Also, sets one of the \ref SEL_SINGLEVAL, \ref SEL_ATOMVAL, or
391  * \ref SEL_VARNUMVAL flags, either based on the children or on the type of
392  * the selection method.
393  * If the types of the children conflict, an error is returned.
394  *
395  * The flags of the children of \p sel are also updated if not done earlier.
396  * The flags are initialized only once for any element; if \ref SEL_FLAGSSET
397  * is set for an element, the function returns immediately, and the recursive
398  * operation does not descend beyond such elements.
399  */
400 void
401 _gmx_selelem_update_flags(const gmx::SelectionTreeElementPointer &sel)
402 {
403     bool                bUseChildType = false;
404     bool                bOnlySingleChildren;
405
406     /* Return if the flags have already been set */
407     if (sel->flags & SEL_FLAGSSET)
408     {
409         return;
410     }
411     /* Set the flags based on the current element type */
412     switch (sel->type)
413     {
414         case SEL_CONST:
415         case SEL_GROUPREF:
416             sel->flags   |= SEL_SINGLEVAL;
417             bUseChildType = false;
418             break;
419
420         case SEL_EXPRESSION:
421             if (sel->u.expr.method->flags & SMETH_DYNAMIC)
422             {
423                 sel->flags |= SEL_DYNAMIC;
424             }
425             if (sel->u.expr.method->flags & SMETH_SINGLEVAL)
426             {
427                 sel->flags |= SEL_SINGLEVAL;
428             }
429             else if (sel->u.expr.method->flags & SMETH_VARNUMVAL)
430             {
431                 sel->flags |= SEL_VARNUMVAL;
432             }
433             else
434             {
435                 sel->flags |= SEL_ATOMVAL;
436             }
437             bUseChildType = false;
438             break;
439
440         case SEL_ARITHMETIC:
441             sel->flags   |= SEL_ATOMVAL;
442             bUseChildType = false;
443             break;
444
445         case SEL_MODIFIER:
446             if (sel->v.type != NO_VALUE)
447             {
448                 sel->flags |= SEL_VARNUMVAL;
449             }
450             bUseChildType = false;
451             break;
452
453         case SEL_ROOT:
454             bUseChildType = false;
455             break;
456
457         case SEL_BOOLEAN:
458         case SEL_SUBEXPR:
459         case SEL_SUBEXPRREF:
460             bUseChildType = true;
461             break;
462     }
463     /* Loop through children to propagate their flags upwards */
464     bOnlySingleChildren = true;
465     SelectionTreeElementPointer child = sel->child;
466     while (child)
467     {
468         /* Update the child */
469         _gmx_selelem_update_flags(child);
470         /* Propagate the dynamic and unsorted flags */
471         sel->flags |= (child->flags & (SEL_DYNAMIC | SEL_UNSORTED));
472         /* Propagate the type flag if necessary and check for problems */
473         if (bUseChildType)
474         {
475             if ((sel->flags & SEL_VALTYPEMASK)
476                 && !(sel->flags & child->flags & SEL_VALTYPEMASK))
477             {
478                 // TODO: Recollect when this is triggered, and whether the type
479                 // is appropriate.
480                 GMX_THROW(gmx::InvalidInputError("Invalid combination of selection expressions"));
481             }
482             sel->flags |= (child->flags & SEL_VALTYPEMASK);
483         }
484         if (!(child->flags & SEL_SINGLEVAL))
485         {
486             bOnlySingleChildren = false;
487         }
488
489         child = child->next;
490     }
491     /* For arithmetic expressions consisting only of single values,
492      * the result is also a single value. */
493     if (sel->type == SEL_ARITHMETIC && bOnlySingleChildren)
494     {
495         sel->flags = (sel->flags & ~SEL_VALTYPEMASK) | SEL_SINGLEVAL;
496     }
497     /* For root elements, the type should be propagated here, after the
498      * children have been updated. */
499     if (sel->type == SEL_ROOT)
500     {
501         GMX_ASSERT(sel->child, "Root elements should always have a child");
502         sel->flags |= (sel->child->flags & SEL_VALTYPEMASK);
503     }
504     /* Mark that the flags are set */
505     sel->flags |= SEL_FLAGSSET;
506 }
507
508 /*!
509  * \param[in,out] sel    Selection element to initialize.
510  * \param[in]     scanner Scanner data structure.
511  *
512  * A deep copy of the parameters is made to allow several
513  * expressions with the same method to coexist peacefully.
514  * Calls sel_datafunc() if one is specified for the method.
515  */
516 void
517 _gmx_selelem_init_method_params(const gmx::SelectionTreeElementPointer &sel,
518                                 yyscan_t                                scanner)
519 {
520     int                 nparams;
521     gmx_ana_selparam_t *orgparam;
522     gmx_ana_selparam_t *param;
523     int                 i;
524     void               *mdata;
525
526     nparams   = sel->u.expr.method->nparams;
527     orgparam  = sel->u.expr.method->param;
528     snew(param, nparams);
529     memcpy(param, orgparam, nparams*sizeof(gmx_ana_selparam_t));
530     for (i = 0; i < nparams; ++i)
531     {
532         param[i].flags &= ~SPAR_SET;
533         _gmx_selvalue_setstore(&param[i].val, NULL);
534         if (param[i].flags & SPAR_VARNUM)
535         {
536             param[i].val.nr = -1;
537         }
538         /* Duplicate the enum value array if it is given statically */
539         if ((param[i].flags & SPAR_ENUMVAL) && orgparam[i].val.u.ptr != NULL)
540         {
541             int n;
542
543             /* Count the values */
544             n = 1;
545             while (orgparam[i].val.u.s[n] != NULL)
546             {
547                 ++n;
548             }
549             _gmx_selvalue_reserve(&param[i].val, n+1);
550             memcpy(param[i].val.u.s, orgparam[i].val.u.s,
551                    (n+1)*sizeof(param[i].val.u.s[0]));
552         }
553     }
554     mdata = NULL;
555     if (sel->u.expr.method->init_data)
556     {
557         mdata = sel->u.expr.method->init_data(nparams, param);
558     }
559     if (sel->u.expr.method->set_poscoll)
560     {
561         gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
562
563         sel->u.expr.method->set_poscoll(&sc->pcc, mdata);
564     }
565     /* Store the values */
566     sel->u.expr.method->param = param;
567     sel->u.expr.mdata         = mdata;
568 }
569
570 /*!
571  * \param[in,out] sel    Selection element to initialize.
572  * \param[in]     method Selection method to set.
573  * \param[in]     scanner Scanner data structure.
574  *
575  * Makes a copy of \p method and stores it in \p sel->u.expr.method,
576  * and calls _gmx_selelem_init_method_params();
577  */
578 void
579 _gmx_selelem_set_method(const gmx::SelectionTreeElementPointer &sel,
580                         gmx_ana_selmethod_t                    *method,
581                         yyscan_t                                scanner)
582 {
583     _gmx_selelem_set_vtype(sel, method->type);
584     sel->setName(method->name);
585     snew(sel->u.expr.method, 1);
586     memcpy(sel->u.expr.method, method, sizeof(gmx_ana_selmethod_t));
587     _gmx_selelem_init_method_params(sel, scanner);
588 }
589
590 /*! \brief
591  * Initializes the reference position calculation for a \ref SEL_EXPRESSION
592  * element.
593  *
594  * \param[in,out] pcc    Position calculation collection to use.
595  * \param[in,out] sel    Selection element to initialize.
596  * \param[in]     rpost  Reference position type to use (NULL = default).
597  * \param[in]     scanner Scanner data structure.
598  * \returns       0 on success, a non-zero error code on error.
599  */
600 static void
601 set_refpos_type(gmx::PositionCalculationCollection *pcc,
602                 const SelectionTreeElementPointer &sel,
603                 const char *rpost, yyscan_t scanner)
604 {
605     if (!rpost)
606     {
607         return;
608     }
609
610     if (sel->u.expr.method->pupdate)
611     {
612         /* By default, use whole residues/molecules. */
613         sel->u.expr.pc
614             = pcc->createCalculationFromEnum(rpost, POS_COMPLWHOLE);
615     }
616     else
617     {
618         // TODO: Should this be treated as a real error?
619         _gmx_selparser_error(scanner, "modifier '%s' is not applicable for '%s'",
620                              rpost, sel->u.expr.method->name);
621     }
622 }
623
624 gmx::SelectionTreeElementPointer
625 _gmx_sel_init_arithmetic(const gmx::SelectionTreeElementPointer &left,
626                          const gmx::SelectionTreeElementPointer &right,
627                          char op, yyscan_t scanner)
628 {
629     SelectionTreeElementPointer sel(
630             new SelectionTreeElement(
631                     SEL_ARITHMETIC, _gmx_sel_lexer_get_current_location(scanner)));
632     sel->v.type        = REAL_VALUE;
633     switch (op)
634     {
635         case '+': sel->u.arith.type = ARITH_PLUS; break;
636         case '-': sel->u.arith.type = (right ? ARITH_MINUS : ARITH_NEG); break;
637         case '*': sel->u.arith.type = ARITH_MULT; break;
638         case '/': sel->u.arith.type = ARITH_DIV;  break;
639         case '^': sel->u.arith.type = ARITH_EXP;  break;
640     }
641     char               buf[2];
642     buf[0] = op;
643     buf[1] = 0;
644     sel->setName(buf);
645     sel->u.arith.opstr = gmx_strdup(buf);
646     sel->child         = left;
647     sel->child->next   = right;
648     return sel;
649 }
650
651 /*!
652  * \param[in]  left   Selection element for the left hand side.
653  * \param[in]  right  Selection element for the right hand side.
654  * \param[in]  cmpop  String representation of the comparison operator.
655  * \param[in]  scanner Scanner data structure.
656  * \returns    The created selection element.
657  *
658  * This function handles the creation of a gmx::SelectionTreeElement object for
659  * comparison expressions.
660  */
661 SelectionTreeElementPointer
662 _gmx_sel_init_comparison(const gmx::SelectionTreeElementPointer &left,
663                          const gmx::SelectionTreeElementPointer &right,
664                          const char *cmpop, yyscan_t scanner)
665 {
666     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
667     gmx::MessageStringContext    context(errors, formatCurrentErrorContext(scanner));
668
669     SelectionTreeElementPointer  sel(
670             new SelectionTreeElement(
671                     SEL_EXPRESSION, _gmx_sel_lexer_get_current_location(scanner)));
672     _gmx_selelem_set_method(sel, &sm_compare, scanner);
673
674     SelectionParserParameterList params;
675     const char                  *name;
676     // Create the parameter for the left expression.
677     name  = left->v.type == INT_VALUE ? "int1" : "real1";
678     params.push_back(SelectionParserParameter::createFromExpression(name, left));
679     // Create the parameter for the right expression.
680     name  = right->v.type == INT_VALUE ? "int2" : "real2";
681     params.push_back(SelectionParserParameter::createFromExpression(name, right));
682     // Create the parameter for the operator.
683     // TODO: Consider whether a proper location is needed.
684     SelectionLocation location(SelectionLocation::createEmpty());
685     params.push_back(
686             SelectionParserParameter::create(
687                     "op", SelectionParserValue::createString(cmpop, location),
688                     location));
689     if (!_gmx_sel_parse_params(params, sel->u.expr.method->nparams,
690                                sel->u.expr.method->param, sel, scanner))
691     {
692         return SelectionTreeElementPointer();
693     }
694
695     return sel;
696 }
697
698 /*! \brief
699  * Implementation method for keyword expression creation.
700  *
701  * \param[in]  method Method to use.
702  * \param[in]  matchType String matching type (only used if \p method is
703  *      a string keyword and \p args is not empty.
704  * \param[in]  args   Pointer to the first argument.
705  * \param[in]  rpost  Reference position type to use (NULL = default).
706  * \param[in]  scanner Scanner data structure.
707  * \returns    The created selection element.
708  *
709  * This function handles the creation of a gmx::SelectionTreeElement object for
710  * selection methods that do not take parameters.
711  */
712 static SelectionTreeElementPointer
713 init_keyword_internal(gmx_ana_selmethod_t *method,
714                       gmx::SelectionStringMatchType matchType,
715                       SelectionParserValueListPointer args,
716                       const char *rpost, yyscan_t scanner)
717 {
718     gmx_ana_selcollection_t     *sc = _gmx_sel_lexer_selcollection(scanner);
719
720     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
721     gmx::MessageStringContext    context(errors, formatCurrentErrorContext(scanner));
722
723     if (method->nparams > 0)
724     {
725         // TODO: Would assert be better?
726         GMX_THROW(gmx::InternalError(
727                           "Keyword initialization called with non-keyword method"));
728     }
729
730     const SelectionLocation    &location = _gmx_sel_lexer_get_current_location(scanner);
731     // TODO: If there are arguments, the location would be better as just the
732     // location of the keyword itself.
733     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION, location));
734     SelectionTreeElementPointer child = root;
735     _gmx_selelem_set_method(child, method, scanner);
736
737     /* Initialize the evaluation of keyword matching if values are provided */
738     if (args)
739     {
740         gmx_ana_selmethod_t *kwmethod;
741         switch (method->type)
742         {
743             case INT_VALUE:  kwmethod = &sm_keyword_int;  break;
744             case REAL_VALUE: kwmethod = &sm_keyword_real; break;
745             case STR_VALUE:  kwmethod = &sm_keyword_str;  break;
746             default:
747                 GMX_THROW(gmx::InternalError(
748                                   "Unknown type for keyword selection"));
749         }
750         /* Initialize the selection element */
751         root.reset(new SelectionTreeElement(SEL_EXPRESSION, location));
752         _gmx_selelem_set_method(root, kwmethod, scanner);
753         if (method->type == STR_VALUE)
754         {
755             _gmx_selelem_set_kwstr_match_type(root, matchType);
756         }
757         SelectionParserParameterList params;
758         params.push_back(
759                 SelectionParserParameter::createFromExpression(NULL, child));
760         params.push_back(
761                 SelectionParserParameter::create(NULL, move(args), location));
762         if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
763                                    root->u.expr.method->param, root, scanner))
764         {
765             return SelectionTreeElementPointer();
766         }
767     }
768     set_refpos_type(&sc->pcc, child, rpost, scanner);
769
770     return root;
771 }
772
773 /*!
774  * \param[in]  method Method to use.
775  * \param[in]  args   Pointer to the first argument.
776  * \param[in]  rpost  Reference position type to use (NULL = default).
777  * \param[in]  scanner Scanner data structure.
778  * \returns    The created selection element.
779  *
780  * This function handles the creation of a gmx::SelectionTreeElement object for
781  * selection methods that do not take parameters.
782  */
783 SelectionTreeElementPointer
784 _gmx_sel_init_keyword(gmx_ana_selmethod_t *method,
785                       gmx::SelectionParserValueListPointer args,
786                       const char *rpost, yyscan_t scanner)
787 {
788     return init_keyword_internal(method, gmx::eStringMatchType_Auto, move(args),
789                                  rpost, scanner);
790 }
791
792 /*!
793  * \param[in]  method    Method to use.
794  * \param[in]  matchType String matching type.
795  * \param[in]  args      Pointer to the first argument.
796  * \param[in]  rpost     Reference position type to use (NULL = default).
797  * \param[in]  scanner   Scanner data structure.
798  * \returns    The created selection element.
799  *
800  * This function handles the creation of a gmx::SelectionTreeElement object for
801  * keyword string matching.
802  */
803 SelectionTreeElementPointer
804 _gmx_sel_init_keyword_strmatch(gmx_ana_selmethod_t *method,
805                                gmx::SelectionStringMatchType matchType,
806                                gmx::SelectionParserValueListPointer args,
807                                const char *rpost, yyscan_t scanner)
808 {
809     GMX_RELEASE_ASSERT(method->type == STR_VALUE,
810                        "String keyword method called for a non-string-valued method");
811     GMX_RELEASE_ASSERT(args && !args->empty(),
812                        "String keyword matching method called without any values");
813     return init_keyword_internal(method, matchType, move(args), rpost, scanner);
814 }
815
816 /*!
817  * \param[in]  method Method to use for initialization.
818  * \param[in]  group  Selection in which the keyword should be evaluated.
819  * \param[in]  rpost  Reference position type to use (NULL = default).
820  * \param[in]  scanner Scanner data structure.
821  * \returns    The created selection element.
822  *
823  * This function handles the creation of a gmx::SelectionTreeElement object for
824  * expressions like "z of ...".
825  */
826 SelectionTreeElementPointer
827 _gmx_sel_init_keyword_of(gmx_ana_selmethod_t                    *method,
828                          const gmx::SelectionTreeElementPointer &group,
829                          const char *rpost, yyscan_t scanner)
830 {
831     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
832     gmx::MessageStringContext    context(errors, formatCurrentErrorContext(scanner));
833
834     GMX_UNUSED_VALUE(rpost);
835     return _gmx_sel_init_keyword_evaluator(method, group, scanner);
836 }
837
838 /*!
839  * \param[in]  method Method to use for initialization.
840  * \param[in]  params Pointer to the first parameter.
841  * \param[in]  rpost  Reference position type to use (NULL = default).
842  * \param[in]  scanner Scanner data structure.
843  * \returns    The created selection element.
844  *
845  * This function handles the creation of a gmx::SelectionTreeElement object for
846  * selection methods that take parameters.
847  *
848  * Part of the behavior of the \c same selection keyword is hardcoded into
849  * this function (or rather, into _gmx_selelem_custom_init_same()) to allow the
850  * use of any keyword in \c "same KEYWORD as" without requiring special
851  * handling somewhere else (or sacrificing the simple syntax).
852  */
853 SelectionTreeElementPointer
854 _gmx_sel_init_method(gmx_ana_selmethod_t                      *method,
855                      gmx::SelectionParserParameterListPointer  params,
856                      const char *rpost, yyscan_t scanner)
857 {
858     gmx_ana_selcollection_t     *sc = _gmx_sel_lexer_selcollection(scanner);
859     int                          rc;
860
861     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
862     gmx::MessageStringContext    context(errors, formatCurrentErrorContext(scanner));
863
864     _gmx_sel_finish_method(scanner);
865     /* The "same" keyword needs some custom massaging of the parameters. */
866     rc = _gmx_selelem_custom_init_same(&method, params, scanner);
867     if (rc != 0)
868     {
869         return SelectionTreeElementPointer();
870     }
871     SelectionTreeElementPointer root(
872             new SelectionTreeElement(
873                     SEL_EXPRESSION, _gmx_sel_lexer_get_current_location(scanner)));
874     _gmx_selelem_set_method(root, method, scanner);
875     /* Process the parameters */
876     if (!_gmx_sel_parse_params(*params, root->u.expr.method->nparams,
877                                root->u.expr.method->param, root, scanner))
878     {
879         return SelectionTreeElementPointer();
880     }
881     set_refpos_type(&sc->pcc, root, rpost, scanner);
882
883     return root;
884 }
885
886 /*!
887  * \param[in]  method Modifier to use for initialization.
888  * \param[in]  params Pointer to the first parameter.
889  * \param[in]  sel    Selection element that the modifier should act on.
890  * \param[in]  scanner Scanner data structure.
891  * \returns    The created selection element.
892  *
893  * This function handles the creation of a gmx::SelectionTreeElement object for
894  * selection modifiers.
895  */
896 SelectionTreeElementPointer
897 _gmx_sel_init_modifier(gmx_ana_selmethod_t                      *method,
898                        gmx::SelectionParserParameterListPointer  params,
899                        const gmx::SelectionTreeElementPointer   &sel,
900                        yyscan_t                                  scanner)
901 {
902     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
903     gmx::MessageStringContext    context(errors, formatCurrentErrorContext(scanner));
904
905     _gmx_sel_finish_method(scanner);
906     SelectionTreeElementPointer modifier(
907             new SelectionTreeElement(
908                     SEL_MODIFIER, _gmx_sel_lexer_get_current_location(scanner)));
909     _gmx_selelem_set_method(modifier, method, scanner);
910     SelectionTreeElementPointer root;
911     if (method->type == NO_VALUE)
912     {
913         SelectionTreeElementPointer child = sel;
914         while (child->next)
915         {
916             child = child->next;
917         }
918         child->next = modifier;
919         root        = sel;
920     }
921     else
922     {
923         params->push_front(
924                 SelectionParserParameter::createFromExpression(NULL, sel));
925         root = modifier;
926     }
927     /* Process the parameters */
928     if (!_gmx_sel_parse_params(*params, modifier->u.expr.method->nparams,
929                                modifier->u.expr.method->param, modifier, scanner))
930     {
931         return SelectionTreeElementPointer();
932     }
933
934     return root;
935 }
936
937 /*!
938  * \param[in]  expr    Input selection element for the position calculation.
939  * \param[in]  type    Reference position type or NULL for default.
940  * \param[in]  scanner Scanner data structure.
941  * \returns    The created selection element.
942  *
943  * This function handles the creation of a gmx::SelectionTreeElement object for
944  * evaluation of reference positions.
945  */
946 SelectionTreeElementPointer
947 _gmx_sel_init_position(const gmx::SelectionTreeElementPointer &expr,
948                        const char *type, yyscan_t scanner)
949 {
950     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
951     gmx::MessageStringContext    context(errors, formatCurrentErrorContext(scanner));
952
953     SelectionTreeElementPointer  root(
954             new SelectionTreeElement(
955                     SEL_EXPRESSION, _gmx_sel_lexer_get_current_location(scanner)));
956     _gmx_selelem_set_method(root, &sm_keyword_pos, scanner);
957     _gmx_selelem_set_kwpos_type(root.get(), type);
958     /* Create the parameters for the parameter parser. */
959     SelectionParserParameterList params;
960     params.push_back(SelectionParserParameter::createFromExpression(NULL, expr));
961     /* Parse the parameters. */
962     if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
963                                root->u.expr.method->param, root, scanner))
964     {
965         return SelectionTreeElementPointer();
966     }
967
968     return root;
969 }
970
971 /*!
972  * \param[in] x,y,z   Coordinates for the position.
973  * \param[in] scanner Scanner data structure.
974  * \returns   The creates selection element.
975  */
976 SelectionTreeElementPointer
977 _gmx_sel_init_const_position(real x, real y, real z, yyscan_t scanner)
978 {
979     rvec                        pos;
980
981     SelectionTreeElementPointer sel(
982             new SelectionTreeElement(
983                     SEL_CONST, _gmx_sel_lexer_get_current_location(scanner)));
984     _gmx_selelem_set_vtype(sel, POS_VALUE);
985     _gmx_selvalue_reserve(&sel->v, 1);
986     pos[XX] = x;
987     pos[YY] = y;
988     pos[ZZ] = z;
989     gmx_ana_pos_init_const(sel->v.u.p, pos);
990     return sel;
991 }
992
993 /*!
994  * \param[in] name  Name of an index group to search for.
995  * \param[in] scanner Scanner data structure.
996  * \returns   The created selection element.
997  *
998  * See gmx_ana_indexgrps_find() for information on how \p name is matched
999  * against the index groups.
1000  */
1001 SelectionTreeElementPointer
1002 _gmx_sel_init_group_by_name(const char *name, yyscan_t scanner)
1003 {
1004
1005     SelectionTreeElementPointer sel(
1006             new SelectionTreeElement(
1007                     SEL_GROUPREF, _gmx_sel_lexer_get_current_location(scanner)));
1008     _gmx_selelem_set_vtype(sel, GROUP_VALUE);
1009     sel->setName(gmx::formatString("group \"%s\"", name));
1010     sel->u.gref.name = gmx_strdup(name);
1011     sel->u.gref.id   = -1;
1012
1013     if (_gmx_sel_lexer_has_groups_set(scanner))
1014     {
1015         gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
1016         gmx_ana_selcollection_t *sc   = _gmx_sel_lexer_selcollection(scanner);
1017         sel->resolveIndexGroupReference(grps, sc->gall.isize);
1018     }
1019
1020     return sel;
1021 }
1022
1023 /*!
1024  * \param[in] id    Zero-based index number of the group to extract.
1025  * \param[in] scanner Scanner data structure.
1026  * \returns   The created selection element.
1027  */
1028 SelectionTreeElementPointer
1029 _gmx_sel_init_group_by_id(int id, yyscan_t scanner)
1030 {
1031     SelectionTreeElementPointer sel(
1032             new SelectionTreeElement(
1033                     SEL_GROUPREF, _gmx_sel_lexer_get_current_location(scanner)));
1034     _gmx_selelem_set_vtype(sel, GROUP_VALUE);
1035     sel->setName(gmx::formatString("group %d", id));
1036     sel->u.gref.name = NULL;
1037     sel->u.gref.id   = id;
1038
1039     if (_gmx_sel_lexer_has_groups_set(scanner))
1040     {
1041         gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
1042         gmx_ana_selcollection_t *sc   = _gmx_sel_lexer_selcollection(scanner);
1043         sel->resolveIndexGroupReference(grps, sc->gall.isize);
1044     }
1045
1046     return sel;
1047 }
1048
1049 /*!
1050  * \param[in,out] sel      Value of the variable.
1051  * \param         scanner  Scanner data structure.
1052  * \returns       The created selection element that references \p sel.
1053  *
1054  * The reference count of \p sel is updated, but no other modifications are
1055  * made.
1056  */
1057 SelectionTreeElementPointer
1058 _gmx_sel_init_variable_ref(const gmx::SelectionTreeElementPointer &sel,
1059                            yyscan_t                                scanner)
1060 {
1061     SelectionTreeElementPointer ref;
1062
1063     if (sel->v.type == POS_VALUE && sel->type == SEL_CONST)
1064     {
1065         ref = sel;
1066     }
1067     else
1068     {
1069         ref.reset(new SelectionTreeElement(
1070                           SEL_SUBEXPRREF, _gmx_sel_lexer_get_current_location(scanner)));
1071         _gmx_selelem_set_vtype(ref, sel->v.type);
1072         ref->setName(sel->name());
1073         ref->child = sel;
1074     }
1075     return ref;
1076 }
1077
1078 /*!
1079  * \param[in]  name     Name for the selection
1080  *     (if NULL, a default name is constructed).
1081  * \param[in]  sel      The selection element that evaluates the selection.
1082  * \param      scanner  Scanner data structure.
1083  * \returns    The created root selection element.
1084  *
1085  * This function handles the creation of root (\ref SEL_ROOT)
1086  * gmx::SelectionTreeElement objects for selections.
1087  */
1088 SelectionTreeElementPointer
1089 _gmx_sel_init_selection(const char                             *name,
1090                         const gmx::SelectionTreeElementPointer &sel,
1091                         yyscan_t                                scanner)
1092 {
1093     if (sel->v.type != POS_VALUE)
1094     {
1095         /* FIXME: Better handling of this error */
1096         GMX_THROW(gmx::InternalError(
1097                           "Each selection must evaluate to a position"));
1098     }
1099
1100     SelectionTreeElementPointer root(
1101             new SelectionTreeElement(
1102                     SEL_ROOT, _gmx_sel_lexer_get_current_location(scanner)));
1103     root->child = sel;
1104     if (name)
1105     {
1106         root->setName(name);
1107     }
1108     /* Update the flags */
1109     _gmx_selelem_update_flags(root);
1110     gmx::ExceptionInitializer errors("Invalid index group reference(s)");
1111     root->checkUnsortedAtoms(true, &errors);
1112     if (errors.hasNestedExceptions())
1113     {
1114         GMX_THROW(gmx::InconsistentInputError(errors));
1115     }
1116
1117     root->fillNameIfMissing(_gmx_sel_lexer_pselstr(scanner));
1118
1119     /* Print out some information if the parser is interactive */
1120     if (_gmx_sel_is_lexer_interactive(scanner))
1121     {
1122         fprintf(stderr, "Selection '%s' parsed\n",
1123                 _gmx_sel_lexer_pselstr(scanner));
1124     }
1125
1126     return root;
1127 }
1128
1129
1130 /*!
1131  * \param[in]  name     Name of the variable.
1132  * \param[in]  expr     The selection element that evaluates the variable.
1133  * \param      scanner  Scanner data structure.
1134  * \returns    The created root selection element.
1135  *
1136  * This function handles the creation of root gmx::SelectionTreeElement objects
1137  * for variable assignments. A \ref SEL_ROOT element and a \ref SEL_SUBEXPR
1138  * element are both created.
1139  */
1140 SelectionTreeElementPointer
1141 _gmx_sel_assign_variable(const char                             *name,
1142                          const gmx::SelectionTreeElementPointer &expr,
1143                          yyscan_t                                scanner)
1144 {
1145     gmx_ana_selcollection_t     *sc      = _gmx_sel_lexer_selcollection(scanner);
1146     const char                  *pselstr = _gmx_sel_lexer_pselstr(scanner);
1147     SelectionTreeElementPointer  root;
1148
1149     _gmx_selelem_update_flags(expr);
1150     /* Check if this is a constant non-group value */
1151     if (expr->type == SEL_CONST && expr->v.type != GROUP_VALUE)
1152     {
1153         /* If so, just assign the constant value to the variable */
1154         sc->symtab->addVariable(name, expr);
1155     }
1156     /* Check if we are assigning a variable to another variable */
1157     else if (expr->type == SEL_SUBEXPRREF)
1158     {
1159         /* If so, make a simple alias */
1160         sc->symtab->addVariable(name, expr->child);
1161     }
1162     else
1163     {
1164         SelectionLocation location(_gmx_sel_lexer_get_current_location(scanner));
1165         /* Create the root element */
1166         root.reset(new SelectionTreeElement(SEL_ROOT, location));
1167         root->setName(name);
1168         /* Create the subexpression element */
1169         root->child.reset(new SelectionTreeElement(SEL_SUBEXPR, location));
1170         root->child->setName(name);
1171         _gmx_selelem_set_vtype(root->child, expr->v.type);
1172         root->child->child  = expr;
1173         /* Update flags */
1174         _gmx_selelem_update_flags(root);
1175         gmx::ExceptionInitializer errors("Invalid index group reference(s)");
1176         root->checkUnsortedAtoms(true, &errors);
1177         if (errors.hasNestedExceptions())
1178         {
1179             GMX_THROW(gmx::InconsistentInputError(errors));
1180         }
1181         /* Add the variable to the symbol table */
1182         sc->symtab->addVariable(name, root->child);
1183     }
1184     srenew(sc->varstrs, sc->nvars + 1);
1185     sc->varstrs[sc->nvars] = gmx_strdup(pselstr);
1186     ++sc->nvars;
1187     if (_gmx_sel_is_lexer_interactive(scanner))
1188     {
1189         fprintf(stderr, "Variable '%s' parsed\n", pselstr);
1190     }
1191     return root;
1192 }
1193
1194 /*!
1195  * \param         sel   Selection to append (can be NULL, in which
1196  *   case nothing is done).
1197  * \param         last  Last selection, or NULL if not present or not known.
1198  * \param         scanner  Scanner data structure.
1199  * \returns       The last selection after the append.
1200  *
1201  * Appends \p sel after the last root element, and returns either \p sel
1202  * (if it was non-NULL) or the last element (if \p sel was NULL).
1203  */
1204 SelectionTreeElementPointer
1205 _gmx_sel_append_selection(const gmx::SelectionTreeElementPointer &sel,
1206                           gmx::SelectionTreeElementPointer        last,
1207                           yyscan_t                                scanner)
1208 {
1209     gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1210
1211     /* Append sel after last, or the last element of sc if last is NULL */
1212     if (last)
1213     {
1214         last->next = sel;
1215     }
1216     else
1217     {
1218         if (sc->root)
1219         {
1220             last = sc->root;
1221             while (last->next)
1222             {
1223                 last = last->next;
1224             }
1225             last->next = sel;
1226         }
1227         else
1228         {
1229             sc->root = sel;
1230         }
1231     }
1232     /* Initialize a selection object if necessary */
1233     if (sel)
1234     {
1235         last = sel;
1236         /* Add the new selection to the collection if it is not a variable. */
1237         if (sel->child->type != SEL_SUBEXPR)
1238         {
1239             gmx::SelectionDataPointer selPtr(
1240                     new gmx::internal::SelectionData(
1241                             sel.get(), _gmx_sel_lexer_pselstr(scanner)));
1242             sc->sel.push_back(gmx::move(selPtr));
1243         }
1244     }
1245     /* Clear the selection string now that we've saved it */
1246     _gmx_sel_lexer_clear_pselstr(scanner);
1247     return last;
1248 }
1249
1250 /*!
1251  * \param[in] scanner Scanner data structure.
1252  * \returns   true if the parser should finish, false if parsing should
1253  *   continue.
1254  *
1255  * This function is called always after _gmx_sel_append_selection() to
1256  * check whether a sufficient number of selections has already been provided.
1257  * This is used to terminate interactive parsers when the correct number of
1258  * selections has been provided.
1259  */
1260 bool
1261 _gmx_sel_parser_should_finish(yyscan_t scanner)
1262 {
1263     gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1264     return (int)sc->sel.size() == _gmx_sel_lexer_exp_selcount(scanner);
1265 }