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