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