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