2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2009,2010,2011,2012,2013 by the GROMACS development team.
5 * Copyright (c) 2014,2015,2016,2017,2018 by the GROMACS development team.
6 * Copyright (c) 2019,2020, by the GROMACS development team, led by
7 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8 * and including many others, as listed in the AUTHORS file in the
9 * top-level source directory and at http://www.gromacs.org.
11 * GROMACS is free software; you can redistribute it and/or
12 * modify it under the terms of the GNU Lesser General Public License
13 * as published by the Free Software Foundation; either version 2.1
14 * of the License, or (at your option) any later version.
16 * GROMACS is distributed in the hope that it will be useful,
17 * but WITHOUT ANY WARRANTY; without even the implied warranty of
18 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19 * Lesser General Public License for more details.
21 * You should have received a copy of the GNU Lesser General Public
22 * License along with GROMACS; if not, see
23 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
26 * If you want to redistribute modifications to GROMACS, please
27 * consider that scientific software is very special. Version
28 * control is crucial - bugs must be traceable. We will be happy to
29 * consider code for inclusion in the official distribution, but
30 * derived work must not be called official GROMACS. Details are found
31 * in the README & COPYING files - if they are missing, get the
32 * official version at http://www.gromacs.org.
34 * To help us fund GROMACS development, we humbly ask that you cite
35 * the research papers on the package. Check out http://www.gromacs.org.
39 * Implements functions in selparam.h.
41 * \author Teemu Murtola <teemu.murtola@gmail.com>
42 * \ingroup module_selection
50 #include "gromacs/math/units.h"
51 #include "gromacs/math/vec.h"
52 #include "gromacs/utility/cstringutil.h"
53 #include "gromacs/utility/exceptions.h"
54 #include "gromacs/utility/gmxassert.h"
55 #include "gromacs/utility/smalloc.h"
56 #include "gromacs/utility/stringutil.h"
57 #include "gromacs/utility/unique_cptr.h"
59 #include "parsetree.h"
63 #include "selmethod.h"
69 * \param[in] name Name of the parameter to search.
70 * \param[in] nparam Number of parameters in the \p param array.
71 * \param[in] param Parameter array to search.
72 * \returns Pointer to the parameter in the \p param
73 * or NULL if no parameter with name \p name was found.
75 * The comparison is case-sensitive.
77 gmx_ana_selparam_t* gmx_ana_selparam_find(const char* name, int nparam, gmx_ana_selparam_t* param)
85 /* Find the first non-null parameter */
87 while (i < nparam && param[i].name == nullptr)
91 /* Process the special case of a NULL parameter */
94 return (i == 0) ? nullptr : ¶m[i - 1];
96 for (; i < nparam; ++i)
98 if (!strcmp(param[i].name, name))
102 /* Check for 'no' prefix on boolean parameters */
103 if (param[i].val.type == NO_VALUE && strlen(name) > 2 && name[0] == 'n' && name[1] == 'o'
104 && !strcmp(param[i].name, name + 2))
113 * Does a type conversion on a SelectionParserValue.
115 * \param[in,out] value Value to convert.
116 * \param[in] type Type to convert to.
117 * \param[in] errors Errors will be reported into this as nested exceptions.
118 * \param[in] scanner Scanner data structure.
120 static void convert_value(SelectionParserValue* value, e_selvalue_t type, ExceptionInitializer* errors, void* scanner)
122 if (value->type == type || type == NO_VALUE)
126 if (value->hasExpressionValue())
128 /* Conversion from atom selection to position using default
129 * reference positions. */
130 if (value->type == GROUP_VALUE && type == POS_VALUE)
134 SelectionTreeElementPointer expr = _gmx_sel_init_position(value->expr, nullptr, scanner);
135 *value = SelectionParserValue::createExpr(expr);
137 catch (UserInputError& ex)
139 std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
140 std::string context(formatString("In '%s'", text.c_str()));
141 ex.prependContext(context);
142 errors->addCurrentExceptionAsNested();
149 /* Integers to floating point are easy */
150 if (value->type == INT_VALUE && type == REAL_VALUE)
152 *value = SelectionParserValue::createRealRange(
153 value->u.i.i1, value->u.i.i2, value->location());
156 /* Reals that are integer-valued can also be converted */
157 if (value->type == REAL_VALUE && type == INT_VALUE)
159 int i1 = static_cast<int>(value->u.r.r1);
160 int i2 = static_cast<int>(value->u.r.r2);
161 if (gmx_within_tol(value->u.r.r1, i1, GMX_REAL_EPS)
162 && gmx_within_tol(value->u.r.r2, i2, GMX_REAL_EPS))
164 *value = SelectionParserValue::createIntegerRange(i1, i2, value->location());
169 std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
170 std::string message(formatString(
171 "Expression '%s' evaluates to a type is not valid in this context", text.c_str()));
172 InvalidInputError ex(message);
173 errors->addNested(ex);
177 * Does a type conversion on a list of values.
179 * \param[in,out] values Values to convert.
180 * \param[in] type Type to convert to.
181 * \param[in] scanner Scanner data structure.
183 static void convert_values(SelectionParserValueList* values, e_selvalue_t type, void* scanner)
185 ExceptionInitializer errors("");
186 SelectionParserValueList::iterator value;
187 for (value = values->begin(); value != values->end(); ++value)
189 convert_value(&*value, type, &errors, scanner);
191 if (errors.hasNestedExceptions())
193 GMX_THROW(InvalidInputError(errors));
198 * Adds a child element for a parameter, keeping the parameter order.
200 * \param[in,out] root Root element to which the child is added.
201 * \param[in] child Child to add.
202 * \param[in] param Parameter for which this child is a value.
204 * Puts \p child in the child list of \p root such that the list remains
205 * in the same order as the corresponding parameters.
207 static void place_child(const SelectionTreeElementPointer& root,
208 const SelectionTreeElementPointer& child,
209 gmx_ana_selparam_t* param)
211 gmx_ana_selparam_t* ps;
214 ps = root->u.expr.method->param;
216 /* Put the child element in the correct place */
217 if (!root->child || n < root->child->u.param - ps)
219 child->next = root->child;
224 SelectionTreeElementPointer prev = root->child;
225 while (prev->next && prev->next->u.param - ps >= n)
229 child->next = prev->next;
235 * Comparison function for sorting ranges.
237 * \param[in] a First range.
238 * \param[in] b Second range.
239 * \returns return true if a < b
241 * The ranges are primarily sorted based on their starting point, and
242 * secondarily based on length (longer ranges come first).
245 static bool cmp_range(const std::array<T, 2>& a, const std::array<T, 2>& b)
247 return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
251 * Parses the values for a parameter that takes integer or real ranges.
253 * \param[in] values List of values.
254 * \param param Parameter to parse.
255 * \param[in] scanner Scanner data structure.
257 static void parse_values_range(const SelectionParserValueList& values, gmx_ana_selparam_t* param, void* scanner)
261 param->flags &= ~SPAR_DYNAMIC;
262 GMX_RELEASE_ASSERT(param->val.type == INT_VALUE || param->val.type == REAL_VALUE,
263 "Invalid range parameter type");
264 int* idata = nullptr;
265 real* rdata = nullptr;
266 sfree_guard dataGuard;
267 if (param->val.type == INT_VALUE)
269 snew(idata, values.size() * 2);
270 dataGuard.reset(idata);
274 snew(rdata, values.size() * 2);
275 dataGuard.reset(rdata);
278 SelectionParserValueList::const_iterator value;
279 for (value = values.begin(); value != values.end(); ++value)
281 GMX_RELEASE_ASSERT(value->type == param->val.type,
282 "Invalid range value type (should have been caught earlier)");
283 if (value->hasExpressionValue())
285 std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
287 "Only simple values or 'A to B' ranges are "
288 "supported in this context");
289 InvalidInputError ex(message);
290 ex.prependContext(formatString("Invalid expression '%s'", text.c_str()));
293 if (param->val.type == INT_VALUE)
295 int i1 = std::min(value->u.i.i1, value->u.i.i2);
296 int i2 = std::max(value->u.i.i1, value->u.i.i2);
297 /* Check if the new range overlaps or extends the previous one */
298 if (i > 0 && i1 <= idata[i - 1] + 1 && i2 >= idata[i - 2] - 1)
300 idata[i - 2] = std::min(idata[i - 2], i1);
301 idata[i - 1] = std::max(idata[i - 1], i2);
311 real r1 = std::min(value->u.r.r1, value->u.r.r2);
312 real r2 = std::max(value->u.r.r1, value->u.r.r2);
313 /* Check if the new range overlaps or extends the previous one */
314 if (i > 0 && r1 <= rdata[i - 1] && r2 >= rdata[i - 2])
316 rdata[i - 2] = std::min(rdata[i - 2], r1);
317 rdata[i - 1] = std::max(rdata[i - 1], r2);
327 /* Sort the ranges and merge consequent ones */
328 if (param->val.type == INT_VALUE)
330 const auto range_data = reinterpret_cast<std::array<int, 2>*>(idata);
331 sort(range_data, range_data + n, cmp_range<int>);
332 for (i = j = 2; i < 2 * n; i += 2)
334 if (idata[j - 1] + 1 >= idata[i])
336 if (idata[i + 1] > idata[j - 1])
338 idata[j - 1] = idata[i + 1];
344 idata[j + 1] = idata[i + 1];
351 const auto range_data = reinterpret_cast<std::array<real, 2>*>(rdata);
352 sort(range_data, range_data + n, cmp_range<real>);
353 for (i = j = 2; i < 2 * n; i += 2)
355 if (rdata[j - 1] >= rdata[i])
357 if (rdata[i + 1] > rdata[j - 1])
359 rdata[j - 1] = rdata[i + 1];
365 rdata[j + 1] = rdata[i + 1];
371 /* Store the values */
372 if (param->flags & SPAR_VARNUM)
374 (void)dataGuard.release();
376 if (param->val.type == INT_VALUE)
379 _gmx_selvalue_setstore_alloc(¶m->val, idata, j);
384 _gmx_selvalue_setstore_alloc(¶m->val, rdata, j);
389 if (n != param->val.nr)
391 GMX_ASSERT(n == 1, "Range parameters with a fixed count > 1 do not make sense");
393 InvalidInputError("Only one value or 'A to B' range is "
394 "supported in this context"));
396 if (param->val.type == INT_VALUE)
398 memcpy(param->val.u.i, idata, 2 * n * sizeof(int));
402 memcpy(param->val.u.r, rdata, 2 * n * sizeof(real));
407 *param->nvalptr = param->val.nr;
409 param->nvalptr = nullptr;
413 * Parses the values for a parameter that takes a variable number of values.
415 * \param[in] values List of values.
416 * \param param Parameter to parse.
417 * \param root Selection element to which child expressions are added.
418 * \param[in] scanner Scanner data structure.
420 * For integer ranges, the sequence of numbers from the first to second value
421 * is stored, each as a separate value.
423 static void parse_values_varnum(const SelectionParserValueList& values,
424 gmx_ana_selparam_t* param,
425 const SelectionTreeElementPointer& root,
430 param->flags &= ~SPAR_DYNAMIC;
431 /* Compute number of values, considering also integer ranges. */
432 int valueCount = ssize(values);
433 if (param->val.type == INT_VALUE)
435 SelectionParserValueList::const_iterator value;
436 for (value = values.begin(); value != values.end(); ++value)
438 if (value->type == INT_VALUE && !value->hasExpressionValue())
440 valueCount += abs(value->u.i.i2 - value->u.i.i1);
445 /* Check that the value type is actually implemented */
446 if (param->val.type != INT_VALUE && param->val.type != REAL_VALUE
447 && param->val.type != STR_VALUE && param->val.type != POS_VALUE)
449 GMX_THROW(InternalError("Variable-count value type not implemented"));
452 /* Reserve appropriate amount of memory */
453 if (param->val.type == POS_VALUE)
455 gmx_ana_pos_reserve(param->val.u.p, valueCount, 0);
456 gmx_ana_indexmap_init(¶m->val.u.p->m, nullptr, nullptr, INDEX_UNKNOWN);
457 gmx_ana_pos_set_nr(param->val.u.p, valueCount);
461 _gmx_selvalue_reserve(¶m->val, valueCount);
463 /* Create a dummy child element to store the string values.
464 * This element is responsible for freeing the values, but carries no
466 if (param->val.type == STR_VALUE)
468 SelectionTreeElementPointer child(
469 new SelectionTreeElement(SEL_CONST, SelectionLocation::createEmpty()));
470 _gmx_selelem_set_vtype(child, STR_VALUE);
471 child->setName(param->name);
472 child->flags &= ~SEL_ALLOCVAL;
473 child->flags |= SEL_FLAGSSET | SEL_VARNUMVAL | SEL_ALLOCDATA;
474 child->v.nr = valueCount;
475 _gmx_selvalue_setstore(&child->v, param->val.u.s);
476 /* Because the child is not group-valued, the u union is not used
477 * for anything, so we can abuse it by storing the parameter value
478 * as place_child() expects, but this is really ugly... */
479 child->u.param = param;
480 place_child(root, child, param);
482 param->val.nr = valueCount;
485 SelectionParserValueList::const_iterator value;
486 for (value = values.begin(); value != values.end(); ++value)
488 GMX_RELEASE_ASSERT(value->type == param->val.type,
489 "Invalid value type (should have been caught earlier)");
490 if (value->hasExpressionValue())
492 std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
494 "Selection expressions are not supported in this "
495 "context when multiple values are provided");
496 InvalidInputError ex(message);
497 ex.prependContext(formatString("Invalid expression '%s'", text.c_str()));
500 switch (param->val.type)
503 if (value->u.i.i1 <= value->u.i.i2)
505 for (j = value->u.i.i1; j <= value->u.i.i2; ++j)
507 param->val.u.i[i++] = j;
512 for (j = value->u.i.i1; j >= value->u.i.i2; --j)
514 param->val.u.i[i++] = j;
519 if (value->u.r.r1 != value->u.r.r2)
521 std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
522 std::string message = formatString(
523 "Real range ('%s') is not supported in this context", text.c_str());
524 InvalidInputError ex(message);
527 param->val.u.r[i++] = value->u.r.r1;
529 case STR_VALUE: param->val.u.s[i++] = gmx_strdup(value->stringValue().c_str()); break;
530 case POS_VALUE: copy_rvec(value->u.x, param->val.u.p->x[i++]); break;
531 default: /* Should not be reached */
532 GMX_RELEASE_ASSERT(false, "Variable-count value type not implemented");
535 GMX_RELEASE_ASSERT(i == valueCount, "Inconsistent value count wrt. the actual value population");
538 *param->nvalptr = param->val.nr;
540 param->nvalptr = nullptr;
544 * Adds a new subexpression reference to a selection element.
546 * \param[in,out] root Root element to which the subexpression is added.
547 * \param[in] param Parameter for which this expression is a value.
548 * \param[in] expr Expression to add.
549 * \param[in] scanner Scanner data structure.
550 * \returns The created child element.
552 * Creates a new \ref SEL_SUBEXPRREF element and adds it into the child
554 * If \p expr is already a \ref SEL_SUBEXPRREF, it is used as it is.
555 * \ref SEL_ALLOCVAL is cleared for the returned element.
557 static SelectionTreeElementPointer add_child(const SelectionTreeElementPointer& root,
558 gmx_ana_selparam_t* param,
559 const SelectionTreeElementPointer& expr,
562 GMX_RELEASE_ASSERT(root->type == SEL_EXPRESSION || root->type == SEL_MODIFIER,
563 "Unsupported root element for selection parameter parser");
564 SelectionTreeElementPointer child;
565 /* Create a subexpression reference element if necessary */
566 if (expr->type == SEL_SUBEXPRREF)
572 // TODO: Initialize such that it includes the parameter.
573 child = std::make_shared<SelectionTreeElement>(SEL_SUBEXPRREF, expr->location());
574 _gmx_selelem_set_vtype(child, expr->v.type);
577 /* Setup the child element */
578 child->flags &= ~SEL_ALLOCVAL;
579 child->u.param = param;
580 if (child->v.type != param->val.type)
582 // TODO: It would be nice to say what is the expected type.
583 std::string text(_gmx_sel_lexer_get_text(scanner, expr->location()));
584 std::string message = formatString(
585 "Expression '%s' is not valid in this context "
586 "(produces the wrong type of values)",
588 GMX_THROW(InvalidInputError(message));
590 _gmx_selelem_update_flags(child);
591 if ((child->flags & SEL_DYNAMIC) && !(param->flags & SPAR_DYNAMIC))
593 std::string text(_gmx_sel_lexer_get_text(scanner, expr->location()));
594 std::string message = formatString(
595 "Expression '%s' is dynamic, which is not "
596 "valid in this context",
598 GMX_THROW(InvalidInputError(message));
600 if (!(child->flags & SEL_DYNAMIC))
602 param->flags &= ~SPAR_DYNAMIC;
604 /* Put the child element in the correct place */
605 place_child(root, child, param);
610 * Parses an expression value for a parameter that takes a variable number of values.
612 * \param[in] values List of values.
613 * \param param Parameter to parse.
614 * \param root Selection element to which child expressions are added.
615 * \param[in] scanner Scanner data structure.
617 static void parse_values_varnum_expr(const SelectionParserValueList& values,
618 gmx_ana_selparam_t* param,
619 const SelectionTreeElementPointer& root,
622 GMX_RELEASE_ASSERT(values.size() == 1 && values.front().hasExpressionValue(),
623 "Called with an invalid type of value");
625 SelectionTreeElementPointer child = add_child(root, param, values.front().expr, scanner);
627 /* Process single-valued expressions */
628 /* TODO: We should also handle SEL_SINGLEVAL expressions here */
629 if (child->v.type == POS_VALUE || child->v.type == GROUP_VALUE)
631 /* Set the value storage */
632 _gmx_selvalue_setstore(&child->v, param->val.u.ptr);
636 *param->nvalptr = param->val.nr;
638 param->nvalptr = nullptr;
642 if (!(child->flags & SEL_VARNUMVAL))
644 std::string text(_gmx_sel_lexer_get_text(scanner, values.front().location()));
645 std::string message = formatString("Expression '%s' is invalid in this context", text.c_str());
646 GMX_THROW(InvalidInputError(message));
649 child->flags |= SEL_ALLOCVAL;
651 *param->nvalptr = param->val.nr;
652 /* Rest of the initialization is done during compilation in
657 * Initializes the storage of an expression value.
659 * \param[in,out] sel Selection element that evaluates the value.
660 * \param[in] param Parameter to receive the value.
661 * \param[in] i The value of \p sel evaluates the value \p i for
663 * \param[in] scanner Scanner data structure.
665 * Initializes the data pointer of \p sel such that the result is stored
666 * as the value \p i of \p param.
667 * This function is used internally by parse_values_std().
669 static void set_expr_value_store(const SelectionTreeElementPointer& sel,
670 gmx_ana_selparam_t* param,
674 if (sel->v.type != GROUP_VALUE && !(sel->flags & SEL_SINGLEVAL))
676 std::string text(_gmx_sel_lexer_get_text(scanner, sel->location()));
677 std::string message = formatString("Expression '%s' is invalid in this context", text.c_str());
678 GMX_THROW(InvalidInputError(message));
682 case INT_VALUE: sel->v.u.i = ¶m->val.u.i[i]; break;
683 case REAL_VALUE: sel->v.u.r = ¶m->val.u.r[i]; break;
684 case STR_VALUE: sel->v.u.s = ¶m->val.u.s[i]; break;
685 case POS_VALUE: sel->v.u.p = ¶m->val.u.p[i]; break;
686 case GROUP_VALUE: sel->v.u.g = ¶m->val.u.g[i]; break;
687 default: /* Error */ GMX_THROW(InternalError("Invalid value type"));
694 * Parses the values for a parameter that takes a constant number of values.
696 * \param[in] values List of values.
697 * \param param Parameter to parse.
698 * \param root Selection element to which child expressions are added.
699 * \param[in] scanner Scanner data structure.
701 * For integer ranges, the sequence of numbers from the first to second value
702 * is stored, each as a separate value.
704 static void parse_values_std(const SelectionParserValueList& values,
705 gmx_ana_selparam_t* param,
706 const SelectionTreeElementPointer& root,
712 /* Handle atom-valued parameters */
713 if (param->flags & SPAR_ATOMVAL)
715 if (values.size() > 1)
718 InvalidInputError("Only a single value or a single expression is "
719 "supported in this context"));
721 if (values.front().hasExpressionValue())
723 SelectionTreeElementPointer child = add_child(root, param, values.front().expr, scanner);
724 child->flags |= SEL_ALLOCVAL;
725 if (child->v.type != GROUP_VALUE && (child->flags & SEL_ATOMVAL))
727 /* Rest of the initialization is done during compilation in
729 /* TODO: Positions are not correctly handled */
733 *param->nvalptr = -1;
737 param->flags &= ~SPAR_ATOMVAL;
743 param->nvalptr = nullptr;
744 if (param->val.type == INT_VALUE || param->val.type == REAL_VALUE || param->val.type == STR_VALUE)
746 _gmx_selvalue_reserve(¶m->val, 1);
748 set_expr_value_store(child, param, 0, scanner);
751 /* If we reach here, proceed with normal parameter handling */
753 if (param->val.type == INT_VALUE || param->val.type == REAL_VALUE || param->val.type == STR_VALUE)
755 _gmx_selvalue_reserve(¶m->val, 1);
757 param->flags &= ~SPAR_ATOMVAL;
758 param->flags &= ~SPAR_DYNAMIC;
763 SelectionParserValueList::const_iterator value;
764 for (value = values.begin(); value != values.end() && i < param->val.nr; ++value)
766 GMX_RELEASE_ASSERT(value->type == param->val.type,
767 "Invalid value type (should have been caught earlier)");
768 if (value->hasExpressionValue())
770 SelectionTreeElementPointer child = add_child(root, param, value->expr, scanner);
771 set_expr_value_store(child, param, i, scanner);
772 if (child->flags & SEL_DYNAMIC)
779 /* Value is not an expression */
785 if (value->u.i.i1 <= value->u.i.i2)
787 for (j = value->u.i.i1; j <= value->u.i.i2 && i < param->val.nr; ++j)
789 param->val.u.i[i++] = j;
791 bTooManyValues = (j != value->u.i.i2 + 1);
795 for (j = value->u.i.i1; j >= value->u.i.i2 && i < param->val.nr; --j)
797 param->val.u.i[i++] = j;
799 bTooManyValues = (j != value->u.i.i2 - 1);
803 std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
804 std::string message = formatString(
805 "Range ('%s') produces more values than is "
806 "accepted in this context",
808 GMX_THROW(InvalidInputError(message));
814 if (value->u.r.r1 != value->u.r.r2)
816 std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
817 std::string message = formatString(
818 "Real range ('%s') is not supported in this context", text.c_str());
819 GMX_THROW(InvalidInputError(message));
821 param->val.u.r[i] = value->u.r.r1;
823 case STR_VALUE: param->val.u.s[i] = gmx_strdup(value->stringValue().c_str()); break;
824 case POS_VALUE: gmx_ana_pos_init_const(¶m->val.u.p[i], value->u.x); break;
826 case GROUP_VALUE: GMX_THROW(InternalError("Invalid non-expression value type"));
831 if (value != values.end())
833 std::string message = formatString("Too many values provided, expected %d", param->val.nr);
834 GMX_THROW(InvalidInputError(message));
836 if (i < param->val.nr)
838 std::string message = formatString("Too few values provided, expected %d", param->val.nr);
839 GMX_THROW(InvalidInputError(message));
843 param->flags &= ~SPAR_DYNAMIC;
847 *param->nvalptr = param->val.nr;
849 param->nvalptr = nullptr;
853 * Parses the values for a boolean parameter.
855 * \param[in] name Name by which the parameter was given.
856 * \param[in] values List of values.
857 * \param param Parameter to parse.
858 * \param[in] scanner Scanner data structure.
860 static void parse_values_bool(const std::string& name,
861 const SelectionParserValueList& values,
862 gmx_ana_selparam_t* param,
865 GMX_UNUSED_VALUE(scanner);
866 GMX_ASSERT(param->val.type == NO_VALUE, "Boolean parser called for non-boolean parameter");
867 if (values.size() > 1 || (!values.empty() && values.front().type != INT_VALUE))
869 std::string message =
870 formatString("'%s' only accepts yes/no/on/off/0/1 (and empty) as a value", param->name);
871 GMX_THROW(InvalidInputError(message));
875 /* Check if the parameter name is given with a 'no' prefix */
876 if (name.length() > 2 && name[0] == 'n' && name[1] == 'o'
877 && name.compare(2, name.length() - 2, param->name) == 0)
881 if (bSetNo && !values.empty())
883 std::string message = formatString("'no%s' cannot be followed by any value", param->name);
884 GMX_THROW(InvalidInputError(message));
886 if (!values.empty() && values.front().u.i.i1 == 0)
891 *param->val.u.b = !bSetNo;
895 * Parses the values for an enumeration parameter.
897 * \param[in] values List of values.
898 * \param param Parameter to parse.
899 * \param[in] scanner Scanner data structure.
900 * \returns true if the values were parsed successfully, false otherwise.
902 static void parse_values_enum(const SelectionParserValueList& values, gmx_ana_selparam_t* param, void* scanner)
904 GMX_ASSERT(param->val.type == STR_VALUE, "Enum parser called for non-string parameter");
905 if (values.size() != 1)
907 GMX_THROW(InvalidInputError("Only a single string value is supported in this context"));
909 const SelectionParserValue& value = values.front();
910 GMX_RELEASE_ASSERT(value.type == param->val.type,
911 "Invalid value type (should have been caught earlier)");
912 if (value.hasExpressionValue())
914 std::string text(_gmx_sel_lexer_get_text(scanner, value.location()));
915 std::string message =
916 formatString("Expression ('%s') is not supported in this context", text.c_str());
917 GMX_THROW(InvalidInputError(message));
920 const std::string& svalue = value.stringValue();
923 while (param->val.u.s[i] != nullptr)
925 if (startsWith(param->val.u.s[i], svalue))
927 /* Check if there is a duplicate match */
930 std::string message = formatString("Value '%s' is ambiguous", svalue.c_str());
931 GMX_THROW(InvalidInputError(message));
939 std::string message = formatString("Value '%s' is not recognized", svalue.c_str());
940 GMX_THROW(InvalidInputError(message));
942 param->val.u.s[0] = param->val.u.s[match];
946 * Replaces constant expressions with their values.
948 * \param[in,out] values First element in the value list to process.
950 static void convert_const_values(SelectionParserValueList* values)
952 SelectionParserValueList::iterator value;
953 for (value = values->begin(); value != values->end(); ++value)
955 if (value->hasExpressionValue() && value->expr->v.type != GROUP_VALUE && value->expr->type == SEL_CONST)
957 SelectionTreeElementPointer expr = value->expr;
958 const SelectionLocation& location = value->location();
959 switch (expr->v.type)
962 *value = SelectionParserValue::createInteger(expr->v.u.i[0], location);
965 *value = SelectionParserValue::createReal(expr->v.u.r[0], location);
968 *value = SelectionParserValue::createString(expr->v.u.s[0], location);
971 *value = SelectionParserValue::createPosition(expr->v.u.p->x[0], location);
973 default: GMX_RELEASE_ASSERT(false, "Unsupported constant expression value type");
980 * \param pparams List of parameters from the selection parser.
981 * \param[in] nparam Number of parameters in \p params.
982 * \param params Array of parameters to parse.
983 * \param root Selection element to which child expressions are added.
984 * \param[in] scanner Scanner data structure.
986 * Initializes the \p params array based on the parameters in \p pparams.
987 * See the documentation of \c gmx_ana_selparam_t for different options
988 * available for parsing.
990 * The list \p pparams and any associated values are freed after the parameters
991 * have been processed, no matter is there was an error or not.
993 void _gmx_sel_parse_params(const gmx::SelectionParserParameterList& pparams,
995 gmx_ana_selparam_t* params,
996 const gmx::SelectionTreeElementPointer& root,
999 ExceptionInitializer errors("");
1000 /* Check that the value pointers of SPAR_VARNUM parameters are NULL and
1001 * that they are not NULL for other parameters */
1002 for (int i = 0; i < nparam; ++i)
1004 if (params[i].val.type != POS_VALUE && (params[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL)))
1006 GMX_RELEASE_ASSERT(params[i].val.u.ptr == nullptr,
1007 "value pointer is not NULL "
1008 "although it should be for SPAR_VARNUM "
1009 "and SPAR_ATOMVAL parameters");
1010 GMX_RELEASE_ASSERT(!((params[i].flags & SPAR_VARNUM) && (params[i].flags & SPAR_DYNAMIC))
1011 || params[i].nvalptr != nullptr,
1012 "nvalptr is NULL but both "
1013 "SPAR_VARNUM and SPAR_DYNAMIC are specified");
1017 GMX_RELEASE_ASSERT(params[i].val.u.ptr != nullptr, "value pointer is NULL");
1020 /* Parse the parameters */
1021 int nullParamIndex = 0;
1022 SelectionParserParameterList::const_iterator pparam;
1023 for (pparam = pparams.begin(); pparam != pparams.end(); ++pparam)
1027 // Always assigned afterwards, but clang does not see that.
1028 gmx_ana_selparam_t* oparam = nullptr;
1029 /* Find the parameter and make some checks */
1030 if (!pparam->name().empty())
1032 nullParamIndex = -1;
1033 oparam = gmx_ana_selparam_find(pparam->name().c_str(), nparam, params);
1034 GMX_RELEASE_ASSERT(oparam != nullptr, "Inconsistent selection parameter");
1036 else if (nullParamIndex >= 0)
1038 oparam = ¶ms[nullParamIndex];
1039 if (oparam->name != nullptr)
1041 std::string text(_gmx_sel_lexer_get_text(scanner, pparam->location()));
1042 std::string message = formatString("Unexpected '%s'", text.c_str());
1043 GMX_THROW(InvalidInputError(message));
1049 GMX_RELEASE_ASSERT(false,
1050 "All NULL parameters should appear in "
1051 "the beginning of the list");
1053 if (oparam->flags & SPAR_SET)
1055 std::string message =
1056 formatString("'%s' appears multiple times", pparam->name().c_str());
1057 GMX_THROW(InvalidInputError(message));
1059 oparam->flags |= SPAR_SET;
1060 if (oparam->val.type != NO_VALUE && pparam->values().empty())
1063 if (pparam->name().empty())
1065 text = root->name();
1069 text = _gmx_sel_lexer_get_text(scanner, pparam->location());
1071 std::string message =
1072 formatString("'%s' should be followed by a value/expression", text.c_str());
1073 GMX_THROW(InvalidInputError(message));
1075 /* Process the values for the parameter */
1076 convert_const_values(pparam->values_.get());
1077 convert_values(pparam->values_.get(), oparam->val.type, scanner);
1078 if (oparam->val.type == NO_VALUE)
1080 parse_values_bool(pparam->name(), pparam->values(), oparam, scanner);
1082 else if (oparam->flags & SPAR_RANGES)
1084 parse_values_range(pparam->values(), oparam, scanner);
1086 else if (oparam->flags & SPAR_VARNUM)
1088 if (pparam->values().size() == 1 && pparam->values().front().hasExpressionValue())
1090 parse_values_varnum_expr(pparam->values(), oparam, root, scanner);
1094 parse_values_varnum(pparam->values(), oparam, root, scanner);
1097 else if (oparam->flags & SPAR_ENUMVAL)
1099 parse_values_enum(pparam->values(), oparam, scanner);
1103 parse_values_std(pparam->values(), oparam, root, scanner);
1106 catch (UserInputError& ex)
1108 if (!pparam->name().empty())
1110 std::string text(_gmx_sel_lexer_get_text(scanner, pparam->location()));
1111 ex.prependContext(formatString("In '%s'", text.c_str()));
1113 errors.addCurrentExceptionAsNested();
1116 /* Check that all required parameters are present */
1117 for (int i = 0; i < nparam; ++i)
1119 if (!(params[i].flags & SPAR_OPTIONAL) && !(params[i].flags & SPAR_SET))
1121 std::string message;
1122 if (params[i].name == nullptr)
1124 message = formatString("'%s' should be followed by a value/expression",
1125 root->name().c_str());
1129 message = formatString("'%s' is missing", params[i].name);
1131 InvalidInputError ex(message);
1132 errors.addNested(ex);
1135 if (errors.hasNestedExceptions())
1137 GMX_THROW(InvalidInputError(errors));