2 * This file is part of the GROMACS molecular simulation package.
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.
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.
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.
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.
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.
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.
37 * Implements functions in parsetree.h.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_selection
43 * \page page_module_selection_parser Selection parsing
45 * The selection parser is implemented in the following files:
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.
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.
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().
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
88 * The rest of this page describes the resulting gmx::SelectionTreeElement
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
95 * \section selparser_tree Element tree constructed by the parser
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
104 * Fields that are not initialized are set to zero, NULL, or other similar
108 * \subsection selparser_tree_root Root elements
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.
117 * The \ref SEL_ROOT elements are linked together in a chain in the same order
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.
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.
137 * \subsection selparser_tree_const Constant elements
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
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.
154 * \subsection selparser_tree_method Method evaluation elements
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
161 * If a non-standard reference position type was set,
162 * gmx::SelectionTreeElement::pc has also been created, but only the type has
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.
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").
177 * \subsection selparser_tree_subexpr Subexpression elements
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
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
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
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.
203 * \subsection selparser_tree_bool Boolean elements
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
214 * \subsection selparser_tree_arith Arithmetic elements
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.
225 #include <boost/exception_ptr.hpp>
226 #include <boost/shared_ptr.hpp>
228 #include "gromacs/selection/poscalc.h"
229 #include "gromacs/selection/selection.h"
230 #include "gromacs/selection/selmethod.h"
231 #include "gromacs/utility/exceptions.h"
232 #include "gromacs/utility/file.h"
233 #include "gromacs/utility/messagestringcollector.h"
234 #include "gromacs/utility/smalloc.h"
235 #include "gromacs/utility/stringutil.h"
237 #include "keywords.h"
238 #include "parsetree.h"
239 #include "selectioncollection-impl.h"
245 using gmx::SelectionParserValue;
246 using gmx::SelectionParserValueList;
247 using gmx::SelectionParserValueListPointer;
248 using gmx::SelectionParserParameter;
249 using gmx::SelectionParserParameterList;
250 using gmx::SelectionParserParameterListPointer;
251 using gmx::SelectionParserValue;
252 using gmx::SelectionTreeElement;
253 using gmx::SelectionTreeElementPointer;
256 _gmx_selparser_error(yyscan_t scanner, const char *fmt, ...)
258 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
259 // FIXME: Use an arbitrary length buffer.
263 vsprintf(buf, fmt, ap);
269 _gmx_selparser_handle_exception(yyscan_t scanner, const std::exception &ex)
271 if (dynamic_cast<const gmx::UserInputError *>(&ex) != NULL)
273 // TODO: Consider whether also the non-interactive parser should
274 // postpone the exception such that the whole selection can be added as
276 if (_gmx_sel_is_lexer_interactive(scanner))
278 // TODO: Handle exceptions that printing the message may produce.
279 gmx::formatExceptionMessageToFile(stderr, ex);
283 _gmx_sel_lexer_set_exception(scanner, boost::current_exception());
290 /********************************************************************
291 * SelectionParserValue
294 SelectionParserValue::SelectionParserValue(e_selvalue_t type)
297 memset(&u, 0, sizeof(u));
300 SelectionParserValue::SelectionParserValue(
301 const SelectionTreeElementPointer &expr)
302 : type(expr->v.type), expr(expr)
304 memset(&u, 0, sizeof(u));
307 /********************************************************************
308 * SelectionParserParameter
311 SelectionParserParameter::SelectionParserParameter(
313 SelectionParserValueListPointer values)
314 : name_(name != NULL ? name : ""),
315 values_(values ? move(values)
316 : SelectionParserValueListPointer(new SelectionParserValueList))
323 * \param[in,out] sel Root of the selection element tree to initialize.
324 * \param[in] scanner Scanner data structure.
325 * \returns 0 on success, an error code on error.
327 * Propagates the \ref SEL_DYNAMIC flag from the children of \p sel to \p sel
328 * (if any child of \p sel is dynamic, \p sel is also marked as such).
329 * The \ref SEL_DYNAMIC flag is also set for \ref SEL_EXPRESSION elements with
331 * Also, sets one of the \ref SEL_SINGLEVAL, \ref SEL_ATOMVAL, or
332 * \ref SEL_VARNUMVAL flags, either based on the children or on the type of
333 * the selection method.
334 * If the types of the children conflict, an error is returned.
336 * The flags of the children of \p sel are also updated if not done earlier.
337 * The flags are initialized only once for any element; if \ref SEL_FLAGSSET
338 * is set for an element, the function returns immediately, and the recursive
339 * operation does not descend beyond such elements.
342 _gmx_selelem_update_flags(const gmx::SelectionTreeElementPointer &sel,
345 bool bUseChildType = false;
346 bool bOnlySingleChildren;
348 /* Return if the flags have already been set */
349 if (sel->flags & SEL_FLAGSSET)
353 /* Set the flags based on the current element type */
358 sel->flags |= SEL_SINGLEVAL;
359 bUseChildType = false;
363 if (sel->u.expr.method->flags & SMETH_DYNAMIC)
365 sel->flags |= SEL_DYNAMIC;
367 if (sel->u.expr.method->flags & SMETH_SINGLEVAL)
369 sel->flags |= SEL_SINGLEVAL;
371 else if (sel->u.expr.method->flags & SMETH_VARNUMVAL)
373 sel->flags |= SEL_VARNUMVAL;
377 sel->flags |= SEL_ATOMVAL;
379 bUseChildType = false;
383 sel->flags |= SEL_ATOMVAL;
384 bUseChildType = false;
388 if (sel->v.type != NO_VALUE)
390 sel->flags |= SEL_VARNUMVAL;
392 bUseChildType = false;
396 bUseChildType = false;
402 bUseChildType = true;
405 /* Loop through children to propagate their flags upwards */
406 bOnlySingleChildren = true;
407 SelectionTreeElementPointer child = sel->child;
410 /* Update the child */
411 _gmx_selelem_update_flags(child, scanner);
412 /* Propagate the dynamic flag */
413 sel->flags |= (child->flags & SEL_DYNAMIC);
414 /* Propagate the type flag if necessary and check for problems */
417 if ((sel->flags & SEL_VALTYPEMASK)
418 && !(sel->flags & child->flags & SEL_VALTYPEMASK))
420 _gmx_selparser_error(scanner, "invalid combination of selection expressions");
421 // FIXME: Use an exception.
424 sel->flags |= (child->flags & SEL_VALTYPEMASK);
426 if (!(child->flags & SEL_SINGLEVAL))
428 bOnlySingleChildren = false;
433 /* For arithmetic expressions consisting only of single values,
434 * the result is also a single value. */
435 if (sel->type == SEL_ARITHMETIC && bOnlySingleChildren)
437 sel->flags = (sel->flags & ~SEL_VALTYPEMASK) | SEL_SINGLEVAL;
439 /* For root elements, the type should be propagated here, after the
440 * children have been updated. */
441 if (sel->type == SEL_ROOT)
443 GMX_ASSERT(sel->child, "Root elements should always have a child");
444 sel->flags |= (sel->child->flags & SEL_VALTYPEMASK);
446 /* Mark that the flags are set */
447 sel->flags |= SEL_FLAGSSET;
451 * \param[in,out] sel Selection element to initialize.
452 * \param[in] scanner Scanner data structure.
454 * A deep copy of the parameters is made to allow several
455 * expressions with the same method to coexist peacefully.
456 * Calls sel_datafunc() if one is specified for the method.
459 _gmx_selelem_init_method_params(const gmx::SelectionTreeElementPointer &sel,
463 gmx_ana_selparam_t *orgparam;
464 gmx_ana_selparam_t *param;
468 nparams = sel->u.expr.method->nparams;
469 orgparam = sel->u.expr.method->param;
470 snew(param, nparams);
471 memcpy(param, orgparam, nparams*sizeof(gmx_ana_selparam_t));
472 for (i = 0; i < nparams; ++i)
474 param[i].flags &= ~SPAR_SET;
475 _gmx_selvalue_setstore(¶m[i].val, NULL);
476 if (param[i].flags & SPAR_VARNUM)
478 param[i].val.nr = -1;
480 /* Duplicate the enum value array if it is given statically */
481 if ((param[i].flags & SPAR_ENUMVAL) && orgparam[i].val.u.ptr != NULL)
485 /* Count the values */
487 while (orgparam[i].val.u.s[n] != NULL)
491 _gmx_selvalue_reserve(¶m[i].val, n+1);
492 memcpy(param[i].val.u.s, orgparam[i].val.u.s,
493 (n+1)*sizeof(param[i].val.u.s[0]));
497 if (sel->u.expr.method->init_data)
499 mdata = sel->u.expr.method->init_data(nparams, param);
501 if (sel->u.expr.method->set_poscoll)
503 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
505 sel->u.expr.method->set_poscoll(&sc->pcc, mdata);
507 /* Store the values */
508 sel->u.expr.method->param = param;
509 sel->u.expr.mdata = mdata;
513 * \param[in,out] sel Selection element to initialize.
514 * \param[in] method Selection method to set.
515 * \param[in] scanner Scanner data structure.
517 * Makes a copy of \p method and stores it in \p sel->u.expr.method,
518 * and calls _gmx_selelem_init_method_params();
521 _gmx_selelem_set_method(const gmx::SelectionTreeElementPointer &sel,
522 gmx_ana_selmethod_t *method,
525 _gmx_selelem_set_vtype(sel, method->type);
526 sel->setName(method->name);
527 snew(sel->u.expr.method, 1);
528 memcpy(sel->u.expr.method, method, sizeof(gmx_ana_selmethod_t));
529 _gmx_selelem_init_method_params(sel, scanner);
533 * Initializes the reference position calculation for a \ref SEL_EXPRESSION
536 * \param[in,out] pcc Position calculation collection to use.
537 * \param[in,out] sel Selection element to initialize.
538 * \param[in] rpost Reference position type to use (NULL = default).
539 * \param[in] scanner Scanner data structure.
540 * \returns 0 on success, a non-zero error code on error.
543 set_refpos_type(gmx::PositionCalculationCollection *pcc,
544 const SelectionTreeElementPointer &sel,
545 const char *rpost, yyscan_t scanner)
552 if (sel->u.expr.method->pupdate)
554 /* By default, use whole residues/molecules. */
556 = pcc->createCalculationFromEnum(rpost, POS_COMPLWHOLE);
560 // TODO: Should this be treated as a real error?
561 _gmx_selparser_error(scanner, "modifier '%s' is not applicable for '%s'",
562 rpost, sel->u.expr.method->name);
566 gmx::SelectionTreeElementPointer
567 _gmx_sel_init_arithmetic(const gmx::SelectionTreeElementPointer &left,
568 const gmx::SelectionTreeElementPointer &right,
569 char op, yyscan_t /* scanner */)
571 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_ARITHMETIC));
572 sel->v.type = REAL_VALUE;
575 case '+': sel->u.arith.type = ARITH_PLUS; break;
576 case '-': sel->u.arith.type = (right ? ARITH_MINUS : ARITH_NEG); break;
577 case '*': sel->u.arith.type = ARITH_MULT; break;
578 case '/': sel->u.arith.type = ARITH_DIV; break;
579 case '^': sel->u.arith.type = ARITH_EXP; break;
585 sel->u.arith.opstr = strdup(buf);
587 sel->child->next = right;
592 * \param[in] left Selection element for the left hand side.
593 * \param[in] right Selection element for the right hand side.
594 * \param[in] cmpop String representation of the comparison operator.
595 * \param[in] scanner Scanner data structure.
596 * \returns The created selection element.
598 * This function handles the creation of a gmx::SelectionTreeElement object for
599 * comparison expressions.
601 SelectionTreeElementPointer
602 _gmx_sel_init_comparison(const gmx::SelectionTreeElementPointer &left,
603 const gmx::SelectionTreeElementPointer &right,
604 const char *cmpop, yyscan_t scanner)
606 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
607 gmx::MessageStringContext context(errors, "In comparison initialization");
609 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_EXPRESSION));
610 _gmx_selelem_set_method(sel, &sm_compare, scanner);
612 SelectionParserParameterList params;
614 // Create the parameter for the left expression.
615 name = left->v.type == INT_VALUE ? "int1" : "real1";
616 params.push_back(SelectionParserParameter::createFromExpression(name, left));
617 // Create the parameter for the right expression.
618 name = right->v.type == INT_VALUE ? "int2" : "real2";
619 params.push_back(SelectionParserParameter::createFromExpression(name, right));
620 // Create the parameter for the operator.
622 SelectionParserParameter::create(
623 "op", SelectionParserValue::createString(cmpop)));
624 if (!_gmx_sel_parse_params(params, sel->u.expr.method->nparams,
625 sel->u.expr.method->param, sel, scanner))
627 return SelectionTreeElementPointer();
634 * Implementation method for keyword expression creation.
636 * \param[in] method Method to use.
637 * \param[in] matchType String matching type (only used if \p method is
638 * a string keyword and \p args is not empty.
639 * \param[in] args Pointer to the first argument.
640 * \param[in] rpost Reference position type to use (NULL = default).
641 * \param[in] scanner Scanner data structure.
642 * \returns The created selection element.
644 * This function handles the creation of a gmx::SelectionTreeElement object for
645 * selection methods that do not take parameters.
647 static SelectionTreeElementPointer
648 init_keyword_internal(gmx_ana_selmethod_t *method,
649 gmx::SelectionStringMatchType matchType,
650 SelectionParserValueListPointer args,
651 const char *rpost, yyscan_t scanner)
653 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
655 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
657 sprintf(buf, "In keyword '%s'", method->name);
658 gmx::MessageStringContext context(errors, buf);
660 if (method->nparams > 0)
662 // TODO: Would assert be better?
663 GMX_THROW(gmx::InternalError(
664 "Keyword initialization called with non-keyword method"));
667 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
668 SelectionTreeElementPointer child = root;
669 _gmx_selelem_set_method(child, method, scanner);
671 /* Initialize the evaluation of keyword matching if values are provided */
674 gmx_ana_selmethod_t *kwmethod;
675 switch (method->type)
677 case INT_VALUE: kwmethod = &sm_keyword_int; break;
678 case REAL_VALUE: kwmethod = &sm_keyword_real; break;
679 case STR_VALUE: kwmethod = &sm_keyword_str; break;
681 GMX_THROW(gmx::InternalError(
682 "Unknown type for keyword selection"));
684 /* Initialize the selection element */
685 root.reset(new SelectionTreeElement(SEL_EXPRESSION));
686 _gmx_selelem_set_method(root, kwmethod, scanner);
687 if (method->type == STR_VALUE)
689 _gmx_selelem_set_kwstr_match_type(root, matchType);
691 SelectionParserParameterList params;
693 SelectionParserParameter::createFromExpression(NULL, child));
694 params.push_back(SelectionParserParameter::create(NULL, move(args)));
695 if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
696 root->u.expr.method->param, root, scanner))
698 return SelectionTreeElementPointer();
701 set_refpos_type(&sc->pcc, child, rpost, scanner);
707 * \param[in] method Method to use.
708 * \param[in] args Pointer to the first argument.
709 * \param[in] rpost Reference position type to use (NULL = default).
710 * \param[in] scanner Scanner data structure.
711 * \returns The created selection element.
713 * This function handles the creation of a gmx::SelectionTreeElement object for
714 * selection methods that do not take parameters.
716 SelectionTreeElementPointer
717 _gmx_sel_init_keyword(gmx_ana_selmethod_t *method,
718 gmx::SelectionParserValueListPointer args,
719 const char *rpost, yyscan_t scanner)
721 return init_keyword_internal(method, gmx::eStringMatchType_Auto, move(args),
726 * \param[in] method Method to use.
727 * \param[in] matchType String matching type.
728 * \param[in] args Pointer to the first argument.
729 * \param[in] rpost Reference position type to use (NULL = default).
730 * \param[in] scanner Scanner data structure.
731 * \returns The created selection element.
733 * This function handles the creation of a gmx::SelectionTreeElement object for
734 * keyword string matching.
736 SelectionTreeElementPointer
737 _gmx_sel_init_keyword_strmatch(gmx_ana_selmethod_t *method,
738 gmx::SelectionStringMatchType matchType,
739 gmx::SelectionParserValueListPointer args,
740 const char *rpost, yyscan_t scanner)
742 GMX_RELEASE_ASSERT(method->type == STR_VALUE,
743 "String keyword method called for a non-string-valued method");
744 GMX_RELEASE_ASSERT(args && !args->empty(),
745 "String keyword matching method called without any values");
746 return init_keyword_internal(method, matchType, move(args), rpost, scanner);
750 * \param[in] method Method to use for initialization.
751 * \param[in] params Pointer to the first parameter.
752 * \param[in] rpost Reference position type to use (NULL = default).
753 * \param[in] scanner Scanner data structure.
754 * \returns The created selection element.
756 * This function handles the creation of a gmx::SelectionTreeElement object for
757 * selection methods that take parameters.
759 * Part of the behavior of the \c same selection keyword is hardcoded into
760 * this function (or rather, into _gmx_selelem_custom_init_same()) to allow the
761 * use of any keyword in \c "same KEYWORD as" without requiring special
762 * handling somewhere else (or sacrificing the simple syntax).
764 SelectionTreeElementPointer
765 _gmx_sel_init_method(gmx_ana_selmethod_t *method,
766 gmx::SelectionParserParameterListPointer params,
767 const char *rpost, yyscan_t scanner)
769 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
772 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
774 sprintf(buf, "In keyword '%s'", method->name);
775 gmx::MessageStringContext context(errors, buf);
777 _gmx_sel_finish_method(scanner);
778 /* The "same" keyword needs some custom massaging of the parameters. */
779 rc = _gmx_selelem_custom_init_same(&method, params, scanner);
782 return SelectionTreeElementPointer();
784 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
785 _gmx_selelem_set_method(root, method, scanner);
786 /* Process the parameters */
787 if (!_gmx_sel_parse_params(*params, root->u.expr.method->nparams,
788 root->u.expr.method->param, root, scanner))
790 return SelectionTreeElementPointer();
792 set_refpos_type(&sc->pcc, root, rpost, scanner);
798 * \param[in] method Modifier to use for initialization.
799 * \param[in] params Pointer to the first parameter.
800 * \param[in] sel Selection element that the modifier should act on.
801 * \param[in] scanner Scanner data structure.
802 * \returns The created selection element.
804 * This function handles the creation of a gmx::SelectionTreeElement object for
805 * selection modifiers.
807 SelectionTreeElementPointer
808 _gmx_sel_init_modifier(gmx_ana_selmethod_t *method,
809 gmx::SelectionParserParameterListPointer params,
810 const gmx::SelectionTreeElementPointer &sel,
813 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
815 sprintf(buf, "In keyword '%s'", method->name);
816 gmx::MessageStringContext context(errors, buf);
818 _gmx_sel_finish_method(scanner);
819 SelectionTreeElementPointer modifier(new SelectionTreeElement(SEL_MODIFIER));
820 _gmx_selelem_set_method(modifier, method, scanner);
821 SelectionTreeElementPointer root;
822 if (method->type == NO_VALUE)
824 SelectionTreeElementPointer child = sel;
829 child->next = modifier;
835 SelectionParserParameter::createFromExpression(NULL, sel));
838 /* Process the parameters */
839 if (!_gmx_sel_parse_params(*params, modifier->u.expr.method->nparams,
840 modifier->u.expr.method->param, modifier, scanner))
842 return SelectionTreeElementPointer();
849 * \param[in] expr Input selection element for the position calculation.
850 * \param[in] type Reference position type or NULL for default.
851 * \param[in] scanner Scanner data structure.
852 * \returns The created selection element.
854 * This function handles the creation of a gmx::SelectionTreeElement object for
855 * evaluation of reference positions.
857 SelectionTreeElementPointer
858 _gmx_sel_init_position(const gmx::SelectionTreeElementPointer &expr,
859 const char *type, yyscan_t scanner)
861 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
863 sprintf(buf, "In position evaluation");
864 gmx::MessageStringContext context(errors, buf);
866 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
867 _gmx_selelem_set_method(root, &sm_keyword_pos, scanner);
868 _gmx_selelem_set_kwpos_type(root.get(), type);
869 /* Create the parameters for the parameter parser. */
870 SelectionParserParameterList params;
871 params.push_back(SelectionParserParameter::createFromExpression(NULL, expr));
872 /* Parse the parameters. */
873 if (!_gmx_sel_parse_params(params, root->u.expr.method->nparams,
874 root->u.expr.method->param, root, scanner))
876 return SelectionTreeElementPointer();
883 * \param[in] x,y,z Coordinates for the position.
884 * \returns The creates selection element.
886 SelectionTreeElementPointer
887 _gmx_sel_init_const_position(real x, real y, real z)
891 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
892 _gmx_selelem_set_vtype(sel, POS_VALUE);
893 _gmx_selvalue_reserve(&sel->v, 1);
897 gmx_ana_pos_init_const(sel->v.u.p, pos);
902 * \param[in] name Name of an index group to search for.
903 * \param[in] scanner Scanner data structure.
904 * \returns The created selection element.
906 * See gmx_ana_indexgrps_find() for information on how \p name is matched
907 * against the index groups.
909 SelectionTreeElementPointer
910 _gmx_sel_init_group_by_name(const char *name, yyscan_t scanner)
913 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
914 _gmx_selelem_set_vtype(sel, GROUP_VALUE);
915 sel->setName(gmx::formatString("group \"%s\"", name));
916 sel->u.gref.name = strdup(name);
919 if (_gmx_sel_lexer_has_groups_set(scanner))
921 gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
922 sel->resolveIndexGroupReference(grps);
929 * \param[in] id Zero-based index number of the group to extract.
930 * \param[in] scanner Scanner data structure.
931 * \returns The created selection element.
933 SelectionTreeElementPointer
934 _gmx_sel_init_group_by_id(int id, yyscan_t scanner)
936 SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
937 _gmx_selelem_set_vtype(sel, GROUP_VALUE);
938 sel->setName(gmx::formatString("group %d", id));
939 sel->u.gref.name = NULL;
942 if (_gmx_sel_lexer_has_groups_set(scanner))
944 gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
945 sel->resolveIndexGroupReference(grps);
952 * \param[in,out] sel Value of the variable.
953 * \returns The created selection element that references \p sel.
955 * The reference count of \p sel is updated, but no other modifications are
958 SelectionTreeElementPointer
959 _gmx_sel_init_variable_ref(const gmx::SelectionTreeElementPointer &sel)
961 SelectionTreeElementPointer ref;
963 if (sel->v.type == POS_VALUE && sel->type == SEL_CONST)
969 ref.reset(new SelectionTreeElement(SEL_SUBEXPRREF));
970 _gmx_selelem_set_vtype(ref, sel->v.type);
971 ref->setName(sel->name());
978 * \param[in] name Name for the selection
979 * (if NULL, a default name is constructed).
980 * \param[in] sel The selection element that evaluates the selection.
981 * \param scanner Scanner data structure.
982 * \returns The created root selection element.
984 * This function handles the creation of root (\ref SEL_ROOT)
985 * gmx::SelectionTreeElement objects for selections.
987 SelectionTreeElementPointer
988 _gmx_sel_init_selection(const char *name,
989 const gmx::SelectionTreeElementPointer &sel,
992 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
994 sprintf(buf, "In selection '%s'", _gmx_sel_lexer_pselstr(scanner));
995 gmx::MessageStringContext context(errors, buf);
997 if (sel->v.type != POS_VALUE)
999 /* FIXME: Better handling of this error */
1000 GMX_THROW(gmx::InternalError(
1001 "Each selection must evaluate to a position"));
1004 SelectionTreeElementPointer root(new SelectionTreeElement(SEL_ROOT));
1008 root->setName(name);
1010 /* Update the flags */
1011 _gmx_selelem_update_flags(root, scanner);
1013 root->fillNameIfMissing(_gmx_sel_lexer_pselstr(scanner));
1015 /* Print out some information if the parser is interactive */
1016 if (_gmx_sel_is_lexer_interactive(scanner))
1018 fprintf(stderr, "Selection '%s' parsed\n",
1019 _gmx_sel_lexer_pselstr(scanner));
1027 * \param[in] name Name of the variable.
1028 * \param[in] expr The selection element that evaluates the variable.
1029 * \param scanner Scanner data structure.
1030 * \returns The created root selection element.
1032 * This function handles the creation of root gmx::SelectionTreeElement objects
1033 * for variable assignments. A \ref SEL_ROOT element and a \ref SEL_SUBEXPR
1034 * element are both created.
1036 SelectionTreeElementPointer
1037 _gmx_sel_assign_variable(const char *name,
1038 const gmx::SelectionTreeElementPointer &expr,
1041 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1042 const char *pselstr = _gmx_sel_lexer_pselstr(scanner);
1043 SelectionTreeElementPointer root;
1045 gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
1047 sprintf(buf, "In selection '%s'", pselstr);
1048 gmx::MessageStringContext context(errors, buf);
1050 _gmx_selelem_update_flags(expr, scanner);
1051 /* Check if this is a constant non-group value */
1052 if (expr->type == SEL_CONST && expr->v.type != GROUP_VALUE)
1054 /* If so, just assign the constant value to the variable */
1055 sc->symtab->addVariable(name, expr);
1058 /* Check if we are assigning a variable to another variable */
1059 if (expr->type == SEL_SUBEXPRREF)
1061 /* If so, make a simple alias */
1062 sc->symtab->addVariable(name, expr->child);
1065 /* Create the root element */
1066 root.reset(new SelectionTreeElement(SEL_ROOT));
1067 root->setName(name);
1068 /* Create the subexpression element */
1069 root->child.reset(new SelectionTreeElement(SEL_SUBEXPR));
1070 root->child->setName(name);
1071 _gmx_selelem_set_vtype(root->child, expr->v.type);
1072 root->child->child = expr;
1074 _gmx_selelem_update_flags(root, scanner);
1075 /* Add the variable to the symbol table */
1076 sc->symtab->addVariable(name, root->child);
1078 srenew(sc->varstrs, sc->nvars + 1);
1079 sc->varstrs[sc->nvars] = strdup(pselstr);
1081 if (_gmx_sel_is_lexer_interactive(scanner))
1083 fprintf(stderr, "Variable '%s' parsed\n", pselstr);
1089 * \param sel Selection to append (can be NULL, in which
1090 * case nothing is done).
1091 * \param last Last selection, or NULL if not present or not known.
1092 * \param scanner Scanner data structure.
1093 * \returns The last selection after the append.
1095 * Appends \p sel after the last root element, and returns either \p sel
1096 * (if it was non-NULL) or the last element (if \p sel was NULL).
1098 SelectionTreeElementPointer
1099 _gmx_sel_append_selection(const gmx::SelectionTreeElementPointer &sel,
1100 gmx::SelectionTreeElementPointer last,
1103 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1105 /* Append sel after last, or the last element of sc if last is NULL */
1126 /* Initialize a selection object if necessary */
1130 /* Add the new selection to the collection if it is not a variable. */
1131 if (sel->child->type != SEL_SUBEXPR)
1133 gmx::SelectionDataPointer selPtr(
1134 new gmx::internal::SelectionData(
1135 sel.get(), _gmx_sel_lexer_pselstr(scanner)));
1136 sc->sel.push_back(gmx::move(selPtr));
1139 /* Clear the selection string now that we've saved it */
1140 _gmx_sel_lexer_clear_pselstr(scanner);
1145 * \param[in] scanner Scanner data structure.
1146 * \returns true if the parser should finish, false if parsing should
1149 * This function is called always after _gmx_sel_append_selection() to
1150 * check whether a sufficient number of selections has already been provided.
1151 * This is used to terminate interactive parsers when the correct number of
1152 * selections has been provided.
1155 _gmx_sel_parser_should_finish(yyscan_t scanner)
1157 gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
1158 return (int)sc->sel.size() == _gmx_sel_lexer_exp_selcount(scanner);