Nektar++
Loading...
Searching...
No Matches
SessionNode.h
Go to the documentation of this file.
1///////////////////////////////////////////////////////////////////////////////
2//
3// File: SessionNode.h
4//
5// For more information, please see: http://www.nektar.info
6//
7// The MIT License
8//
9// Copyright (c) 2006 Division of Applied Mathematics, Brown University (USA),
10// Department of Aeronautics, Imperial College London (UK), and Scientific
11// Computing and Imaging Institute, University of Utah (USA).
12//
13// Permission is hereby granted, free of charge, to any person obtaining a
14// copy of this software and associated documentation files (the "Software"),
15// to deal in the Software without restriction, including without limitation
16// the rights to use, copy, modify, merge, publish, distribute, sublicense,
17// and/or sell copies of the Software, and to permit persons to whom the
18// Software is furnished to do so, subject to the following conditions:
19//
20// The above copyright notice and this permission notice shall be included
21// in all copies or substantial portions of the Software.
22//
23// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
24// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
25// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
26// THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
27// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
28// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
29// DEALINGS IN THE SOFTWARE.
30//
31// Description: Format-neutral representation of a session configuration
32// section.
33//
34///////////////////////////////////////////////////////////////////////////////
35
36#ifndef NEKTAR_LIB_UTILITIES_BASICUTILS_SESSIONNODE_H
37#define NEKTAR_LIB_UTILITIES_BASICUTILS_SESSIONNODE_H
38
39#include <string>
40#include <utility>
41#include <vector>
42
45
47{
48
49namespace SessionNodeConvert
50{
51/**
52 * @brief Convert the string @p str into @p value.
53 *
54 * Leading and trailing whitespace is ignored for all types except
55 * `std::string`, and the whole of the remaining string must be consumed:
56 * unlike `std::stoi` and friends, `"3abc"` is @b not accepted as the integer
57 * 3. Booleans accept `true`/`false`, `yes`/`no`, `on`/`off` and `1`/`0`, in
58 * any combination of upper and lower case.
59 *
60 * @return `true` if the conversion succeeded, in which case @p value holds
61 * the converted result; `false` otherwise, leaving @p value
62 * untouched.
63 */
64LIB_UTILITIES_EXPORT bool FromString(const std::string &str,
65 std::string &value);
66LIB_UTILITIES_EXPORT bool FromString(const std::string &str, bool &value);
67LIB_UTILITIES_EXPORT bool FromString(const std::string &str, int &value);
68LIB_UTILITIES_EXPORT bool FromString(const std::string &str, long &value);
69LIB_UTILITIES_EXPORT bool FromString(const std::string &str, long long &value);
70LIB_UTILITIES_EXPORT bool FromString(const std::string &str,
71 unsigned int &value);
72LIB_UTILITIES_EXPORT bool FromString(const std::string &str,
73 unsigned long &value);
74LIB_UTILITIES_EXPORT bool FromString(const std::string &str,
75 unsigned long long &value);
76LIB_UTILITIES_EXPORT bool FromString(const std::string &str, float &value);
77LIB_UTILITIES_EXPORT bool FromString(const std::string &str, NekDouble &value);
78} // namespace SessionNodeConvert
79
80/**
81 * @class SessionNode
82 *
83 * @brief A single node of a format-neutral session configuration tree.
84 *
85 * A SessionNode is a named node carrying an optional block of text, an
86 * ordered list of named string attributes, and an ordered list of child
87 * nodes. Child names need not be unique: repeated names are how repeated
88 * entries (such as the individual `FORCE` entries of a `FORCING` section) are
89 * represented, and document order is preserved.
90 *
91 * The point of the class is that it carries no knowledge of the format the
92 * configuration was written in. Solver components that need to read their own
93 * bespoke configuration section -- forcings, mappings, couplings and so on --
94 * take a SessionNode rather than reaching into the session's XML document,
95 * so that the same components work unchanged whether the configuration
96 * arrived from an XML file, some other file format, or was assembled
97 * programmatically by an embedding application.
98 *
99 * Trees are cheap to build and are expected to be small (configuration, not
100 * data), so nodes own their children by value and are freely copyable.
101 *
102 * Reading a section typically looks like:
103 *
104 * @code
105 * // <FORCE TYPE="Absorption">
106 * // <COEFF> SpongeCoefficient </COEFF>
107 * // <BOUNDARYREGIONS> 0 </BOUNDARYREGIONS>
108 * // </FORCE>
109 * std::string type = force.GetAttribute("TYPE");
110 * std::string coeff = force.GetValue("COEFF");
111 * std::string regions = force.GetValue("BOUNDARYREGIONS", "");
112 * @endcode
113 *
114 * Accessors come in three flavours: a `Defines...` predicate; a form taking a
115 * default, which is used when the entry is absent; and a form taking no
116 * default, which raises a fatal error naming the node's path if the entry is
117 * absent. The `...As<T>` forms additionally convert the string, raising a
118 * fatal error if the text is not a valid @p T.
119 */
121{
122public:
123 /// Ordered list of (name, value) attribute pairs.
124 typedef std::vector<std::pair<std::string, std::string>> AttributeMap;
125 /// Ordered list of child nodes.
126 typedef std::vector<SessionNode> ChildList;
127
128 /// Construct an empty, unnamed node.
129 SessionNode() = default;
130
131 /// Construct a node called @p name, optionally carrying @p text.
132 LIB_UTILITIES_EXPORT explicit SessionNode(std::string name,
133 std::string text = "");
134
135 /* ------ IDENTITY ------ */
136
137 /// Returns the name of this node, e.g. "FORCE".
138 LIB_UTILITIES_EXPORT const std::string &GetName() const;
139
140 /**
141 * @brief Returns the path of this node from the root of the tree it
142 * belongs to, e.g. "FORCING/FORCE/COEFF".
143 *
144 * The path is maintained by AddChild() and is used to make error messages
145 * intelligible; it carries no other meaning.
146 */
147 LIB_UTILITIES_EXPORT const std::string &GetPath() const;
148
149 /// Returns the text carried by this node, or an empty string if it
150 /// carries none.
151 LIB_UTILITIES_EXPORT const std::string &GetText() const;
152
153 /// Returns true if this node carries a non-empty block of text.
155
156 /**
157 * @brief Returns a short human-readable rendering of this node, naming
158 * its path and its attributes, for use in diagnostics.
159 *
160 * For example: `COUPLING/I [PROPERTY = "RECEIVESTEPS", VALUE = "1"]`.
161 * This is deliberately not XML: it describes the node as the rest of the
162 * code sees it, whatever format it was read from.
163 */
164 LIB_UTILITIES_EXPORT std::string Describe() const;
165
166 /* ------ ATTRIBUTES ------ */
167
168 /// Returns true if this node has an attribute called @p name.
169 LIB_UTILITIES_EXPORT bool DefinesAttribute(const std::string &name) const;
170
171 /// Returns the value of attribute @p name; a fatal error is raised if the
172 /// attribute is not defined.
173 LIB_UTILITIES_EXPORT const std::string &GetAttribute(
174 const std::string &name) const;
175
176 /// Returns the value of attribute @p name, or @p def if it is not
177 /// defined.
178 LIB_UTILITIES_EXPORT std::string GetAttribute(const std::string &name,
179 const std::string &def) const;
180
181 /// Returns all of this node's attributes, in the order they were
182 /// supplied.
184
185 /// Returns attribute @p name converted to a @p T; a fatal error is raised
186 /// if the attribute is not defined or does not convert.
187 template <typename T> T GetAttributeAs(const std::string &name) const
188 {
189 T result{};
190 const std::string &str = GetAttribute(name);
191 if (!SessionNodeConvert::FromString(str, result))
192 {
193 ThrowConversionError("attribute", name, str);
194 }
195 return result;
196 }
197
198 /// Returns attribute @p name converted to a @p T, or @p def if the
199 /// attribute is not defined; a fatal error is raised if it is defined but
200 /// does not convert.
201 template <typename T>
202 T GetAttributeAs(const std::string &name, const T &def) const
203 {
204 if (!DefinesAttribute(name))
205 {
206 return def;
207 }
208 return GetAttributeAs<T>(name);
209 }
210
211 /* ------ CHILDREN ------ */
212
213 /// Returns true if this node has at least one child called @p name.
214 LIB_UTILITIES_EXPORT bool DefinesChild(const std::string &name) const;
215
216 /// Returns the first child called @p name, or nullptr if there is none.
218 const std::string &name) const;
219
220 /// Returns the first child called @p name; a fatal error is raised if
221 /// there is none.
223 const std::string &name) const;
224
225 /// Returns every child of this node, in document order.
227
228 /// Returns every child called @p name, in document order.
229 LIB_UTILITIES_EXPORT std::vector<const SessionNode *> GetChildren(
230 const std::string &name) const;
231
232 /* ------ CHILD VALUES ------ */
233
234 /**
235 * @brief Returns the text of the first child called @p name.
236 *
237 * This is the dominant way of reading a configuration section, in which
238 * each setting is a child node carrying a single value, as in
239 * `<COEFF> SpongeCoefficient </COEFF>`. A fatal error is raised if there
240 * is no such child.
241 */
242 LIB_UTILITIES_EXPORT const std::string &GetValue(
243 const std::string &name) const;
244
245 /// Returns the text of the first child called @p name, or @p def if there
246 /// is no such child.
247 LIB_UTILITIES_EXPORT std::string GetValue(const std::string &name,
248 const std::string &def) const;
249
250 /// Returns the text of the first child called @p name converted to a
251 /// @p T; a fatal error is raised if there is no such child or it does not
252 /// convert.
253 template <typename T> T GetValueAs(const std::string &name) const
254 {
255 T result{};
256 const std::string &str = GetValue(name);
257 if (!SessionNodeConvert::FromString(str, result))
258 {
259 ThrowConversionError("value", name, str);
260 }
261 return result;
262 }
263
264 /// Returns the text of the first child called @p name converted to a
265 /// @p T, or @p def if there is no such child; a fatal error is raised if
266 /// the child exists but does not convert.
267 template <typename T>
268 T GetValueAs(const std::string &name, const T &def) const
269 {
270 if (!DefinesChild(name))
271 {
272 return def;
273 }
274 return GetValueAs<T>(name);
275 }
276
277 /* ------ TIME LEVEL (PARALLEL-IN-TIME) ------ */
278
279 /**
280 * @brief Resolves the `TIMELEVEL` indirection used by parallel-in-time
281 * runs.
282 *
283 * A section may replace its contents with a series of `TIMELEVEL`
284 * children, each carrying a `VALUE` attribute, so that different time
285 * levels see different settings.
286 *
287 * If this node has no `TIMELEVEL` children then it is itself returned, so
288 * that the common case of a section which does not vary with time level
289 * needs no special handling by the caller. Otherwise the child matching
290 * @p timeLevel is returned, or nullptr if none matches -- meaning that
291 * this section simply does not apply at @p timeLevel, and the caller
292 * should skip it.
293 *
294 * @param timeLevel The time level to select.
295 * @param enableCheck If true, a fatal error is raised, rather than
296 * nullptr returned, when this node has `TIMELEVEL`
297 * children but none matches @p timeLevel.
298 */
300 const size_t timeLevel, const bool enableCheck = true) const;
301
302 /* ------ CONSTRUCTION ------ */
303
304 /**
305 * @brief Appends @p child to this node's list of children.
306 *
307 * Intended for the readers that build trees and for applications
308 * assembling configuration programmatically. Note that this rewrites the
309 * paths of @p child and its descendants, so any pointer or reference
310 * previously obtained from @p child is invalidated.
311 */
313
314 /// Sets attribute @p name to @p value, replacing any existing value.
315 LIB_UTILITIES_EXPORT void SetAttribute(std::string name, std::string value);
316
317 /// Sets the text carried by this node.
318 LIB_UTILITIES_EXPORT void SetText(std::string text);
319
320private:
321 /// Name of this node.
322 std::string m_name;
323 /// Path of this node from the root of its tree; see GetPath().
324 std::string m_path;
325 /// Text carried by this node, if any.
326 std::string m_text;
327 /// Attributes of this node, in the order supplied.
329 /// Children of this node, in the order supplied.
331
332 /// Recomputes #m_path from @p parentPath, recursing into #m_children.
333 void UpdatePath(const std::string &parentPath);
334
335 /// Raises a fatal error describing a failed string conversion.
337 const std::string &kind, const std::string &name,
338 const std::string &str) const;
339};
340
341} // namespace Nektar::LibUtilities
342
343#endif
#define LIB_UTILITIES_EXPORT
A single node of a format-neutral session configuration tree.
ChildList m_children
Children of this node, in the order supplied.
bool DefinesText() const
Returns true if this node carries a non-empty block of text.
void AddChild(SessionNode child)
Appends child to this node's list of children.
const SessionNode * GetChildPtr(const std::string &name) const
Returns the first child called name, or nullptr if there is none.
const std::string & GetPath() const
Returns the path of this node from the root of the tree it belongs to, e.g. "FORCING/FORCE/COEFF".
const std::string & GetValue(const std::string &name) const
Returns the text of the first child called name.
std::vector< std::pair< std::string, std::string > > AttributeMap
Ordered list of (name, value) attribute pairs.
const std::string & GetName() const
Returns the name of this node, e.g. "FORCE".
void SetAttribute(std::string name, std::string value)
Sets attribute name to value, replacing any existing value.
bool DefinesChild(const std::string &name) const
Returns true if this node has at least one child called name.
SessionNode()=default
Construct an empty, unnamed node.
T GetValueAs(const std::string &name, const T &def) const
Returns the text of the first child called name converted to a T, or def if there is no such child; a...
void UpdatePath(const std::string &parentPath)
Recomputes m_path from parentPath, recursing into m_children.
std::string m_text
Text carried by this node, if any.
std::string m_path
Path of this node from the root of its tree; see GetPath().
T GetAttributeAs(const std::string &name) const
Returns attribute name converted to a T; a fatal error is raised if the attribute is not defined or d...
std::vector< SessionNode > ChildList
Ordered list of child nodes.
void SetText(std::string text)
Sets the text carried by this node.
const std::string & GetAttribute(const std::string &name) const
Returns the value of attribute name; a fatal error is raised if the attribute is not defined.
T GetAttributeAs(const std::string &name, const T &def) const
Returns attribute name converted to a T, or def if the attribute is not defined; a fatal error is rai...
const AttributeMap & GetAttributes() const
Returns all of this node's attributes, in the order they were supplied.
std::string m_name
Name of this node.
const std::string & GetText() const
Returns the text carried by this node, or an empty string if it carries none.
void ThrowConversionError(const std::string &kind, const std::string &name, const std::string &str) const
Raises a fatal error describing a failed string conversion.
const SessionNode & GetChild(const std::string &name) const
Returns the first child called name; a fatal error is raised if there is none.
bool DefinesAttribute(const std::string &name) const
Returns true if this node has an attribute called name.
std::string Describe() const
Returns a short human-readable rendering of this node, naming its path and its attributes,...
const ChildList & GetChildren() const
Returns every child of this node, in document order.
AttributeMap m_attributes
Attributes of this node, in the order supplied.
const SessionNode * GetTimeLevel(const size_t timeLevel, const bool enableCheck=true) const
Resolves the TIMELEVEL indirection used by parallel-in-time runs.
T GetValueAs(const std::string &name) const
Returns the text of the first child called name converted to a T; a fatal error is raised if there is...
bool FromString(const std::string &str, std::string &value)
Convert the string str into value.