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