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