root/library/bdm/base/user_info.h @ 544

Revision 544, 22.9 kB (checked in by vbarta, 15 years ago)

corrected dynamic memory handling in UI::from_setting, more UIException tests

  • Property svn:eol-style set to native
Line 
1/*!
2  \file
3  \brief UI (user info) class for loading/saving objects from/to configuration files.
4  It is designed with use of libconfig C/C++ Configuration File Library
5  \ref ui_page
6  \author Vaclav Smidl.
7
8  -----------------------------------
9  BDM++ - C++ library for Bayesian Decision Making under Uncertainty
10
11  Using IT++ for numerical operations
12  -----------------------------------
13*/
14
15#ifndef USER_INFO_H
16#define USER_INFO_H
17
18#include <stdio.h>
19#include <string>
20#include <typeinfo>
21#include <map>
22#include <stdexcept>
23
24#include "libconfig/libconfig.h++"
25#include "../bdmroot.h"
26#include "../shared_ptr.h"
27#include "itpp/itbase.h"
28
29
30using std::string;
31using namespace std;
32using namespace libconfig;
33
34namespace bdm {
35
36//! Generic exception for reporting configuration errors
37//!
38//!  \ref ui_page
39class UIException : public std::exception {
40private:
41        //! Error message
42        const string message;
43
44public:
45        /*!
46          \brief The constructor
47          \param message the reason for throwing the exception. Should be a complete English sentence (or a couple sentences), starting with "UIException: ".
48        */
49        UIException ( const string &message ) :
50                message ( message ) {
51        }
52
53        //! Overriden method for reporting the error message
54        virtual const char* what() const throw() {
55                return message.c_str();
56        }
57
58        ~UIException() throw() {};
59
60protected:
61        /*!
62          Formats error messages for derived classes, which use a
63          Setting path in addition to the message.
64        */
65        static string format_message( const string &reason, const string &path );
66};
67
68//! Exception for reporting configuration errors related to some concrete Setting path
69//!
70//!  \ref ui_page
71class UISettingException : public UIException {
72public:
73        //! Use this constructor when you can pass the problematical Setting as a parameter
74        UISettingException ( const string &message, const Setting &element ):
75                UIException ( format_message ( message, string ( element.getPath() ) ) ) {
76        }
77
78        //! This constructor is for other occasions, when only path of problematical Setting is known
79        UISettingException ( const string &message, const string &path ):
80                UIException ( format_message ( message, path ) ) {
81        }
82
83        ~UISettingException() throw() {};
84};
85
86//! Exception for reporting configuration errors in the "class" attribute
87//!
88//!  \ref ui_page
89class UIClassException : public UIException {
90public:
91        //! Use this constructor when you can pass the problematical Setting as a parameter
92        UIClassException ( const string &message, const Setting &element ):
93                UIException ( format_message ( message, string ( element.getPath() ) ) ) {
94        }
95
96        //! This constructor is for other occasions, when only path of problematical Setting is known
97        UIClassException ( const string &message, const string &path ):
98                UIException ( format_message ( message, path ) ) {
99        }
100
101        ~UIClassException() throw() {};
102};
103
104/*!
105@brief This class serves to load and/or save user-infos into/from
106configuration files stored on a hard-disk.
107
108Firstly, save some user-infos into the new UIFile instance. Then,
109call the save method with a filename as its only argument:
110
111\code
112        CAudi audi;
113        UIFile file;
114        UI::save( audi, file, "TT");
115        file.save("cars.cfg");
116\endcode
117
118In the other way round, when loading object from a configuration file,
119the appropriate code looks like this:
120
121\code
122        UIFile file("cars.cfg");
123        CAudi *audi = UI::build<CAudi>(file,"TT");
124\endcode
125
126\ref ui_page
127*/
128class UIFile : public Config {
129public:
130        //! Create empty file instance prepared to store Settings
131        UIFile();
132
133        //! Creates instance and fills it from the configuration file file_name
134        UIFile ( const string &file_name );
135
136        //! Save all the stored Settings into the configuration file file_name
137        void save ( const string &file_name );
138
139        //! This operator allows the ability of substituting Setting parameter by UIFile instance
140        operator Setting&();
141};
142
143/*!
144@brief This class serves to expand links used within configuration files.
145
146Value of any type but string can be linked to some other value of the same type
147defined elsewhere in the current configuration file or even in some different
148configuration file.
149
150Link have three parts, \<name\> : \<path\> \<\@filename\>. Field \<name\> contains the
151name of the new setting, \<path\> is the relative path to the referenced setting, which
152has to be taken from the %root Setting element. The last part \<\@filename\> is optional,
153it contains filename in the case the link should refer to a variable stored in a different
154file. From the previous part \<path\>, it has to be separated by '@'.
155
156\code
157    ...
158        jardovo :
159        {
160          class = "Car";
161          year = 1992;
162          manufacturer = "liaz";
163          kilometers = 1555000;
164        };
165        ondrejovo :
166        {
167          class = "Bike";
168          year = 1996;
169          manufacturer = "author";
170          electricLights = true;
171          matr = ( 2, 2, [ 1.0, 0.0, 0.0, 1.0 ] );
172        };
173
174        #this is the example of local link to another mean of transport
175        elisky = "jardovo";
176
177        ...
178
179        # And this link is external link pointing to the file "other_cars.cfg" stored in the
180        # same directory. In that file, it refers to the local Setting "magic_cars.skubankovo".
181        kati = "magic_cars.skubankovo@other_cars.cfg";
182
183    ...
184\endcode
185
186When you want to expand a possible linked setting "element" within your code, it has to be treated this way:
187
188\code
189        ...
190
191        const SettingResolver link( element );
192
193        ...
194
195        int len = link.result.getLength();
196
197        ...
198\endcode
199
200The whole point is that a resolved link (class member #result, i.e., "link.result" in the previous example) could point
201into a different configuration file. In that case there has to be an UIFile instance managing reading from this
202file. As the libconfig::Config deletes all its Settings when dealocated, UIFile must not be dealocated until all
203the necessary operation on the linked Setting are finished (otherwise, the link #result would be invalid just after
204the UIFile dealocation). And that is exactly the mechanism implemented within SettingResolver class. It assures,
205that the #result Setting reference is valid within the scope of SettingResolver instance.
206
207\ref ui_page
208 */
209class SettingResolver : root {
210private:
211        //! If necessary, this pointer stores an addres of an opened UIFile, else it equals NULL
212        UIFile *file;
213
214        //! This method initialize #result reference, i.e., it executes the main code of SettingResolver class
215        //!
216        //! This code could be also located directly in constructor. The only reason why we made this
217        //! method is the keyword 'const' within the declaration of #result reference . Such a reference
218        //! have to be intialized before any other constructor command, exactly in the way it is implemented now.
219        const Setting &initialize_reference ( UIFile* &file, const Setting &potential_link );
220
221public:
222        //! Reference to a resolved link or to the original Setting in the case it does not contain a link
223        const Setting &result;
224
225        //! If potential_link contains a link to some other setting, it is resolved here. Anyway, the Setting reference #result is prepared for use.
226        SettingResolver ( const Setting &potential_link );
227
228        //! An opened UIFile file is closed here if necessary.
229        ~SettingResolver();
230};
231
232/*!
233@brief UI is an abstract class which collects all the auxiliary functions useful to prepare some concrete
234user-infos.
235
236See static methods 'build', 'get' and 'save'. Writing user-infos with these methods is rather  simple. The
237rest of this class is intended for internal purposes only. Its meaning is to allow pointers to its templated
238descendant ParticularUI<T>.
239
240\ref ui_page
241*/
242class UI {
243private:
244        //! Class with state shared across all its instances ("monostate"), encapsulating two maps, one mapping names to UI instances and the other mapping type_infos to class names
245        //!
246        //! The key property of this class is that it initializes the internal maps on global init,
247        //! before the instance is used for a first time. Therefore, we do not have to care about initialization
248        //! during a call of UIREGISTER macro operating with both these mappings.
249        class MappedUI {
250        private:
251                //! Type definition of mapping which transforms class names to the related UI instances
252                typedef map< const string, const UI* const > StringToUIMap;
253
254                //! Type definition of mapping which transforms RTTI type_infos to the related class names
255                typedef map< const type_info * const, const string > TypeInfoToStringMap;
256
257                //! Immediately initialized instance of type StringToUIMap
258                static StringToUIMap& mapped_strings();
259
260                //! Immediately initialized instance of type TypeInfoToStringMap
261                static TypeInfoToStringMap& mapped_type_infos();
262
263                //! Method for reporting a error when an attempt to operate with an unregistered class occures
264                static void unregistered_class_error ( const string &unregistered_class_name );
265
266        public:
267                //! Add a pair key-userinfo into the internal map
268                static void add_class ( const string &class_name, const type_info * const class_type_info, const UI* const ui );
269
270                //! Search for an userinfo related to the passed class name within the internal map
271                static const UI& retrieve_ui ( const string &class_name );
272
273                //! Search for an class name related to the passed type_info within the internal map
274                static const string& retrieve_class_name ( const type_info* const class_type_info );
275        };
276
277        //! Function assertting that the setting element is of the SettingType type
278        static void assert_type ( const Setting &element, Setting::Type type );
279
280        /*!
281          \brief Method constructing a configured instance
282
283          The returned pointer must be allocated using operator new
284          (it's deleted at the end of its life cycle). The method is
285          implemented in descendant class ParticularUI<T>, which knows
286          the correct type T.
287        */
288        virtual root* new_instance() const = 0;
289
290        //! Method switching from the \a element to its child Setting according the passed \a index, it also does all the necessary error-checking
291        static const Setting& to_child_setting ( const Setting &element, const int index );
292
293        //! Method switching from the \a element to its child Setting according the passed \a name, it also does all the necessary error-checking
294        static const Setting& to_child_setting ( const Setting &element, const string &name );
295
296        //! This method converts a Setting into a matrix
297        static void from_setting ( mat& matrix, const Setting &element );
298        //! This method converts a Setting into an integer vector
299        static void from_setting ( ivec &vector, const Setting &element );
300        //! This method converts a Setting into a string
301        static void from_setting ( string &str, const Setting &element );
302        //! This method converts a Setting into a real vector
303        static void from_setting ( vec &vector, const Setting &element );
304        //! This method converts a Setting into a integer scalar
305        static void from_setting ( int &integer, const Setting &element );
306        //! This method converts a Setting into a real scalar
307        static void from_setting ( double &real, const Setting &element );
308
309        //! This method converts a Setting into a class T descendant
310        template<class T> static void from_setting ( T* &instance, const Setting &element ) {
311                const SettingResolver link ( element );
312                assert_type ( link.result, Setting::TypeGroup );
313
314                // we get a value stored in the "class" attribute
315                string class_name;
316                if ( !link.result.lookupValue ( "class", class_name ) )
317                        throw UIClassException ( "UIException: the obligatory \"class\" identifier is missing.", link.result );
318
319                // then we find a user-info related to this type
320                const UI& related_UI = MappedUI::retrieve_ui ( class_name );
321
322                root *typeless_instance = related_UI.new_instance();
323                it_assert_debug ( typeless_instance, "UI::new_instance failed" );
324
325                instance = dynamic_cast<T*> ( typeless_instance );
326                if ( !instance ) {
327                        delete typeless_instance;
328                        throw UIClassException ( "UIException: class " + class_name + " is not a descendant of the desired output class. Try to call the UI::build<T> function with a different type parameter.", link.result );
329                }
330
331                try {
332                        instance->from_setting ( link.result );
333                } catch ( SettingException &sttng_xcptn ) {
334                        delete instance;
335                        instance = 0;
336                        string msg = "UIException: method ";
337                        msg += class_name;
338                        msg += ".from_setting(Setting&) has thrown a SettingException.";
339                        throw UISettingException(msg, sttng_xcptn.getPath());
340                } catch (...) {
341                        delete instance;
342                        instance = 0;
343                        throw;
344                }
345        }
346
347        //! This method converts a Setting into a descendant of class
348        //! T, wrapped in an instance of shared_ptr<T> .
349        template<class T>
350        static void from_setting ( shared_ptr<T> &instance, const Setting &element ) {
351                T *tmp_inst = 0;
352                from_setting ( tmp_inst, element );
353                it_assert_debug ( tmp_inst, "UI::from_setting failed" );
354                instance = tmp_inst;
355        }
356
357        //! This methods converts a Setting into a new templated array of type Array<T>
358        template<class T> static void from_setting ( Array<T> &array_to_load, const Setting &element ) {
359                const SettingResolver link ( element );
360
361                assert_type ( link.result, Setting::TypeList );
362
363                int len = link.result.getLength();
364                array_to_load.set_length ( len );
365                if ( len == 0 ) return;
366
367                for ( int i = 0; i < len; i++ )
368                        from_setting ( array_to_load ( i ), link.result[i] );
369        }
370
371        //! This is dummy version of the from_setting method for other, unsupported types. It just throws an exception.
372        //!
373        //! At the moment, this is the only way how to compile the library without obtaining the compiler error c2665.
374        //! The exception can help to find the place where the template is misused and also to correct it.
375        template<class T> static void from_setting ( T &variable_to_load, const Setting &element ) {
376                std::string msg = "UIException: from_setting is not implemented for type ";
377                msg += typeid(T).name();
378                msg += '.';
379                throw UISettingException ( msg, element );
380        }
381
382
383protected:
384        //! Constructor for internal use only, see \sa ParticularUI<T>
385        UI ( const string& class_name, const type_info * const class_type_info ) {
386                MappedUI::add_class ( class_name, class_type_info, this );
387        }
388
389public:
390
391        //! Enum type used to determine whether the data for concrete Settingis is compulsory or optional
392        enum SettingPresence { optional, compulsory } ;
393
394        //! \name Initialization of classes
395        //!@{
396        //! The type T has to be a #bdm::root descendant class
397
398        //! The new instance of type T* is constructed and initialized with values stored in the Setting element[name]
399        //!
400        //! If there is not any sub-element named #name and settingPresence is #optional, an empty shared_ptr<T> is returned. When settingPresence is #compulsory, the returned shared_ptr<T> is never empty (an exception is thrown when the object isn't found).
401        template<class T>
402        static shared_ptr<T> build ( const Setting &element, const string &name, SettingPresence settingPresence = optional ) {
403                if ( !element.exists ( name ) ) {
404                        if ( settingPresence == optional )
405                                return shared_ptr<T>();
406                        else
407                                throw UISettingException ( "UIException: the compulsory Setting named \"" + name + "\" is missing.", element );
408                }
409
410                shared_ptr<T> instance;
411                from_setting<T> ( instance, to_child_setting ( element, name ) );
412                return instance;
413        }
414
415        //! The new instance of type T* is constructed and initialized with values stored in the Setting element[index]
416        //!
417        //! If there is not any sub-element indexed by #index, and settingPresence is #optional, an empty shared_ptr<T> is returned. When settingPresence is #compulsory, the returned shared_ptr<T> is never empty (an exception is thrown when the object isn't found).
418        template<class T>
419        static shared_ptr<T> build ( const Setting &element, const int index, SettingPresence settingPresence = optional ) {
420                if ( element.getLength() <= index ) {
421                        if ( settingPresence == optional )
422                                return shared_ptr<T>();
423                        else {
424                                stringstream stream;
425                                stream << index;
426                                throw UISettingException ( "UIException: the compulsory Setting with the index " + stream.str() + " is missing.", element );
427                        }
428                }
429
430                shared_ptr<T> instance;
431                from_setting<T> ( instance, to_child_setting ( element, index ) );
432                return instance;
433        }
434
435        //!@}
436
437        //! \name Initialization of structures
438        //!@{
439        //! The type T has to be int, double, string, vec, ivec or mat.
440
441        //! The existing instance of type T is initialized with values stored in the Setting element[name]
442        //! If there is not any sub-element named #name, this method returns false.
443        template<class T> static bool get ( T &instance, const Setting &element, const string &name, SettingPresence settingPresence = optional ) {
444                if ( !element.exists ( name ) ) {
445                        if ( settingPresence == optional )
446                                return false;
447                        else
448                                throw UISettingException ( "UIException: the compulsory Setting named \"" + name + "\" is missing.", element );
449                }
450
451                from_setting ( instance, to_child_setting ( element, name ) );
452                return true;
453        }
454
455        //! The existing instance of type T is initialized with values stored in the Setting element[index]
456        //! If there is not any sub-element indexed by #index, this method returns false.
457        template<class T> static bool get ( T &instance, const Setting &element, const int index, SettingPresence settingPresence = optional ) {
458                if ( element.getLength() <= index ) {
459                        if ( settingPresence == optional )
460                                return false;
461                        else {
462                                stringstream stream;
463                                stream << "UIException: the compulsory Setting with the index " << index << " is missing.";
464                                stream << index;
465                                throw UISettingException (stream.str(), element );
466                        }
467                }
468
469                from_setting ( instance, to_child_setting ( element, index ) );
470                return true;
471        }
472
473        //! The existing instance of type T is initialized with values stored in the Setting element directly
474        template<class T> static bool get ( T &instance, const Setting &element ) {
475                from_setting ( instance, element );
476                return true;
477        }
478        //!@}
479
480        //! \name Initialization of arrays Array<T>
481        //!@{
482        //! The type T has to be int, double, string, vec, ivec or mat, or pointer to any root descendant.
483
484        //! The existing array of type T is initialized with values stored in the Setting element[name]
485        //! If there is not any sub-element named #name, this method returns false.
486        template<class T> static bool get ( Array<T> &array_to_load, const Setting &element, const string &name, SettingPresence settingPresence = optional ) {
487                if ( !element.exists ( name ) )
488                        return false;
489
490                from_setting ( array_to_load, to_child_setting ( element, name ) );
491                return true;
492        }
493
494        //! The existing array of type T is initialized with values stored in the Setting element[index]
495        //! If there is not any sub-element indexed by #index, this method returns false.
496        template<class T> static bool get ( Array<T> &array_to_load, const Setting &element, const int index, SettingPresence settingPresence = optional ) {
497                if ( element.getLength() <= index )
498                        return false;
499
500                from_setting ( array_to_load, to_child_setting ( element, index ) );
501                return true;
502        }
503
504        //! The existing array of type T is initialized with values stored in the Setting element
505        template<class T> static bool get ( Array<T> &array_to_load, const Setting &element ) {
506                from_setting ( array_to_load, element );
507                return true;
508        }
509        //!@}
510
511        //! \name Serialization of objects and structures into a new Setting
512        //!@{
513        //! The new child Setting can be accessed either by its name - if some name is passed as a parameter -
514        //! or by its integer index. In that case, the new element is added at the very end of the current list of child Settings.
515
516        //! A root descendant instance is stored in the new child Setting appended to the passed element
517        template< class T> static void save ( const T * const instance, Setting &element, const string &name = "" ) {
518                Setting &set = ( name == "" ) ? element.add ( Setting::TypeGroup )
519                               : element.add ( name, Setting::TypeGroup );
520
521                const string &class_name = MappedUI::retrieve_class_name ( &typeid ( *instance ) );
522
523                // add attribute "class"
524                Setting &type = set.add ( "class", Setting::TypeString );
525                type = class_name;
526
527                try {
528                        instance->to_setting ( set );
529                } catch ( SettingException &sttng_xcptn ) {
530                        string msg = "UIException: method ";
531                        msg += class_name;
532                        msg += ".to_setting(Setting&) has thrown a SettingException.";
533                        throw UISettingException(msg, sttng_xcptn.getPath());
534                }
535        }
536
537        template< class T> static void save ( const shared_ptr<T> &instance, Setting &element, const string &name = "" ) {
538                save<T> ( instance.get(), element, name );
539        }
540
541        //! An Array<T> instance is stored in the new child Setting appended to the passed element
542        template<class T> static void save ( const Array<T> &array_to_save, Setting &element, const string &name = "" ) {
543                assert_type ( element, Setting::TypeGroup );
544                Setting &list = ( name == "" ) ? element.add ( Setting::TypeList )
545                                : element.add ( name, Setting::TypeList );
546                for ( int i = 0; i < array_to_save.length(); i++ )
547                        save ( array_to_save ( i ), list );
548        }
549
550        //! A matrix(of type mat) is stored in the new child Setting appended to the passed element
551        static void save ( const mat &matrix, Setting &element, const string &name = "" );
552
553        //! An integer vector (of type ivec) is stored in the new child Setting appended to the passed element
554        static void save ( const ivec &vec, Setting &element, const string &name = "" );
555
556        //! A double vector (of type vec) is stored in the new child Setting appended to the passed element
557        static void save ( const vec &vector, Setting &element, const string &name = "" );
558
559        //! A string is stored in the new child Setting appended to the passed element
560        static void save ( const string &str, Setting &element, const string &name = "" );
561
562        //! An integer is stored in the new child Setting appended to the passed element
563        static void save ( const int &integer, Setting &element, const string &name = "" );
564
565        //! A double is stored in the new child Setting appended to the passed element
566        static void save ( const double &real, Setting &element, const string &name = "" );
567        //!@}
568
569};
570
571
572//! The only UI descendant class which is not intended for direct use. It should be accessed within the UIREGISTER macro only.
573//! \ref ui_page
574template<typename T> class ParticularUI : private UI {
575public:
576        //! Constructor used by the UIREGISTER macro.
577        ParticularUI<T> ( const string &class_name ) : UI ( class_name, &typeid ( T ) ) {};
578
579        //! A method returning a brand new instance of class T, this method is the reason why there have to be a parameterless constructor in class T
580        root* new_instance() const {
581                return new T();
582        }
583};
584
585}
586
587/*!
588  \def UIREGISTER(class_name)
589  \brief Macro for registration of class into map of user-infos, registered class is scriptable using UI static methods
590
591  Argument \a class_name has to be a descendant of root class and also to have a default constructor.
592  This macro should be used in header file, immediately after a class declaration.
593
594  \ref ui_page
595*/
596#ifndef BDMLIB
597#define UIREGISTER(class_name) static bdm::ParticularUI<class_name> UI##class_name(#class_name)
598#else
599#define UIREGISTER(class_name)
600#endif
601
602//! Instrumental macro for UIREGISTER2
603#define QUOTEME(x) #x
604
605/*!
606  \def UIREGISTER2(class_name,template_name)
607  \brief Variant of UIREGISTER for templated classes
608
609  Technical meann of registering UIREGISTER(class_name<template_name>).
610
611  \ref ui_page
612 */
613#ifndef BDMLIB
614#define UIREGISTER2(class_name, temp_name) static bdm::ParticularUI<class_name<temp_name> > UI##class_name##_##temp_name( QUOTEME(class_name<temp_name>) )
615#else
616#define UIREGISTER2(class_name,temp_name)
617#endif
618
619#endif // #ifndef USER_INFO_H
Note: See TracBrowser for help on using the browser.