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