Split lines with many copyright years
[alexxy/gromacs.git] / src / gromacs / selection / params.cpp
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2009,2010,2011,2012,2013 by the GROMACS development team.
5  * Copyright (c) 2014,2015,2016,2017,2018 by the GROMACS development team.
6  * Copyright (c) 2019,2020, by the GROMACS development team, led by
7  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
8  * and including many others, as listed in the AUTHORS file in the
9  * top-level source directory and at http://www.gromacs.org.
10  *
11  * GROMACS is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public License
13  * as published by the Free Software Foundation; either version 2.1
14  * of the License, or (at your option) any later version.
15  *
16  * GROMACS is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with GROMACS; if not, see
23  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
24  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
25  *
26  * If you want to redistribute modifications to GROMACS, please
27  * consider that scientific software is very special. Version
28  * control is crucial - bugs must be traceable. We will be happy to
29  * consider code for inclusion in the official distribution, but
30  * derived work must not be called official GROMACS. Details are found
31  * in the README & COPYING files - if they are missing, get the
32  * official version at http://www.gromacs.org.
33  *
34  * To help us fund GROMACS development, we humbly ask that you cite
35  * the research papers on the package. Check out http://www.gromacs.org.
36  */
37 /*! \internal \file
38  * \brief
39  * Implements functions in selparam.h.
40  *
41  * \author Teemu Murtola <teemu.murtola@gmail.com>
42  * \ingroup module_selection
43  */
44 #include "gmxpre.h"
45
46 #include <algorithm>
47 #include <array>
48 #include <string>
49
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"
58
59 #include "parsetree.h"
60 #include "position.h"
61 #include "scanner.h"
62 #include "selelem.h"
63 #include "selmethod.h"
64 #include "selparam.h"
65
66 using namespace gmx;
67
68 /*!
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.
74  *
75  * The comparison is case-sensitive.
76  */
77 gmx_ana_selparam_t* gmx_ana_selparam_find(const char* name, int nparam, gmx_ana_selparam_t* param)
78 {
79     int i;
80
81     if (nparam == 0)
82     {
83         return nullptr;
84     }
85     /* Find the first non-null parameter */
86     i = 0;
87     while (i < nparam && param[i].name == nullptr)
88     {
89         ++i;
90     }
91     /* Process the special case of a NULL parameter */
92     if (name == nullptr)
93     {
94         return (i == 0) ? nullptr : &param[i - 1];
95     }
96     for (; i < nparam; ++i)
97     {
98         if (!strcmp(param[i].name, name))
99         {
100             return &param[i];
101         }
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))
105         {
106             return &param[i];
107         }
108     }
109     return nullptr;
110 }
111
112 /*! \brief
113  * Does a type conversion on a SelectionParserValue.
114  *
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.
119  */
120 static void convert_value(SelectionParserValue* value, e_selvalue_t type, ExceptionInitializer* errors, void* scanner)
121 {
122     if (value->type == type || type == NO_VALUE)
123     {
124         return;
125     }
126     if (value->hasExpressionValue())
127     {
128         /* Conversion from atom selection to position using default
129          * reference positions. */
130         if (value->type == GROUP_VALUE && type == POS_VALUE)
131         {
132             try
133             {
134                 SelectionTreeElementPointer expr = _gmx_sel_init_position(value->expr, nullptr, scanner);
135                 *value                           = SelectionParserValue::createExpr(expr);
136             }
137             catch (UserInputError& ex)
138             {
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();
143             }
144             return;
145         }
146     }
147     else
148     {
149         /* Integers to floating point are easy */
150         if (value->type == INT_VALUE && type == REAL_VALUE)
151         {
152             *value = SelectionParserValue::createRealRange(value->u.i.i1, value->u.i.i2,
153                                                            value->location());
154             return;
155         }
156         /* Reals that are integer-valued can also be converted */
157         if (value->type == REAL_VALUE && type == INT_VALUE)
158         {
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))
163             {
164                 *value = SelectionParserValue::createIntegerRange(i1, i2, value->location());
165                 return;
166             }
167         }
168     }
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);
174 }
175
176 /*! \brief
177  * Does a type conversion on a list of values.
178  *
179  * \param[in,out] values   Values to convert.
180  * \param[in]     type     Type to convert to.
181  * \param[in]     scanner  Scanner data structure.
182  */
183 static void convert_values(SelectionParserValueList* values, e_selvalue_t type, void* scanner)
184 {
185     ExceptionInitializer               errors("");
186     SelectionParserValueList::iterator value;
187     for (value = values->begin(); value != values->end(); ++value)
188     {
189         convert_value(&*value, type, &errors, scanner);
190     }
191     if (errors.hasNestedExceptions())
192     {
193         GMX_THROW(InvalidInputError(errors));
194     }
195 }
196
197 /*! \brief
198  * Adds a child element for a parameter, keeping the parameter order.
199  *
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.
203  *
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.
206  */
207 static void place_child(const SelectionTreeElementPointer& root,
208                         const SelectionTreeElementPointer& child,
209                         gmx_ana_selparam_t*                param)
210 {
211     gmx_ana_selparam_t* ps;
212     int                 n;
213
214     ps = root->u.expr.method->param;
215     n  = param - ps;
216     /* Put the child element in the correct place */
217     if (!root->child || n < root->child->u.param - ps)
218     {
219         child->next = root->child;
220         root->child = child;
221     }
222     else
223     {
224         SelectionTreeElementPointer prev = root->child;
225         while (prev->next && prev->next->u.param - ps >= n)
226         {
227             prev = prev->next;
228         }
229         child->next = prev->next;
230         prev->next  = child;
231     }
232 }
233
234 /*! \brief
235  * Comparison function for sorting ranges.
236  *
237  * \param[in] a First range.
238  * \param[in] b Second range.
239  * \returns   return true if a < b
240  *
241  * The ranges are primarily sorted based on their starting point, and
242  * secondarily based on length (longer ranges come first).
243  */
244 template<typename T>
245 static bool cmp_range(const std::array<T, 2>& a, const std::array<T, 2>& b)
246 {
247     return a[0] < b[0] || (a[0] == b[0] && a[1] > b[1]);
248 }
249
250 /*! \brief
251  * Parses the values for a parameter that takes integer or real ranges.
252  *
253  * \param[in] values List of values.
254  * \param     param  Parameter to parse.
255  * \param[in] scanner Scanner data structure.
256  */
257 static void parse_values_range(const SelectionParserValueList& values, gmx_ana_selparam_t* param, void* scanner)
258 {
259     int i, j, n;
260
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)
268     {
269         snew(idata, values.size() * 2);
270         dataGuard.reset(idata);
271     }
272     else
273     {
274         snew(rdata, values.size() * 2);
275         dataGuard.reset(rdata);
276     }
277     i = 0;
278     SelectionParserValueList::const_iterator value;
279     for (value = values.begin(); value != values.end(); ++value)
280     {
281         GMX_RELEASE_ASSERT(value->type == param->val.type,
282                            "Invalid range value type (should have been caught earlier)");
283         if (value->hasExpressionValue())
284         {
285             std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
286             std::string message(
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()));
291             GMX_THROW(ex);
292         }
293         if (param->val.type == INT_VALUE)
294         {
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)
299             {
300                 idata[i - 2] = std::min(idata[i - 2], i1);
301                 idata[i - 1] = std::max(idata[i - 1], i2);
302             }
303             else
304             {
305                 idata[i++] = i1;
306                 idata[i++] = i2;
307             }
308         }
309         else
310         {
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])
315             {
316                 rdata[i - 2] = std::min(rdata[i - 2], r1);
317                 rdata[i - 1] = std::max(rdata[i - 1], r2);
318             }
319             else
320             {
321                 rdata[i++] = r1;
322                 rdata[i++] = r2;
323             }
324         }
325     }
326     n = i / 2;
327     /* Sort the ranges and merge consequent ones */
328     if (param->val.type == INT_VALUE)
329     {
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)
333         {
334             if (idata[j - 1] + 1 >= idata[i])
335             {
336                 if (idata[i + 1] > idata[j - 1])
337                 {
338                     idata[j - 1] = idata[i + 1];
339                 }
340             }
341             else
342             {
343                 idata[j]     = idata[i];
344                 idata[j + 1] = idata[i + 1];
345                 j += 2;
346             }
347         }
348     }
349     else
350     {
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)
354         {
355             if (rdata[j - 1] >= rdata[i])
356             {
357                 if (rdata[i + 1] > rdata[j - 1])
358                 {
359                     rdata[j - 1] = rdata[i + 1];
360                 }
361             }
362             else
363             {
364                 rdata[j]     = rdata[i];
365                 rdata[j + 1] = rdata[i + 1];
366                 j += 2;
367             }
368         }
369     }
370     n = j / 2;
371     /* Store the values */
372     if (param->flags & SPAR_VARNUM)
373     {
374         (void)dataGuard.release();
375         param->val.nr = n;
376         if (param->val.type == INT_VALUE)
377         {
378             srenew(idata, j);
379             _gmx_selvalue_setstore_alloc(&param->val, idata, j);
380         }
381         else
382         {
383             srenew(rdata, j);
384             _gmx_selvalue_setstore_alloc(&param->val, rdata, j);
385         }
386     }
387     else
388     {
389         if (n != param->val.nr)
390         {
391             GMX_ASSERT(n == 1, "Range parameters with a fixed count > 1 do not make sense");
392             GMX_THROW(
393                     InvalidInputError("Only one value or 'A to B' range is "
394                                       "supported in this context"));
395         }
396         if (param->val.type == INT_VALUE)
397         {
398             memcpy(param->val.u.i, idata, 2 * n * sizeof(int));
399         }
400         else
401         {
402             memcpy(param->val.u.r, rdata, 2 * n * sizeof(real));
403         }
404     }
405     if (param->nvalptr)
406     {
407         *param->nvalptr = param->val.nr;
408     }
409     param->nvalptr = nullptr;
410 }
411
412 /*! \brief
413  * Parses the values for a parameter that takes a variable number of values.
414  *
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.
419  *
420  * For integer ranges, the sequence of numbers from the first to second value
421  * is stored, each as a separate value.
422  */
423 static void parse_values_varnum(const SelectionParserValueList&    values,
424                                 gmx_ana_selparam_t*                param,
425                                 const SelectionTreeElementPointer& root,
426                                 void*                              scanner)
427 {
428     int i, j;
429
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)
434     {
435         SelectionParserValueList::const_iterator value;
436         for (value = values.begin(); value != values.end(); ++value)
437         {
438             if (value->type == INT_VALUE && !value->hasExpressionValue())
439             {
440                 valueCount += abs(value->u.i.i2 - value->u.i.i1);
441             }
442         }
443     }
444
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)
448     {
449         GMX_THROW(InternalError("Variable-count value type not implemented"));
450     }
451
452     /* Reserve appropriate amount of memory */
453     if (param->val.type == POS_VALUE)
454     {
455         gmx_ana_pos_reserve(param->val.u.p, valueCount, 0);
456         gmx_ana_indexmap_init(&param->val.u.p->m, nullptr, nullptr, INDEX_UNKNOWN);
457         gmx_ana_pos_set_nr(param->val.u.p, valueCount);
458     }
459     else
460     {
461         _gmx_selvalue_reserve(&param->val, valueCount);
462     }
463     /* Create a dummy child element to store the string values.
464      * This element is responsible for freeing the values, but carries no
465      * other function. */
466     if (param->val.type == STR_VALUE)
467     {
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);
481     }
482     param->val.nr = valueCount;
483
484     i = 0;
485     SelectionParserValueList::const_iterator value;
486     for (value = values.begin(); value != values.end(); ++value)
487     {
488         GMX_RELEASE_ASSERT(value->type == param->val.type,
489                            "Invalid value type (should have been caught earlier)");
490         if (value->hasExpressionValue())
491         {
492             std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
493             std::string message(
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()));
498             GMX_THROW(ex);
499         }
500         switch (param->val.type)
501         {
502             case INT_VALUE:
503                 if (value->u.i.i1 <= value->u.i.i2)
504                 {
505                     for (j = value->u.i.i1; j <= value->u.i.i2; ++j)
506                     {
507                         param->val.u.i[i++] = j;
508                     }
509                 }
510                 else
511                 {
512                     for (j = value->u.i.i1; j >= value->u.i.i2; --j)
513                     {
514                         param->val.u.i[i++] = j;
515                     }
516                 }
517                 break;
518             case REAL_VALUE:
519                 if (value->u.r.r1 != value->u.r.r2)
520                 {
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);
525                     GMX_THROW(ex);
526                 }
527                 param->val.u.r[i++] = value->u.r.r1;
528                 break;
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");
533         }
534     }
535     GMX_RELEASE_ASSERT(i == valueCount,
536                        "Inconsistent value count wrt. the actual value population");
537     if (param->nvalptr)
538     {
539         *param->nvalptr = param->val.nr;
540     }
541     param->nvalptr = nullptr;
542 }
543
544 /*! \brief
545  * Adds a new subexpression reference to a selection element.
546  *
547  * \param[in,out] root  Root element to which the subexpression is added.
548  * \param[in]     param Parameter for which this expression is a value.
549  * \param[in]     expr  Expression to add.
550  * \param[in]     scanner Scanner data structure.
551  * \returns       The created child element.
552  *
553  * Creates a new \ref SEL_SUBEXPRREF element and adds it into the child
554  * list of \p root.
555  * If \p expr is already a \ref SEL_SUBEXPRREF, it is used as it is.
556  * \ref SEL_ALLOCVAL is cleared for the returned element.
557  */
558 static SelectionTreeElementPointer add_child(const SelectionTreeElementPointer& root,
559                                              gmx_ana_selparam_t*                param,
560                                              const SelectionTreeElementPointer& expr,
561                                              void*                              scanner)
562 {
563     GMX_RELEASE_ASSERT(root->type == SEL_EXPRESSION || root->type == SEL_MODIFIER,
564                        "Unsupported root element for selection parameter parser");
565     SelectionTreeElementPointer child;
566     /* Create a subexpression reference element if necessary */
567     if (expr->type == SEL_SUBEXPRREF)
568     {
569         child = expr;
570     }
571     else
572     {
573         // TODO: Initialize such that it includes the parameter.
574         child = std::make_shared<SelectionTreeElement>(SEL_SUBEXPRREF, expr->location());
575         _gmx_selelem_set_vtype(child, expr->v.type);
576         child->child = expr;
577     }
578     /* Setup the child element */
579     child->flags &= ~SEL_ALLOCVAL;
580     child->u.param = param;
581     if (child->v.type != param->val.type)
582     {
583         // TODO: It would be nice to say what is the expected type.
584         std::string text(_gmx_sel_lexer_get_text(scanner, expr->location()));
585         std::string message = formatString(
586                 "Expression '%s' is not valid in this context "
587                 "(produces the wrong type of values)",
588                 text.c_str());
589         GMX_THROW(InvalidInputError(message));
590     }
591     _gmx_selelem_update_flags(child);
592     if ((child->flags & SEL_DYNAMIC) && !(param->flags & SPAR_DYNAMIC))
593     {
594         std::string text(_gmx_sel_lexer_get_text(scanner, expr->location()));
595         std::string message = formatString(
596                 "Expression '%s' is dynamic, which is not "
597                 "valid in this context",
598                 text.c_str());
599         GMX_THROW(InvalidInputError(message));
600     }
601     if (!(child->flags & SEL_DYNAMIC))
602     {
603         param->flags &= ~SPAR_DYNAMIC;
604     }
605     /* Put the child element in the correct place */
606     place_child(root, child, param);
607     return child;
608 }
609
610 /*! \brief
611  * Parses an expression value for a parameter that takes a variable number of values.
612  *
613  * \param[in] values List of values.
614  * \param     param  Parameter to parse.
615  * \param     root   Selection element to which child expressions are added.
616  * \param[in] scanner Scanner data structure.
617  */
618 static void parse_values_varnum_expr(const SelectionParserValueList&    values,
619                                      gmx_ana_selparam_t*                param,
620                                      const SelectionTreeElementPointer& root,
621                                      void*                              scanner)
622 {
623     GMX_RELEASE_ASSERT(values.size() == 1 && values.front().hasExpressionValue(),
624                        "Called with an invalid type of value");
625
626     SelectionTreeElementPointer child = add_child(root, param, values.front().expr, scanner);
627
628     /* Process single-valued expressions */
629     /* TODO: We should also handle SEL_SINGLEVAL expressions here */
630     if (child->v.type == POS_VALUE || child->v.type == GROUP_VALUE)
631     {
632         /* Set the value storage */
633         _gmx_selvalue_setstore(&child->v, param->val.u.ptr);
634         param->val.nr = 1;
635         if (param->nvalptr)
636         {
637             *param->nvalptr = param->val.nr;
638         }
639         param->nvalptr = nullptr;
640         return;
641     }
642
643     if (!(child->flags & SEL_VARNUMVAL))
644     {
645         std::string text(_gmx_sel_lexer_get_text(scanner, values.front().location()));
646         std::string message = formatString("Expression '%s' is invalid in this context", text.c_str());
647         GMX_THROW(InvalidInputError(message));
648     }
649
650     child->flags |= SEL_ALLOCVAL;
651     param->val.nr   = -1;
652     *param->nvalptr = param->val.nr;
653     /* Rest of the initialization is done during compilation in
654      * init_method(). */
655 }
656
657 /*! \brief
658  * Initializes the storage of an expression value.
659  *
660  * \param[in,out] sel   Selection element that evaluates the value.
661  * \param[in]     param Parameter to receive the value.
662  * \param[in]     i     The value of \p sel evaluates the value \p i for
663  *   \p param.
664  * \param[in]     scanner Scanner data structure.
665  *
666  * Initializes the data pointer of \p sel such that the result is stored
667  * as the value \p i of \p param.
668  * This function is used internally by parse_values_std().
669  */
670 static void set_expr_value_store(const SelectionTreeElementPointer& sel,
671                                  gmx_ana_selparam_t*                param,
672                                  int                                i,
673                                  void*                              scanner)
674 {
675     if (sel->v.type != GROUP_VALUE && !(sel->flags & SEL_SINGLEVAL))
676     {
677         std::string text(_gmx_sel_lexer_get_text(scanner, sel->location()));
678         std::string message = formatString("Expression '%s' is invalid in this context", text.c_str());
679         GMX_THROW(InvalidInputError(message));
680     }
681     switch (sel->v.type)
682     {
683         case INT_VALUE: sel->v.u.i = &param->val.u.i[i]; break;
684         case REAL_VALUE: sel->v.u.r = &param->val.u.r[i]; break;
685         case STR_VALUE: sel->v.u.s = &param->val.u.s[i]; break;
686         case POS_VALUE: sel->v.u.p = &param->val.u.p[i]; break;
687         case GROUP_VALUE: sel->v.u.g = &param->val.u.g[i]; break;
688         default: /* Error */ GMX_THROW(InternalError("Invalid value type"));
689     }
690     sel->v.nr     = 1;
691     sel->v.nalloc = -1;
692 }
693
694 /*! \brief
695  * Parses the values for a parameter that takes a constant number of values.
696  *
697  * \param[in] values List of values.
698  * \param     param  Parameter to parse.
699  * \param     root   Selection element to which child expressions are added.
700  * \param[in] scanner Scanner data structure.
701  *
702  * For integer ranges, the sequence of numbers from the first to second value
703  * is stored, each as a separate value.
704  */
705 static void parse_values_std(const SelectionParserValueList&    values,
706                              gmx_ana_selparam_t*                param,
707                              const SelectionTreeElementPointer& root,
708                              void*                              scanner)
709 {
710     int  i, j;
711     bool bDynamic;
712
713     /* Handle atom-valued parameters */
714     if (param->flags & SPAR_ATOMVAL)
715     {
716         if (values.size() > 1)
717         {
718             GMX_THROW(
719                     InvalidInputError("Only a single value or a single expression is "
720                                       "supported in this context"));
721         }
722         if (values.front().hasExpressionValue())
723         {
724             SelectionTreeElementPointer child = add_child(root, param, values.front().expr, scanner);
725             child->flags |= SEL_ALLOCVAL;
726             if (child->v.type != GROUP_VALUE && (child->flags & SEL_ATOMVAL))
727             {
728                 /* Rest of the initialization is done during compilation in
729                  * init_method(). */
730                 /* TODO: Positions are not correctly handled */
731                 param->val.nr = -1;
732                 if (param->nvalptr)
733                 {
734                     *param->nvalptr = -1;
735                 }
736                 return;
737             }
738             param->flags &= ~SPAR_ATOMVAL;
739             param->val.nr = 1;
740             if (param->nvalptr)
741             {
742                 *param->nvalptr = 1;
743             }
744             param->nvalptr = nullptr;
745             if (param->val.type == INT_VALUE || param->val.type == REAL_VALUE || param->val.type == STR_VALUE)
746             {
747                 _gmx_selvalue_reserve(&param->val, 1);
748             }
749             set_expr_value_store(child, param, 0, scanner);
750             return;
751         }
752         /* If we reach here, proceed with normal parameter handling */
753         param->val.nr = 1;
754         if (param->val.type == INT_VALUE || param->val.type == REAL_VALUE || param->val.type == STR_VALUE)
755         {
756             _gmx_selvalue_reserve(&param->val, 1);
757         }
758         param->flags &= ~SPAR_ATOMVAL;
759         param->flags &= ~SPAR_DYNAMIC;
760     }
761
762     i        = 0;
763     bDynamic = false;
764     SelectionParserValueList::const_iterator value;
765     for (value = values.begin(); value != values.end() && i < param->val.nr; ++value)
766     {
767         GMX_RELEASE_ASSERT(value->type == param->val.type,
768                            "Invalid value type (should have been caught earlier)");
769         if (value->hasExpressionValue())
770         {
771             SelectionTreeElementPointer child = add_child(root, param, value->expr, scanner);
772             set_expr_value_store(child, param, i, scanner);
773             if (child->flags & SEL_DYNAMIC)
774             {
775                 bDynamic = true;
776             }
777         }
778         else
779         {
780             /* Value is not an expression */
781             switch (value->type)
782             {
783                 case INT_VALUE:
784                 {
785                     bool bTooManyValues;
786                     if (value->u.i.i1 <= value->u.i.i2)
787                     {
788                         for (j = value->u.i.i1; j <= value->u.i.i2 && i < param->val.nr; ++j)
789                         {
790                             param->val.u.i[i++] = j;
791                         }
792                         bTooManyValues = (j != value->u.i.i2 + 1);
793                     }
794                     else
795                     {
796                         for (j = value->u.i.i1; j >= value->u.i.i2 && i < param->val.nr; --j)
797                         {
798                             param->val.u.i[i++] = j;
799                         }
800                         bTooManyValues = (j != value->u.i.i2 - 1);
801                     }
802                     if (bTooManyValues)
803                     {
804                         std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
805                         std::string message = formatString(
806                                 "Range ('%s') produces more values than is "
807                                 "accepted in this context",
808                                 text.c_str());
809                         GMX_THROW(InvalidInputError(message));
810                     }
811                     --i;
812                     break;
813                 }
814                 case REAL_VALUE:
815                     if (value->u.r.r1 != value->u.r.r2)
816                     {
817                         std::string text(_gmx_sel_lexer_get_text(scanner, value->location()));
818                         std::string message = formatString(
819                                 "Real range ('%s') is not supported in this context", text.c_str());
820                         GMX_THROW(InvalidInputError(message));
821                     }
822                     param->val.u.r[i] = value->u.r.r1;
823                     break;
824                 case STR_VALUE: param->val.u.s[i] = gmx_strdup(value->stringValue().c_str()); break;
825                 case POS_VALUE: gmx_ana_pos_init_const(&param->val.u.p[i], value->u.x); break;
826                 case NO_VALUE:
827                 case GROUP_VALUE: GMX_THROW(InternalError("Invalid non-expression value type"));
828             }
829         }
830         ++i;
831     }
832     if (value != values.end())
833     {
834         std::string message = formatString("Too many values provided, expected %d", param->val.nr);
835         GMX_THROW(InvalidInputError(message));
836     }
837     if (i < param->val.nr)
838     {
839         std::string message = formatString("Too few values provided, expected %d", param->val.nr);
840         GMX_THROW(InvalidInputError(message));
841     }
842     if (!bDynamic)
843     {
844         param->flags &= ~SPAR_DYNAMIC;
845     }
846     if (param->nvalptr)
847     {
848         *param->nvalptr = param->val.nr;
849     }
850     param->nvalptr = nullptr;
851 }
852
853 /*! \brief
854  * Parses the values for a boolean parameter.
855  *
856  * \param[in] name   Name by which the parameter was given.
857  * \param[in] values List of values.
858  * \param     param  Parameter to parse.
859  * \param[in] scanner Scanner data structure.
860  */
861 static void parse_values_bool(const std::string&              name,
862                               const SelectionParserValueList& values,
863                               gmx_ana_selparam_t*             param,
864                               void*                           scanner)
865 {
866     GMX_UNUSED_VALUE(scanner);
867     GMX_ASSERT(param->val.type == NO_VALUE, "Boolean parser called for non-boolean parameter");
868     if (values.size() > 1 || (!values.empty() && values.front().type != INT_VALUE))
869     {
870         std::string message =
871                 formatString("'%s' only accepts yes/no/on/off/0/1 (and empty) as a value", param->name);
872         GMX_THROW(InvalidInputError(message));
873     }
874
875     bool bSetNo = false;
876     /* Check if the parameter name is given with a 'no' prefix */
877     if (name.length() > 2 && name[0] == 'n' && name[1] == 'o'
878         && name.compare(2, name.length() - 2, param->name) == 0)
879     {
880         bSetNo = true;
881     }
882     if (bSetNo && !values.empty())
883     {
884         std::string message = formatString("'no%s' cannot be followed by any value", param->name);
885         GMX_THROW(InvalidInputError(message));
886     }
887     if (!values.empty() && values.front().u.i.i1 == 0)
888     {
889         bSetNo = true;
890     }
891
892     *param->val.u.b = !bSetNo;
893 }
894
895 /*! \brief
896  * Parses the values for an enumeration parameter.
897  *
898  * \param[in] values List of values.
899  * \param     param  Parameter to parse.
900  * \param[in] scanner Scanner data structure.
901  * \returns   true if the values were parsed successfully, false otherwise.
902  */
903 static void parse_values_enum(const SelectionParserValueList& values, gmx_ana_selparam_t* param, void* scanner)
904 {
905     GMX_ASSERT(param->val.type == STR_VALUE, "Enum parser called for non-string parameter");
906     if (values.size() != 1)
907     {
908         GMX_THROW(InvalidInputError("Only a single string value is supported in this context"));
909     }
910     const SelectionParserValue& value = values.front();
911     GMX_RELEASE_ASSERT(value.type == param->val.type,
912                        "Invalid value type (should have been caught earlier)");
913     if (value.hasExpressionValue())
914     {
915         std::string text(_gmx_sel_lexer_get_text(scanner, value.location()));
916         std::string message =
917                 formatString("Expression ('%s') is not supported in this context", text.c_str());
918         GMX_THROW(InvalidInputError(message));
919     }
920
921     const std::string& svalue = value.stringValue();
922     int                i      = 1;
923     int                match  = 0;
924     while (param->val.u.s[i] != nullptr)
925     {
926         if (startsWith(param->val.u.s[i], svalue))
927         {
928             /* Check if there is a duplicate match */
929             if (match > 0)
930             {
931                 std::string message = formatString("Value '%s' is ambiguous", svalue.c_str());
932                 GMX_THROW(InvalidInputError(message));
933             }
934             match = i;
935         }
936         ++i;
937     }
938     if (match == 0)
939     {
940         std::string message = formatString("Value '%s' is not recognized", svalue.c_str());
941         GMX_THROW(InvalidInputError(message));
942     }
943     param->val.u.s[0] = param->val.u.s[match];
944 }
945
946 /*! \brief
947  * Replaces constant expressions with their values.
948  *
949  * \param[in,out] values First element in the value list to process.
950  */
951 static void convert_const_values(SelectionParserValueList* values)
952 {
953     SelectionParserValueList::iterator value;
954     for (value = values->begin(); value != values->end(); ++value)
955     {
956         if (value->hasExpressionValue() && value->expr->v.type != GROUP_VALUE && value->expr->type == SEL_CONST)
957         {
958             SelectionTreeElementPointer expr     = value->expr;
959             const SelectionLocation&    location = value->location();
960             switch (expr->v.type)
961             {
962                 case INT_VALUE:
963                     *value = SelectionParserValue::createInteger(expr->v.u.i[0], location);
964                     break;
965                 case REAL_VALUE:
966                     *value = SelectionParserValue::createReal(expr->v.u.r[0], location);
967                     break;
968                 case STR_VALUE:
969                     *value = SelectionParserValue::createString(expr->v.u.s[0], location);
970                     break;
971                 case POS_VALUE:
972                     *value = SelectionParserValue::createPosition(expr->v.u.p->x[0], location);
973                     break;
974                 default: GMX_RELEASE_ASSERT(false, "Unsupported constant expression value type");
975             }
976         }
977     }
978 }
979
980 /*!
981  * \param     pparams List of parameters from the selection parser.
982  * \param[in] nparam  Number of parameters in \p params.
983  * \param     params  Array of parameters to parse.
984  * \param     root    Selection element to which child expressions are added.
985  * \param[in] scanner Scanner data structure.
986  *
987  * Initializes the \p params array based on the parameters in \p pparams.
988  * See the documentation of \c gmx_ana_selparam_t for different options
989  * available for parsing.
990  *
991  * The list \p pparams and any associated values are freed after the parameters
992  * have been processed, no matter is there was an error or not.
993  */
994 void _gmx_sel_parse_params(const gmx::SelectionParserParameterList& pparams,
995                            int                                      nparam,
996                            gmx_ana_selparam_t*                      params,
997                            const gmx::SelectionTreeElementPointer&  root,
998                            void*                                    scanner)
999 {
1000     ExceptionInitializer errors("");
1001     /* Check that the value pointers of SPAR_VARNUM parameters are NULL and
1002      * that they are not NULL for other parameters */
1003     for (int i = 0; i < nparam; ++i)
1004     {
1005         if (params[i].val.type != POS_VALUE && (params[i].flags & (SPAR_VARNUM | SPAR_ATOMVAL)))
1006         {
1007             GMX_RELEASE_ASSERT(params[i].val.u.ptr == nullptr,
1008                                "value pointer is not NULL "
1009                                "although it should be for SPAR_VARNUM "
1010                                "and SPAR_ATOMVAL parameters");
1011             GMX_RELEASE_ASSERT(!((params[i].flags & SPAR_VARNUM) && (params[i].flags & SPAR_DYNAMIC))
1012                                        || params[i].nvalptr != nullptr,
1013                                "nvalptr is NULL but both "
1014                                "SPAR_VARNUM and SPAR_DYNAMIC are specified");
1015         }
1016         else
1017         {
1018             GMX_RELEASE_ASSERT(params[i].val.u.ptr != nullptr, "value pointer is NULL");
1019         }
1020     }
1021     /* Parse the parameters */
1022     int                                          nullParamIndex = 0;
1023     SelectionParserParameterList::const_iterator pparam;
1024     for (pparam = pparams.begin(); pparam != pparams.end(); ++pparam)
1025     {
1026         try
1027         {
1028             // Always assigned afterwards, but clang does not see that.
1029             gmx_ana_selparam_t* oparam = nullptr;
1030             /* Find the parameter and make some checks */
1031             if (!pparam->name().empty())
1032             {
1033                 nullParamIndex = -1;
1034                 oparam         = gmx_ana_selparam_find(pparam->name().c_str(), nparam, params);
1035                 GMX_RELEASE_ASSERT(oparam != nullptr, "Inconsistent selection parameter");
1036             }
1037             else if (nullParamIndex >= 0)
1038             {
1039                 oparam = &params[nullParamIndex];
1040                 if (oparam->name != nullptr)
1041                 {
1042                     std::string text(_gmx_sel_lexer_get_text(scanner, pparam->location()));
1043                     std::string message = formatString("Unexpected '%s'", text.c_str());
1044                     GMX_THROW(InvalidInputError(message));
1045                 }
1046                 ++nullParamIndex;
1047             }
1048             else
1049             {
1050                 GMX_RELEASE_ASSERT(false,
1051                                    "All NULL parameters should appear in "
1052                                    "the beginning of the list");
1053             }
1054             if (oparam->flags & SPAR_SET)
1055             {
1056                 std::string message =
1057                         formatString("'%s' appears multiple times", pparam->name().c_str());
1058                 GMX_THROW(InvalidInputError(message));
1059             }
1060             oparam->flags |= SPAR_SET;
1061             if (oparam->val.type != NO_VALUE && pparam->values().empty())
1062             {
1063                 std::string text;
1064                 if (pparam->name().empty())
1065                 {
1066                     text = root->name();
1067                 }
1068                 else
1069                 {
1070                     text = _gmx_sel_lexer_get_text(scanner, pparam->location());
1071                 }
1072                 std::string message =
1073                         formatString("'%s' should be followed by a value/expression", text.c_str());
1074                 GMX_THROW(InvalidInputError(message));
1075             }
1076             /* Process the values for the parameter */
1077             convert_const_values(pparam->values_.get());
1078             convert_values(pparam->values_.get(), oparam->val.type, scanner);
1079             if (oparam->val.type == NO_VALUE)
1080             {
1081                 parse_values_bool(pparam->name(), pparam->values(), oparam, scanner);
1082             }
1083             else if (oparam->flags & SPAR_RANGES)
1084             {
1085                 parse_values_range(pparam->values(), oparam, scanner);
1086             }
1087             else if (oparam->flags & SPAR_VARNUM)
1088             {
1089                 if (pparam->values().size() == 1 && pparam->values().front().hasExpressionValue())
1090                 {
1091                     parse_values_varnum_expr(pparam->values(), oparam, root, scanner);
1092                 }
1093                 else
1094                 {
1095                     parse_values_varnum(pparam->values(), oparam, root, scanner);
1096                 }
1097             }
1098             else if (oparam->flags & SPAR_ENUMVAL)
1099             {
1100                 parse_values_enum(pparam->values(), oparam, scanner);
1101             }
1102             else
1103             {
1104                 parse_values_std(pparam->values(), oparam, root, scanner);
1105             }
1106         }
1107         catch (UserInputError& ex)
1108         {
1109             if (!pparam->name().empty())
1110             {
1111                 std::string text(_gmx_sel_lexer_get_text(scanner, pparam->location()));
1112                 ex.prependContext(formatString("In '%s'", text.c_str()));
1113             }
1114             errors.addCurrentExceptionAsNested();
1115         }
1116     }
1117     /* Check that all required parameters are present */
1118     for (int i = 0; i < nparam; ++i)
1119     {
1120         if (!(params[i].flags & SPAR_OPTIONAL) && !(params[i].flags & SPAR_SET))
1121         {
1122             std::string message;
1123             if (params[i].name == nullptr)
1124             {
1125                 message = formatString("'%s' should be followed by a value/expression",
1126                                        root->name().c_str());
1127             }
1128             else
1129             {
1130                 message = formatString("'%s' is missing", params[i].name);
1131             }
1132             InvalidInputError ex(message);
1133             errors.addNested(ex);
1134         }
1135     }
1136     if (errors.hasNestedExceptions())
1137     {
1138         GMX_THROW(InvalidInputError(errors));
1139     }
1140 }