Treat exceptions better in interactive selections.
[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, by the GROMACS development team, led by
5  * David van der Spoel, Berk Hess, Erik Lindahl, and including many
6  * others, as listed in the AUTHORS file in the top-level source
7  * 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 <stdio.h>
223 #include <stdarg.h>
224
225 #include <boost/exception_ptr.hpp>
226 #include <boost/shared_ptr.hpp>
227
228 #include "gromacs/legacyheaders/futil.h"
229 #include "gromacs/legacyheaders/smalloc.h"
230 #include "gromacs/legacyheaders/string2.h"
231
232 #include "gromacs/onlinehelp/helpmanager.h"
233 #include "gromacs/onlinehelp/helpwritercontext.h"
234 #include "gromacs/selection/poscalc.h"
235 #include "gromacs/selection/selection.h"
236 #include "gromacs/selection/selmethod.h"
237 #include "gromacs/utility/exceptions.h"
238 #include "gromacs/utility/file.h"
239 #include "gromacs/utility/messagestringcollector.h"
240
241 #include "keywords.h"
242 #include "parsetree.h"
243 #include "selectioncollection-impl.h"
244 #include "selelem.h"
245 #include "selhelp.h"
246 #include "symrec.h"
247
248 #include "scanner.h"
249
250 using gmx::SelectionParserValue;
251 using gmx::SelectionParserValueList;
252 using gmx::SelectionParserValueListPointer;
253 using gmx::SelectionParserParameter;
254 using gmx::SelectionParserParameterList;
255 using gmx::SelectionParserParameterListPointer;
256 using gmx::SelectionParserValue;
257 using gmx::SelectionTreeElement;
258 using gmx::SelectionTreeElementPointer;
259
260 void
261 _gmx_selparser_error(yyscan_t scanner, const char *fmt, ...)
262 {
263     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
264     // FIXME: Use an arbitrary length buffer.
265     char    buf[1024];
266     va_list ap;
267     va_start(ap, fmt);
268     vsprintf(buf, fmt, ap);
269     va_end(ap);
270     errors->append(buf);
271 }
272
273 bool
274 _gmx_selparser_handle_exception(yyscan_t scanner, const std::exception &ex)
275 {
276     if (dynamic_cast<const gmx::UserInputError *>(&ex) != NULL)
277     {
278         // TODO: Consider whether also the non-interactive parser should
279         // postpone the exception such that the whole selection can be added as
280         // context.
281         if (_gmx_sel_is_lexer_interactive(scanner))
282         {
283             // TODO: Handle exceptions that printing the message may produce.
284             gmx::formatExceptionMessageToFile(stderr, ex);
285             return true;
286         }
287     }
288     _gmx_sel_lexer_set_exception(scanner, boost::current_exception());
289     return false;
290 }
291
292 namespace gmx
293 {
294
295 /********************************************************************
296  * SelectionParserValue
297  */
298
299 SelectionParserValue::SelectionParserValue(e_selvalue_t type)
300     : type(type)
301 {
302     memset(&u, 0, sizeof(u));
303 }
304
305 SelectionParserValue::SelectionParserValue(
306         const SelectionTreeElementPointer &expr)
307     : type(expr->v.type), expr(expr)
308 {
309     memset(&u, 0, sizeof(u));
310 }
311
312 /********************************************************************
313  * SelectionParserParameter
314  */
315
316 SelectionParserParameter::SelectionParserParameter(
317         const char                     *name,
318         SelectionParserValueListPointer values)
319     : name_(name != NULL ? name : ""),
320       values_(values ? move(values)
321               : SelectionParserValueListPointer(new SelectionParserValueList))
322 {
323 }
324
325 } // namespace gmx
326
327 /*!
328  * \param[in,out] sel  Root of the selection element tree to initialize.
329  * \param[in]     scanner Scanner data structure.
330  * \returns       0 on success, an error code on error.
331  *
332  * Propagates the \ref SEL_DYNAMIC flag from the children of \p sel to \p sel
333  * (if any child of \p sel is dynamic, \p sel is also marked as such).
334  * The \ref SEL_DYNAMIC flag is also set for \ref SEL_EXPRESSION elements with
335  * a dynamic method.
336  * Also, sets one of the \ref SEL_SINGLEVAL, \ref SEL_ATOMVAL, or
337  * \ref SEL_VARNUMVAL flags, either based on the children or on the type of
338  * the selection method.
339  * If the types of the children conflict, an error is returned.
340  *
341  * The flags of the children of \p sel are also updated if not done earlier.
342  * The flags are initialized only once for any element; if \ref SEL_FLAGSSET
343  * is set for an element, the function returns immediately, and the recursive
344  * operation does not descend beyond such elements.
345  */
346 void
347 _gmx_selelem_update_flags(const SelectionTreeElementPointer &sel,
348                           yyscan_t                           scanner)
349 {
350     bool                bUseChildType = false;
351     bool                bOnlySingleChildren;
352
353     /* Return if the flags have already been set */
354     if (sel->flags & SEL_FLAGSSET)
355     {
356         return;
357     }
358     /* Set the flags based on the current element type */
359     switch (sel->type)
360     {
361         case SEL_CONST:
362         case SEL_GROUPREF:
363             sel->flags   |= SEL_SINGLEVAL;
364             bUseChildType = false;
365             break;
366
367         case SEL_EXPRESSION:
368             if (sel->u.expr.method->flags & SMETH_DYNAMIC)
369             {
370                 sel->flags |= SEL_DYNAMIC;
371             }
372             if (sel->u.expr.method->flags & SMETH_SINGLEVAL)
373             {
374                 sel->flags |= SEL_SINGLEVAL;
375             }
376             else if (sel->u.expr.method->flags & SMETH_VARNUMVAL)
377             {
378                 sel->flags |= SEL_VARNUMVAL;
379             }
380             else
381             {
382                 sel->flags |= SEL_ATOMVAL;
383             }
384             bUseChildType = false;
385             break;
386
387         case SEL_ARITHMETIC:
388             sel->flags   |= SEL_ATOMVAL;
389             bUseChildType = false;
390             break;
391
392         case SEL_MODIFIER:
393             if (sel->v.type != NO_VALUE)
394             {
395                 sel->flags |= SEL_VARNUMVAL;
396             }
397             bUseChildType = false;
398             break;
399
400         case SEL_ROOT:
401             bUseChildType = false;
402             break;
403
404         case SEL_BOOLEAN:
405         case SEL_SUBEXPR:
406         case SEL_SUBEXPRREF:
407             bUseChildType = true;
408             break;
409     }
410     /* Loop through children to propagate their flags upwards */
411     bOnlySingleChildren = true;
412     SelectionTreeElementPointer child = sel->child;
413     while (child)
414     {
415         /* Update the child */
416         _gmx_selelem_update_flags(child, scanner);
417         /* Propagate the dynamic flag */
418         sel->flags |= (child->flags & SEL_DYNAMIC);
419         /* Propagate the type flag if necessary and check for problems */
420         if (bUseChildType)
421         {
422             if ((sel->flags & SEL_VALTYPEMASK)
423                 && !(sel->flags & child->flags & SEL_VALTYPEMASK))
424             {
425                 _gmx_selparser_error(scanner, "invalid combination of selection expressions");
426                 // FIXME: Use an exception.
427                 return;
428             }
429             sel->flags |= (child->flags & SEL_VALTYPEMASK);
430         }
431         if (!(child->flags & SEL_SINGLEVAL))
432         {
433             bOnlySingleChildren = false;
434         }
435
436         child = child->next;
437     }
438     /* For arithmetic expressions consisting only of single values,
439      * the result is also a single value. */
440     if (sel->type == SEL_ARITHMETIC && bOnlySingleChildren)
441     {
442         sel->flags = (sel->flags & ~SEL_VALTYPEMASK) | SEL_SINGLEVAL;
443     }
444     /* For root elements, the type should be propagated here, after the
445      * children have been updated. */
446     if (sel->type == SEL_ROOT)
447     {
448         GMX_ASSERT(sel->child, "Root elements should always have a child");
449         sel->flags |= (sel->child->flags & SEL_VALTYPEMASK);
450     }
451     /* Mark that the flags are set */
452     sel->flags |= SEL_FLAGSSET;
453 }
454
455 /*!
456  * \param[in,out] sel    Selection element to initialize.
457  * \param[in]     scanner Scanner data structure.
458  *
459  * A deep copy of the parameters is made to allow several
460  * expressions with the same method to coexist peacefully.
461  * Calls sel_datafunc() if one is specified for the method.
462  */
463 void
464 _gmx_selelem_init_method_params(const SelectionTreeElementPointer &sel,
465                                 yyscan_t                           scanner)
466 {
467     int                 nparams;
468     gmx_ana_selparam_t *orgparam;
469     gmx_ana_selparam_t *param;
470     int                 i;
471     void               *mdata;
472
473     nparams   = sel->u.expr.method->nparams;
474     orgparam  = sel->u.expr.method->param;
475     snew(param, nparams);
476     memcpy(param, orgparam, nparams*sizeof(gmx_ana_selparam_t));
477     for (i = 0; i < nparams; ++i)
478     {
479         param[i].flags &= ~SPAR_SET;
480         _gmx_selvalue_setstore(&param[i].val, NULL);
481         if (param[i].flags & SPAR_VARNUM)
482         {
483             param[i].val.nr = -1;
484         }
485         /* Duplicate the enum value array if it is given statically */
486         if ((param[i].flags & SPAR_ENUMVAL) && orgparam[i].val.u.ptr != NULL)
487         {
488             int n;
489
490             /* Count the values */
491             n = 1;
492             while (orgparam[i].val.u.s[n] != NULL)
493             {
494                 ++n;
495             }
496             _gmx_selvalue_reserve(&param[i].val, n+1);
497             memcpy(param[i].val.u.s, orgparam[i].val.u.s,
498                    (n+1)*sizeof(param[i].val.u.s[0]));
499         }
500     }
501     mdata = NULL;
502     if (sel->u.expr.method->init_data)
503     {
504         mdata = sel->u.expr.method->init_data(nparams, param);
505     }
506     if (sel->u.expr.method->set_poscoll)
507     {
508         gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
509
510         sel->u.expr.method->set_poscoll(&sc->pcc, mdata);
511     }
512     /* Store the values */
513     sel->u.expr.method->param = param;
514     sel->u.expr.mdata         = mdata;
515 }
516
517 /*!
518  * \param[in,out] sel    Selection element to initialize.
519  * \param[in]     method Selection method to set.
520  * \param[in]     scanner Scanner data structure.
521  *
522  * Makes a copy of \p method and stores it in \p sel->u.expr.method,
523  * and calls _gmx_selelem_init_method_params();
524  */
525 void
526 _gmx_selelem_set_method(const SelectionTreeElementPointer &sel,
527                         gmx_ana_selmethod_t               *method,
528                         yyscan_t                           scanner)
529 {
530     _gmx_selelem_set_vtype(sel, method->type);
531     sel->setName(method->name);
532     snew(sel->u.expr.method, 1);
533     memcpy(sel->u.expr.method, method, sizeof(gmx_ana_selmethod_t));
534     _gmx_selelem_init_method_params(sel, scanner);
535 }
536
537 /*! \brief
538  * Initializes the reference position calculation for a \ref SEL_EXPRESSION
539  * element.
540  *
541  * \param[in,out] pcc    Position calculation collection to use.
542  * \param[in,out] sel    Selection element to initialize.
543  * \param[in]     rpost  Reference position type to use (NULL = default).
544  * \param[in]     scanner Scanner data structure.
545  * \returns       0 on success, a non-zero error code on error.
546  */
547 static void
548 set_refpos_type(gmx::PositionCalculationCollection *pcc,
549                 const SelectionTreeElementPointer &sel,
550                 const char *rpost, yyscan_t scanner)
551 {
552     if (!rpost)
553     {
554         return;
555     }
556
557     if (sel->u.expr.method->pupdate)
558     {
559         /* By default, use whole residues/molecules. */
560         sel->u.expr.pc
561             = pcc->createCalculationFromEnum(rpost, POS_COMPLWHOLE);
562     }
563     else
564     {
565         // TODO: Should this be treated as a real error?
566         _gmx_selparser_error(scanner, "modifier '%s' is not applicable for '%s'",
567                              rpost, sel->u.expr.method->name);
568     }
569 }
570
571 /*!
572  * \param[in]  left    Selection element for the left hand side.
573  * \param[in]  right   Selection element for the right hand side.
574  * \param[in]  op      String representation of the operator.
575  * \param[in]  scanner Scanner data structure.
576  * \returns    The created selection element.
577  *
578  * This function handles the creation of a gmx::SelectionTreeElement object for
579  * arithmetic expressions.
580  */
581 SelectionTreeElementPointer
582 _gmx_sel_init_arithmetic(const SelectionTreeElementPointer &left,
583                          const SelectionTreeElementPointer &right,
584                          char op, yyscan_t scanner)
585 {
586     SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_ARITHMETIC));
587     sel->v.type        = REAL_VALUE;
588     switch (op)
589     {
590         case '+': sel->u.arith.type = ARITH_PLUS; break;
591         case '-': sel->u.arith.type = (right ? ARITH_MINUS : ARITH_NEG); break;
592         case '*': sel->u.arith.type = ARITH_MULT; break;
593         case '/': sel->u.arith.type = ARITH_DIV;  break;
594         case '^': sel->u.arith.type = ARITH_EXP;  break;
595     }
596     char               buf[2];
597     buf[0] = op;
598     buf[1] = 0;
599     sel->setName(buf);
600     sel->u.arith.opstr = strdup(buf);
601     sel->child         = left;
602     sel->child->next   = right;
603     return sel;
604 }
605
606 /*!
607  * \param[in]  left   Selection element for the left hand side.
608  * \param[in]  right  Selection element for the right hand side.
609  * \param[in]  cmpop  String representation of the comparison operator.
610  * \param[in]  scanner Scanner data structure.
611  * \returns    The created selection element.
612  *
613  * This function handles the creation of a gmx::SelectionTreeElement object for
614  * comparison expressions.
615  */
616 SelectionTreeElementPointer
617 _gmx_sel_init_comparison(const SelectionTreeElementPointer &left,
618                          const SelectionTreeElementPointer &right,
619                          const char *cmpop, yyscan_t scanner)
620 {
621     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
622     gmx::MessageStringContext    context(errors, "In comparison initialization");
623
624     SelectionTreeElementPointer  sel(new SelectionTreeElement(SEL_EXPRESSION));
625     _gmx_selelem_set_method(sel, &sm_compare, scanner);
626
627     SelectionParserParameterList params;
628     const char                  *name;
629     // Create the parameter for the left expression.
630     name  = left->v.type == INT_VALUE ? "int1" : "real1";
631     params.push_back(SelectionParserParameter::createFromExpression(name, left));
632     // Create the parameter for the right expression.
633     name  = right->v.type == INT_VALUE ? "int2" : "real2";
634     params.push_back(SelectionParserParameter::createFromExpression(name, right));
635     // Create the parameter for the operator.
636     params.push_back(
637             SelectionParserParameter::create(
638                     "op", SelectionParserValue::createString(cmpop)));
639     if (!_gmx_sel_parse_params(params, sel->u.expr.method->nparams,
640                                sel->u.expr.method->param, sel, scanner))
641     {
642         return SelectionTreeElementPointer();
643     }
644
645     return sel;
646 }
647
648 /*! \brief
649  * Implementation method for keyword expression creation.
650  *
651  * \param[in]  method Method to use.
652  * \param[in]  matchType String matching type (only used if \p method is
653  *      a string keyword and \p args is not empty.
654  * \param[in]  args   Pointer to the first argument.
655  * \param[in]  rpost  Reference position type to use (NULL = default).
656  * \param[in]  scanner Scanner data structure.
657  * \returns    The created selection element.
658  *
659  * This function handles the creation of a gmx::SelectionTreeElement object for
660  * selection methods that do not take parameters.
661  */
662 static SelectionTreeElementPointer
663 init_keyword_internal(gmx_ana_selmethod_t *method,
664                       gmx::SelectionStringMatchType matchType,
665                       SelectionParserValueListPointer args,
666                       const char *rpost, yyscan_t scanner)
667 {
668     gmx_ana_selcollection_t     *sc = _gmx_sel_lexer_selcollection(scanner);
669
670     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
671     char  buf[128];
672     sprintf(buf, "In keyword '%s'", method->name);
673     gmx::MessageStringContext  context(errors, buf);
674
675     if (method->nparams > 0)
676     {
677         // TODO: Would assert be better?
678         GMX_THROW(gmx::InternalError(
679                           "Keyword initialization called with non-keyword method"));
680     }
681
682     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
683     SelectionTreeElementPointer child = root;
684     _gmx_selelem_set_method(child, method, scanner);
685
686     /* Initialize the evaluation of keyword matching if values are provided */
687     if (args)
688     {
689         gmx_ana_selmethod_t *kwmethod;
690         switch (method->type)
691         {
692             case INT_VALUE:  kwmethod = &sm_keyword_int;  break;
693             case REAL_VALUE: kwmethod = &sm_keyword_real; break;
694             case STR_VALUE:  kwmethod = &sm_keyword_str;  break;
695             default:
696                 GMX_THROW(gmx::InternalError(
697                                   "Unknown type for keyword selection"));
698         }
699         /* Initialize the selection element */
700         root.reset(new SelectionTreeElement(SEL_EXPRESSION));
701         _gmx_selelem_set_method(root, kwmethod, scanner);
702         if (method->type == STR_VALUE)
703         {
704             _gmx_selelem_set_kwstr_match_type(root, matchType);
705         }
706         SelectionParserParameterList params;
707         params.push_back(
708                 SelectionParserParameter::createFromExpression(NULL, child));
709         params.push_back(SelectionParserParameter::create(NULL, move(args)));
710         if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
711                                    root->u.expr.method->param, root, scanner))
712         {
713             return SelectionTreeElementPointer();
714         }
715     }
716     set_refpos_type(&sc->pcc, child, rpost, scanner);
717
718     return root;
719 }
720
721 /*!
722  * \param[in]  method Method to use.
723  * \param[in]  args   Pointer to the first argument.
724  * \param[in]  rpost  Reference position type to use (NULL = default).
725  * \param[in]  scanner Scanner data structure.
726  * \returns    The created selection element.
727  *
728  * This function handles the creation of a gmx::SelectionTreeElement object for
729  * selection methods that do not take parameters.
730  */
731 SelectionTreeElementPointer
732 _gmx_sel_init_keyword(gmx_ana_selmethod_t *method,
733                       SelectionParserValueListPointer args,
734                       const char *rpost, yyscan_t scanner)
735 {
736     return init_keyword_internal(method, gmx::eStringMatchType_Auto, move(args),
737                                  rpost, scanner);
738 }
739
740 /*!
741  * \param[in]  method    Method to use.
742  * \param[in]  matchType String matching type.
743  * \param[in]  args      Pointer to the first argument.
744  * \param[in]  rpost     Reference position type to use (NULL = default).
745  * \param[in]  scanner   Scanner data structure.
746  * \returns    The created selection element.
747  *
748  * This function handles the creation of a gmx::SelectionTreeElement object for
749  * keyword string matching.
750  */
751 SelectionTreeElementPointer
752 _gmx_sel_init_keyword_strmatch(gmx_ana_selmethod_t *method,
753                                gmx::SelectionStringMatchType matchType,
754                                SelectionParserValueListPointer args,
755                                const char *rpost, yyscan_t scanner)
756 {
757     GMX_RELEASE_ASSERT(method->type == STR_VALUE,
758                        "String keyword method called for a non-string-valued method");
759     GMX_RELEASE_ASSERT(args && !args->empty(),
760                        "String keyword matching method called without any values");
761     return init_keyword_internal(method, matchType, move(args), rpost, scanner);
762 }
763
764 /*!
765  * \param[in]  method Method to use for initialization.
766  * \param[in]  params Pointer to the first parameter.
767  * \param[in]  rpost  Reference position type to use (NULL = default).
768  * \param[in]  scanner Scanner data structure.
769  * \returns    The created selection element.
770  *
771  * This function handles the creation of a gmx::SelectionTreeElement object for
772  * selection methods that take parameters.
773  *
774  * Part of the behavior of the \c same selection keyword is hardcoded into
775  * this function (or rather, into _gmx_selelem_custom_init_same()) to allow the
776  * use of any keyword in \c "same KEYWORD as" without requiring special
777  * handling somewhere else (or sacrificing the simple syntax).
778  */
779 SelectionTreeElementPointer
780 _gmx_sel_init_method(gmx_ana_selmethod_t *method,
781                      SelectionParserParameterListPointer params,
782                      const char *rpost, yyscan_t scanner)
783 {
784     gmx_ana_selcollection_t     *sc = _gmx_sel_lexer_selcollection(scanner);
785     int                          rc;
786
787     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
788     char  buf[128];
789     sprintf(buf, "In keyword '%s'", method->name);
790     gmx::MessageStringContext  context(errors, buf);
791
792     _gmx_sel_finish_method(scanner);
793     /* The "same" keyword needs some custom massaging of the parameters. */
794     rc = _gmx_selelem_custom_init_same(&method, params, scanner);
795     if (rc != 0)
796     {
797         return SelectionTreeElementPointer();
798     }
799     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
800     _gmx_selelem_set_method(root, method, scanner);
801     /* Process the parameters */
802     if (!_gmx_sel_parse_params(*params, root->u.expr.method->nparams,
803                                root->u.expr.method->param, root, scanner))
804     {
805         return SelectionTreeElementPointer();
806     }
807     set_refpos_type(&sc->pcc, root, rpost, scanner);
808
809     return root;
810 }
811
812 /*!
813  * \param[in]  method Modifier to use for initialization.
814  * \param[in]  params Pointer to the first parameter.
815  * \param[in]  sel    Selection element that the modifier should act on.
816  * \param[in]  scanner Scanner data structure.
817  * \returns    The created selection element.
818  *
819  * This function handles the creation of a gmx::SelectionTreeElement object for
820  * selection modifiers.
821  */
822 SelectionTreeElementPointer
823 _gmx_sel_init_modifier(gmx_ana_selmethod_t *method,
824                        SelectionParserParameterListPointer params,
825                        const SelectionTreeElementPointer &sel, yyscan_t scanner)
826 {
827     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
828     char  buf[128];
829     sprintf(buf, "In keyword '%s'", method->name);
830     gmx::MessageStringContext  context(errors, buf);
831
832     _gmx_sel_finish_method(scanner);
833     SelectionTreeElementPointer modifier(new SelectionTreeElement(SEL_MODIFIER));
834     _gmx_selelem_set_method(modifier, method, scanner);
835     SelectionTreeElementPointer root;
836     if (method->type == NO_VALUE)
837     {
838         SelectionTreeElementPointer child = sel;
839         while (child->next)
840         {
841             child = child->next;
842         }
843         child->next = modifier;
844         root        = sel;
845     }
846     else
847     {
848         params->push_front(
849                 SelectionParserParameter::createFromExpression(NULL, sel));
850         root = modifier;
851     }
852     /* Process the parameters */
853     if (!_gmx_sel_parse_params(*params, modifier->u.expr.method->nparams,
854                                modifier->u.expr.method->param, modifier, scanner))
855     {
856         return SelectionTreeElementPointer();
857     }
858
859     return root;
860 }
861
862 /*!
863  * \param[in]  expr    Input selection element for the position calculation.
864  * \param[in]  type    Reference position type or NULL for default.
865  * \param[in]  scanner Scanner data structure.
866  * \returns    The created selection element.
867  *
868  * This function handles the creation of a gmx::SelectionTreeElement object for
869  * evaluation of reference positions.
870  */
871 SelectionTreeElementPointer
872 _gmx_sel_init_position(const SelectionTreeElementPointer &expr,
873                        const char *type, yyscan_t scanner)
874 {
875     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
876     char  buf[128];
877     sprintf(buf, "In position evaluation");
878     gmx::MessageStringContext   context(errors, buf);
879
880     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
881     _gmx_selelem_set_method(root, &sm_keyword_pos, scanner);
882     _gmx_selelem_set_kwpos_type(root.get(), type);
883     /* Create the parameters for the parameter parser. */
884     SelectionParserParameterList params;
885     params.push_back(SelectionParserParameter::createFromExpression(NULL, expr));
886     /* Parse the parameters. */
887     if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
888                                root->u.expr.method->param, root, scanner))
889     {
890         return SelectionTreeElementPointer();
891     }
892
893     return root;
894 }
895
896 /*!
897  * \param[in] x,y,z  Coordinates for the position.
898  * \returns   The creates selection element.
899  */
900 SelectionTreeElementPointer
901 _gmx_sel_init_const_position(real x, real y, real z)
902 {
903     rvec                        pos;
904
905     SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
906     _gmx_selelem_set_vtype(sel, POS_VALUE);
907     _gmx_selvalue_reserve(&sel->v, 1);
908     pos[XX] = x;
909     pos[YY] = y;
910     pos[ZZ] = z;
911     gmx_ana_pos_init_const(sel->v.u.p, pos);
912     return sel;
913 }
914
915 /*!
916  * \param[in] name  Name of an index group to search for.
917  * \param[in] scanner Scanner data structure.
918  * \returns   The created constant selection element, or NULL if no matching
919  *     index group found.
920  *
921  * See gmx_ana_indexgrps_find() for information on how \p name is matched
922  * against the index groups.
923  */
924 SelectionTreeElementPointer
925 _gmx_sel_init_group_by_name(const char *name, yyscan_t scanner)
926 {
927     gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
928
929     if (!_gmx_sel_lexer_has_groups_set(scanner))
930     {
931         SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
932         _gmx_selelem_set_vtype(sel, GROUP_VALUE);
933         sel->setName(name);
934         sel->u.gref.name = strdup(name);
935         sel->u.gref.id   = -1;
936         return sel;
937     }
938     if (!grps)
939     {
940         _gmx_selparser_error(scanner, "No index groups set; cannot match 'group %s'", name);
941         return SelectionTreeElementPointer();
942     }
943     SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
944     _gmx_selelem_set_vtype(sel, GROUP_VALUE);
945     std::string                 foundName;
946     if (!gmx_ana_indexgrps_find(&sel->u.cgrp, &foundName, grps, name))
947     {
948         _gmx_selparser_error(scanner, "Cannot match 'group %s'", name);
949         return SelectionTreeElementPointer();
950     }
951     sel->setName(foundName);
952     return sel;
953 }
954
955 /*!
956  * \param[in] id    Zero-based index number of the group to extract.
957  * \param[in] scanner Scanner data structure.
958  * \returns   The created constant selection element, or NULL if no matching
959  *     index group found.
960  */
961 SelectionTreeElementPointer
962 _gmx_sel_init_group_by_id(int id, yyscan_t scanner)
963 {
964     gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
965
966     if (!_gmx_sel_lexer_has_groups_set(scanner))
967     {
968         SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
969         _gmx_selelem_set_vtype(sel, GROUP_VALUE);
970         sel->u.gref.name = NULL;
971         sel->u.gref.id   = id;
972         return sel;
973     }
974     if (!grps)
975     {
976         _gmx_selparser_error(scanner, "No index groups set; cannot match 'group %d'", id);
977         return SelectionTreeElementPointer();
978     }
979     SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
980     _gmx_selelem_set_vtype(sel, GROUP_VALUE);
981     std::string                 foundName;
982     if (!gmx_ana_indexgrps_extract(&sel->u.cgrp, &foundName, grps, id))
983     {
984         _gmx_selparser_error(scanner, "Cannot match 'group %d'", id);
985         return SelectionTreeElementPointer();
986     }
987     sel->setName(foundName);
988     return sel;
989 }
990
991 /*!
992  * \param[in,out] sel  Value of the variable.
993  * \returns       The created selection element that references \p sel.
994  *
995  * The reference count of \p sel is updated, but no other modifications are
996  * made.
997  */
998 SelectionTreeElementPointer
999 _gmx_sel_init_variable_ref(const SelectionTreeElementPointer &sel)
1000 {
1001     SelectionTreeElementPointer ref;
1002
1003     if (sel->v.type == POS_VALUE && sel->type == SEL_CONST)
1004     {
1005         ref = sel;
1006     }
1007     else
1008     {
1009         ref.reset(new SelectionTreeElement(SEL_SUBEXPRREF));
1010         _gmx_selelem_set_vtype(ref, sel->v.type);
1011         ref->setName(sel->name());
1012         ref->child = sel;
1013     }
1014     return ref;
1015 }
1016
1017 /*!
1018  * \param[in]  name     Name for the selection
1019  *     (if NULL, a default name is constructed).
1020  * \param[in]  sel      The selection element that evaluates the selection.
1021  * \param      scanner  Scanner data structure.
1022  * \returns    The created root selection element.
1023  *
1024  * This function handles the creation of root (\ref SEL_ROOT)
1025  * gmx::SelectionTreeElement objects for selections.
1026  */
1027 SelectionTreeElementPointer
1028 _gmx_sel_init_selection(const char                        *name,
1029                         const SelectionTreeElementPointer &sel,
1030                         yyscan_t                           scanner)
1031 {
1032     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
1033     char  buf[1024];
1034     sprintf(buf, "In selection '%s'", _gmx_sel_lexer_pselstr(scanner));
1035     gmx::MessageStringContext  context(errors, buf);
1036
1037     if (sel->v.type != POS_VALUE)
1038     {
1039         /* FIXME: Better handling of this error */
1040         GMX_THROW(gmx::InternalError(
1041                           "Each selection must evaluate to a position"));
1042     }
1043
1044     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_ROOT));
1045     root->child = sel;
1046     if (name)
1047     {
1048         root->setName(name);
1049     }
1050     /* Update the flags */
1051     _gmx_selelem_update_flags(root, scanner);
1052
1053     root->fillNameIfMissing(_gmx_sel_lexer_pselstr(scanner));
1054
1055     /* Print out some information if the parser is interactive */
1056     if (_gmx_sel_is_lexer_interactive(scanner))
1057     {
1058         fprintf(stderr, "Selection '%s' parsed\n",
1059                 _gmx_sel_lexer_pselstr(scanner));
1060     }
1061
1062     return root;
1063 }
1064
1065
1066 /*!
1067  * \param[in]  name     Name of the variable.
1068  * \param[in]  expr     The selection element that evaluates the variable.
1069  * \param      scanner  Scanner data structure.
1070  * \returns    The created root selection element.
1071  *
1072  * This function handles the creation of root gmx::SelectionTreeElement objects
1073  * for variable assignments. A \ref SEL_ROOT element and a \ref SEL_SUBEXPR
1074  * element are both created.
1075  */
1076 SelectionTreeElementPointer
1077 _gmx_sel_assign_variable(const char                        *name,
1078                          const SelectionTreeElementPointer &expr,
1079                          yyscan_t                           scanner)
1080 {
1081     gmx_ana_selcollection_t     *sc      = _gmx_sel_lexer_selcollection(scanner);
1082     const char                  *pselstr = _gmx_sel_lexer_pselstr(scanner);
1083     SelectionTreeElementPointer  root;
1084
1085     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
1086     char  buf[1024];
1087     sprintf(buf, "In selection '%s'", pselstr);
1088     gmx::MessageStringContext  context(errors, buf);
1089
1090     _gmx_selelem_update_flags(expr, scanner);
1091     /* Check if this is a constant non-group value */
1092     if (expr->type == SEL_CONST && expr->v.type != GROUP_VALUE)
1093     {
1094         /* If so, just assign the constant value to the variable */
1095         sc->symtab->addVariable(name, expr);
1096         goto finish;
1097     }
1098     /* Check if we are assigning a variable to another variable */
1099     if (expr->type == SEL_SUBEXPRREF)
1100     {
1101         /* If so, make a simple alias */
1102         sc->symtab->addVariable(name, expr->child);
1103         goto finish;
1104     }
1105     /* Create the root element */
1106     root.reset(new SelectionTreeElement(SEL_ROOT));
1107     root->setName(name);
1108     /* Create the subexpression element */
1109     root->child.reset(new SelectionTreeElement(SEL_SUBEXPR));
1110     root->child->setName(name);
1111     _gmx_selelem_set_vtype(root->child, expr->v.type);
1112     root->child->child  = expr;
1113     /* Update flags */
1114     _gmx_selelem_update_flags(root, scanner);
1115     /* Add the variable to the symbol table */
1116     sc->symtab->addVariable(name, root->child);
1117 finish:
1118     srenew(sc->varstrs, sc->nvars + 1);
1119     sc->varstrs[sc->nvars] = strdup(pselstr);
1120     ++sc->nvars;
1121     if (_gmx_sel_is_lexer_interactive(scanner))
1122     {
1123         fprintf(stderr, "Variable '%s' parsed\n", pselstr);
1124     }
1125     return root;
1126 }
1127
1128 /*!
1129  * \param         sel   Selection to append (can be NULL, in which
1130  *   case nothing is done).
1131  * \param         last  Last selection, or NULL if not present or not known.
1132  * \param         scanner  Scanner data structure.
1133  * \returns       The last selection after the append.
1134  *
1135  * Appends \p sel after the last root element, and returns either \p sel
1136  * (if it was non-NULL) or the last element (if \p sel was NULL).
1137  */
1138 SelectionTreeElementPointer
1139 _gmx_sel_append_selection(const SelectionTreeElementPointer &sel,
1140                           SelectionTreeElementPointer        last,
1141                           yyscan_t                           scanner)
1142 {
1143     gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1144
1145     /* Append sel after last, or the last element of sc if last is NULL */
1146     if (last)
1147     {
1148         last->next = sel;
1149     }
1150     else
1151     {
1152         if (sc->root)
1153         {
1154             last = sc->root;
1155             while (last->next)
1156             {
1157                 last = last->next;
1158             }
1159             last->next = sel;
1160         }
1161         else
1162         {
1163             sc->root = sel;
1164         }
1165     }
1166     /* Initialize a selection object if necessary */
1167     if (sel)
1168     {
1169         last = sel;
1170         /* Add the new selection to the collection if it is not a variable. */
1171         if (sel->child->type != SEL_SUBEXPR)
1172         {
1173             gmx::SelectionDataPointer selPtr(
1174                     new gmx::internal::SelectionData(
1175                             sel.get(), _gmx_sel_lexer_pselstr(scanner)));
1176             sc->sel.push_back(gmx::move(selPtr));
1177         }
1178     }
1179     /* Clear the selection string now that we've saved it */
1180     _gmx_sel_lexer_clear_pselstr(scanner);
1181     return last;
1182 }
1183
1184 /*!
1185  * \param[in] scanner Scanner data structure.
1186  * \returns   true if the parser should finish, false if parsing should
1187  *   continue.
1188  *
1189  * This function is called always after _gmx_sel_append_selection() to
1190  * check whether a sufficient number of selections has already been provided.
1191  * This is used to terminate interactive parsers when the correct number of
1192  * selections has been provided.
1193  */
1194 bool
1195 _gmx_sel_parser_should_finish(yyscan_t scanner)
1196 {
1197     gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1198     return (int)sc->sel.size() == _gmx_sel_lexer_exp_selcount(scanner);
1199 }
1200
1201 /*!
1202  * \param[in] scanner Scanner data structure.
1203  */
1204 void
1205 _gmx_sel_handle_empty_cmd(yyscan_t scanner)
1206 {
1207     gmx_ana_selcollection_t *sc   = _gmx_sel_lexer_selcollection(scanner);
1208     gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
1209     int                      i;
1210
1211     if (!_gmx_sel_is_lexer_interactive(scanner))
1212     {
1213         return;
1214     }
1215
1216     if (grps)
1217     {
1218         fprintf(stderr, "Available index groups:\n");
1219         gmx_ana_indexgrps_print(stderr, _gmx_sel_lexer_indexgrps(scanner), 0);
1220     }
1221     if (sc->nvars > 0 || !sc->sel.empty())
1222     {
1223         fprintf(stderr, "Currently provided selections:\n");
1224         for (i = 0; i < sc->nvars; ++i)
1225         {
1226             fprintf(stderr, "     %s\n", sc->varstrs[i]);
1227         }
1228         for (i = 0; i < (int)sc->sel.size(); ++i)
1229         {
1230             fprintf(stderr, " %2d. %s\n", i+1, sc->sel[i]->selectionText());
1231         }
1232     }
1233 }
1234
1235 /*!
1236  * \param[in] topic   Topic for which help was requested, or NULL for general
1237  *                    help.
1238  * \param[in] scanner Scanner data structure.
1239  *
1240  * \p topic is freed by this function.
1241  */
1242 void
1243 _gmx_sel_handle_help_cmd(const SelectionParserValueListPointer &topic,
1244                          yyscan_t                               scanner)
1245 {
1246     gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1247
1248     if (sc->rootHelp.get() == NULL)
1249     {
1250         sc->rootHelp = gmx::createSelectionHelpTopic();
1251     }
1252     gmx::HelpWriterContext context(&gmx::File::standardError(),
1253                                    gmx::eHelpOutputFormat_Console);
1254     gmx::HelpManager       manager(*sc->rootHelp, context);
1255     try
1256     {
1257         SelectionParserValueList::const_iterator value;
1258         for (value = topic->begin(); value != topic->end(); ++value)
1259         {
1260             manager.enterTopic(value->stringValue());
1261         }
1262     }
1263     catch (const gmx::InvalidInputError &ex)
1264     {
1265         fprintf(stderr, "%s\n", ex.what());
1266         return;
1267     }
1268     manager.writeCurrentTopic();
1269 }