inifile.hh revision 160
1/*
2 * Copyright (c) 2003 The Regents of The University of Michigan
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions are
7 * met: redistributions of source code must retain the above copyright
8 * notice, this list of conditions and the following disclaimer;
9 * redistributions in binary form must reproduce the above copyright
10 * notice, this list of conditions and the following disclaimer in the
11 * documentation and/or other materials provided with the distribution;
12 * neither the name of the copyright holders nor the names of its
13 * contributors may be used to endorse or promote products derived from
14 * this software without specific prior written permission.
15 *
16 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28
29#ifndef __INIFILE_HH__
30#define __INIFILE_HH__
31
32#include <fstream>
33#include <list>
34#include <string>
35#include <vector>
36
37#include "base/hashmap.hh"
38
39///
40/// @file
41/// Declaration of IniFile object.
42///
43
44///
45/// This class represents the contents of a ".ini" file.
46///
47/// It's basically a two level lookup table: a set of named sections,
48/// where each section is a set of key/value pairs.  Section names,
49/// keys, and values are all uninterpreted strings.
50///
51class IniFile
52{
53  protected:
54
55    ///
56    /// A single key/value pair.
57    ///
58    class Entry
59    {
60        std::string	value;		///< The entry value.
61        mutable bool	referenced;	///< Has this entry been used?
62
63      public:
64        /// Constructor.
65        Entry(const std::string &v)
66            : value(v), referenced(false)
67        {
68        }
69
70        /// Has this entry been used?
71        bool isReferenced() { return referenced; }
72
73        /// Fetch the value.
74        const std::string &getValue() const;
75
76        /// Set the value.
77        void setValue(const std::string &v) { value = v; }
78
79        /// Append the given string to the value.  A space is inserted
80        /// between the existing value and the new value.  Since this
81        /// operation is typically used with values that are
82        /// space-separated lists of tokens, this keeps the tokens
83        /// separate.
84        void appendValue(const std::string &v) { value += " "; value += v; }
85    };
86
87    ///
88    /// A section.
89    ///
90    class Section
91    {
92        /// EntryTable type.  Map of strings to Entry object pointers.
93        typedef m5::hash_map<std::string, Entry *> EntryTable;
94
95        EntryTable	table;		///< Table of entries.
96        mutable bool	referenced;	///< Has this section been used?
97
98      public:
99        /// Constructor.
100        Section()
101            : table(), referenced(false)
102        {
103        }
104
105        /// Has this section been used?
106        bool isReferenced() { return referenced; }
107
108        /// Add an entry to the table.  If an entry with the same name
109        /// already exists, the 'append' parameter is checked If true,
110        /// the new value will be appended to the existing entry.  If
111        /// false, the new value will replace the existing entry.
112        void addEntry(const std::string &entryName, const std::string &value,
113                      bool append);
114
115        /// Add an entry to the table given a string assigment.
116        /// Assignment should be of the form "param=value" or
117        /// "param+=value" (for append).  This funciton parses the
118        /// assignment statment and calls addEntry().
119        /// @retval True for success, false if parse error.
120        bool add(const std::string &assignment);
121
122        /// Find the entry with the given name.
123        /// @retval Pointer to the entry object, or NULL if none.
124        Entry *findEntry(const std::string &entryName) const;
125
126        /// Print the unreferenced entries in this section to cerr.
127        /// Messages can be suppressed using "unref_section_ok" and
128        /// "unref_entries_ok".
129        /// @param sectionName Name of this section, for use in output message.
130        /// @retval True if any entries were printed.
131        bool printUnreferenced(const std::string &sectionName);
132
133        /// Print the contents of this section to cout (for debugging).
134        void dump(const std::string &sectionName);
135    };
136
137    /// SectionTable type.  Map of strings to Section object pointers.
138    typedef m5::hash_map<std::string, Section *> SectionTable;
139
140  protected:
141    /// Hash of section names to Section object pointers.
142    SectionTable table;
143
144    /// Look up section with the given name, creating a new section if
145    /// not found.
146    /// @retval Pointer to section object.
147    Section *addSection(const std::string &sectionName);
148
149    /// Look up section with the given name.
150    /// @retval Pointer to section object, or NULL if not found.
151    Section *findSection(const std::string &sectionName) const;
152
153    /// Load parameter settings from given istream.  This is a helper
154    /// function for load(string) and loadCPP(), which open a file
155    /// and then pass it here.
156    /// @retval True if successful, false if errors were encountered.
157    bool load(std::istream &f);
158
159  public:
160    /// Constructor.
161    IniFile();
162
163    /// Destructor.
164    ~IniFile();
165
166    /// Load the specified file, passing it through the C preprocessor.
167    /// Parameter settings found in the file will be merged with any
168    /// already defined in this object.
169    /// @param file The path of the file to load.
170    /// @param cppFlags Vector of extra flags to pass to cpp.
171    /// @retval True if successful, false if errors were encountered.
172    bool loadCPP(const std::string &file, std::vector<char *> &cppFlags);
173
174    /// Load the specified file.
175    /// Parameter settings found in the file will be merged with any
176    /// already defined in this object.
177    /// @param file The path of the file to load.
178    /// @retval True if successful, false if errors were encountered.
179    bool load(const std::string &file);
180
181    /// Take string of the form "<section>:<parameter>=<value>" or
182    /// "<section>:<parameter>+=<value>" and add to database.
183    /// @retval True if successful, false if parse error.
184    bool add(const std::string &s);
185
186    /// Find value corresponding to given section and entry names.
187    /// Value is returned by reference in 'value' param.
188    /// @retval True if found, false if not.
189    bool find(const std::string &section, const std::string &entry,
190              std::string &value) const;
191
192    /// Find value corresponding to given section and entry names,
193    /// following "default" links to other sections where possible.
194    /// Value is returned by reference in 'value' param.
195    /// @retval True if found, false if not.
196    bool findDefault(const std::string &section, const std::string &entry,
197                     std::string &value) const;
198
199    /// Print unreferenced entries in object.  Iteratively calls
200    /// printUnreferend() on all the constituent sections.
201    bool printUnreferenced();
202
203    /// Dump contents to cout.  For debugging.
204    void dump();
205};
206
207#endif // __INIFILE_HH__
208