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