Introduce SimulatorBuilder
[gromacs.git] / src / gromacs / commandline / cmdlineparser.cpp
blobb3902c00e354fd0b0a825131014f35725fe54682
1 /*
2 * This file is part of the GROMACS molecular simulation package.
4 * Copyright (c) 2010,2011,2012,2013,2014,2015,2017,2018, by the GROMACS development team, led by
5 * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
6 * and including many others, as listed in the AUTHORS file in the
7 * top-level source directory and at http://www.gromacs.org.
9 * GROMACS is free software; you can redistribute it and/or
10 * modify it under the terms of the GNU Lesser General Public License
11 * as published by the Free Software Foundation; either version 2.1
12 * of the License, or (at your option) any later version.
14 * GROMACS is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * Lesser General Public License for more details.
19 * You should have received a copy of the GNU Lesser General Public
20 * License along with GROMACS; if not, see
21 * http://www.gnu.org/licenses, or write to the Free Software Foundation,
22 * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
24 * If you want to redistribute modifications to GROMACS, please
25 * consider that scientific software is very special. Version
26 * control is crucial - bugs must be traceable. We will be happy to
27 * consider code for inclusion in the official distribution, but
28 * derived work must not be called official GROMACS. Details are found
29 * in the README & COPYING files - if they are missing, get the
30 * official version at http://www.gromacs.org.
32 * To help us fund GROMACS development, we humbly ask that you cite
33 * the research papers on the package. Check out http://www.gromacs.org.
35 /*! \internal \file
36 * \brief
37 * Implements gmx::CommandLineParser.
39 * \author Teemu Murtola <teemu.murtola@gmail.com>
40 * \ingroup module_commandline
42 #include "gmxpre.h"
44 #include "cmdlineparser.h"
46 #include <cstdlib>
48 #include <string>
49 #include <vector>
51 #include "gromacs/options/optionsassigner.h"
52 #include "gromacs/utility/basedefinitions.h"
53 #include "gromacs/utility/exceptions.h"
55 namespace gmx
58 /********************************************************************
59 * CommandLineParser::Impl
62 /*! \internal \brief
63 * Private implementation class for CommandLineParser.
65 * \ingroup module_commandline
67 class CommandLineParser::Impl
69 public:
70 //! Sets the options object to parse to.
71 explicit Impl(Options *options);
73 /*! \brief
74 * Determines whether a cmdline parameter starts an option and the name
75 * of that option.
77 * \param[in] arg Individual argument from \c argv.
78 * \returns The beginning of the option name in \p arg, or NULL if
79 * \p arg does not look like an option.
81 const char *toOptionName(const char *arg) const;
83 //! Helper object for assigning the options.
84 OptionsAssigner assigner_;
85 //! Whether to allow and skip unknown options.
86 bool bSkipUnknown_;
87 /*! \brief Whether to allow positional arguments
89 * These are not options (no leading hyphen), and come before
90 * all options. */
91 bool bAllowPositionalArguments_;
94 CommandLineParser::Impl::Impl(Options *options)
95 : assigner_(options), bSkipUnknown_(false), bAllowPositionalArguments_(false)
97 assigner_.setAcceptBooleanNoPrefix(true);
100 const char *CommandLineParser::Impl::toOptionName(const char *arg) const
102 // Lone '-' or '--' is not an option.
103 if (arg[0] != '-' || arg[1] == '\0' || (arg[1] == '-' && arg[2] == '\0'))
105 return nullptr;
107 // Something starting with '--' is always an option.
108 if (arg[1] == '-')
110 return arg + 2;
112 // Don't return numbers as option names.
113 char *endptr;
114 // We are only interested in endptr, not in the actual value.
115 GMX_IGNORE_RETURN_VALUE(std::strtod(arg, &endptr));
116 if (*endptr == '\0')
118 return nullptr;
120 return arg + 1;
123 /********************************************************************
124 * CommandLineParser
127 CommandLineParser::CommandLineParser(Options *options)
128 : impl_(new Impl(options))
132 CommandLineParser::~CommandLineParser()
136 CommandLineParser &CommandLineParser::skipUnknown(bool bEnabled)
138 impl_->bSkipUnknown_ = bEnabled;
139 return *this;
142 CommandLineParser &CommandLineParser::allowPositionalArguments(bool bEnabled)
144 impl_->bAllowPositionalArguments_ = bEnabled;
145 return *this;
148 void CommandLineParser::parse(int *argc, char *argv[])
150 ExceptionInitializer errors("Invalid command-line options");
151 std::string currentContext;
152 bool bInOption = false;
154 // Note that this function gets called multiple times in typical
155 // cases of calling gmx. Command lines like "gmx -hidden mdrun -h"
156 // work because the first call has argv[0] == "gmx" and skips
157 // unknown things, and the second has argv[0] == "mdrun".
158 int i = 1, newi = 1;
160 // First, process any permitted leading positional arguments.
161 for (; i < *argc; ++i)
163 const char *const arg = argv[i];
164 if (impl_->toOptionName(arg) != nullptr)
166 // If we find an option, no more positional arguments
167 // can be handled.
168 break;
171 if (!impl_->bAllowPositionalArguments_)
173 GMX_THROW(InvalidInputError
174 ("Positional argument '" + std::string(arg) + "' cannot be accepted. "
175 "Perhaps you forgot to put a hyphen before an option name."));
177 // argv[i] is not an option, so preserve it in the argument list
178 // by incrementing newi. There's no need to copy argv contents
179 // because they cannot have changed yet.
180 ++newi;
183 // Now handle the option arguments.
184 impl_->assigner_.start();
185 for (; i < *argc; ++i)
187 const char *const arg = argv[i];
188 const char *const optionName = impl_->toOptionName(arg);
189 if (optionName != nullptr)
191 if (bInOption)
195 impl_->assigner_.finishOption();
197 catch (UserInputError &ex)
199 ex.prependContext(currentContext);
200 errors.addCurrentExceptionAsNested();
203 currentContext = "In command-line option " + std::string(arg);
206 bInOption = impl_->assigner_.tryStartOption(optionName);
207 if (!bInOption)
209 currentContext.clear();
210 if (!impl_->bSkipUnknown_)
212 std::string message =
213 "Unknown command-line option " + std::string(arg);
214 GMX_THROW(InvalidInputError(message));
218 catch (UserInputError &ex)
220 // If tryStartOption() throws, make sure that the rest gets
221 // ignored.
222 // TODO: Consider whether we should remove the option from the
223 // command line nonetheless, as it is recognized, but just
224 // invalid.
225 bInOption = false;
226 ex.prependContext(currentContext);
227 errors.addCurrentExceptionAsNested();
228 currentContext.clear();
231 else if (bInOption)
235 impl_->assigner_.appendValue(arg);
237 // TODO: Consider if some types of exceptions would be better left
238 // unhandled.
239 catch (GromacsException &ex)
241 ex.prependContext(currentContext);
242 errors.addCurrentExceptionAsNested();
245 // Retain unrecognized options if applicable.
246 if (!bInOption && impl_->bSkipUnknown_)
248 argv[newi] = argv[i];
249 ++newi;
252 // Update the args if argv was modified.
253 if (impl_->bSkipUnknown_)
255 *argc = newi;
256 argv[newi] = nullptr;
259 // Finish the last option.
260 if (bInOption)
264 impl_->assigner_.finishOption();
266 catch (UserInputError &ex)
268 ex.prependContext(currentContext);
269 errors.addCurrentExceptionAsNested();
272 impl_->assigner_.finish();
273 if (errors.hasNestedExceptions())
275 // TODO: This exception type may not always be appropriate.
276 GMX_THROW(InvalidInputError(errors));
280 } // namespace gmx