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