Merge release-5-0 into master
[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, 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/common.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     assigner_.setNoStrictSectioning(true);
94 }
95
96 const char *CommandLineParser::Impl::toOptionName(const char *arg) const
97 {
98     // Lone '-' or '--' is not an option.
99     if (arg[0] != '-' || arg[1] == '\0' || (arg[1] == '-' && arg[2] == '\0'))
100     {
101         return NULL;
102     }
103     // Something starting with '--' is always an option.
104     if (arg[1] == '-')
105     {
106         return arg + 2;
107     }
108     // Don't return numbers as option names.
109     char *endptr;
110     // We are only interested in endptr, not in the actual value.
111     GMX_IGNORE_RETURN_VALUE(std::strtod(arg, &endptr));
112     if (*endptr == '\0')
113     {
114         return NULL;
115     }
116     return arg + 1;
117 }
118
119 /********************************************************************
120  * CommandLineParser
121  */
122
123 CommandLineParser::CommandLineParser(Options *options)
124     : impl_(new Impl(options))
125 {
126 }
127
128 CommandLineParser::~CommandLineParser()
129 {
130 }
131
132 CommandLineParser &CommandLineParser::skipUnknown(bool bEnabled)
133 {
134     impl_->bSkipUnknown_ = bEnabled;
135     return *this;
136 }
137
138 void CommandLineParser::parse(int *argc, char *argv[])
139 {
140     ExceptionInitializer errors("Invalid command-line options");
141     std::string          currentContext;
142     bool                 bInOption = false;
143
144     impl_->assigner_.start();
145     int newi = 1;
146     for (int i = 1; i != *argc; ++i)
147     {
148         const char *const arg        = argv[i];
149         const char *const optionName = impl_->toOptionName(arg);
150         if (optionName != NULL)
151         {
152             if (bInOption)
153             {
154                 try
155                 {
156                     impl_->assigner_.finishOption();
157                 }
158                 catch (UserInputError &ex)
159                 {
160                     ex.prependContext(currentContext);
161                     errors.addCurrentExceptionAsNested();
162                 }
163             }
164             currentContext = "In command-line option " + std::string(arg);
165             try
166             {
167                 bInOption = impl_->assigner_.tryStartOption(optionName);
168                 if (!bInOption)
169                 {
170                     currentContext.clear();
171                     if (!impl_->bSkipUnknown_)
172                     {
173                         std::string message =
174                             "Unknown command-line option " + std::string(arg);
175                         GMX_THROW(InvalidInputError(message));
176                     }
177                 }
178             }
179             catch (UserInputError &ex)
180             {
181                 // If tryStartOption() throws, make sure that the rest gets
182                 // ignored.
183                 // TODO: Consider whether we should remove the option from the
184                 // command line nonetheless, as it is recognized, but just
185                 // invalid.
186                 bInOption = false;
187                 ex.prependContext(currentContext);
188                 errors.addCurrentExceptionAsNested();
189                 currentContext.clear();
190             }
191         }
192         else if (bInOption)
193         {
194             try
195             {
196                 impl_->assigner_.appendValue(arg);
197             }
198             catch (UserInputError &ex)
199             {
200                 ex.prependContext(currentContext);
201                 errors.addCurrentExceptionAsNested();
202             }
203         }
204         // Remove recognized options if applicable.
205         if (!bInOption && impl_->bSkipUnknown_)
206         {
207             argv[newi] = argv[i];
208             ++newi;
209         }
210     }
211     // Update the argc count if argv was modified.
212     if (impl_->bSkipUnknown_)
213     {
214         *argc      = newi;
215         argv[newi] = NULL;
216     }
217     // Finish the last option.
218     if (bInOption)
219     {
220         try
221         {
222             impl_->assigner_.finishOption();
223         }
224         catch (UserInputError &ex)
225         {
226             ex.prependContext(currentContext);
227             errors.addCurrentExceptionAsNested();
228         }
229     }
230     impl_->assigner_.finish();
231     if (errors.hasNestedExceptions())
232     {
233         // TODO: This exception type may not always be appropriate.
234         GMX_THROW(InvalidInputError(errors));
235     }
236 }
237
238 } // namespace gmx