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