Sort all includes in src/gromacs
[alexxy/gromacs.git] / src / gromacs / selection / parsetree.cpp
index 1a01d5da8864356ab02e4f1e67211146400fd88b..14d5d27dbdaddb8dc4d518fd3bbd6f7130c6ad4a 100644 (file)
@@ -1,38 +1,42 @@
 /*
+ * This file is part of the GROMACS molecular simulation package.
  *
- *                This source code is part of
+ * Copyright (c) 2009,2010,2011,2012,2013,2014, by the GROMACS development team, led by
+ * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
+ * and including many others, as listed in the AUTHORS file in the
+ * top-level source directory and at http://www.gromacs.org.
  *
- *                 G   R   O   M   A   C   S
+ * GROMACS is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public License
+ * as published by the Free Software Foundation; either version 2.1
+ * of the License, or (at your option) any later version.
  *
- *          GROningen MAchine for Chemical Simulations
+ * GROMACS is distributed in the hope that it will be useful,
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ * Lesser General Public License for more details.
  *
- * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
- * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
- * Copyright (c) 2001-2009, The GROMACS development team,
- * check out http://www.gromacs.org for more information.
-
- * This program is free software; you can redistribute it and/or
- * modify it under the terms of the GNU General Public License
- * as published by the Free Software Foundation; either version 2
- * of the License, or (at your option) any later version.
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with GROMACS; if not, see
+ * http://www.gnu.org/licenses, or write to the Free Software Foundation,
+ * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
  *
- * If you want to redistribute modifications, please consider that
- * scientific software is very special. Version control is crucial -
- * bugs must be traceable. We will be happy to consider code for
- * inclusion in the official distribution, but derived work must not
- * be called official GROMACS. Details are found in the README & COPYING
- * files - if they are missing, get the official version at www.gromacs.org.
+ * If you want to redistribute modifications to GROMACS, please
+ * consider that scientific software is very special. Version
+ * control is crucial - bugs must be traceable. We will be happy to
+ * consider code for inclusion in the official distribution, but
+ * derived work must not be called official GROMACS. Details are found
+ * in the README & COPYING files - if they are missing, get the
+ * official version at http://www.gromacs.org.
  *
  * To help us fund GROMACS development, we humbly ask that you cite
- * the papers on the package - you can find them in the top README file.
- *
- * For more info, check our website at http://www.gromacs.org
+ * the research papers on the package. Check out http://www.gromacs.org.
  */
 /*! \internal \file
  * \brief
  * Implements functions in parsetree.h.
  *
- * \author Teemu Murtola <teemu.murtola@cbr.su.se>
+ * \author Teemu Murtola <teemu.murtola@gmail.com>
  * \ingroup module_selection
  */
 /*! \internal
  * Each element has exactly two children (one for unary negation elements),
  * which are in the order given in the input.
  */
-#include <stdio.h>
+#include "gmxpre.h"
+
+#include "parsetree.h"
+
 #include <stdarg.h>
+#include <stdio.h>
 
 #include <boost/exception_ptr.hpp>
 #include <boost/shared_ptr.hpp>
 
-#include "gromacs/legacyheaders/futil.h"
-#include "gromacs/legacyheaders/smalloc.h"
-#include "gromacs/legacyheaders/string2.h"
-
-#include "gromacs/onlinehelp/helpmanager.h"
-#include "gromacs/onlinehelp/helpwritercontext.h"
-#include "gromacs/selection/poscalc.h"
 #include "gromacs/selection/selection.h"
-#include "gromacs/selection/selmethod.h"
+#include "gromacs/utility/cstringutil.h"
 #include "gromacs/utility/exceptions.h"
 #include "gromacs/utility/file.h"
 #include "gromacs/utility/messagestringcollector.h"
+#include "gromacs/utility/smalloc.h"
+#include "gromacs/utility/stringutil.h"
 
 #include "keywords.h"
-#include "parsetree.h"
+#include "poscalc.h"
+#include "scanner.h"
 #include "selectioncollection-impl.h"
 #include "selelem.h"
-#include "selhelp.h"
+#include "selmethod.h"
 #include "symrec.h"
 
