2db9afd01666db2d72928446d0a6bef83241cfb7
[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,2011,2012,2013,2014,2015, 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.
8  *
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.
13  *
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.
18  *
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.
23  *
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.
31  *
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.
34  */
35 /*! \internal \file
36  * \brief
37  * Implements gmx::CommandLineParser.
38  *
39  * \author Teemu Murtola <teemu.murtola@gmail.com>
40  * \ingroup module_commandline
41  */
42 #include "gmxpre.h"
43
44 #include "cmdlineparser.h"
45
46 #include <cstdlib>
47
48 #include <string>
49 #include <vector>
50
51 #include "gromacs/options/optionsassigner.h"
52 #include "gromacs/utility/basedefinitions.h"
53 #include "gromacs/utility/exceptions.h"
54
55 namespace gmx
56 {
57
58 /********************************************************************
59  * CommandLineParser::Impl
60  */
61
62 /*! \internal \brief
63  * Private implementation class for CommandLineParser.
64  *
65  * \ingroup module_commandline
66  */
67 class CommandLineParser::Impl
68 {
69     public:
70         //! Sets the options object to parse to.
71         explicit Impl(Options *options);
72
73         /*! \brief
74          * Determines whether a cmdline parameter starts an option and the name
75          * of that option.
76          *
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.
80          */
81         const char *toOptionName(const char *arg) const;
82
83         //! Helper object for assigning the options.
84         OptionsAssigner         assigner_;
85         //! Whether to allow and skip unknown options.
86         bool                    bSkipUnknown_;
87 };
88
89 CommandLineParser::Impl::Impl(Options *options)
90     : assigner_(options), bSkipUnknown_(false)
91 {
92     assigner_.setAcceptBooleanNoPrefix(true);
93 }
94
95 const char *CommandLineParser::Impl::toOptionName(const char *arg) const
96 {
97     // Lone '-' or '--' is not an option.
98     if (arg[0] != '-' || arg[1] == '\0' || (arg[1] == '-' && arg[2] == '\0'))
99     {
100         return NULL;
101     }
102     // Something starting with '--' is always an option.
103     if (arg[1] == '-')
104     {
105         return arg + 2;
106     }
107     // Don't return numbers as option names.
108     char *endptr;
109     // We are only interested in endptr, not in the actual value.
110     GMX_IGNORE_RETURN_VALUE(std::strtod(arg, &endptr));
111     if (*endptr == '\0')
112     {
113         return NULL;
114     }
115     return arg + 1;
116 }
117
118 /********************************************************************
119  * CommandLineParser
120  */
121
122 CommandLineParser::CommandLineParser(Options *options)
123     : impl_(new Impl(options))
124 {
125 }
126
127 CommandLineParser::~CommandLineParser()
128 {
129 }
130
131 CommandLineParser &CommandLineParser::skipUnknown(bool bEnabled)
132 {
133     impl_->bSkipUnknown_ = bEnabled;
134     return *this;
135 }
136
137 void CommandLineParser::parse(int *argc, char *argv[])
138 {
139     ExceptionInitializer errors("Invalid command-line options");
140     std::string          currentContext;
141     bool                 bInOption = false;
142
143     impl_->assigner_.start();
144     int newi = 1;
145     for (int i = 1; i != *argc; ++i)
146     {
147         const char *const arg        = argv[i];
148         const char *const optionName = impl_->toOptionName(arg);
149         if (optionName != NULL)
150         {
151             if (bInOption)
152             {
153                 try
154                 {
155                     impl_->assigner_.finishOption();
156                 }
157                 catch (UserInputError &ex)
158                 {
159                     ex.prependContext(currentContext);
160                     errors.addCurrentExceptionAsNested();
161                 }
162             }
163             currentContext = "In command-line option " + std::string(arg);
164             try
165             {
166                 bInOption = impl_->assigner_.tryStartOption(optionName);
167                 if (!bInOption)
168                 {
169                     currentContext.clear();
170                     if (!impl_->bSkipUnknown_)
171                     {
172                         std::string message =
173                             "Unknown command-line option " + std::string(arg);
174                         GMX_THROW(InvalidInputError(message));
175                     }
176                 }
177             }
178             catch (UserInputError &ex)
179             {
180                 // If tryStartOption() throws, make sure that the rest gets
181                 // ignored.
182                 // TODO: Consider whether we should remove the option from the
183                 // command line nonetheless, as it is recognized, but just
184                 // invalid.
185                 bInOption = false;
186                 ex.prependContext(currentContext);
187                 errors.addCurrentExceptionAsNested();
188                 currentContext.clear();
189             }
190         }
191         else if (bInOption)
192         {
193             try
194             {
195                 impl_->assigner_.appendValue(arg);
196             }
197             // TODO: Consider if some types of exceptions would be better left
198             // unhandled.
199             catch (GromacsException &ex)
200             {
201                 ex.prependContext(currentContext);
202                 errors.addCurrentExceptionAsNested();
203             }
204         }
205         // Remove recognized options if applicable.
206         if (!bInOption && impl_->bSkipUnknown_)
207         {
208             argv[newi] = argv[i];
209             ++newi;
210         }
211     }
212     // Update the argc count if argv was modified.
213     if (impl_->bSkipUnknown_)
214     {
215         *argc      = newi;
216         argv[newi] = NULL;
217     }
218     // Finish the last option.
219     if (bInOption)
220     {
221         try
222         {
223             impl_->assigner_.finishOption();
224         }
225         catch (UserInputError &ex)
226         {
227             ex.prependContext(currentContext);
228             errors.addCurrentExceptionAsNested();
229         }
230     }
231     impl_->assigner_.finish();
232     if (errors.hasNestedExceptions())
233     {
234         // TODO: This exception type may not always be appropriate.
235         GMX_THROW(InvalidInputError(errors));
236     }
237 }
238
239 } // namespace gmx