Better invalid option value handling.
[alexxy/gromacs.git] / src / gromacs / options / basicoptions.cpp
1 /*
2  *
3  *                This source code is part of
4  *
5  *                 G   R   O   M   A   C   S
6  *
7  *          GROningen MAchine for Chemical Simulations
8  *
9  * Written by David van der Spoel, Erik Lindahl, Berk Hess, and others.
10  * Copyright (c) 1991-2000, University of Groningen, The Netherlands.
11  * Copyright (c) 2001-2009, The GROMACS development team,
12  * check out http://www.gromacs.org for more information.
13
14  * This program is free software; you can redistribute it and/or
15  * modify it under the terms of the GNU General Public License
16  * as published by the Free Software Foundation; either version 2
17  * of the License, or (at your option) any later version.
18  *
19  * If you want to redistribute modifications, please consider that
20  * scientific software is very special. Version control is crucial -
21  * bugs must be traceable. We will be happy to consider code for
22  * inclusion in the official distribution, but derived work must not
23  * be called official GROMACS. Details are found in the README & COPYING
24  * files - if they are missing, get the official version at www.gromacs.org.
25  *
26  * To help us fund GROMACS development, we humbly ask that you cite
27  * the papers on the package - you can find them in the top README file.
28  *
29  * For more info, check our website at http://www.gromacs.org
30  */
31 /*! \internal \file
32  * \brief
33  * Implements classes in basicoptions.h, basicoptioninfo.h and
34  * basicoptionstorage.h.
35  *
36  * \author Teemu Murtola <teemu.murtola@cbr.su.se>
37  * \ingroup module_options
38  */
39 #include "gromacs/options/basicoptions.h"
40
41 #include <cerrno>
42 #include <cstdio>
43 #include <cstdlib>
44
45 #include <limits>
46 #include <string>
47 #include <vector>
48
49 #include "gromacs/options/basicoptioninfo.h"
50 #include "gromacs/utility/exceptions.h"
51 #include "gromacs/utility/stringutil.h"
52
53 #include "basicoptionstorage.h"
54
55 namespace
56 {
57
58 /*! \brief
59  * Expands a single value to a vector by copying the value.
60  *
61  * \tparam        ValueType  Type of values to process.
62  * \param[in]     length     Length of the resulting vector.
63  * \param[in,out] values     Values to process.
64  * \throws   std::bad_alloc    if out of memory.
65  * \throws   InvalidInputError if \p values has an invalid number of values.
66  *
67  * \p values should have 0, 1, or \p length values.
68  * If \p values has 1 value, it is expanded such that it has \p length
69  * identical values.  In other valid cases, nothing is done.
70  */
71 template <typename ValueType>
72 void expandVector(size_t length, std::vector<ValueType> *values)
73 {
74     if (length > 0 && values->size() > 0 && values->size() != length)
75     {
76         if (values->size() != 1)
77         {
78             GMX_THROW(gmx::InvalidInputError(gmx::formatString(
79                       "Expected 1 or %d values, got %d", length, values->size())));
80         }
81         const ValueType &value = (*values)[0];
82         values->resize(length, value);
83     }
84 }
85
86 } // namespace
87
88 namespace gmx
89 {
90
91 /********************************************************************
92  * BooleanOptionStorage
93  */
94
95 std::string BooleanOptionStorage::formatSingleValue(const bool &value) const
96 {
97     return value ? "yes" : "no";
98 }
99
100 void BooleanOptionStorage::convertValue(const std::string &value)
101 {
102     // TODO: Case-independence
103     if (value == "1" || value == "yes" || value == "true")
104     {
105         addValue(true);
106         return;
107     }
108     else if (value == "0" || value == "no" || value == "false")
109     {
110         addValue(false);
111         return;
112     }
113     GMX_THROW(InvalidInputError("Invalid value: '" + value + "'; supported values are: 1, 0, yes, no, true, false"));
114 }
115
116 /********************************************************************
117  * BooleanOptionInfo
118  */
119
120 BooleanOptionInfo::BooleanOptionInfo(BooleanOptionStorage *option)
121     : OptionInfo(option)
122 {
123 }
124
125 /********************************************************************
126  * BooleanOption
127  */
128
129 AbstractOptionStoragePointer BooleanOption::createStorage() const
130 {
131     return AbstractOptionStoragePointer(new BooleanOptionStorage(*this));
132 }
133
134
135 /********************************************************************
136  * IntegerOptionStorage
137  */
138
139 std::string IntegerOptionStorage::formatSingleValue(const int &value) const
140 {
141     return formatString("%d", value);
142 }
143
144 void IntegerOptionStorage::convertValue(const std::string &value)
145 {
146     const char *ptr = value.c_str();
147     char *endptr;
148     errno = 0;
149     long int ival = std::strtol(ptr, &endptr, 10);
150     if (errno == ERANGE
151         || ival < std::numeric_limits<int>::min()
152         || ival > std::numeric_limits<int>::max())
153     {
154         GMX_THROW(InvalidInputError("Invalid value: '" + value
155                                     + "'; it causes an integer overflow"));
156     }
157     if (*ptr == '\0' || *endptr != '\0')
158     {
159         GMX_THROW(InvalidInputError("Invalid value: '" + value
160                                     + "'; expected an integer"));
161     }
162     addValue(ival);
163 }
164
165 void IntegerOptionStorage::processSetValues(ValueList *values)
166 {
167     if (isVector())
168     {
169         expandVector(maxValueCount(), values);
170     }
171 }
172
173 /********************************************************************
174  * IntegerOptionInfo
175  */
176
177 IntegerOptionInfo::IntegerOptionInfo(IntegerOptionStorage *option)
178     : OptionInfo(option)
179 {
180 }
181
182 /********************************************************************
183  * IntegerOption
184  */
185
186 AbstractOptionStoragePointer IntegerOption::createStorage() const
187 {
188     return AbstractOptionStoragePointer(new IntegerOptionStorage(*this));
189 }
190
191
192 /********************************************************************
193  * DoubleOptionStorage
194  */
195
196 DoubleOptionStorage::DoubleOptionStorage(const DoubleOption &settings)
197     : MyBase(settings), info_(this), bTime_(settings.bTime_), factor_(1.0)
198 {
199 }
200
201 const char *DoubleOptionStorage::typeString() const
202 {
203     return isVector() ? "vector" : (isTime() ? "time" : "double");
204 }
205
206 std::string DoubleOptionStorage::formatSingleValue(const double &value) const
207 {
208     return formatString("%g", value / factor_);
209 }
210
211 void DoubleOptionStorage::convertValue(const std::string &value)
212 {
213     const char *ptr = value.c_str();
214     char *endptr;
215     errno = 0;
216     double dval = std::strtod(ptr, &endptr);
217     if (errno == ERANGE)
218     {
219         GMX_THROW(InvalidInputError("Invalid value: '" + value
220                                     + "'; it causes an overflow/underflow"));
221     }
222     if (*ptr == '\0' || *endptr != '\0')
223     {
224         GMX_THROW(InvalidInputError("Invalid value: '" + value
225                                     + "'; expected a number"));
226     }
227     addValue(dval * factor_);
228 }
229
230 void DoubleOptionStorage::processSetValues(ValueList *values)
231 {
232     if (isVector())
233     {
234         expandVector(maxValueCount(), values);
235     }
236 }
237
238 void DoubleOptionStorage::processAll()
239 {
240 }
241
242 void DoubleOptionStorage::setScaleFactor(double factor)
243 {
244     GMX_RELEASE_ASSERT(factor > 0.0, "Invalid scaling factor");
245     if (!hasFlag(efOption_HasDefaultValue))
246     {
247         double scale = factor / factor_;
248         ValueList::iterator i;
249         for (i = values().begin(); i != values().end(); ++i)
250         {
251             (*i) *= scale;
252         }
253         refreshValues();
254     }
255     factor_ = factor;
256 }
257
258 /********************************************************************
259  * DoubleOptionInfo
260  */
261
262 DoubleOptionInfo::DoubleOptionInfo(DoubleOptionStorage *option)
263     : OptionInfo(option)
264 {
265 }
266
267 DoubleOptionStorage &DoubleOptionInfo::option()
268 {
269     return static_cast<DoubleOptionStorage &>(OptionInfo::option());
270 }
271
272 const DoubleOptionStorage &DoubleOptionInfo::option() const
273 {
274     return static_cast<const DoubleOptionStorage &>(OptionInfo::option());
275 }
276
277 bool DoubleOptionInfo::isTime() const
278 {
279     return option().isTime();
280 }
281
282 void DoubleOptionInfo::setScaleFactor(double factor)
283 {
284     option().setScaleFactor(factor);
285 }
286
287 /********************************************************************
288  * DoubleOption
289  */
290
291 AbstractOptionStoragePointer DoubleOption::createStorage() const
292 {
293     return AbstractOptionStoragePointer(new DoubleOptionStorage(*this));
294 }
295
296
297 /********************************************************************
298  * StringOptionStorage
299  */
300
301 StringOptionStorage::StringOptionStorage(const StringOption &settings)
302     : MyBase(settings), info_(this), enumIndexStore_(NULL)
303 {
304     if (settings.defaultEnumIndex_ >= 0 && settings.enumValues_ == NULL)
305     {
306         GMX_THROW(APIError("Cannot set default enum index without enum values"));
307     }
308     if (settings.enumIndexStore_ != NULL && settings.enumValues_ == NULL)
309     {
310         GMX_THROW(APIError("Cannot set enum index store without enum values"));
311     }
312     if (settings.enumIndexStore_ != NULL && settings.maxValueCount_ < 0)
313     {
314         GMX_THROW(APIError("Cannot set enum index store with arbitrary number of values"));
315     }
316     if (settings.enumValues_ != NULL)
317     {
318         enumIndexStore_ = settings.enumIndexStore_;
319         const std::string *defaultValue = settings.defaultValue();
320         int match = -1;
321         for (int i = 0; settings.enumValues_[i] != NULL; ++i)
322         {
323             if (defaultValue != NULL && settings.enumValues_[i] == *defaultValue)
324             {
325                 match = i;
326             }
327             allowed_.push_back(settings.enumValues_[i]);
328         }
329         if (defaultValue != NULL)
330         {
331             if (match < 0)
332             {
333                 GMX_THROW(APIError("Default value is not one of allowed values"));
334             }
335         }
336         if (settings.defaultEnumIndex_ >= 0)
337         {
338             if (settings.defaultEnumIndex_ >= static_cast<int>(allowed_.size()))
339             {
340                 GMX_THROW(APIError("Default enumeration index is out of range"));
341             }
342             if (defaultValue != NULL && *defaultValue != allowed_[settings.defaultEnumIndex_])
343             {
344                 GMX_THROW(APIError("Conflicting default values"));
345             }
346         }
347         // If there is no default value, match is still -1.
348         if (enumIndexStore_ != NULL)
349         {
350             *enumIndexStore_ = match;
351         }
352     }
353     if (settings.defaultEnumIndex_ >= 0)
354     {
355         clear();
356         addValue(allowed_[settings.defaultEnumIndex_]);
357         commitValues();
358     }
359 }
360
361 std::string StringOptionStorage::formatSingleValue(const std::string &value) const
362 {
363     return value;
364 }
365
366 void StringOptionStorage::convertValue(const std::string &value)
367 {
368     if (allowed_.size() == 0)
369     {
370         addValue(value);
371     }
372     else
373     {
374         ValueList::const_iterator  i;
375         ValueList::const_iterator  match = allowed_.end();
376         for (i = allowed_.begin(); i != allowed_.end(); ++i)
377         {
378             // TODO: Case independence.
379             if (i->find(value) == 0)
380             {
381                 if (match == allowed_.end() || i->size() < match->size())
382                 {
383                     match = i;
384                 }
385             }
386         }
387         if (match == allowed_.end())
388         {
389             GMX_THROW(InvalidInputError("Invalid value: " + value));
390         }
391         addValue(*match);
392     }
393 }
394
395 void StringOptionStorage::refreshValues()
396 {
397     MyBase::refreshValues();
398     if (enumIndexStore_ != NULL)
399     {
400         for (size_t i = 0; i < values().size(); ++i)
401         {
402             ValueList::const_iterator match =
403                 std::find(allowed_.begin(), allowed_.end(), values()[i]);
404             GMX_ASSERT(match != allowed_.end(),
405                        "Enum value not found (internal error)");
406             enumIndexStore_[i] = static_cast<int>(match - allowed_.begin());
407         }
408     }
409 }
410
411 /********************************************************************
412  * StringOptionInfo
413  */
414
415 StringOptionInfo::StringOptionInfo(StringOptionStorage *option)
416     : OptionInfo(option)
417 {
418 }
419
420 /********************************************************************
421  * StringOption
422  */
423
424 AbstractOptionStoragePointer StringOption::createStorage() const
425 {
426     return AbstractOptionStoragePointer(new StringOptionStorage(*this));
427 }
428
429 std::string StringOption::createDescription() const
430 {
431     std::string value(MyBase::createDescription());
432
433     if (enumValues_ != NULL)
434     {
435         value.append(": ");
436         for (int i = 0; enumValues_[i] != NULL; ++i)
437         {
438             value.append(enumValues_[i]);
439             if (enumValues_[i + 1] != NULL)
440             {
441                 value.append(enumValues_[i + 2] != NULL ? ", " : ", or ");
442             }
443         }
444     }
445     return value;
446 }
447
448 } // namespace gmx