-#include "scanner.h"
-
 using gmx::SelectionParserValue;
 using gmx::SelectionParserValueList;
 using gmx::SelectionParserValueListPointer;
@@ -258,17 +260,29 @@ _gmx_selparser_error(yyscan_t scanner, const char *fmt, ...)
 {
     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
     // FIXME: Use an arbitrary length buffer.
-    char buf[1024];
+    char    buf[1024];
     va_list ap;
     va_start(ap, fmt);
-    vsprintf(buf, fmt, ap);
+    vsnprintf(buf, 1024, fmt, ap);
     va_end(ap);
     errors->append(buf);
 }
 
 bool
-_gmx_selparser_handle_exception(yyscan_t scanner, const std::exception &/*ex*/)
+_gmx_selparser_handle_exception(yyscan_t scanner, const std::exception &ex)
 {
+    if (dynamic_cast<const gmx::UserInputError *>(&ex) != NULL)
+    {
+        // TODO: Consider whether also the non-interactive parser should
+        // postpone the exception such that the whole selection can be added as
+        // context.
+        if (_gmx_sel_is_lexer_interactive(scanner))
+        {
+            // TODO: Handle exceptions that printing the message may produce.
+            gmx::formatExceptionMessageToFile(stderr, ex);
+            return true;
+        }
+    }
     _gmx_sel_lexer_set_exception(scanner, boost::current_exception());
     return false;
 }
@@ -298,11 +312,11 @@ SelectionParserValue::SelectionParserValue(
  */
 
 SelectionParserParameter::SelectionParserParameter(
-        const char *name,
+        const char                     *name,
         SelectionParserValueListPointer values)
     : name_(name != NULL ? name : ""),
       values_(values ? move(values)
-                     : SelectionParserValueListPointer(new SelectionParserValueList))
+              : SelectionParserValueListPointer(new SelectionParserValueList))
 {
 }
 
