Apply clang-format-11
[alexxy/gromacs.git] / src / gromacs / options / optionstoragetemplate.h
1 /*
2  * This file is part of the GROMACS molecular simulation package.
3  *
4  * Copyright (c) 2010-2018, The GROMACS development team.
5  * Copyright (c) 2019,2020,2021, by the GROMACS development team, led by
6  * Mark Abraham, David van der Spoel, Berk Hess, and Erik Lindahl,
7  * and including many others, as listed in the AUTHORS file in the
8  * top-level source directory and at http://www.gromacs.org.
9  *
10  * GROMACS is free software; you can redistribute it and/or
11  * modify it under the terms of the GNU Lesser General Public License
12  * as published by the Free Software Foundation; either version 2.1
13  * of the License, or (at your option) any later version.
14  *
15  * GROMACS is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  * Lesser General Public License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public
21  * License along with GROMACS; if not, see
22  * http://www.gnu.org/licenses, or write to the Free Software Foundation,
23  * Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA.
24  *
25  * If you want to redistribute modifications to GROMACS, please
26  * consider that scientific software is very special. Version
27  * control is crucial - bugs must be traceable. We will be happy to
28  * consider code for inclusion in the official distribution, but
29  * derived work must not be called official GROMACS. Details are found
30  * in the README & COPYING files - if they are missing, get the
31  * official version at http://www.gromacs.org.
32  *
33  * To help us fund GROMACS development, we humbly ask that you cite
34  * the research papers on the package. Check out http://www.gromacs.org.
35  */
36 /*! \libinternal \file
37  * \brief
38  * Defines gmx::OptionStorageTemplate template.
39  *
40  * \author Teemu Murtola <teemu.murtola@gmail.com>
41  * \inlibraryapi
42  * \ingroup module_options
43  */
44 #ifndef GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
45 #define GMX_OPTIONS_OPTIONSTORAGETEMPLATE_H
46
47 #include <memory>
48 #include <string>
49 #include <vector>
50
51 #include "gromacs/options/abstractoption.h"
52 #include "gromacs/options/abstractoptionstorage.h"
53 #include "gromacs/utility/any.h"
54 #include "gromacs/utility/arrayref.h"
55 #include "gromacs/utility/basedefinitions.h"
56 #include "gromacs/utility/exceptions.h"
57 #include "gromacs/utility/gmxassert.h"
58
59 #include "valueconverter.h"
60 #include "valuestore.h"
61
62 namespace gmx
63 {
64
65 class Options;
66
67 /*! \libinternal \brief
68  * Templated base class for constructing option value storage classes.
69  *
70  * \tparam T Assignable type that stores a single option value.
71  *
72  * Provides an implementation of the clearSet(), valueCount(), processSet(),
73  * and defaultValuesAsStrings() methods of AbstractOptionStorage, as well as a
74  * basic no-action implementation of processAll().  Two new virtual methods are
75  * added: processSetValues() and formatSingleValue().
76  * This leaves typeString(), convertValue() and formatStringValue() to be
77  * implemented in derived classes.
78  * processSetValues() and processAll() can also be implemented if necessary.
79  *
80  * Implements transaction support for adding values within a set: all calls to
81  * addValue() add the value to a temporary storage, processSetValues() operates
82  * on this temporary storage, and commitValues() then copies these values to
83  * the real storage.  commitValues() provides a strong exception safety
84  * guarantee for the process (and it only throws if it runs out of memory).
85  *
86  * \inlibraryapi
87  * \ingroup module_options
88  */
89 template<typename T>
90 class OptionStorageTemplate : public AbstractOptionStorage
91 {
92 public:
93     //! Alias for the template class for use in base classes.
94     typedef OptionStorageTemplate<T> MyBase;
95     //! Type of the container that contains the current values.
96     typedef std::vector<T> ValueList;
97
98     // No implementation in this class for the pure virtual methods, but
99     // the declarations are still included for clarity.
100     // The various copydoc calls are needed with Doxygen 1.8.10, although
101     // things work without with 1.8.5...
102     std::string typeString() const override = 0;
103     //! \copydoc gmx::AbstractOptionStorage::valueCount()
104     int valueCount() const override { return store_->valueCount(); }
105     //! \copydoc gmx::AbstractOptionStorage::defaultValues()
106     std::vector<Any> defaultValues() const override;
107     /*! \copydoc gmx::AbstractOptionStorage::defaultValuesAsStrings()
108      *
109      * OptionStorageTemplate implements handling of defaultValueIfSet()
110      * cases and composing the vector.
111      * Derived classes must implement formatSingleValue() to provide the
112      * actual formatting for a value of type \p T.
113      */
114     std::vector<std::string> defaultValuesAsStrings() const override;
115
116 protected:
117     //! Smart pointer for managing the final storage interface.
118     typedef std::unique_ptr<IOptionValueStore<T>> StorePointer;
119
120     /*! \brief
121      * Initializes the storage from option settings.
122      *
123      * \param[in] settings  Option settings.
124      * \param[in] staticFlags Option flags that are always set and specify
125      *      generic behavior of the option.
126      * \throws  APIError if invalid settings have been provided.
127      */
128     template<class U>
129     explicit OptionStorageTemplate(const OptionTemplate<T, U>& settings,
130                                    OptionFlags                 staticFlags = OptionFlags());
131     /*! \brief
132      * Initializes the storage from base option settings.
133      *
134      * \param[in] settings  Option settings.
135      * \param[in] store     Final storage location.
136      * \throws  APIError if invalid settings have been provided.
137      *
138      * This constructor works for cases where there is no matching
139      * OptionTemplate (e.g., EnumOption).
140      */
141     OptionStorageTemplate(const AbstractOption& settings, StorePointer store);
142
143     //! \copydoc gmx::AbstractOptionStorage::clearSet()
144     void clearSet() override;
145     /*! \copydoc gmx::AbstractOptionStorage::convertValue()
146      *
147      * Derived classes should call addValue() after they have converted
148      * \p value to the storage type.  It is allowed to call addValue()
149      * more than once, or not at all.  OptionsAssigner::appendValue()
150      * provides the same exception safety guarantee as this method, so it
151      * should be considered whether the implementation can be made strongly
152      * exception safe.
153      */
154     void convertValue(const Any& value) override = 0;
155     /*! \brief
156      * Processes values for a set after all have been converted.
157      *
158      * \param[in,out] values Valid values in the set.
159      * \throws InvalidInputError if the values do not form a valid set.
160      *
161      * This method is called after all convertValue() calls for a set.
162      * \p values contains all values that were validly converted by
163      * convertValue().  The derived class may alter the values, but should
164      * in such a case ensure that a correct number of values is produced.
165      * If the derived class throws, all values in \p values are discarded.
166      */
167     virtual void processSetValues(ValueList* values) { GMX_UNUSED_VALUE(values); }
168     /*! \copydoc gmx::AbstractOptionStorage::processSet()
169      *
170      * OptionStorageTemplate implements transaction support for a set of
171      * values in this method (see the class description), and provides a
172      * more detailed processSetValues() method that can be overridden in
173      * subclasses to process the actual values.  Derived classes should
174      * override that method instead of this one if set value processing is
175      * necessary.
176      */
177     void processSet() override;
178     /*! \copydoc gmx::AbstractOptionStorage::processAll()
179      *
180      * The implementation in OptionStorageTemplate does nothing.
181      */
182     void processAll() override {}
183     /*! \brief
184      * Formats a single value as a string.
185      *
186      * \param[in] value  Value to format.
187      * \returns   \p value formatted as a string.
188      *
189      * The derived class must provide this method to format values a
190      * strings.  Called by defaultValuesAsStrings() to do the actual
191      * formatting.
192      */
193     virtual std::string formatSingleValue(const T& value) const = 0;
194
195     /*! \brief
196      * Adds a value to a temporary storage.
197      *
198      * \param[in] value  Value to add. A copy is made.
199      * \throws std::bad_alloc if out of memory.
200      * \throws InvalidInputError if the maximum value count has been reached.
201      *
202      * Derived classes should call this function from the convertValue()
203      * implementation to add converted values to the storage.
204      * If the maximum value count has been reached, the value is discarded
205      * and an exception is thrown.
206      *
207      * If adding values outside convertValue() (e.g., to set a custom
208      * default value), derived classes should call clearSet() before adding
209      * values (unless in the constructor) and commitValues() once all
210      * values are added.
211      */
212     void addValue(const T& value);
213     /*! \brief
214      * Commits values added with addValue().
215      *
216      * \throws std::bad_alloc if out of memory.
217      *
218      * If this function succeeds, values added with addValue() since the
219      * previous clearSet() are added to the storage for the option.
220      * Only throws in out-of-memory conditions, and provides the strong
221      * exception safety guarantee as long as the copy constructor of `T`
222      * does not throw.
223      *
224      * See addValue() for cases where this method should be used in derived
225      * classes.
226      *
227      * Calls clearSet() if it is successful.
228      */
229     void commitValues();
230
231     /*! \brief
232      * Sets the default value for the option.
233      *
234      * \param[in] value  Default value to set.
235      * \throws    std::bad_alloc if out of memory.
236      *
237      * This method can be used from the derived class constructor to
238      * programmatically set a default value.
239      */
240     void setDefaultValue(const T& value);
241     /*! \brief
242      * Sets the default value if set for the option.
243      *
244      * \param[in] value  Default value to set.
245      * \throws    std::bad_alloc if out of memory.
246      *
247      * This method can be used from the derived class constructor to
248      * programmatically set a default value.
249      */
250     void setDefaultValueIfSet(const T& value);
251
252     /*! \brief
253      * Provides derived classes access to the current list of values.
254      *
255      * The non-const any should only be used from processAll() in
256      * derived classes if necessary.
257      */
258     ArrayRef<T> values() { return store_->values(); }
259     //! Provides derived classes access to the current list of values.
260     ArrayRef<const T> values() const { return store_->values(); }
261
262 private:
263     //! Creates the internal storage object for final values..
264     StorePointer createStore(ValueList* storeVector, T* store, int* storeCount, int initialCount);
265
266     /*! \brief
267      * Vector for temporary storage of values before commitSet() is called.
268      */
269     ValueList setValues_;
270     //! Final storage for option values.
271     const StorePointer store_;
272     // This never releases ownership.
273     std::unique_ptr<T> defaultValueIfSet_;
274
275     // Copy and assign disallowed by base.
276 };
277
278
279 /*! \libinternal \brief
280  * Simplified option storage template for options that have one-to-one value
281  * conversion.
282  *
283  * \tparam T Assignable type that stores a single option value.
284  *
285  * To implement an option that always map a single input value to a single
286  * output value, derive from this class instead of OptionStorageTemplate.
287  * This class implements convertValue() in terms of two new virtual methods:
288  * initConverter() and processValue().
289  *
290  * To specify how different types of values need to be converted, implement
291  * initConverter().
292  * To do common post-processing of the values after conversion, but before they
293  * are added to the underlying storage, override processValue().
294  *
295  * \inlibraryapi
296  * \ingroup module_options
297  */
298 template<typename T>
299 class OptionStorageTemplateSimple : public OptionStorageTemplate<T>
300 {
301 public:
302     //! Alias for the template class for use in base classes.
303     typedef OptionStorageTemplateSimple<T> MyBase;
304
305 protected:
306     //! Alias for the converter parameter type for initConverter().
307     typedef OptionValueConverterSimple<T> ConverterType;
308
309     //! Initializes the storage.
310     template<class U>
311     explicit OptionStorageTemplateSimple(const OptionTemplate<T, U>& settings,
312                                          OptionFlags                 staticFlags = OptionFlags()) :
313         OptionStorageTemplate<T>(settings, staticFlags), initialized_(false)
314     {
315     }
316     //! Initializes the storage.
317     OptionStorageTemplateSimple(const AbstractOption&                           settings,
318                                 typename OptionStorageTemplate<T>::StorePointer store) :
319         OptionStorageTemplate<T>(settings, std::move(store)), initialized_(false)
320     {
321     }
322
323     std::vector<Any> normalizeValues(const std::vector<Any>& values) const override
324     {
325         const_cast<MyBase*>(this)->ensureConverterInitialized();
326         std::vector<Any> result;
327         result.reserve(values.size());
328         for (const auto& value : values)
329         {
330             result.push_back(normalizeValue(converter_.convert(value)));
331         }
332         return result;
333     }
334
335     /*! \brief
336      * Specifies how different types are converted.
337      *
338      * See OptionValueConverterSimple for more details.
339      */
340     virtual void initConverter(ConverterType* converter) = 0;
341     /*! \brief
342      * Post-processes a value after conversion to the output type.
343      *
344      * \param[in] value  Value after conversion.
345      * \returns   Value to store for the option.
346      *
347      * The default implementation only provides an identity mapping.
348      */
349     virtual T processValue(const T& value) const { return value; }
350     /*! \brief
351      * Converts a single value to normalized type.
352      *
353      * \param[in] value  Value after conversion.
354      * \returns   Value to store for the option.
355      *
356      * This can be overridden to serialize a different type than `T`
357      * when using the option with KeyValueTreeObject.
358      */
359     virtual Any normalizeValue(const T& value) const { return Any::create<T>(processValue(value)); }
360
361 private:
362     void convertValue(const Any& any) override
363     {
364         ensureConverterInitialized();
365         this->addValue(processValue(converter_.convert(any)));
366     }
367     void ensureConverterInitialized()
368     {
369         if (!initialized_)
370         {
371             initConverter(&converter_);
372             initialized_ = true;
373         }
374     }
375
376     ConverterType converter_;
377     bool          initialized_;
378 };
379
380
381 /********************************************************************
382  * OptionStorageTemplate implementation
383  */
384
385 template<typename T>
386 template<class U>
387 OptionStorageTemplate<T>::OptionStorageTemplate(const OptionTemplate<T, U>& settings,
388                                                 OptionFlags                 staticFlags) :
389     AbstractOptionStorage(settings, staticFlags),
390     store_(createStore(settings.storeVector_,
391                        settings.store_,
392                        settings.countptr_,
393                        (settings.isVector() ? settings.maxValueCount_ : settings.minValueCount_)))
394 {
395     if (hasFlag(efOption_NoDefaultValue)
396         && (settings.defaultValue_ != nullptr || settings.defaultValueIfSet_ != nullptr))
397     {
398         GMX_THROW(APIError("Option does not support default value, but one is set"));
399     }
400     if (!hasFlag(efOption_NoDefaultValue))
401     {
402         setFlag(efOption_HasDefaultValue);
403         if (settings.defaultValue_ != nullptr)
404         {
405             setDefaultValue(*settings.defaultValue_);
406         }
407         if (settings.defaultValueIfSet_ != nullptr)
408         {
409             setDefaultValueIfSet(*settings.defaultValueIfSet_);
410         }
411     }
412 }
413
414
415 template<typename T>
416 OptionStorageTemplate<T>::OptionStorageTemplate(const AbstractOption& settings, StorePointer store) :
417     AbstractOptionStorage(settings, OptionFlags()), store_(std::move(store))
418 {
419 }
420
421
422 template<typename T>
423 std::unique_ptr<IOptionValueStore<T>> OptionStorageTemplate<T>::createStore(ValueList* storeVector,
424                                                                             T*         store,
425                                                                             int* storeCount, // NOLINT(readability-non-const-parameter) passed non-const to OptionValueStorePlain
426                                                                             int initialCount)
427 {
428     if (storeVector != nullptr)
429     {
430         GMX_RELEASE_ASSERT(store == nullptr && storeCount == nullptr,
431                            "Cannot specify more than one storage location");
432         return StorePointer(new OptionValueStoreVector<T>(storeVector));
433     }
434     else if (store != nullptr)
435     {
436         // If the maximum number of values is not known, storage to
437         // caller-allocated memory is unsafe.
438         if (maxValueCount() < 0 || hasFlag(efOption_MultipleTimes))
439         {
440             GMX_THROW(APIError("Cannot set user-allocated storage for arbitrary number of values"));
441         }
442         if (storeCount == nullptr && !isVector() && minValueCount() != maxValueCount())
443         {
444             GMX_THROW(
445                     APIError("Count storage is not set, although the number of produced values is "
446                              "not known"));
447         }
448         if (hasFlag(efOption_NoDefaultValue))
449         {
450             initialCount = 0;
451         }
452         return StorePointer(new OptionValueStorePlain<T>(store, storeCount, initialCount));
453     }
454     GMX_RELEASE_ASSERT(storeCount == nullptr, "Cannot specify count storage without value storage");
455     return StorePointer(new OptionValueStoreNull<T>());
456 }
457
458
459 template<typename T>
460 std::vector<Any> OptionStorageTemplate<T>::defaultValues() const
461 {
462     std::vector<Any> result;
463     if (hasFlag(efOption_NoDefaultValue))
464     {
465         return result;
466     }
467     GMX_RELEASE_ASSERT(
468             hasFlag(efOption_HasDefaultValue),
469             "Current option implementation can only provide default values before assignment");
470     for (const auto& value : values())
471     {
472         result.push_back(Any::create<T>(value));
473     }
474     return normalizeValues(result);
475 }
476
477
478 template<typename T>
479 std::vector<std::string> OptionStorageTemplate<T>::defaultValuesAsStrings() const
480 {
481     std::vector<std::string> result;
482     if (hasFlag(efOption_NoDefaultValue))
483     {
484         return result;
485     }
486     GMX_RELEASE_ASSERT(
487             hasFlag(efOption_HasDefaultValue),
488             "Current option implementation can only provide default values before assignment");
489     for (const auto& value : values())
490     {
491         result.push_back(formatSingleValue(value));
492     }
493     if (result.empty() || (result.size() == 1 && result[0].empty()))
494     {
495         result.clear();
496         if (defaultValueIfSet_ != nullptr)
497         {
498             result.push_back(formatSingleValue(*defaultValueIfSet_));
499         }
500     }
501     return result;
502 }
503
504
505 template<typename T>
506 void OptionStorageTemplate<T>::clearSet()
507 {
508     setValues_.clear();
509 }
510
511
512 template<typename T>
513 void OptionStorageTemplate<T>::processSet()
514 {
515     processSetValues(&setValues_);
516     if (setValues_.empty() && defaultValueIfSet_ != nullptr)
517     {
518         addValue(*defaultValueIfSet_);
519         setFlag(efOption_HasDefaultValue);
520     }
521     else
522     {
523         clearFlag(efOption_HasDefaultValue);
524     }
525     if (!hasFlag(efOption_DontCheckMinimumCount)
526         && setValues_.size() < static_cast<size_t>(minValueCount()))
527     {
528         GMX_THROW(InvalidInputError("Too few (valid) values"));
529     }
530     commitValues();
531 }
532
533
534 template<typename T>
535 void OptionStorageTemplate<T>::addValue(const T& value)
536 {
537     if (maxValueCount() >= 0 && setValues_.size() >= static_cast<size_t>(maxValueCount()))
538     {
539         GMX_THROW(InvalidInputError("Too many values"));
540     }
541     setValues_.push_back(value);
542 }
543
544 template<typename T>
545 void OptionStorageTemplate<T>::commitValues()
546 {
547     if (hasFlag(efOption_ClearOnNextSet))
548     {
549         store_->clear();
550     }
551     store_->reserve(setValues_.size());
552     // For bool the loop variable isn't a reference (it's its special reference type)
553     // clang-format off
554     CLANG_DIAGNOSTIC_IGNORE(-Wrange-loop-analysis);
555     // clang-format on
556     for (const auto& value : setValues_)
557     {
558         store_->append(value);
559     }
560     CLANG_DIAGNOSTIC_RESET;
561     clearSet();
562 }
563
564 template<typename T>
565 void OptionStorageTemplate<T>::setDefaultValue(const T& value)
566 {
567     if (hasFlag(efOption_NoDefaultValue))
568     {
569         GMX_THROW(APIError("Option does not support default value, but one is set"));
570     }
571     if (hasFlag(efOption_HasDefaultValue))
572     {
573         setFlag(efOption_ExplicitDefaultValue);
574         store_->clear();
575         store_->append(value);
576     }
577 }
578
579
580 template<typename T>
581 void OptionStorageTemplate<T>::setDefaultValueIfSet(const T& value)
582 {
583     if (hasFlag(efOption_NoDefaultValue))
584     {
585         GMX_THROW(APIError("Option does not support default value, but one is set"));
586     }
587     if (hasFlag(efOption_MultipleTimes))
588     {
589         GMX_THROW(APIError("defaultValueIfSet() is not supported with allowMultiple()"));
590     }
591     setFlag(efOption_DefaultValueIfSetExists);
592     defaultValueIfSet_ = std::make_unique<T>(value);
593 }
594
595 } // namespace gmx
596
597 #endif