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