@@ -310,8 +324,6 @@ SelectionParserParameter::SelectionParserParameter(
 
 /*!
  * \param[in,out] sel  Root of the selection element tree to initialize.
- * \param[in]     scanner Scanner data structure.
- * \returns       0 on success, an error code on error.
  *
  * Propagates the \ref SEL_DYNAMIC flag from the children of \p sel to \p sel
  * (if any child of \p sel is dynamic, \p sel is also marked as such).
@@ -328,10 +340,9 @@ SelectionParserParameter::SelectionParserParameter(
  * operation does not descend beyond such elements.
  */
 void
-_gmx_selelem_update_flags(const SelectionTreeElementPointer &sel,
-                          yyscan_t scanner)
+_gmx_selelem_update_flags(const gmx::SelectionTreeElementPointer &sel)
 {
-    bool                bUseChildType=false;
+    bool                bUseChildType = false;
     bool                bOnlySingleChildren;
 
     /* Return if the flags have already been set */
@@ -344,7 +355,7 @@ _gmx_selelem_update_flags(const SelectionTreeElementPointer &sel,
     {
         case SEL_CONST:
         case SEL_GROUPREF:
-            sel->flags |= SEL_SINGLEVAL;
+            sel->flags   |= SEL_SINGLEVAL;
             bUseChildType = false;
             break;
 
@@ -369,7 +380,7 @@ _gmx_selelem_update_flags(const SelectionTreeElementPointer &sel,
             break;
 
         case SEL_ARITHMETIC:
-            sel->flags |= SEL_ATOMVAL;
+            sel->flags   |= SEL_ATOMVAL;
             bUseChildType = false;
             break;
 
@@ -397,18 +408,18 @@ _gmx_selelem_update_flags(const SelectionTreeElementPointer &sel,
     while (child)
     {
         /* Update the child */
-        _gmx_selelem_update_flags(child, scanner);
-        /* Propagate the dynamic flag */
-        sel->flags |= (child->flags & SEL_DYNAMIC);
+        _gmx_selelem_update_flags(child);
+        /* Propagate the dynamic and unsorted flags */
+        sel->flags |= (child->flags & (SEL_DYNAMIC | SEL_UNSORTED));
         /* Propagate the type flag if necessary and check for problems */
         if (bUseChildType)
         {
             if ((sel->flags & SEL_VALTYPEMASK)
                 && !(sel->flags & child->flags & SEL_VALTYPEMASK))
             {
-                _gmx_selparser_error(scanner, "invalid combination of selection expressions");
-                // FIXME: Use an exception.
-                return;
+                // TODO: Recollect when this is triggered, and whether the type
+                // is appropriate.
+                GMX_THROW(gmx::InvalidInputError("Invalid combination of selection expressions"));
             }
             sel->flags |= (child->flags & SEL_VALTYPEMASK);
         }
@@ -445,8 +456,8 @@ _gmx_selelem_update_flags(const SelectionTreeElementPointer &sel,
  * Calls sel_datafunc() if one is specified for the method.
  */
 void
-_gmx_selelem_init_method_params(const SelectionTreeElementPointer &sel,
-                                yyscan_t scanner)
+_gmx_selelem_init_method_params(const gmx::SelectionTreeElementPointer &sel,
+                                yyscan_t                                scanner)
 {
     int                 nparams;
     gmx_ana_selparam_t *orgparam;
@@ -507,9 +518,9 @@ _gmx_selelem_init_method_params(const SelectionTreeElementPointer &sel,
  * and calls _gmx_selelem_init_method_params();
  */
 void
-_gmx_selelem_set_method(const SelectionTreeElementPointer &sel,
-                        gmx_ana_selmethod_t *method,
-                        yyscan_t scanner)
+_gmx_selelem_set_method(const gmx::SelectionTreeElementPointer &sel,
+                        gmx_ana_selmethod_t                    *method,
+                        yyscan_t                                scanner)
 {
     _gmx_selelem_set_vtype(sel, method->type);
     sel->setName(method->name);
@@ -552,24 +563,14 @@ set_refpos_type(gmx::PositionCalculationCollection *pcc,
     }
 }
 
-/*!
- * \param[in]  left    Selection element for the left hand side.
- * \param[in]  right   Selection element for the right hand side.
- * \param[in]  op      String representation of the operator.
- * \param[in]  scanner Scanner data structure.
- * \returns    The created selection element.
- *
- * This function handles the creation of a gmx::SelectionTreeElement object for
- * arithmetic expressions.
- */
-SelectionTreeElementPointer
-_gmx_sel_init_arithmetic(const SelectionTreeElementPointer &left,
-                         const SelectionTreeElementPointer &right,
-                         char op, yyscan_t scanner)
+gmx::SelectionTreeElementPointer
+_gmx_sel_init_arithmetic(const gmx::SelectionTreeElementPointer &left,
+                         const gmx::SelectionTreeElementPointer &right,
+                         char op, yyscan_t /* scanner */)
 {
     SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_ARITHMETIC));
     sel->v.type        = REAL_VALUE;
-    switch(op)
+    switch (op)
     {
         case '+': sel->u.arith.type = ARITH_PLUS; break;
         case '-': sel->u.arith.type = (right ? ARITH_MINUS : ARITH_NEG); break;
@@ -581,7 +582,7 @@ _gmx_sel_init_arithmetic(const SelectionTreeElementPointer &left,
     buf[0] = op;
     buf[1] = 0;
     sel->setName(buf);
-    sel->u.arith.opstr = strdup(buf);
+    sel->u.arith.opstr = gmx_strdup(buf);
     sel->child         = left;
     sel->child->next   = right;
     return sel;
@@ -598,18 +599,18 @@ _gmx_sel_init_arithmetic(const SelectionTreeElementPointer &left,
  * comparison expressions.
  */
 SelectionTreeElementPointer
-_gmx_sel_init_comparison(const SelectionTreeElementPointer &left,
-                         const SelectionTreeElementPointer &right,
+_gmx_sel_init_comparison(const gmx::SelectionTreeElementPointer &left,
+                         const gmx::SelectionTreeElementPointer &right,
                          const char *cmpop, yyscan_t scanner)
 {
     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
-    gmx::MessageStringContext  context(errors, "In comparison initialization");
+    gmx::MessageStringContext    context(errors, "In comparison initialization");
 
-    SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_EXPRESSION));
+    SelectionTreeElementPointer  sel(new SelectionTreeElement(SEL_EXPRESSION));
     _gmx_selelem_set_method(sel, &sm_compare, scanner);
 
     SelectionParserParameterList params;
-    const char        *name;
+    const char                  *name;
     // Create the parameter for the left expression.
     name  = left->v.type == INT_VALUE ? "int1" : "real1";
     params.push_back(SelectionParserParameter::createFromExpression(name, left));
@@ -619,7 +620,7 @@ _gmx_sel_init_comparison(const SelectionTreeElementPointer &left,
     // Create the parameter for the operator.
     params.push_back(
             SelectionParserParameter::create(
-                "op", SelectionParserValue::createString(cmpop)));
+                    "op", SelectionParserValue::createString(cmpop)));
     if (!_gmx_sel_parse_params(params, sel->u.expr.method->nparams,
                                sel->u.expr.method->param, sel, scanner))
     {
@@ -649,7 +650,7 @@ init_keyword_internal(gmx_ana_selmethod_t *method,
                       SelectionParserValueListPointer args,
                       const char *rpost, yyscan_t scanner)
 {
-    gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
+    gmx_ana_selcollection_t     *sc = _gmx_sel_lexer_selcollection(scanner);
 
     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
     char  buf[128];
@@ -660,7 +661,7 @@ init_keyword_internal(gmx_ana_selmethod_t *method,
     {
         // TODO: Would assert be better?
         GMX_THROW(gmx::InternalError(
-                "Keyword initialization called with non-keyword method"));
+                          "Keyword initialization called with non-keyword method"));
     }
 
     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
@@ -678,7 +679,7 @@ init_keyword_internal(gmx_ana_selmethod_t *method,
             case STR_VALUE:  kwmethod = &sm_keyword_str;  break;
             default:
                 GMX_THROW(gmx::InternalError(
-                        "Unknown type for keyword selection"));
+                                  "Unknown type for keyword selection"));
         }
         /* Initialize the selection element */
         root.reset(new SelectionTreeElement(SEL_EXPRESSION));
@@ -714,7 +715,7 @@ init_keyword_internal(gmx_ana_selmethod_t *method,
  */
 SelectionTreeElementPointer
 _gmx_sel_init_keyword(gmx_ana_selmethod_t *method,
-                      SelectionParserValueListPointer args,
+                      gmx::SelectionParserValueListPointer args,
                       const char *rpost, yyscan_t scanner)
 {
     return init_keyword_internal(method, gmx::eStringMatchType_Auto, move(args),
@@ -735,13 +736,13 @@ _gmx_sel_init_keyword(gmx_ana_selmethod_t *method,
 SelectionTreeElementPointer
 _gmx_sel_init_keyword_strmatch(gmx_ana_selmethod_t *method,
                                gmx::SelectionStringMatchType matchType,
-                               SelectionParserValueListPointer args,
+                               gmx::SelectionParserValueListPointer args,
                                const char *rpost, yyscan_t scanner)
 {
     GMX_RELEASE_ASSERT(method->type == STR_VALUE,
-            "String keyword method called for a non-string-valued method");
+                       "String keyword method called for a non-string-valued method");
     GMX_RELEASE_ASSERT(args && !args->empty(),
-            "String keyword matching method called without any values");
+                       "String keyword matching method called without any values");
     return init_keyword_internal(method, matchType, move(args), rpost, scanner);
 }
 
@@ -761,12 +762,12 @@ _gmx_sel_init_keyword_strmatch(gmx_ana_selmethod_t *method,
  * handling somewhere else (or sacrificing the simple syntax).
  */
 SelectionTreeElementPointer
-_gmx_sel_init_method(gmx_ana_selmethod_t *method,
-                     SelectionParserParameterListPointer params,
+_gmx_sel_init_method(gmx_ana_selmethod_t                      *method,
+                     gmx::SelectionParserParameterListPointer  params,
                      const char *rpost, yyscan_t scanner)
 {
-    gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
-    int              rc;
+    gmx_ana_selcollection_t     *sc = _gmx_sel_lexer_selcollection(scanner);
+    int                          rc;
 
     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
     char  buf[128];
@@ -804,9 +805,10 @@ _gmx_sel_init_method(gmx_ana_selmethod_t *method,
  * selection modifiers.
  */
 SelectionTreeElementPointer
-_gmx_sel_init_modifier(gmx_ana_selmethod_t *method,
-                       SelectionParserParameterListPointer params,
-                       const SelectionTreeElementPointer &sel, yyscan_t scanner)
+_gmx_sel_init_modifier(gmx_ana_selmethod_t                      *method,
+                       gmx::SelectionParserParameterListPointer  params,
+                       const gmx::SelectionTreeElementPointer   &sel,
+                       yyscan_t                                  scanner)
 {
     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
     char  buf[128];
@@ -853,13 +855,13 @@ _gmx_sel_init_modifier(gmx_ana_selmethod_t *method,
  * evaluation of reference positions.
  */
 SelectionTreeElementPointer
-_gmx_sel_init_position(const SelectionTreeElementPointer &expr,
+_gmx_sel_init_position(const gmx::SelectionTreeElementPointer &expr,
                        const char *type, yyscan_t scanner)
 {
     gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
     char  buf[128];
     sprintf(buf, "In position evaluation");
-    gmx::MessageStringContext  context(errors, buf);
+    gmx::MessageStringContext   context(errors, buf);
 
     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_EXPRESSION));
     _gmx_selelem_set_method(root, &sm_keyword_pos, scanner);
@@ -884,7 +886,7 @@ _gmx_sel_init_position(const SelectionTreeElementPointer &expr,
 SelectionTreeElementPointer
 _gmx_sel_init_const_position(real x, real y, real z)
 {
-    rvec       pos;
+    rvec                        pos;
 
     SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
     _gmx_selelem_set_vtype(sel, POS_VALUE);
@@ -899,8 +901,7 @@ _gmx_sel_init_const_position(real x, real y, real z)
 /*!
  * \param[in] name  Name of an index group to search for.
  * \param[in] scanner Scanner data structure.
- * \returns   The created constant selection element, or NULL if no matching
- *     index group found.
+ * \returns   The created selection element.
  *
  * See gmx_ana_indexgrps_find() for information on how \p name is matched
  * against the index groups.
@@ -908,66 +909,44 @@ _gmx_sel_init_const_position(real x, real y, real z)
 SelectionTreeElementPointer
 _gmx_sel_init_group_by_name(const char *name, yyscan_t scanner)
 {
-    gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
 
-    if (!_gmx_sel_lexer_has_groups_set(scanner))
-    {
-        SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
-        _gmx_selelem_set_vtype(sel, GROUP_VALUE);
-        sel->setName(name);
-        sel->u.gref.name = strdup(name);
-        sel->u.gref.id = -1;
-        return sel;
-    }
-    if (!grps)
-    {
-        _gmx_selparser_error(scanner, "No index groups set; cannot match 'group %s'", name);
-        return SelectionTreeElementPointer();
-    }
-    SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
+    SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
     _gmx_selelem_set_vtype(sel, GROUP_VALUE);
-    /* FIXME: The constness should not be cast away */
-    if (!gmx_ana_indexgrps_find(&sel->u.cgrp, grps, (char *)name))
+    sel->setName(gmx::formatString("group \"%s\"", name));
+    sel->u.gref.name = gmx_strdup(name);
+    sel->u.gref.id   = -1;
+
+    if (_gmx_sel_lexer_has_groups_set(scanner))
     {
-        _gmx_selparser_error(scanner, "Cannot match 'group %s'", name);
-        return SelectionTreeElementPointer();
+        gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
+        gmx_ana_selcollection_t *sc   = _gmx_sel_lexer_selcollection(scanner);
+        sel->resolveIndexGroupReference(grps, sc->gall.isize);
     }
-    sel->setName(sel->u.cgrp.name);
+
     return sel;
 }
 
 /*!
  * \param[in] id    Zero-based index number of the group to extract.
  * \param[in] scanner Scanner data structure.
- * \returns   The created constant selection element, or NULL if no matching
- *     index group found.
+ * \returns   The created selection element.
  */
 SelectionTreeElementPointer
 _gmx_sel_init_group_by_id(int id, yyscan_t scanner)
 {
-    gmx_ana_indexgrps_t *grps = _gmx_sel_lexer_indexgrps(scanner);
-
-    if (!_gmx_sel_lexer_has_groups_set(scanner))
-    {
-        SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
-        _gmx_selelem_set_vtype(sel, GROUP_VALUE);
-        sel->u.gref.name = NULL;
-        sel->u.gref.id = id;
-        return sel;
-    }
-    if (!grps)
-    {
-        _gmx_selparser_error(scanner, "No index groups set; cannot match 'group %d'", id);
-        return SelectionTreeElementPointer();
-    }
-    SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_CONST));
+    SelectionTreeElementPointer sel(new SelectionTreeElement(SEL_GROUPREF));
     _gmx_selelem_set_vtype(sel, GROUP_VALUE);
-    if (!gmx_ana_indexgrps_extract(&sel->u.cgrp, grps, id))
+    sel->setName(gmx::formatString("group %d", id));
+    sel->u.gref.name = NULL;
+    sel->u.gref.id   = id;
+
+    if (_gmx_sel_lexer_has_groups_set(scanner))
     {
-        _gmx_selparser_error(scanner, "Cannot match 'group %d'", id);
-        return SelectionTreeElementPointer();
+        gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
+        gmx_ana_selcollection_t *sc   = _gmx_sel_lexer_selcollection(scanner);
+        sel->resolveIndexGroupReference(grps, sc->gall.isize);
     }
-    sel->setName(sel->u.cgrp.name);
+
     return sel;
 }
 
@@ -979,7 +958,7 @@ _gmx_sel_init_group_by_id(int id, yyscan_t scanner)
  * made.
  */
 SelectionTreeElementPointer
-_gmx_sel_init_variable_ref(const SelectionTreeElementPointer &sel)
+_gmx_sel_init_variable_ref(const gmx::SelectionTreeElementPointer &sel)
 {
     SelectionTreeElementPointer ref;
 
@@ -1008,20 +987,15 @@ _gmx_sel_init_variable_ref(const SelectionTreeElementPointer &sel)
  * gmx::SelectionTreeElement objects for selections.
  */
 SelectionTreeElementPointer
-_gmx_sel_init_selection(const char *name,
-                        const SelectionTreeElementPointer &sel,
-                        yyscan_t scanner)
+_gmx_sel_init_selection(const char                             *name,
+                        const gmx::SelectionTreeElementPointer &sel,
+                        yyscan_t                                scanner)
 {
-    gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
-    char  buf[1024];
-    sprintf(buf, "In selection '%s'", _gmx_sel_lexer_pselstr(scanner));
-    gmx::MessageStringContext  context(errors, buf);
-
     if (sel->v.type != POS_VALUE)
     {
         /* FIXME: Better handling of this error */
         GMX_THROW(gmx::InternalError(
-                "Each selection must evaluate to a position"));
+                          "Each selection must evaluate to a position"));
     }
 
     SelectionTreeElementPointer root(new SelectionTreeElement(SEL_ROOT));
@@ -1029,45 +1003,18 @@ _gmx_sel_init_selection(const char *name,
     if (name)
     {
         root->setName(name);
-        root->u.cgrp.name = strdup(name);
     }
     /* Update the flags */
-    _gmx_selelem_update_flags(root, scanner);
-
-    /* If there is no name provided by the user, check whether the actual
-     * selection given was from an external group, and if so, use the name
-     * of the external group. */
-    if (root->name().empty())
-    {
-        SelectionTreeElementPointer child = root->child;
-        while (child->type == SEL_MODIFIER)
-        {
-            if (!child->child || child->child->type != SEL_SUBEXPRREF
-                || !child->child->child)
-            {
-                break;
-            }
-            child = child->child->child;
-        }
-        if (child->type == SEL_EXPRESSION
-            && child->child && child->child->type == SEL_SUBEXPRREF
-            && child->child->child
-            && child->child->child->type == SEL_CONST
-            && child->child->child->v.type == GROUP_VALUE)
-        {
-            const char *grpName = child->child->child->u.cgrp.name;
-            root->setName(grpName);
-            root->u.cgrp.name = strdup(grpName);
-        }
-    }
-    /* If there still is no name, use the selection string */
-    if (root->name().empty())
+    _gmx_selelem_update_flags(root);
+    gmx::ExceptionInitializer errors("Invalid index group reference(s)");
+    root->checkUnsortedAtoms(true, &errors);
+    if (errors.hasNestedExceptions())
     {
-        const char *selStr = _gmx_sel_lexer_pselstr(scanner);
-        root->setName(selStr);
-        root->u.cgrp.name = strdup(selStr);
+        GMX_THROW(gmx::InconsistentInputError(errors));
     }
 
+    root->fillNameIfMissing(_gmx_sel_lexer_pselstr(scanner));
+
     /* Print out some information if the parser is interactive */
     if (_gmx_sel_is_lexer_interactive(scanner))
     {
@@ -1090,50 +1037,50 @@ _gmx_sel_init_selection(const char *name,
  * element are both created.
  */
 SelectionTreeElementPointer
-_gmx_sel_assign_variable(const char *name,
-                         const SelectionTreeElementPointer &expr,
-                         yyscan_t scanner)
+_gmx_sel_assign_variable(const char                             *name,
+                         const gmx::SelectionTreeElementPointer &expr,
+                         yyscan_t                                scanner)
 {
-    gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
-    const char              *pselstr = _gmx_sel_lexer_pselstr(scanner);
-    SelectionTreeElementPointer root;
-
-    gmx::MessageStringCollector *errors = _gmx_sel_lexer_error_reporter(scanner);
-    char  buf[1024];
-    sprintf(buf, "In selection '%s'", pselstr);
-    gmx::MessageStringContext  context(errors, buf);
+    gmx_ana_selcollection_t     *sc      = _gmx_sel_lexer_selcollection(scanner);
+    const char                  *pselstr = _gmx_sel_lexer_pselstr(scanner);
+    SelectionTreeElementPointer  root;
 
-    _gmx_selelem_update_flags(expr, scanner);
+    _gmx_selelem_update_flags(expr);
     /* Check if this is a constant non-group value */
     if (expr->type == SEL_CONST && expr->v.type != GROUP_VALUE)
     {
         /* If so, just assign the constant value to the variable */
         sc->symtab->addVariable(name, expr);
-        goto finish;
     }
     /* Check if we are assigning a variable to another variable */
-    if (expr->type == SEL_SUBEXPRREF)
+    else if (expr->type == SEL_SUBEXPRREF)
     {
         /* If so, make a simple alias */
         sc->symtab->addVariable(name, expr->child);
-        goto finish;
     }
-    /* Create the root element */
-    root.reset(new SelectionTreeElement(SEL_ROOT));
-    root->setName(name);
-    root->u.cgrp.name = strdup(name);
-    /* Create the subexpression element */
-    root->child.reset(new SelectionTreeElement(SEL_SUBEXPR));
-    root->child->setName(name);
-    _gmx_selelem_set_vtype(root->child, expr->v.type);
-    root->child->child  = expr;
-    /* Update flags */
-    _gmx_selelem_update_flags(root, scanner);
-    /* Add the variable to the symbol table */
-    sc->symtab->addVariable(name, root->child);
-finish:
+    else
+    {
+        /* Create the root element */
+        root.reset(new SelectionTreeElement(SEL_ROOT));
+        root->setName(name);
+        /* Create the subexpression element */
+        root->child.reset(new SelectionTreeElement(SEL_SUBEXPR));
+        root->child->setName(name);
+        _gmx_selelem_set_vtype(root->child, expr->v.type);
+        root->child->child  = expr;
+        /* Update flags */
+        _gmx_selelem_update_flags(root);
+        gmx::ExceptionInitializer errors("Invalid index group reference(s)");
+        root->checkUnsortedAtoms(true, &errors);
+        if (errors.hasNestedExceptions())
+        {
+            GMX_THROW(gmx::InconsistentInputError(errors));
+        }
+        /* Add the variable to the symbol table */
+        sc->symtab->addVariable(name, root->child);
+    }
     srenew(sc->varstrs, sc->nvars + 1);
-    sc->varstrs[sc->nvars] = strdup(pselstr);
+    sc->varstrs[sc->nvars] = gmx_strdup(pselstr);
     ++sc->nvars;
     if (_gmx_sel_is_lexer_interactive(scanner))
     {
@@ -1153,9 +1100,9 @@ finish:
  * (if it was non-NULL) or the last element (if \p sel was NULL).
  */
 SelectionTreeElementPointer
-_gmx_sel_append_selection(const SelectionTreeElementPointer &sel,
-                          SelectionTreeElementPointer last,
-                          yyscan_t scanner)
+_gmx_sel_append_selection(const gmx::SelectionTreeElementPointer &sel,
+                          gmx::SelectionTreeElementPointer        last,
+                          yyscan_t                                scanner)
 {
     gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
 
@@ -1189,7 +1136,7 @@ _gmx_sel_append_selection(const SelectionTreeElementPointer &sel,
         {
             gmx::SelectionDataPointer selPtr(
                     new gmx::internal::SelectionData(
-                        sel.get(), _gmx_sel_lexer_pselstr(scanner)));
+                            sel.get(), _gmx_sel_lexer_pselstr(scanner)));
             sc->sel.push_back(gmx::move(selPtr));
         }
     }
@@ -1214,71 +1161,3 @@ _gmx_sel_parser_should_finish(yyscan_t scanner)
     gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
     return (int)sc->sel.size() == _gmx_sel_lexer_exp_selcount(scanner);
 }
-
-/*!
- * \param[in] scanner Scanner data structure.
- */
-void
-_gmx_sel_handle_empty_cmd(yyscan_t scanner)
-{
-    gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
-    gmx_ana_indexgrps_t     *grps = _gmx_sel_lexer_indexgrps(scanner);
-    int                      i;
-
-    if (!_gmx_sel_is_lexer_interactive(scanner))
-        return;
-
-    if (grps)
-    {
-        fprintf(stderr, "Available index groups:\n");
-        gmx_ana_indexgrps_print(stderr, _gmx_sel_lexer_indexgrps(scanner), 0);
-    }
-    if (sc->nvars > 0 || !sc->sel.empty())
-    {
-        fprintf(stderr, "Currently provided selections:\n");
-        for (i = 0; i < sc->nvars; ++i)
-        {
-            fprintf(stderr, "     %s\n", sc->varstrs[i]);
-        }
-        for (i = 0; i < (int)sc->sel.size(); ++i)
-        {
-            fprintf(stderr, " %2d. %s\n", i+1, sc->sel[i]->selectionText());
-        }
-    }
-}
-
-/*!
- * \param[in] topic   Topic for which help was requested, or NULL for general
- *                    help.
- * \param[in] scanner Scanner data structure.
- *
- * \p topic is freed by this function.
- */
-void
-_gmx_sel_handle_help_cmd(const SelectionParserValueListPointer &topic,
-                         yyscan_t scanner)
-{
-    gmx_ana_selcollection_t *sc = _gmx_sel_lexer_selcollection(scanner);
-
-    if (sc->rootHelp.get() == NULL)
-    {
-        sc->rootHelp = gmx::createSelectionHelpTopic();
-    }
-    gmx::HelpWriterContext context(&gmx::File::standardError(),
-                                   gmx::eHelpOutputFormat_Console);
-    gmx::HelpManager manager(*sc->rootHelp, context);
-    try
-    {
-        SelectionParserValueList::const_iterator value;
-        for (value = topic->begin(); value != topic->end(); ++value)
-        {
-            manager.enterTopic(value->stringValue());
-        }
-    }
-    catch (const gmx::InvalidInputError &ex)
-    {
-        fprintf(stderr, "%s\n", ex.what());
-        return;
-    }
-    manager.writeCurrentTopic();
-}