Merge release-5-0 into master
[alexxy/gromacs.git] / src / gromacs / options / abstractoption.h
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 /*! \file
36  * \brief
37  * Defines gmx::AbstractOption, gmx::OptionTemplate and gmx::OptionInfo.
38  *
39  * This header defines base classes for option settings that are used with
40  * Options::addOption().  These classes implement the "named parameter"
41  * idiom for specifying option properties.
42  *
43  * These classes also take care of creating and setting up the actual option
44  * objects.
45  *
46  * This header is needed directly only when implementing new option types,
47  * but methods of OptionTemplate are visible even to the normal user through
48  * its subclasses.
49  *
50  * \author Teemu Murtola <teemu.murtola@gmail.com>
51  * \inlibraryapi
52  * \ingroup module_options
53  */
54 #ifndef GMX_OPTIONS_ABSTRACTOPTION_H
55 #define GMX_OPTIONS_ABSTRACTOPTION_H
56
57 #include <string>
58 #include <vector>
59
60 #include "../utility/common.h"
61 #include "../utility/uniqueptr.h"
62
63 #include "optionflags.h"
64
65 namespace gmx
66 {
67
68 class AbstractOptionStorage;
69 template <typename T> class OptionStorageTemplate;
70 class OptionManagerContainer;
71 class Options;
72
73 //! Smart pointer for managing an AbstractOptionStorage object.
74 typedef gmx_unique_ptr<AbstractOptionStorage>::type
75     AbstractOptionStoragePointer;
76
77 /*! \brief
78  * Abstract base class for specifying option properties.
79  *
80  * Concrete classes should normally not derive directly from this class,
81  * but from OptionTemplate instead.  Classes derived from this class
82  * are mainly designed to implement the "named parameter" idiom.  For
83  * efficiency and clarity, these classes should only store values provided to
84  * them.  All error checking and memory management should be postponed to the
85  * point when the actual option is created.
86  *
87  * Subclasses should override createStorage() to create the correct type
88  * of storage object.  If they use their own info type derived from OptionInfo,
89  * they should also have a public typedef \c InfoType that specifies that
90  * info type.  This is required for Options::addOption() to return the correct
91  * info type.
92  *
93  * \ingroup module_options
94  */
95 class AbstractOption
96 {
97     public:
98         // Virtual only for completeness, in normal use should not be needed.
99         virtual ~AbstractOption() { }
100
101     protected:
102         /*! \cond libapi */
103         //! Initializes the name and default values for an option.
104         explicit AbstractOption(const char *name)
105             : minValueCount_(1), maxValueCount_(1),
106               name_(name), descr_(NULL)
107         { }
108
109         /*! \brief
110          * Creates a default storage object for the option.
111          *
112          * \param[in] managers  Manager container (unused if the option does
113          *     not use a manager).
114          * \returns   The created storage object.
115          * \throws    APIError if invalid option settings have been provided.
116          *
117          * This method is called by Options::addOption() when initializing an
118          * option from the settings.
119          *
120          * Derived classes should implement the method to create an actual
121          * storage object and populate it with correct values.
122          * They should also throw APIError if they detect problems.
123          *
124          * Should only be called by Options::addOption().
125          */
126         virtual AbstractOptionStoragePointer createStorage(
127             const OptionManagerContainer &managers) const = 0;
128
129         //! Sets the description for the option.
130         void setDescription(const char *descr) { descr_ = descr; }
131         //! Sets a flag for the option.
132         void setFlag(OptionFlag flag) { flags_.set(flag); }
133         //! Clears a flag for the option.
134         void clearFlag(OptionFlag flag) { flags_.clear(flag); }
135         //! Sets or clears a flag for the option.
136         void setFlag(OptionFlag flag, bool bSet) { flags_.set(flag, bSet); }
137         //! Returns true if the option is vector-valued.
138         bool isVector() const { return hasFlag(efOption_Vector); }
139         /*! \brief
140          * Sets the option to be vector-valued.
141          *
142          * This method is provided for convenience to make management of value
143          * counts easier.  In order to implement a vector-valued option, the
144          * class derived from AbstractOption should expose a method that calls
145          * this method, and the storage object derived from
146          * AbstractOptionStorage should check isVector().
147          * If only a single value is provided, the storage object should fill
148          * the whole vector with that value.
149          *
150          * The length of the vector (the value of maxValueCount_) must be
151          * fixed.  The default length is 3 elements.
152          */
153         void setVector()
154         {
155             setFlag(efOption_Vector);
156             minValueCount_ = 1;
157             if (maxValueCount_ == 1)
158             {
159                 maxValueCount_ = 3;
160             }
161         }
162         //! Sets the required number of values for the option.
163         void setValueCount(int count)
164         {
165             if (!hasFlag(efOption_Vector))
166             {
167                 minValueCount_ = count;
168             }
169             maxValueCount_ = count;
170         }
171
172         //! Minimum number of values required for the option.
173         int                     minValueCount_;
174         //! Maximum number of values allowed for the option.
175         int                     maxValueCount_;
176         //! \endcond
177
178     private:
179         //! Returns true if a flag has been set.
180         bool hasFlag(OptionFlag flag) const { return flags_.test(flag); }
181
182         const char             *name_;
183         //! Pointer to description of the option.
184         const char             *descr_;
185         OptionFlags             flags_;
186
187         /*! \brief
188          * Needed to initialize an AbstractOptionStorage object from this class
189          * without otherwise unnecessary accessors.
190          */
191         friend class AbstractOptionStorage;
192         /*! \brief
193          * Needed to be able to call createStorage().
194          */
195         friend class Options;
196 };
197
198 /*! \brief
199  * Templated base class for constructing concrete option settings classes.
200  *
201  * \tparam T Assignable type that stores a single option value.
202  * \tparam U Type of the derived class.
203  *
204  * This template is used as a base class like this:
205  * \code
206    class ConcreteOption : public OptionTemplate<int, ConcreteOption>
207    {
208  * \endcode
209  *
210  * All public functions in this class return \c *this casted to a reference to
211  * \p U.  They do not throw.
212  *
213  * For examples of how to use classes derived from this class, see the class
214  * documentation for Options.
215  *
216  * \inlibraryapi
217  * \ingroup module_options
218  */
219 template <typename T, class U>
220 class OptionTemplate : public AbstractOption
221 {
222     public:
223         //! Type that stores a single option value.
224         typedef T ValueType;
225         //! Alias for the derived class type.
226         typedef U MyClass;
227
228         /*! \brief
229          * Sets a description for the option.
230          *
231          * \param[in] descr Description to set.
232          *
233          * String in \p descr is copied when the option is created.
234          */
235         MyClass &description(const char *descr)
236         { setDescription(descr); return me(); }
237         //! Hides the option from normal help output.
238         MyClass &hidden(bool bHidden = true)
239         { setFlag(efOption_Hidden, bHidden); return me(); }
240         /*! \brief
241          * Requires the option to be specified explicitly.
242          *
243          * Note that if you specify defaultValue() together with required(),
244          * the user is not required to explicitly provide the option.
245          * In this case, required() only affects possible help output.
246          */
247         MyClass &required(bool bRequired = true)
248         { setFlag(efOption_Required, bRequired); return me(); }
249         //! Allows the option to be specified multiple times.
250         MyClass &allowMultiple(bool bMulti = true)
251         { setFlag(efOption_MultipleTimes, bMulti); return me(); }
252         //! Requires exactly \p count values for the option.
253         MyClass &valueCount(int count) { setValueCount(count); return me(); }
254         //! Allows any number of values for the option.
255         MyClass &multiValue(bool bMulti = true)
256         { if (bMulti) { maxValueCount_ = -1; } return me(); }
257
258         /*! \brief
259          * Sets a default value for the option.
260          *
261          * \param[in] defaultValue Default value.
262          *
263          * If the option is never set, the default value is copied to the
264          * assigned storage.  Note that if the option is not set and there
265          * is no default value, the storage is not altered, which can also be
266          * used to provide a default value.  The latter method has to be used
267          * if the option can take multiple values.
268          *
269          * \p defaultValue is copied when the option is created.
270          */
271         MyClass &defaultValue(const T &defaultValue)
272         { defaultValue_ = &defaultValue; return me(); }
273         /*! \brief
274          * Sets a default value for the option when it is set.
275          *
276          * \param[in] defaultValue Default value.
277          *
278          * This value is used if the option is set, but no value is provided.
279          * If the option is never set, the value set with defaultValue() is
280          * used.  Can only be used for options that accept a single value.
281          *
282          * \p defaultValue is copied when the option is created.
283          */
284         MyClass &defaultValueIfSet(const T &defaultValue)
285         { defaultValueIfSet_ = &defaultValue; return me(); }
286         /*! \brief
287          * Stores value(s) in memory pointed by \p store.
288          *
289          * \param[in] store  Storage for option value(s).
290          *
291          * The caller is responsible for allocating enough memory such that
292          * the any allowed number of values fits into the array pointed by
293          * \p store.  If there is no maximum allowed number or if the maximum
294          * is inconveniently large, storeVector() should be used.
295          *
296          * For information on when values are available in the storage, see
297          * storeVector().
298          *
299          * The pointer provided should remain valid as long as the associated
300          * Options object exists.
301          */
302         MyClass &store(T *store)
303         { store_ = store; return me(); }
304         /*! \brief
305          * Stores number of values in the value pointed by \p countptr.
306          *
307          * \param[in] countptr Storage for the number of values.
308          *
309          * For information on when values are available in the storage, see
310          * storeVector().
311          *
312          * The pointers provided should remain valid as long as the associated
313          * Options object exists.
314          */
315         MyClass &storeCount(int *countptr)
316         { countptr_ = countptr; return me(); }
317         /*! \brief
318          * Stores option values in the provided vector.
319          *
320          * \param[in] store  Vector to store option values in.
321          *
322          * Values are added to the vector after each successful set of values
323          * is parsed.  Note that for some options, the value may be changed
324          * later, and is only guaranteed to be correct after Options::finish()
325          * has been called.
326          *
327          * The pointer provided should remain valid as long as the associated
328          * Options object exists.
329          */
330         MyClass &storeVector(std::vector<T> *store)
331         { storeVector_ = store; return me(); }
332
333     protected:
334         /*! \cond libapi */
335         //! Alias for the template class for use in base classes.
336         typedef OptionTemplate<T, U> MyBase;
337
338         //! Initializes the name and default values for an option.
339         explicit OptionTemplate(const char *name)
340             : AbstractOption(name),
341               defaultValue_(NULL), defaultValueIfSet_(NULL), store_(NULL),
342               countptr_(NULL), storeVector_(NULL)
343         { }
344
345         /*! \brief
346          * Returns a pointer to user-specified default value, or NULL if there
347          * is none.
348          */
349         const T *defaultValue() const { return defaultValue_; }
350         /*! \brief
351          * Returns a pointer to user-specified default value, or NULL if there
352          * is none.
353          */
354         const T *defaultValueIfSet() const { return defaultValueIfSet_; }
355         //! Returns \p *this casted into MyClass to reduce typing.
356         MyClass &me() { return static_cast<MyClass &>(*this); }
357         //! \endcond
358
359     private:
360         const T                *defaultValue_;
361         const T                *defaultValueIfSet_;
362         T                      *store_;
363         int                    *countptr_;
364         std::vector<T>         *storeVector_;
365
366         /*! \brief
367          * Needed to initialize storage from this class without otherwise
368          * unnecessary accessors.
369          */
370         friend class OptionStorageTemplate<T>;
371 };
372
373 /*! \brief
374  * Gives information and allows modifications to an option after creation.
375  *
376  * When an option is added with Options::addOption(), an object of a subclass
377  * of OptionInfo is returned.  This object can be later used to access
378  * information about the option.  Non-const methods also allow later changing
379  * (some of) the option settings provided at initialization time.
380  * The properties accessible/modifiable through this interface are implemented
381  * based on need, and may not be implemented for all cases.
382  *
383  * \if libapi
384  * This class is also used by OptionsVisitor and OptionsModifyingVisitor as
385  * the interface that allows querying/modifying each visited option.
386  * \endif
387  *
388  * This class isolates the details of the internal option implementation from
389  * callers.  Although this class is a simple reference to the underlying
390  * implementation, it is implemented as non-copyable to allow const/non-const
391  * status of a reference to this class to indicate whether modifications are
392  * allowed.  Otherwise, separate classes would be needed for access and
393  * modification, complicating the implementation.  In the implementation,
394  * there is always a single OptionInfo instance referring to one option.
395  * The underlying implementation object always owns this instance, and only
396  * references are passed to callers.
397  *
398  * \see Options::addOption()
399  * \if libapi
400  * \see OptionsVisitor
401  * \see OptionsModifyingVisitor
402  * \endif
403  *
404  * \inpublicapi
405  * \ingroup module_options
406  */
407 class OptionInfo
408 {
409     public:
410         virtual ~OptionInfo();
411
412         /*! \brief
413          * Test whether the option is of a particular type.
414          *
415          * \tparam InfoType  Option type to test for. Should be a class derived
416          *      from OptionInfo.
417          */
418         template <class InfoType>
419         bool isType() const
420         {
421             return toType<InfoType>() != NULL;
422         }
423         /*! \brief
424          * Convert the info object to a particular type if the type is correct.
425          *
426          * \tparam InfoType  Option type to convert to. Should be a class
427          *      derived from OptionInfo.
428          * \retval this converted to a pointer to \p InfoType, or NULL if the
429          *      conversion is not possible.
430          */
431         template <class InfoType>
432         InfoType *toType()
433         {
434             return dynamic_cast<InfoType *>(this);
435         }
436         //! \copydoc toType()
437         template <class InfoType>
438         const InfoType *toType() const
439         {
440             return dynamic_cast<const InfoType *>(this);
441         }
442
443         //! Returns true if the option has been set.
444         bool isSet() const;
445         //! Returns true if the option is a hidden option.
446         bool isHidden() const;
447         //! Returns true if the option is required.
448         bool isRequired() const;
449         //! Returns the minimum number of values that this option accepts.
450         int minValueCount() const;
451         //! Returns the maximum number of values that this option accepts.
452         int maxValueCount() const;
453         //! Returns the name of the option.
454         const std::string &name() const;
455         //! Returns the type of the option as a string.
456         std::string type() const;
457         //! Returns the description of the option.
458         std::string formatDescription() const;
459         /*! \brief
460          * Returns the default value if set for the option as a string.
461          *
462          * \see OptionTemplate::defaultValueIfSet()
463          */
464         std::string formatDefaultValueIfSet() const;
465
466         //! Returns the number of values given for the option.
467         int valueCount() const;
468         //! Returns the i'th value of the option as a string.
469         std::string formatValue(int i) const;
470
471     protected:
472         /*! \cond libapi */
473         /*! \brief
474          * Wraps a given option object.
475          *
476          * Does not throw.
477          */
478         explicit OptionInfo(AbstractOptionStorage *option);
479
480         //! Returns the wrapped option storage object.
481         AbstractOptionStorage       &option() { return option_; }
482         //! Returns the wrapped option storage object.
483         const AbstractOptionStorage &option() const { return option_; }
484         //! \endcond
485
486     private:
487         //! The wrapped option.
488         AbstractOptionStorage  &option_;
489
490         GMX_DISALLOW_COPY_AND_ASSIGN(OptionInfo);
491 };
492
493 } // namespace gmx
494
495 #endif