3 * This source code is part of
7 * GROningen MAchine for Chemical Simulations
9 * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10 * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11 * Copyright (c) 2001-2009, The GROMACS development team,
12 * check out http://www.gromacs.org for more information.
14 * This program is free software; you can redistribute it and/or
15 * modify it under the terms of the GNU General Public License
16 * as published by the Free Software Foundation; either version 2
17 * of the License, or (at your option) any later version.
19 * If you want to redistribute modifications, please consider that
20 * scientific software is very special. Version control is crucial -
21 * bugs must be traceable. We will be happy to consider code for
22 * inclusion in the official distribution, but derived work must not
23 * be called official GROMACS. Details are found in the README & COPYING
24 * files - if they are missing, get the official version at www.gromacs.org.
26 * To help us fund GROMACS development, we humbly ask that you cite
27 * the papers on the package - you can find them in the top README file.
29 * For more info, check our website at http://www.gromacs.org
33 * Implements functions in parsetree.h.
35 * \author Teemu Murtola <teemu.murtola@cbr.su.se>
36 * \ingroup module_selection
39 * \page page_module_selection_parser Selection parsing
41 * The selection parser is implemented in the following files:
43 * Tokenizer implemented using Flex, splits the input into tokens
44 * (scanner.c and scanner_flex.h are generated from this file).
45 * - scanner.h, scanner_internal.h, scanner_internal.cpp:
46 * Helper functions for scanner.l and for interfacing between
47 * scanner.l and parser.y. Functions in scanner_internal.h are only
48 * used from scanner.l, while scanner.h is used from the parser.
49 * - symrec.h, symrec.cpp:
50 * Functions used by the tokenizer to handle the symbol table, i.e.,
51 * the recognized keywords. Some basic keywords are hardcoded into
52 * scanner.l, but all method and variable references go through the
53 * symbol table, as do position evaluation keywords.
55 * Semantic rules for parsing the grammar
56 * (parser.cpp and parser.h are generated from this file by Bison).
57 * - parsetree.h, parsetree.cpp:
58 * Functions called from actions in parser.y to construct the
59 * evaluation elements corresponding to different grammar elements.
61 * Defines a function that processes the parameters of selection
62 * methods and initializes the children of the method element.
63 * - selectioncollection.h, selectioncollection.cpp:
64 * These files define the high-level public interface to the parser
65 * through SelectionCollection::parseFromStdin(),
66 * SelectionCollection::parseFromFile() and
67 * SelectionCollection::parseFromString().
69 * The basic control flow in the parser is as follows: when a parser function
70 * in SelectionCollection gets called, it performs some
71 * initialization, and then calls the _gmx_sel_yyparse() function generated
72 * by Bison. This function then calls _gmx_sel_yylex() to repeatedly read
73 * tokens from the input (more complex tasks related to token recognition
74 * and bookkeeping are done by functions in scanner_internal.cpp) and uses the
75 * grammar rules to decide what to do with them. Whenever a grammar rule
76 * matches, a corresponding function in parsetree.cpp is called to construct
77 * either a temporary representation for the object or a
78 * gmx::SelectionTreeElement object
79 * (some simple rules are handled internally in parser.y).
80 * When a complete selection has been parsed, the functions in parsetree.cpp
81 * also take care of updating the ::gmx_ana_selcollection_t structure
84 * The rest of this page describes the resulting gmx::SelectionTreeElement
86 * Before the selections can be evaluated, this tree needs to be passed to
87 * the selection compiler, which is described on a separate page:
88 * \ref page_module_selection_compiler
91 * \section selparser_tree Element tree constructed by the parser
93 * The parser initializes the following fields in all selection elements:
94 * gmx::SelectionTreeElement::name, gmx::SelectionTreeElement::type,
95 * gmx::SelectionTreeElement::v\c .type,
96 * gmx::SelectionTreeElement::flags, gmx::SelectionTreeElement::child, and
97 * gmx::SelectionTreeElement::next.
98 * Some other fields are also initialized for particular element types as
100 * Fields that are not initialized are set to zero, NULL, or other similar
104 * \subsection selparser_tree_root Root elements
106 * The parser creates a \ref SEL_ROOT selection element for each variable
107 * assignment and each selection. However, there are two exceptions that do
108 * not result in a \ref SEL_ROOT element (in these cases, only the symbol
109 * table is modified):
110 * - Variable assignments that assign a variable to another variable.
111 * - Variable assignments that assign a non-group constant.
113 * The \ref SEL_ROOT elements are linked together in a chain in the same order
116 * The children of the \ref SEL_ROOT elements can be used to distinguish
117 * the two types of root elements from each other:
118 * - For variable assignments, the first and only child is always
119 * a \ref SEL_SUBEXPR element.
120 * - For selections, the first child is a \ref SEL_EXPRESSION or a
121 * \ref SEL_MODIFIER element that evaluates the final positions (if the
122 * selection defines a constant position, the child is a \ref SEL_CONST).
123 * The rest of the children are \ref SEL_MODIFIER elements with
124 * \ref NO_VALUE, in the order given by the user.
126 * The name of the selection/variable is stored in
127 * gmx::SelectionTreeElement::cgrp\c .name.
128 * It is set to either the name provided by the user or the selection string
129 * for selections not explicitly named by the user.
130 * \ref SEL_ROOT or \ref SEL_SUBEXPR elements do not appear anywhere else.
133 * \subsection selparser_tree_const Constant elements
135 * \ref SEL_CONST elements are created for every constant that is required
136 * for later evaluation.
137 * Currently, \ref SEL_CONST elements can be present for
138 * - selections that consist of a constant position,
139 * - \ref GROUP_VALUE method parameters if provided using external index
142 * For group-valued elements, the value is stored in
143 * gmx::SelectionTreeElement::cgrp; other types of values are stored in
144 * gmx::SelectionTreeElement::v.
145 * Constants that appear as parameters for selection methods are not present
146 * in the selection tree unless they have \ref GROUP_VALUE.
147 * \ref SEL_CONST elements have no children.
150 * \subsection selparser_tree_method Method evaluation elements
152 * \ref SEL_EXPRESSION and \ref SEL_MODIFIER elements are treated very
153 * similarly. The \c gmx_ana_selmethod_t structure corresponding to the
154 * evaluation method is in gmx::SelectionTreeElement::method, and the method
155 * data in gmx::SelectionTreeElement::mdata has been allocated using
157 * If a non-standard reference position type was set,
158 * gmx::SelectionTreeElement::pc has also been created, but only the type has
160 * All children of these elements are of the type \ref SEL_SUBEXPRREF, and
161 * each describes a selection that needs to be evaluated to obtain a value
162 * for one parameter of the method.
163 * No children are present for parameters that were given a constant
164 * non-\ref GROUP_VALUE value.
165 * The children are sorted in the order in which the parameters appear in the
166 * \ref gmx_ana_selmethod_t structure.
168 * In addition to actual selection keywords, \ref SEL_EXPRESSION elements
169 * are used internally to implement numerical comparisons (e.g., "x < 5")
170 * and keyword matching (e.g., "resnr 1 to 3" or "name CA").
173 * \subsection selparser_tree_subexpr Subexpression elements
175 * \ref SEL_SUBEXPR elements only appear for variables, as described above.
176 * gmx::SelectionTreeElement::name points to the name of the variable (from the
177 * \ref SEL_ROOT element).
178 * The element always has exactly one child, which represents the value of
181 * \ref SEL_SUBEXPRREF elements are used for two purposes:
182 * - Variable references that need to be evaluated (i.e., there is a
183 * \ref SEL_SUBEXPR element for the variable) are represented using
184 * \ref SEL_SUBEXPRREF elements.
185 * In this case, gmx::SelectionTreeElement::param is NULL, and the first and
186 * only child of the element is the \ref SEL_SUBEXPR element of the
188 * Such references can appear anywhere where the variable value
189 * (the child of the \ref SEL_SUBEXPR element) would be valid.
190 * - Children of \ref SEL_EXPRESSION and \ref SEL_MODIFIER elements are
191 * always of this type. For these elements, gmx::SelectionTreeElement::param
192 * is initialized to point to the parameter that receives the value from
194 * Each such element has exactly one child, which can be of any type;
195 * the \ref SEL_SUBEXPR element of a variable is used if the value comes
196 * from a variable, otherwise the child type is not \ref SEL_SUBEXPR.
199 * \subsection selparser_tree_bool Boolean elements
201 * One \ref SEL_BOOLEAN element is created for each boolean keyword in the
202 * input, and the tree structure represents the evaluation order.
203 * The gmx::SelectionTreeElement::boolt type gives the type of the operation.
204 * Each element has exactly two children (one for \ref BOOL_NOT elements),
205 * which are in the order given in the input.
206 * The children always have \ref GROUP_VALUE, but different element types
210 * \subsection selparser_tree_arith Arithmetic elements
212 * One \ref SEL_ARITHMETIC element is created for each arithmetic operation in
213 * the input, and the tree structure represents the evaluation order.
214 * The gmx::SelectionTreeElement::optype type gives the name of the operation.
215 * Each element has exactly two children (one for unary negation elements),
216 * which are in the order given in the input.
221 #include <boost/exception_ptr.hpp>
222 #include <boost/shared_ptr.hpp>
224 #include "gromacs/legacyheaders/futil.h"
225 #include "gromacs/legacyheaders/smalloc.h"
226 #include "gromacs/legacyheaders/string2.h"
228 #include "gromacs/onlinehelp/helpmanager.h"
229 #include "gromacs/onlinehelp/helpwritercontext.h"
230 #include "gromacs/selection/poscalc.h"
231 #include "gromacs/selection/selection.h"
232 #include "gromacs/selection/selmethod.h"
233 #include "gromacs/utility/exceptions.h"
234 #include "gromacs/utility/file.h"
235 #include "gromacs/utility/messagestringcollector.h"
237 #include "keywords.h"
238 #include "parsetree.h"
239 #include "selectioncollection-impl.h"
246 using gmx::SelectionParserValue;
247 using gmx::SelectionParserValueList;
248 using gmx::SelectionParserValueListPointer;
249 using gmx::SelectionParserParameter;
250 using gmx::SelectionParserParameterList;
251 using gmx::SelectionParserParameterListPointer;
252 using gmx::SelectionParserValue;
253 using gmx::SelectionTreeElement;
254 using gmx::SelectionTreeElementPointer;
257 _gmx_selparser_error(yyscan_t scanner, const char *fmt, ...)
259 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
260 // FIXME: Use an arbitrary length buffer.
264 vsprintf(buf, fmt, ap);
270 _gmx_selparser_handle_exception(yyscan_t scanner, const std::exception &/*ex*/)
272 _gmx_sel_lexer_set_exception(scanner, boost::current_exception());
279 /********************************************************************
280 * SelectionParserValue
283 SelectionParserValue::SelectionParserValue(e_selvalue_t type)
286 memset(&u, 0, sizeof(u));
289 SelectionParserValue::SelectionParserValue(
290 const SelectionTreeElementPointer &expr)
291 : type(expr->v.type), expr(expr)
293 memset(&u, 0, sizeof(u));
296 /********************************************************************
297 * SelectionParserParameter
300 SelectionParserParameter::SelectionParserParameter(
302 SelectionParserValueListPointer values)
303 : name_(name != NULL ? name : ""),
304 values_(values ? move(values)
305 : SelectionParserValueListPointer(new SelectionParserValueList))
312 * \param[in,out] sel Root of the selection element tree to initialize.
313 * \param[in] scanner Scanner data structure.
314 * \returns 0 on success, an error code on error.
316 * Propagates the \ref SEL_DYNAMIC flag from the children of \p sel to \p sel
317 * (if any child of \p sel is dynamic, \p sel is also marked as such).
318 * The \ref SEL_DYNAMIC flag is also set for \ref SEL_EXPRESSION elements with
320 * Also, sets one of the \ref SEL_SINGLEVAL, \ref SEL_ATOMVAL, or
321 * \ref SEL_VARNUMVAL flags, either based on the children or on the type of
322 * the selection method.
323 * If the types of the children conflict, an error is returned.
325 * The flags of the children of \p sel are also updated if not done earlier.
326 * The flags are initialized only once for any element; if \ref SEL_FLAGSSET
327 * is set for an element, the function returns immediately, and the recursive
328 * operation does not descend beyond such elements.
331 _gmx_selelem_update_flags(const SelectionTreeElementPointer &sel,
334 bool bUseChildType=false;
335 bool bOnlySingleChildren;
337 /* Return if the flags have already been set */
338 if (sel->flags & SEL_FLAGSSET)
342 /* Set the flags based on the current element type */
347 sel->flags |= SEL_SINGLEVAL;
348 bUseChildType = false;
352 if (sel->u.expr.method->flags & SMETH_DYNAMIC)
354 sel->flags |= SEL_DYNAMIC;
356 if (sel->u.expr.method->flags & SMETH_SINGLEVAL)
358 sel->flags |= SEL_SINGLEVAL;
360 else if (sel->u.expr.method->flags & SMETH_VARNUMVAL)
362 sel->flags |= SEL_VARNUMVAL;
366 sel->flags |= SEL_ATOMVAL;
368 bUseChildType = false;
372 sel->flags |= SEL_ATOMVAL;
373 bUseChildType = false;
377 if (sel->v.type != NO_VALUE)
379 sel->flags |= SEL_VARNUMVAL;
381 bUseChildType = false;
385 bUseChildType = false;
391 bUseChildType = true;
394 /* Loop through children to propagate their flags upwards */
395 bOnlySingleChildren = true;
396 SelectionTreeElementPointer child = sel->child;
399 /* Update the child */
400 _gmx_selelem_update_flags(child, scanner);
401 /* Propagate the dynamic flag */
402 sel->flags |= (child->flags & SEL_DYNAMIC);
403 /* Propagate the type flag if necessary and check for problems */
406 if ((sel->flags & SEL_VALTYPEMASK)
407 && !(sel->flags & child->flags & SEL_VALTYPEMASK))
409 _gmx_selparser_error(scanner, "invalid combination of selection expressions");
410 // FIXME: Use an exception.
413 sel->flags |= (child->flags & SEL_VALTYPEMASK);
415 if (!(child->flags & SEL_SINGLEVAL))
417 bOnlySingleChildren = false;
422 /* For arithmetic expressions consisting only of single values,
423 * the result is also a single value. */
424 if (sel->type == SEL_ARITHMETIC && bOnlySingleChildren)
426 sel->flags = (sel->flags & ~SEL_VALTYPEMASK) | SEL_SINGLEVAL;
428 /* For root elements, the type should be propagated here, after the
429 * children have been updated. */
430 if (sel->type == SEL_ROOT)
432 GMX_ASSERT(sel->child, "Root elements should always have a child");
433 sel->flags |= (sel->child->flags & SEL_VALTYPEMASK);
435 /* Mark that the flags are set */
436 sel->flags |= SEL_FLAGSSET;
440 * \param[in,out] sel Selection element to initialize.
441 * \param[in] scanner Scanner data structure.
443 * A deep copy of the parameters is made to allow several
444 * expressions with the same method to coexist peacefully.
445 * Calls sel_datafunc() if one is specified for the method.
448 _gmx_selelem_init_method_params(const SelectionTreeElementPointer &sel,
452 gmx_ana_selparam_t *orgparam;
453 gmx_ana_selparam_t *param;
457 nparams = sel->u.expr.method->nparams;
458 orgparam = sel->u.expr.method->param;
459 snew(param, nparams);
460 memcpy(param, orgparam, nparams*sizeof(gmx_ana_selparam_t));
461 for (i = 0; i < nparams; ++i)
463 param[i].flags &= ~SPAR_SET;
464 _gmx_selvalue_setstore(¶m[i].val, NULL);
465 if (param[i].flags & SPAR_VARNUM)
467 param[i].val.nr = -1;
469 /* Duplicate the enum value array if it is given statically */
470 if ((param[i].flags & SPAR_ENUMVAL) && orgparam[i].val.u.ptr != NULL)
474 /* Count the values */
476 while (orgparam[i].val.u.s[n] != NULL)
480 _gmx_selvalue_reserve(¶m[i].val, n+1);
481 memcpy(param[i].val.u.s, orgparam[i].val.u.s,
482 (n+1)*sizeof(param[i].val.u.s[0]));
486 if (sel->u.expr.method->init_data)
488 mdata = sel->u.expr.method->init_data(nparams, param);
490 if (sel->u.expr.method->set_poscoll)
492 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
494 sel->u.expr.method->set_poscoll(&sc->pcc, mdata);
496 /* Store the values */
497 sel->u.expr.method->param = param;
498 sel->u.expr.mdata = mdata;
502 * \param[in,out] sel Selection element to initialize.
503 * \param[in] method Selection method to set.
504 * \param[in] scanner Scanner data structure.
506 * Makes a copy of \p method and stores it in \p sel->u.expr.method,
507 * and calls _gmx_selelem_init_method_params();
510 _gmx_selelem_set_method(const SelectionTreeElementPointer &sel,
511 gmx_ana_selmethod_t *method,
514 _gmx_selelem_set_vtype(sel, method->type);
515 sel->setName(method->name);
516 snew(sel->u.expr.method, 1);
517 memcpy(sel->u.expr.method, method, sizeof(gmx_ana_selmethod_t));
518 _gmx_selelem_init_method_params(sel, scanner);
522 * Initializes the reference position calculation for a \ref SEL_EXPRESSION
525 * \param[in,out] pcc Position calculation collection to use.
526 * \param[in,out] sel Selection element to initialize.
527 * \param[in] rpost Reference position type to use (NULL = default).
528 * \param[in] scanner Scanner data structure.
529 * \returns 0 on success, a non-zero error code on error.
532 set_refpos_type(gmx::PositionCalculationCollection *pcc,
533 const SelectionTreeElementPointer &sel,
534 const char *rpost, yyscan_t scanner)
541 if (sel->u.expr.method->pupdate)
543 /* By default, use whole residues/molecules. */
545 = pcc->createCalculationFromEnum(rpost, POS_COMPLWHOLE);
549 // TODO: Should this be treated as a real error?
550 _gmx_selparser_error(scanner, "modifier '%s' is not applicable for '%s'",
551 rpost, sel->u.expr.method->name);
556 * \param[in] left Selection element for the left hand side.
557 * \param[in] right Selection element for the right hand side.
558 * \param[in] op String representation of the operator.
559 * \param[in] scanner Scanner data structure.
560 * \returns The created selection element.
562 * This function handles the creation of a gmx::SelectionTreeElement object for
563 * arithmetic expressions.
565 SelectionTreeElementPointer
566 _gmx_sel_init_arithmetic(const SelectionTreeElementPointer &left,
567 const SelectionTreeElementPointer &right,
568 char op, yyscan_t scanner)
570 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_ARITHMETIC));
571 sel->v.type = REAL_VALUE;
574 case '+': sel->u.arith.type = ARITH_PLUS; break;
575 case '-': sel->u.arith.type = (right ? ARITH_MINUS : ARITH_NEG); break;
576 case '*': sel->u.arith.type = ARITH_MULT; break;
577 case '/': sel->u.arith.type = ARITH_DIV; break;
578 case '^': sel->u.arith.type = ARITH_EXP; break;
584 sel->u.arith.opstr = strdup(buf);
586 sel->child->next = right;
591 * \param[in] left Selection element for the left hand side.
592 * \param[in] right Selection element for the right hand side.
593 * \param[in] cmpop String representation of the comparison operator.
594 * \param[in] scanner Scanner data structure.
595 * \returns The created selection element.
597 * This function handles the creation of a gmx::SelectionTreeElement object for
598 * comparison expressions.
600 SelectionTreeElementPointer
601 _gmx_sel_init_comparison(const SelectionTreeElementPointer &left,
602 const SelectionTreeElementPointer &right,
603 const char *cmpop, yyscan_t scanner)
605 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
606 gmx::MessageStringContext context(errors, "In comparison initialization");
608 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_EXPRESSION));
609 _gmx_selelem_set_method(sel, &sm_compare, scanner);
611 SelectionParserParameterList params;
613 // Create the parameter for the left expression.
614 name = left->v.type == INT_VALUE ? "int1" : "real1";
615 params.push_back(SelectionParserParameter::createFromExpression(name, left));
616 // Create the parameter for the right expression.
617 name = right->v.type == INT_VALUE ? "int2" : "real2";
618 params.push_back(SelectionParserParameter::createFromExpression(name, right));
619 // Create the parameter for the operator.
621 SelectionParserParameter::create(
622 "op", SelectionParserValue::createString(cmpop)));
623 if (!_gmx_sel_parse_params(params, sel->u.expr.method->nparams,
624 sel->u.expr.method->param, sel, scanner))
626 return SelectionTreeElementPointer();
633 * Implementation method for keyword expression creation.
635 * \param[in] method Method to use.
636 * \param[in] matchType String matching type (only used if \p method is
637 * a string keyword and \p args is not empty.
638 * \param[in] args Pointer to the first argument.
639 * \param[in] rpost Reference position type to use (NULL = default).
640 * \param[in] scanner Scanner data structure.
641 * \returns The created selection element.
643 * This function handles the creation of a gmx::SelectionTreeElement object for
644 * selection methods that do not take parameters.
646 static SelectionTreeElementPointer
647 init_keyword_internal(gmx_ana_selmethod_t *method,
648 gmx::SelectionStringMatchType matchType,
649 SelectionParserValueListPointer args,
650 const char *rpost, yyscan_t scanner)
652 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
654 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
656 sprintf(buf, "In keyword '%s'", method->name);
657 gmx::MessageStringContext context(errors, buf);
659 if (method->nparams > 0)
661 // TODO: Would assert be better?
662 GMX_THROW(gmx::InternalError(
663 "Keyword initialization called with non-keyword method"));
666 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
667 SelectionTreeElementPointer child = root;
668 _gmx_selelem_set_method(child, method, scanner);
670 /* Initialize the evaluation of keyword matching if values are provided */
673 gmx_ana_selmethod_t *kwmethod;
674 switch (method->type)
676 case INT_VALUE: kwmethod = &sm_keyword_int; break;
677 case REAL_VALUE: kwmethod = &sm_keyword_real; break;
678 case STR_VALUE: kwmethod = &sm_keyword_str; break;
680 GMX_THROW(gmx::InternalError(
681 "Unknown type for keyword selection"));
683 /* Initialize the selection element */
684 root.reset(new SelectionTreeElement(SEL_EXPRESSION));
685 _gmx_selelem_set_method(root, kwmethod, scanner);
686 if (method->type == STR_VALUE)
688 _gmx_selelem_set_kwstr_match_type(root, matchType);
690 SelectionParserParameterList params;
692 SelectionParserParameter::createFromExpression(NULL, child));
693 params.push_back(SelectionParserParameter::create(NULL, move(args)));
694 if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
695 root->u.expr.method->param, root, scanner))
697 return SelectionTreeElementPointer();
700 set_refpos_type(&sc->pcc, child, rpost, scanner);
706 * \param[in] method Method to use.
707 * \param[in] args Pointer to the first argument.
708 * \param[in] rpost Reference position type to use (NULL = default).
709 * \param[in] scanner Scanner data structure.
710 * \returns The created selection element.
712 * This function handles the creation of a gmx::SelectionTreeElement object for
713 * selection methods that do not take parameters.
715 SelectionTreeElementPointer
716 _gmx_sel_init_keyword(gmx_ana_selmethod_t *method,
717 SelectionParserValueListPointer args,
718 const char *rpost, yyscan_t scanner)
720 return init_keyword_internal(method, gmx::eStringMatchType_Auto, move(args),
725 * \param[in] method Method to use.
726 * \param[in] matchType String matching type.
727 * \param[in] args Pointer to the first argument.
728 * \param[in] rpost Reference position type to use (NULL = default).
729 * \param[in] scanner Scanner data structure.
730 * \returns The created selection element.
732 * This function handles the creation of a gmx::SelectionTreeElement object for
733 * keyword string matching.
735 SelectionTreeElementPointer
736 _gmx_sel_init_keyword_strmatch(gmx_ana_selmethod_t *method,
737 gmx::SelectionStringMatchType matchType,
738 SelectionParserValueListPointer args,
739 const char *rpost, yyscan_t scanner)
741 GMX_RELEASE_ASSERT(method->type == STR_VALUE,
742 "String keyword method called for a non-string-valued method");
743 GMX_RELEASE_ASSERT(args && !args->empty(),
744 "String keyword matching method called without any values");
745 return init_keyword_internal(method, matchType, move(args), rpost, scanner);
749 * \param[in] method Method to use for initialization.
750 * \param[in] params Pointer to the first parameter.
751 * \param[in] rpost Reference position type to use (NULL = default).
752 * \param[in] scanner Scanner data structure.
753 * \returns The created selection element.
755 * This function handles the creation of a gmx::SelectionTreeElement object for
756 * selection methods that take parameters.
758 * Part of the behavior of the \c same selection keyword is hardcoded into
759 * this function (or rather, into _gmx_selelem_custom_init_same()) to allow the
760 * use of any keyword in \c "same KEYWORD as" without requiring special
761 * handling somewhere else (or sacrificing the simple syntax).
763 SelectionTreeElementPointer
764 _gmx_sel_init_method(gmx_ana_selmethod_t *method,
765 SelectionParserParameterListPointer params,
766 const char *rpost, yyscan_t scanner)
768 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
771 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
773 sprintf(buf, "In keyword '%s'", method->name);
774 gmx::MessageStringContext context(errors, buf);
776 _gmx_sel_finish_method(scanner);
777 /* The "same" keyword needs some custom massaging of the parameters. */
778 rc = _gmx_selelem_custom_init_same(&method, params, scanner);
781 return SelectionTreeElementPointer();
783 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
784 _gmx_selelem_set_method(root, method, scanner);
785 /* Process the parameters */
786 if (!_gmx_sel_parse_params(*params, root->u.expr.method->nparams,
787 root->u.expr.method->param, root, scanner))
789 return SelectionTreeElementPointer();
791 set_refpos_type(&sc->pcc, root, rpost, scanner);
797 * \param[in] method Modifier to use for initialization.
798 * \param[in] params Pointer to the first parameter.
799 * \param[in] sel Selection element that the modifier should act on.
800 * \param[in] scanner Scanner data structure.
801 * \returns The created selection element.
803 * This function handles the creation of a gmx::SelectionTreeElement object for
804 * selection modifiers.
806 SelectionTreeElementPointer
807 _gmx_sel_init_modifier(gmx_ana_selmethod_t *method,
808 SelectionParserParameterListPointer params,
809 const SelectionTreeElementPointer &sel, yyscan_t scanner)
811 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
813 sprintf(buf, "In keyword '%s'", method->name);
814 gmx::MessageStringContext context(errors, buf);
816 _gmx_sel_finish_method(scanner);
817 SelectionTreeElementPointer modifier(new SelectionTreeElement(SEL_MODIFIER));
818 _gmx_selelem_set_method(modifier, method, scanner);
819 SelectionTreeElementPointer root;
820 if (method->type == NO_VALUE)
822 SelectionTreeElementPointer child = sel;
827 child->next = modifier;
833 SelectionParserParameter::createFromExpression(NULL, sel));
836 /* Process the parameters */
837 if (!_gmx_sel_parse_params(*params, modifier->u.expr.method->nparams,
838 modifier->u.expr.method->param, modifier, scanner))
840 return SelectionTreeElementPointer();
847 * \param[in] expr Input selection element for the position calculation.
848 * \param[in] type Reference position type or NULL for default.
849 * \param[in] scanner Scanner data structure.
850 * \returns The created selection element.
852 * This function handles the creation of a gmx::SelectionTreeElement object for
853 * evaluation of reference positions.
855 SelectionTreeElementPointer
856 _gmx_sel_init_position(const SelectionTreeElementPointer &expr,
857 const char *type, yyscan_t scanner)
859 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
861 sprintf(buf, "In position evaluation");
862 gmx::MessageStringContext context(errors, buf);
864 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
865 _gmx_selelem_set_method(root, &sm_keyword_pos, scanner);
866 _gmx_selelem_set_kwpos_type(root.get(), type);
867 /* Create the parameters for the parameter parser. */
868 SelectionParserParameterList params;
869 params.push_back(SelectionParserParameter::createFromExpression(NULL, expr));
870 /* Parse the parameters. */
871 if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
872 root->u.expr.method->param, root, scanner))
874 return SelectionTreeElementPointer();
881 * \param[in] x,y,z Coordinates for the position.
882 * \returns The creates selection element.
884 SelectionTreeElementPointer
885 _gmx_sel_init_const_position(real x, real y, real z)
889 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
890 _gmx_selelem_set_vtype(sel, POS_VALUE);
891 _gmx_selvalue_reserve(&sel->v, 1);
895 gmx_ana_pos_init_const(sel->v.u.p, pos);
900 * \param[in] name Name of an index group to search for.
901 * \param[in] scanner Scanner data structure.
902 * \returns The created constant selection element, or NULL if no matching
905 * See gmx_ana_indexgrps_find() for information on how \p name is matched
906 * against the index groups.
908 SelectionTreeElementPointer
909 _gmx_sel_init_group_by_name(const char *name, yyscan_t scanner)
911 gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
913 if (!_gmx_sel_lexer_has_groups_set(scanner))
915 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
916 _gmx_selelem_set_vtype(sel, GROUP_VALUE);
918 sel->u.gref.name = strdup(name);
924 _gmx_selparser_error(scanner, "No index groups set; cannot match 'group %s'", name);
925 return SelectionTreeElementPointer();
927 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
928 _gmx_selelem_set_vtype(sel, GROUP_VALUE);
929 /* FIXME: The constness should not be cast away */
930 if (!gmx_ana_indexgrps_find(&sel->u.cgrp, grps, (char *)name))
932 _gmx_selparser_error(scanner, "Cannot match 'group %s'", name);
933 return SelectionTreeElementPointer();
935 sel->setName(sel->u.cgrp.name);
940 * \param[in] id Zero-based index number of the group to extract.
941 * \param[in] scanner Scanner data structure.
942 * \returns The created constant selection element, or NULL if no matching
945 SelectionTreeElementPointer
946 _gmx_sel_init_group_by_id(int id, yyscan_t scanner)
948 gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
950 if (!_gmx_sel_lexer_has_groups_set(scanner))
952 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
953 _gmx_selelem_set_vtype(sel, GROUP_VALUE);
954 sel->u.gref.name = NULL;
960 _gmx_selparser_error(scanner, "No index groups set; cannot match 'group %d'", id);
961 return SelectionTreeElementPointer();
963 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
964 _gmx_selelem_set_vtype(sel, GROUP_VALUE);
965 if (!gmx_ana_indexgrps_extract(&sel->u.cgrp, grps, id))
967 _gmx_selparser_error(scanner, "Cannot match 'group %d'", id);
968 return SelectionTreeElementPointer();
970 sel->setName(sel->u.cgrp.name);
975 * \param[in,out] sel Value of the variable.
976 * \returns The created selection element that references \p sel.
978 * The reference count of \p sel is updated, but no other modifications are
981 SelectionTreeElementPointer
982 _gmx_sel_init_variable_ref(const SelectionTreeElementPointer &sel)
984 SelectionTreeElementPointer ref;
986 if (sel->v.type == POS_VALUE && sel->type == SEL_CONST)
992 ref.reset(new SelectionTreeElement(SEL_SUBEXPRREF));
993 _gmx_selelem_set_vtype(ref, sel->v.type);
994 ref->setName(sel->name());
1001 * \param[in] name Name for the selection
1002 * (if NULL, a default name is constructed).
1003 * \param[in] sel The selection element that evaluates the selection.
1004 * \param scanner Scanner data structure.
1005 * \returns The created root selection element.
1007 * This function handles the creation of root (\ref SEL_ROOT)
1008 * gmx::SelectionTreeElement objects for selections.
1010 SelectionTreeElementPointer
1011 _gmx_sel_init_selection(const char *name,
1012 const SelectionTreeElementPointer &sel,
1015 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
1017 sprintf(buf, "In selection '%s'", _gmx_sel_lexer_pselstr(scanner));
1018 gmx::MessageStringContext context(errors, buf);
1020 if (sel->v.type != POS_VALUE)
1022 /* FIXME: Better handling of this error */
1023 GMX_THROW(gmx::InternalError(
1024 "Each selection must evaluate to a position"));
1027 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_ROOT));
1031 root->setName(name);
1032 root->u.cgrp.name = strdup(name);
1034 /* Update the flags */
1035 _gmx_selelem_update_flags(root, scanner);
1037 /* If there is no name provided by the user, check whether the actual
1038 * selection given was from an external group, and if so, use the name
1039 * of the external group. */
1040 if (root->name().empty())
1042 SelectionTreeElementPointer child = root->child;
1043 while (child->type == SEL_MODIFIER)
1045 if (!child->child || child->child->type != SEL_SUBEXPRREF
1046 || !child->child->child)
1050 child = child->child->child;
1052 if (child->type == SEL_EXPRESSION
1053 && child->child && child->child->type == SEL_SUBEXPRREF
1054 && child->child->child
1055 && child->child->child->type == SEL_CONST
1056 && child->child->child->v.type == GROUP_VALUE)
1058 const char *grpName = child->child->child->u.cgrp.name;
1059 root->setName(grpName);
1060 root->u.cgrp.name = strdup(grpName);
1063 /* If there still is no name, use the selection string */
1064 if (root->name().empty())
1066 const char *selStr = _gmx_sel_lexer_pselstr(scanner);
1067 root->setName(selStr);
1068 root->u.cgrp.name = strdup(selStr);
1071 /* Print out some information if the parser is interactive */
1072 if (_gmx_sel_is_lexer_interactive(scanner))
1074 fprintf(stderr, "Selection '%s' parsed\n",
1075 _gmx_sel_lexer_pselstr(scanner));
1083 * \param[in] name Name of the variable.
1084 * \param[in] expr The selection element that evaluates the variable.
1085 * \param scanner Scanner data structure.
1086 * \returns The created root selection element.
1088 * This function handles the creation of root gmx::SelectionTreeElement objects
1089 * for variable assignments. A \ref SEL_ROOT element and a \ref SEL_SUBEXPR
1090 * element are both created.
1092 SelectionTreeElementPointer
1093 _gmx_sel_assign_variable(const char *name,
1094 const SelectionTreeElementPointer &expr,
1097 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1098 const char *pselstr = _gmx_sel_lexer_pselstr(scanner);
1099 SelectionTreeElementPointer root;
1101 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
1103 sprintf(buf, "In selection '%s'", pselstr);
1104 gmx::MessageStringContext context(errors, buf);
1106 _gmx_selelem_update_flags(expr, scanner);
1107 /* Check if this is a constant non-group value */
1108 if (expr->type == SEL_CONST && expr->v.type != GROUP_VALUE)
1110 /* If so, just assign the constant value to the variable */
1111 sc->symtab->addVariable(name, expr);
1114 /* Check if we are assigning a variable to another variable */
1115 if (expr->type == SEL_SUBEXPRREF)
1117 /* If so, make a simple alias */
1118 sc->symtab->addVariable(name, expr->child);
1121 /* Create the root element */
1122 root.reset(new SelectionTreeElement(SEL_ROOT));
1123 root->setName(name);
1124 root->u.cgrp.name = strdup(name);
1125 /* Create the subexpression element */
1126 root->child.reset(new SelectionTreeElement(SEL_SUBEXPR));
1127 root->child->setName(name);
1128 _gmx_selelem_set_vtype(root->child, expr->v.type);
1129 root->child->child = expr;
1131 _gmx_selelem_update_flags(root, scanner);
1132 /* Add the variable to the symbol table */
1133 sc->symtab->addVariable(name, root->child);
1135 srenew(sc->varstrs, sc->nvars + 1);
1136 sc->varstrs[sc->nvars] = strdup(pselstr);
1138 if (_gmx_sel_is_lexer_interactive(scanner))
1140 fprintf(stderr, "Variable '%s' parsed\n", pselstr);
1146 * \param sel Selection to append (can be NULL, in which
1147 * case nothing is done).
1148 * \param last Last selection, or NULL if not present or not known.
1149 * \param scanner Scanner data structure.
1150 * \returns The last selection after the append.
1152 * Appends \p sel after the last root element, and returns either \p sel
1153 * (if it was non-NULL) or the last element (if \p sel was NULL).
1155 SelectionTreeElementPointer
1156 _gmx_sel_append_selection(const SelectionTreeElementPointer &sel,
1157 SelectionTreeElementPointer last,
1160 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1162 /* Append sel after last, or the last element of sc if last is NULL */
1183 /* Initialize a selection object if necessary */
1187 /* Add the new selection to the collection if it is not a variable. */
1188 if (sel->child->type != SEL_SUBEXPR)
1190 gmx::SelectionDataPointer selPtr(
1191 new gmx::internal::SelectionData(
1192 sel.get(), _gmx_sel_lexer_pselstr(scanner)));
1193 sc->sel.push_back(gmx::move(selPtr));
1196 /* Clear the selection string now that we've saved it */
1197 _gmx_sel_lexer_clear_pselstr(scanner);
1202 * \param[in] scanner Scanner data structure.
1203 * \returns true if the parser should finish, false if parsing should
1206 * This function is called always after _gmx_sel_append_selection() to
1207 * check whether a sufficient number of selections has already been provided.
1208 * This is used to terminate interactive parsers when the correct number of
1209 * selections has been provided.
1212 _gmx_sel_parser_should_finish(yyscan_t scanner)
1214 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1215 return (int)sc->sel.size() == _gmx_sel_lexer_exp_selcount(scanner);
1219 * \param[in] scanner Scanner data structure.
1222 _gmx_sel_handle_empty_cmd(yyscan_t scanner)
1224 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1225 gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
1228 if (!_gmx_sel_is_lexer_interactive(scanner))
1233 fprintf(stderr, "Available index groups:\n");
1234 gmx_ana_indexgrps_print(stderr, _gmx_sel_lexer_indexgrps(scanner), 0);
1236 if (sc->nvars > 0 || !sc->sel.empty())
1238 fprintf(stderr, "Currently provided selections:\n");
1239 for (i = 0; i < sc->nvars; ++i)
1241 fprintf(stderr, " %s\n", sc->varstrs[i]);
1243 for (i = 0; i < (int)sc->sel.size(); ++i)
1245 fprintf(stderr, " %2d. %s\n", i+1, sc->sel[i]->selectionText());
1251 * \param[in] topic Topic for which help was requested, or NULL for general
1253 * \param[in] scanner Scanner data structure.
1255 * \p topic is freed by this function.
1258 _gmx_sel_handle_help_cmd(const SelectionParserValueListPointer &topic,
1261 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1263 if (sc->rootHelp.get() == NULL)
1265 sc->rootHelp = gmx::createSelectionHelpTopic();
1267 gmx::HelpWriterContext context(&gmx::File::standardError(),
1268 gmx::eHelpOutputFormat_Console);
1269 gmx::HelpManager manager(*sc->rootHelp, context);
1272 SelectionParserValueList::const_iterator value;
1273 for (value = topic->begin(); value != topic->end(); ++value)
1275 manager.enterTopic(value->stringValue());
1278 catch (const gmx::InvalidInputError &ex)
1280 fprintf(stderr, "%s\n", ex.what());
1283 manager.writeCurrentTopic();