OGS 6.1.0-1721-g6382411ad
BaseLib::ConfigTree Class Referencefinal

Detailed Description

Wrapper around a Boost Property Tree with some basic error reporting features.

Features. This class:

  • makes sure that every configuration setting in a Property Tree is read exactly once. If some settings is not read (e.g. due to a typo), a warning message is generated. The message contains a hint where it occured.
  • enforces a naming scheme of settings: letters a-z, numbers 0-9, underscore
  • provides some functionality to read lists of values using range-based for loops.
  • has rather long method names that are easily greppable from the source code. So a list of supported configuration options can be easily obtained from the source code.

The purpose of this class is to reduce or completely avoid the amount of error-handling code in routines that take configuration parameters.

Most methods of this class check that they have not been called before for the same ConfigTree and the same parameter. This behaviour helps to enforce that every parameter is read exactly once during parsing of the configuration settings.

The most notable restriction of this class when compared to plain tree traversal is, that one must know all the XML tags (i.e. configuration parameters) at compile time. It is not possible to read from this class, which configuration parameters are present in the tree. This restriction, however, is intended, because it provides the possibility to get all existing configuration parameters from the source code.

This class maintains a read counter for each parameter accessed through any of its methods. Read counters are increased with every read (the only exception being the peekConfigParameter() method). The destructor finally decreases the read counter for every tag/attribute it find on the current level of the XML tree. If the increases/decreases don't cancel each other, warning messages are generated. This check can also be enforced before destruction by using the BaseLib::checkAndInvalidate() functions.

The design of this class entails some limitations compared to traversing a plain tree, e.g., it is not possible to obtain a list of tags or attributes from the tree, but one has to explicitly query the specific tags/attributes one is interested in. That way it is possible to get all used configuration parameters directly from the source code where this class is used, and to maintain the quality of the configuration parameter documentation.

Instances of this class only keep a reference to the underlying boost::property_tree. Therefore it is necessary that the underlying property tree stays intact as long as any instance—i.e. the top level ConfigTree and any of its children—reference it. In order to simplify the handling of this dependence, the class ConfigTreeTopLevel can be used.

The construction of a ConfigTree from the content of an XML file can be done with the function BaseLib::makeConfigTree(), which performs many error checks. For limitations of the used XML parser, please have a look at that function's documentation.

Definition at line 95 of file ConfigTree.h.

#include <ConfigTree.h>

Classes

struct  CountType
 
class  ParameterIterator
 
class  SubtreeIterator
 
class  ValueIterator
 

Public Types

using PTree = boost::property_tree::ptree
 The tree being wrapped by this class. More...
 
using Callback = std::function< void(const std::string &filename, const std::string &path, const std::string &message)>
 

Public Member Functions

 ConfigTree (PTree const &tree, std::string filename, Callback error_cb, Callback warning_cb)
 
 ConfigTree (PTree &&, std::string const &, Callback const &, Callback const &)=delete
 
 ConfigTree (ConfigTree const &)=delete
 copying is not compatible with the semantics of this class More...
 
 ConfigTree (ConfigTree &&other)
 
ConfigTreeoperator= (ConfigTree const &)=delete
 copying is not compatible with the semantics of this class More...
 
ConfigTreeoperator= (ConfigTree &&)
 
 ~ConfigTree ()
 
Methods for directly accessing parameter values
template<typename T >
getConfigParameter (std::string const &param) const
 
template<typename T >
getConfigParameter (std::string const &param, T const &default_value) const
 
template<typename T >
boost::optional< T > getConfigParameterOptional (std::string const &param) const
 
template<typename T >
Range< ValueIterator< T > > getConfigParameterList (std::string const &param) const
 
Methods for accessing parameters that have attributes

The getConfigParameter...() methods in this group—note: they do not have template parameters—check that the queried parameters do not have any children (apart from XML attributes); if they do, error() is called.

The support for parameters with attributes is limited in the sense that it is not possible to peek/check them. However, such functionality can easily be added on demand.

ConfigTree getConfigParameter (std::string const &param) const
 
boost::optional< ConfigTreegetConfigParameterOptional (std::string const &param) const
 
Range< ParameterIteratorgetConfigParameterList (std::string const &param) const
 
template<typename T >
getValue () const
 
template<typename T >
getConfigAttribute (std::string const &attr) const
 
template<typename T >
getConfigAttribute (std::string const &attr, T const &default_value) const
 
template<typename T >
boost::optional< T > getConfigAttributeOptional (std::string const &attr) const
 
Methods for peeking and checking parameters

To be used in builder/factory functions: E.g., one can peek a parameter denoting the type of an object to generate in the builder, and check the type parameter in the constructor of the generated object.

template<typename T >
peekConfigParameter (std::string const &param) const
 
template<typename T >
void checkConfigParameter (std::string const &param, T const &value) const
 
template<typename Ch >
void checkConfigParameter (std::string const &param, Ch const *value) const
 Make checkConfigParameter() work for string literals. More...
 
Methods for accessing subtrees
ConfigTree getConfigSubtree (std::string const &root) const
 
boost::optional< ConfigTreegetConfigSubtreeOptional (std::string const &root) const
 
Range< SubtreeIteratorgetConfigSubtreeList (std::string const &root) const
 
Methods for ignoring parameters
void ignoreConfigParameter (std::string const &param) const
 
void ignoreConfigParameterAll (std::string const &param) const
 
void ignoreConfigAttribute (std::string const &attr) const
 

Static Public Member Functions

static void onerror (std::string const &filename, std::string const &path, std::string const &message)
 
static void onwarning (std::string const &filename, std::string const &path, std::string const &message)
 
static void assertNoSwallowedErrors ()
 Asserts that there have not been any errors reported in the destructor. More...
 

Private Types

enum  Attr : bool { Attr::TAG = false, Attr::ATTR = true }
 Used to indicate if dealing with XML tags or XML attributes. More...
 
using KeyType = std::pair< Attr, std::string >
 A pair (is attribute, tag/attribute name). More...
 

Private Member Functions

template<typename T >
boost::optional< T > getConfigParameterOptionalImpl (std::string const &param, T *) const
 Default implementation of reading a value of type T. More...
 
template<typename T >
boost::optional< std::vector< T > > getConfigParameterOptionalImpl (std::string const &param, std::vector< T > *) const
 Implementation of reading a vector of values of type T. More...
 
 ConfigTree (PTree const &tree, ConfigTree const &parent, std::string const &root)
 Used for wrapping a subtree. More...
 
void error (std::string const &message) const
 
void warning (std::string const &message) const
 
void checkKeyname (std::string const &key) const
 Checks if key complies with the rules [a-z0-9_]. More...
 
std::string joinPaths (std::string const &p1, std::string const &p2) const
 Used to generate the path of a subtree. More...
 
void checkUnique (std::string const &key) const
 Asserts that the key has not been read yet. More...
 
void checkUniqueAttr (std::string const &attr) const
 Asserts that the attribute attr has not been read yet. More...
 
template<typename T >
CountTypemarkVisited (std::string const &key, Attr const is_attr, bool peek_only) const
 
CountTypemarkVisited (std::string const &key, Attr const is_attr, bool const peek_only) const
 
void markVisitedDecrement (Attr const is_attr, std::string const &key) const
 
bool hasChildren () const
 Checks if this tree has any children. More...
 
void checkAndInvalidate ()
 

Static Private Member Functions

static std::string shortString (std::string const &s)
 returns a short string at suitable for error/warning messages More...
 

Private Attributes

boost::property_tree::ptree const * _tree
 The wrapped tree. More...
 
std::string _path
 A path printed in error/warning messages. More...
 
std::string _filename
 The path of the file from which this tree has been read. More...
 
std::map< KeyType, CountType_visited_params
 
bool _have_read_data = false
 Indicates if the plain data contained in this tree has already been read. More...
 
Callback _onerror
 Custom error callback. More...
 
Callback _onwarning
 Custom warning callback. More...
 

Static Private Attributes

static const char pathseparator = '/'
 Character separating two path components. More...
 
static const std::string key_chars_start = "abcdefghijklmnopqrstuvwxyz"
 Set of allowed characters as the first letter of a key name. More...
 
static const std::string key_chars = key_chars_start + "_0123456789"
 Set of allowed characters in a key name. More...
 

Friends

void checkAndInvalidate (ConfigTree *const conf)
 
void checkAndInvalidate (ConfigTree &conf)
 
void checkAndInvalidate (std::unique_ptr< ConfigTree > const &conf)
 

Member Typedef Documentation

◆ Callback

using BaseLib::ConfigTree::Callback = std::function<void(const std::string& filename, const std::string& path, const std::string& message)>

Type of the function objects used as callbacks.

Arguments of the callback:

  • filename the file being from which this ConfigTree has been read.
  • path the path in the tree where the message was generated.
  • message the message to be printed.

Definition at line 229 of file ConfigTree.h.

◆ KeyType

using BaseLib::ConfigTree::KeyType = std::pair<Attr, std::string>
private

A pair (is attribute, tag/attribute name).

Definition at line 615 of file ConfigTree.h.

◆ PTree

using BaseLib::ConfigTree::PTree = boost::property_tree::ptree

The tree being wrapped by this class.

Definition at line 218 of file ConfigTree.h.

Member Enumeration Documentation

◆ Attr

enum BaseLib::ConfigTree::Attr : bool
strongprivate

Used to indicate if dealing with XML tags or XML attributes.

Enumerator
TAG 
ATTR 

Definition at line 534 of file ConfigTree.h.

534  : bool
535  {
536  TAG = false, ATTR = true
537  };

Constructor & Destructor Documentation

◆ ConfigTree() [1/5]

BaseLib::ConfigTree::ConfigTree ( PTree const &  tree,
std::string  filename,
Callback  error_cb,
Callback  warning_cb 
)
explicit

Creates a new instance wrapping the given Boost Property Tree.

Parameters
treethe Boost Property Tree to be wrapped
filenamethe file from which the tree has been read
error_cbcallback function to be called on error.
warning_cbcallback function to be called on warning.

The callback functions must be valid callable functions, i.e. not nullptr's. They are configurable in order to make unit tests of this class easier. They should not be provided in production code!

Defaults are strict: By default, both callbacks are set to the same function, i.e., warnings will also result in program abortion!

Definition at line 34 of file ConfigTree.cpp.

References _onerror, _onwarning, and OGS_FATAL.

Referenced by ConfigTree(), getConfigSubtreeOptional(), BaseLib::ConfigTree::SubtreeIterator::operator*(), and BaseLib::ConfigTree::ValueIterator< ValueType >::operator*().

38  : _tree(&tree),
39  _filename(std::move(filename)),
40  _onerror(std::move(error_cb)),
41  _onwarning(std::move(warning_cb))
42 {
43  if (!_onerror) {
44  OGS_FATAL("ConfigTree: No valid error handler provided.");
45  }
46  if (!_onwarning) {
47  OGS_FATAL("ConfigTree: No valid warning handler provided.");
48  }
49 }
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
std::string _filename
The path of the file from which this tree has been read.
Definition: ConfigTree.h:612
Callback _onerror
Custom error callback.
Definition: ConfigTree.h:629
Callback _onwarning
Custom warning callback.
Definition: ConfigTree.h:630
#define OGS_FATAL(fmt,...)
Definition: Error.h:71

◆ ConfigTree() [2/5]

BaseLib::ConfigTree::ConfigTree ( PTree &&  ,
std::string const &  ,
Callback const &  ,
Callback const &   
)
explicitdelete

This constructor is deleted in order to prevent the user from passing temporary instances of PTree. Doing so would lead to a dangling reference _tree and to program crash.

◆ ConfigTree() [3/5]

BaseLib::ConfigTree::ConfigTree ( ConfigTree const &  )
delete

copying is not compatible with the semantics of this class

◆ ConfigTree() [4/5]

BaseLib::ConfigTree::ConfigTree ( ConfigTree &&  other)

After being moved from, other is in an undefined state and must not be used anymore!

Definition at line 62 of file ConfigTree.cpp.

63  : _tree (other._tree)
64  , _path (std::move(other._path))
65  , _filename (std::move(other._filename))
66  , _visited_params(std::move(other._visited_params))
67  , _have_read_data (other._have_read_data)
68  , _onerror (std::move(other._onerror))
69  , _onwarning (std::move(other._onwarning))
70 {
71  other._tree = nullptr;
72 }
std::string _path
A path printed in error/warning messages.
Definition: ConfigTree.h:609
bool _have_read_data
Indicates if the plain data contained in this tree has already been read.
Definition: ConfigTree.h:627
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
std::map< KeyType, CountType > _visited_params
Definition: ConfigTree.h:624
std::string _filename
The path of the file from which this tree has been read.
Definition: ConfigTree.h:612
Callback _onerror
Custom error callback.
Definition: ConfigTree.h:629
Callback _onwarning
Custom warning callback.
Definition: ConfigTree.h:630

◆ ~ConfigTree()

BaseLib::ConfigTree::~ConfigTree ( )

The destructor performs the check if all nodes at the current level of the tree have been read. Errors raised by the check are swallowed. Use assertNoSwallowedErrors() manually to check for those.

Definition at line 74 of file ConfigTree.cpp.

References checkAndInvalidate(), configtree_destructor_error_messages, and operator=().

75 {
76  if (std::uncaught_exceptions() > 0)
77  {
78  /* If the stack unwinds the check below shall be suppressed in order to
79  * not accumulate false-positive configuration errors.
80  */
81  return;
82  }
83 
84  try {
86  } catch (std::exception& e) {
87  ERR("%s", e.what());
88  configtree_destructor_error_messages.push_front(e.what());
89  }
90 }
static std::forward_list< std::string > configtree_destructor_error_messages
Definition: ConfigTree.cpp:25

◆ ConfigTree() [5/5]

BaseLib::ConfigTree::ConfigTree ( PTree const &  tree,
ConfigTree const &  parent,
std::string const &  root 
)
explicitprivate

Used for wrapping a subtree.

Definition at line 52 of file ConfigTree.cpp.

References checkKeyname(), and ConfigTree().

54  : _tree(&tree), _path(joinPaths(parent._path, root)),
55  _filename(parent._filename),
56  _onerror(parent._onerror), _onwarning(parent._onwarning)
57 {
58  checkKeyname(root);
59 }
std::string _path
A path printed in error/warning messages.
Definition: ConfigTree.h:609
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
std::string _filename
The path of the file from which this tree has been read.
Definition: ConfigTree.h:612
void checkKeyname(std::string const &key) const
Checks if key complies with the rules [a-z0-9_].
Definition: ConfigTree.cpp:266
Callback _onerror
Custom error callback.
Definition: ConfigTree.h:629
Callback _onwarning
Custom warning callback.
Definition: ConfigTree.h:630
std::string joinPaths(std::string const &p1, std::string const &p2) const
Used to generate the path of a subtree.
Definition: ConfigTree.cpp:284

Member Function Documentation

◆ assertNoSwallowedErrors()

void BaseLib::ConfigTree::assertNoSwallowedErrors ( )
static

Asserts that there have not been any errors reported in the destructor.

Definition at line 241 of file ConfigTree.cpp.

References configtree_destructor_error_messages, and OGS_FATAL.

Referenced by main().

242 {
244  return;
245 
246  ERR("ConfigTree: There have been errors when parsing the configuration "
247  "file(s):");
248 
249  for (auto const& msg : configtree_destructor_error_messages) {
250  ERR("%s", msg.c_str());
251  }
252 
253  OGS_FATAL("There have been errors when parsing the configuration file(s).");
254 }
static std::forward_list< std::string > configtree_destructor_error_messages
Definition: ConfigTree.cpp:25
#define OGS_FATAL(fmt,...)
Definition: Error.h:71

◆ checkAndInvalidate()

void BaseLib::ConfigTree::checkAndInvalidate ( )
private

Checks if the top level of this tree has been read entirely (and not too often).

Postcondition
This method also invalidates the instance, i.e., afterwards it must not be used anymore!

Definition at line 365 of file ConfigTree.cpp.

References _have_read_data, _tree, _visited_params, ATTR, markVisitedDecrement(), shortString(), TAG, and warning().

Referenced by BaseLib::checkAndInvalidate(), operator=(), and ~ConfigTree().

366 {
367  if (!_tree) return;
368 
369  // Note: due to a limitation in boost::property_tree it is not possible
370  // to discriminate between <tag></tag> and <tag/> in the input file.
371  // In both cases data() will be empty.
372  if ((!_have_read_data) && !_tree->data().empty()) {
373  warning("The immediate data `" + shortString(_tree->data())
374  +"' of this tag has not been read.");
375  }
376 
377  // iterate over children
378  for (auto const& p : *_tree) {
379  if (p.first != "<xmlattr>") // attributes are handled below
381  }
382 
383  // iterate over attributes
384  if (auto attrs = _tree->get_child_optional("<xmlattr>")) {
385  for (auto const& p : *attrs) {
387  }
388  }
389 
390  for (auto const& p : _visited_params)
391  {
392  auto const& tag = p.first.second;
393  auto const& count = p.second.count;
394 
395  switch (p.first.first) {
396  case Attr::ATTR:
397  if (count > 0) {
398  warning("XML attribute '" + tag + "' has been read " +
399  std::to_string(count) +
400  " time(s) more than it was present in the "
401  "configuration tree.");
402  } else if (count < 0) {
403  warning("XML attribute '" + tag + "' has been read " +
404  std::to_string(-count) +
405  " time(s) less than it was present in the "
406  "configuration tree.");
407  }
408  break;
409  case Attr::TAG:
410  if (count > 0) {
411  warning("Key <" + tag + "> has been read " + std::to_string(count)
412  + " time(s) more than it was present in the configuration tree.");
413  } else if (count < 0) {
414  warning("Key <" + tag + "> has been read " + std::to_string(-count)
415  + " time(s) less than it was present in the configuration tree.");
416  }
417  }
418  }
419 
420  // The following invalidates this instance, s.t. it can not be read from it anymore,
421  // but it also prevents double-checking.
422  _tree = nullptr;
423 }
bool _have_read_data
Indicates if the plain data contained in this tree has already been read.
Definition: ConfigTree.h:627
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void warning(std::string const &message) const
Definition: ConfigTree.cpp:221
std::map< KeyType, CountType > _visited_params
Definition: ConfigTree.h:624
static std::string shortString(std::string const &s)
returns a short string at suitable for error/warning messages
Definition: ConfigTree.cpp:256
void markVisitedDecrement(Attr const is_attr, std::string const &key) const
Definition: ConfigTree.cpp:338

◆ checkConfigParameter() [1/2]

template<typename T >
void BaseLib::ConfigTree::checkConfigParameter ( std::string const &  param,
T const &  value 
) const

Assert that param has the given value.

Convenience method combining getConfigParameter(std::string const&) with a check.

Definition at line 147 of file ConfigTree-impl.h.

Referenced by MaterialLib::PorousMedium::createBrooksCorey(), MaterialLib::PorousMedium::createCapillaryPressureModel(), ProcessLib::createCentralDifferencesJacobianAssembler(), MaterialLib::Fracture::CohesiveZoneModeI::createCohesiveZoneModeI(), ProcessLib::createCompareJacobiansJacobianAssembler(), ProcessLib::ComponentTransport::createComponentTransportProcess(), ProcessLib::createConstantParameter(), ProcessLib::createConstraintDirichletBoundaryCondition(), NumLib::createConvergenceCriterionDeltaX(), NumLib::createConvergenceCriterionPerComponentDeltaX(), NumLib::createConvergenceCriterionPerComponentResidual(), NumLib::createConvergenceCriterionResidual(), MaterialLib::Solids::Creep::createCreepBGRa(), ProcessLib::createCurveScaledParameter(), ProcessLib::createDirichletBoundaryCondition(), ProcessLib::createDirichletBoundaryConditionWithinTimeInterval(), MaterialLib::Solids::Ehlers::createEhlers(), NumLib::createEvolutionaryPIDcontroller(), NumLib::createFixedTimeStepping(), MaterialLib::Fluid::createFluidDensityModel(), ProcessLib::createFunctionParameter(), ProcessLib::GroundwaterFlow::createGroundwaterFlowProcess(), ProcessLib::createGroupBasedParameter(), ProcessLib::HeatConduction::createHeatConductionProcess(), ProcessLib::HeatTransportBHE::createHeatTransportBHEProcess(), ProcessLib::HT::createHTProcess(), ProcessLib::HydroMechanics::createHydroMechanicsProcess(), ProcessLib::LIE::HydroMechanics::createHydroMechanicsProcess(), NumLib::createIterationNumberBasedTimeStepping(), MaterialLib::Fluid::createLinearConcentrationAndPressureDependentDensity(), MaterialLib::Fluid::createLinearConcentrationDependentDensity(), MaterialLib::Solids::createLinearElasticIsotropic(), MaterialLib::Fracture::createLinearElasticIsotropic(), MaterialLib::Fluid::createLinearPressureDependentViscosity(), MaterialLib::Fluid::createLinearTemperatureDependentDensity(), MaterialLib::Fluid::createLiquidDensity(), ProcessLib::LiquidFlow::createLiquidFlowProcess(), MaterialLib::Solids::Lubby2::createLubby2(), ProcessLib::createMeshElementParameter(), ProcessLib::createMeshNodeParameter(), MaterialLib::Fracture::createMohrCoulomb(), ProcessLib::createNeumannBoundaryCondition(), ProcessLib::createNodalSourceTerm(), ProcessLib::createNonuniformDirichletBoundaryCondition(), ProcessLib::createNonuniformNeumannBoundaryCondition(), ProcessLib::createNonuniformVariableDependentNeumannBoundaryCondition(), MaterialLib::PorousMedium::createNonWettingPhaseBrooksCoreyOilGas(), MaterialLib::PorousMedium::createNonWettingPhaseVanGenuchten(), ProcessLib::NormalTractionBoundaryCondition::createNormalTractionBoundaryCondition(), ProcessLib::createOutput(), ProcessLib::createPhaseFieldIrreversibleDamageOracleBoundaryCondition(), ProcessLib::PhaseField::createPhaseFieldProcess(), ProcessLib::createPythonBoundaryCondition(), ProcessLib::createPythonSourceTerm(), MaterialLib::PorousMedium::createRelativePermeabilityModel(), ProcessLib::RichardsComponentTransport::createRichardsComponentTransportProcess(), ProcessLib::RichardsFlow::createRichardsFlowProcess(), ProcessLib::RichardsMechanics::createRichardsMechanicsProcess(), ProcessLib::createRobinBoundaryCondition(), ProcessLib::SmallDeformationNonlocal::createSmallDeformationNonlocalProcess(), ProcessLib::SmallDeformation::createSmallDeformationProcess(), ProcessLib::LIE::SmallDeformation::createSmallDeformationProcess(), MaterialLib::Fluid::createTemperatureDependentViscosity(), ProcessLib::TES::createTESProcess(), ProcessLib::ThermalTwoPhaseFlowWithPP::createThermalTwoPhaseFlowWithPPProcess(), ProcessLib::ThermoMechanicalPhaseField::createThermoMechanicalPhaseFieldProcess(), ProcessLib::ThermoMechanics::createThermoMechanicsProcess(), ProcessLib::TwoPhaseFlowWithPP::createTwoPhaseFlowWithPPProcess(), ProcessLib::TwoPhaseFlowWithPrho::createTwoPhaseFlowWithPrhoProcess(), MaterialLib::PorousMedium::createVanGenuchten(), MaterialLib::Fluid::createViscosityModel(), ProcessLib::createVolumetricSourceTerm(), MaterialLib::PorousMedium::createWettingPhaseBrooksCoreyOilGas(), MaterialLib::PorousMedium::createWettingPhaseVanGenuchten(), and peekConfigParameter().

148 {
149  if (getConfigParameter<T>(param) != value) {
150  error("The value of key <" + param + "> is not the expected one.");
151  }
152 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213

◆ checkConfigParameter() [2/2]

template<typename Ch >
void BaseLib::ConfigTree::checkConfigParameter ( std::string const &  param,
Ch const *  value 
) const

Make checkConfigParameter() work for string literals.

Definition at line 157 of file ConfigTree-impl.h.

References getValue().

158 {
159  if (getConfigParameter<std::string>(param) != value) {
160  error("The value of key <" + param + "> is not the expected one.");
161  }
162 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213

◆ checkKeyname()

void BaseLib::ConfigTree::checkKeyname ( std::string const &  key) const
private

Checks if key complies with the rules [a-z0-9_].

Definition at line 266 of file ConfigTree.cpp.

References error(), joinPaths(), key_chars, and key_chars_start.

Referenced by checkUnique(), checkUniqueAttr(), and ConfigTree().

267 {
268  if (key.empty()) {
269  error("Search for empty key.");
270  } else if (key_chars_start.find(key.front()) == std::string::npos) {
271  error("Key <" + key + "> starts with an illegal character.");
272  } else if (key.find_first_not_of(key_chars, 1) != std::string::npos) {
273  error("Key <" + key + "> contains illegal characters.");
274  } else if (key.find("__") != std::string::npos) {
275  // This is illegal because we use parameter names to generate doxygen
276  // page names. Thereby "__" acts as a separator character. Choosing
277  // other separators is not possible because of observed limitations
278  // for valid doxygen page names.
279  error("Key <" + key + "> contains double underscore.");
280  }
281 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
static const std::string key_chars_start
Set of allowed characters as the first letter of a key name.
Definition: ConfigTree.h:636
static const std::string key_chars
Set of allowed characters in a key name.
Definition: ConfigTree.h:639

◆ checkUnique()

void BaseLib::ConfigTree::checkUnique ( std::string const &  key) const
private

Asserts that the key has not been read yet.

Definition at line 295 of file ConfigTree.cpp.

References _visited_params, checkKeyname(), and error().

Referenced by getConfigParameterList(), getConfigSubtreeList(), getConfigSubtreeOptional(), ignoreConfigParameter(), and ignoreConfigParameterAll().

296 {
297  checkKeyname(key);
298 
299  if (_visited_params.find({Attr::TAG, key}) != _visited_params.end()) {
300  error("Key <" + key + "> has already been processed.");
301  }
302 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
std::map< KeyType, CountType > _visited_params
Definition: ConfigTree.h:624
void checkKeyname(std::string const &key) const
Checks if key complies with the rules [a-z0-9_].
Definition: ConfigTree.cpp:266

◆ checkUniqueAttr()

void BaseLib::ConfigTree::checkUniqueAttr ( std::string const &  attr) const
private

Asserts that the attribute attr has not been read yet.

Definition at line 304 of file ConfigTree.cpp.

References _visited_params, checkKeyname(), error(), and markVisited().

Referenced by ignoreConfigAttribute().

305 {
306  // Workaround for handling attributes with xml namespaces and uppercase letters.
307  if (attr.find(':') != attr.npos) {
308  auto pos = decltype(attr.npos){0};
309 
310  // Replace colon and uppercase letters with an allowed character 'a'.
311  // That means, attributes containing a colon are also allowed to contain
312  // uppercase letters.
313  auto attr2 = attr;
314  do {
315  pos = attr2.find_first_of(":ABCDEFGHIJKLMNOPQRSTUVWXYZ", pos);
316  if (pos != attr.npos) attr2[pos] = 'a';
317  } while (pos != attr.npos);
318 
319  checkKeyname(attr2);
320  } else {
321  checkKeyname(attr);
322  }
323 
324  if (_visited_params.find({Attr::ATTR, attr}) != _visited_params.end()) {
325  error("Attribute '" + attr + "' has already been processed.");
326  }
327 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
std::map< KeyType, CountType > _visited_params
Definition: ConfigTree.h:624
void checkKeyname(std::string const &key) const
Checks if key complies with the rules [a-z0-9_].
Definition: ConfigTree.cpp:266

◆ error()

void BaseLib::ConfigTree::error ( std::string const &  message) const
private

Called if an error occurs. Will call the error callback.

This method only acts as a helper method and throws std::runtime_error.

Definition at line 213 of file ConfigTree.cpp.

References _filename, _onerror, _path, and OGS_FATAL.

Referenced by checkKeyname(), checkUnique(), checkUniqueAttr(), getConfigParameter(), getConfigParameterOptional(), getConfigSubtree(), joinPaths(), and BaseLib::ConfigTree::ParameterIterator::operator*().

214 {
215  _onerror(_filename, _path, message);
216  OGS_FATAL(
217  "ConfigTree: The error handler does not break out of the normal "
218  "control flow.");
219 }
std::string _path
A path printed in error/warning messages.
Definition: ConfigTree.h:609
std::string _filename
The path of the file from which this tree has been read.
Definition: ConfigTree.h:612
Callback _onerror
Custom error callback.
Definition: ConfigTree.h:629
#define OGS_FATAL(fmt,...)
Definition: Error.h:71

◆ getConfigAttribute() [1/2]

template<typename T >
T BaseLib::ConfigTree::getConfigAttribute ( std::string const &  attr) const

Get XML attribute attr of type T for the current parameter.

Returns
the requested attribute's value.
Precondition
attr must not have been read before from the current parameter.

Definition at line 185 of file ConfigTree-impl.h.

Referenced by ProcessLib::LiquidFlow::createLiquidFlowMaterialProperties(), MaterialLib::PorousMedium::createPorousMediaProperties(), and getValue().

186 {
187  if (auto a = getConfigAttributeOptional<T>(attr))
188  return *a;
189 
190  error("Did not find XML attribute with name '" + attr + "'.");
191 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213

◆ getConfigAttribute() [2/2]

template<typename T >
T BaseLib::ConfigTree::getConfigAttribute ( std::string const &  attr,
T const &  default_value 
) const

Get XML attribute attr of type T for the current parameter or the default_value.

This method has a similar behaviour as getConfigAttribute(std::string const&) except the default_value is returned if the attribute has not been found.

Returns
the requested attribute's value.
Precondition
attr must not have been read before from the current parameter.

Definition at line 194 of file ConfigTree-impl.h.

References getConfigAttributeOptional().

196 {
197  if (auto a = getConfigAttributeOptional<T>(attr))
198  return *a;
199 
200  return default_value;
201 }

◆ getConfigAttributeOptional()

template<typename T >
boost::optional< T > BaseLib::ConfigTree::getConfigAttributeOptional ( std::string const &  attr) const

Get XML attribute attr of type T for the current parameter if present.

Returns
the requested attribute's value.
Precondition
attr must not have been read before from the current parameter.

Definition at line 206 of file ConfigTree-impl.h.

References markVisited().

Referenced by ProcessLib::RichardsFlow::createRichardsFlowMaterialProperties(), MaterialLib::TwoPhaseFlowWithPP::createTwoPhaseFlowMaterialProperties(), ProcessLib::TwoPhaseFlowWithPrho::createTwoPhaseFlowPrhoMaterialProperties(), ProcessLib::TwoPhaseFlowWithPP::createTwoPhaseFlowWithPPMaterialProperties(), getConfigAttribute(), and anonymous_namespace{ProjectData.cpp}::readSingleMesh().

207 {
208  checkUniqueAttr(attr);
209  auto& ct = markVisited<T>(attr, Attr::ATTR, true);
210 
211  if (auto attrs = _tree->get_child_optional("<xmlattr>")) {
212  if (auto a = attrs->get_child_optional(attr)) {
213  ++ct.count; // count only if attribute has been found
214  if (auto v = a->get_value_optional<T>()) {
215  return v;
216  }
217  error("Value for XML attribute '" + attr + "' `" +
218  shortString(a->data()) +
219  "' not convertible to the desired type.");
220  }
221  }
222 
223  return boost::none;
224 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUniqueAttr(std::string const &attr) const
Asserts that the attribute attr has not been read yet.
Definition: ConfigTree.cpp:304
static std::string shortString(std::string const &s)
returns a short string at suitable for error/warning messages
Definition: ConfigTree.cpp:256

◆ getConfigParameter() [1/3]

template<typename T >
T BaseLib::ConfigTree::getConfigParameter ( std::string const &  param) const

Get parameter param of type T from the configuration tree.

Returns
the value looked for.
Precondition
param must not have been read before from this ConfigTree.

Definition at line 40 of file ConfigTree-impl.h.

Referenced by ProcessLib::HeatTransportBHE::BHE::createBoreholeGeometry(), MaterialLib::PorousMedium::createBrooksCorey(), ProcessLib::createCompareJacobiansJacobianAssembler(), anonymous_namespace{CreateComponent.cpp}::createComponent(), ProcessLib::createConstantParameter(), ProcessLib::createConstraintDirichletBoundaryCondition(), NumLib::createConvergenceCriterionDeltaX(), NumLib::createConvergenceCriterionPerComponentDeltaX(), NumLib::createConvergenceCriterionPerComponentResidual(), NumLib::createConvergenceCriterionResidual(), ProcessLib::createCurveScaledParameter(), ProcessLib::createDeactivatedSubdomain(), ProcessLib::createDirichletBoundaryCondition(), ProcessLib::createDirichletBoundaryConditionWithinTimeInterval(), NumLib::createEvolutionaryPIDcontroller(), NumLib::createFixedTimeStepping(), ProcessLib::HeatTransportBHE::BHE::createFlowAndTemperatureControl(), MaterialLib::Fluid::createFluidDensityModel(), MaterialLib::Fluid::createFluidThermalConductivityModel(), ProcessLib::createGroupBasedParameter(), ProcessLib::HeatTransportBHE::BHE::createGroutParameters(), NumLib::createIterationNumberBasedTimeStepping(), MaterialLib::Fluid::createLinearConcentrationAndPressureDependentDensity(), MaterialLib::Fluid::createLinearConcentrationDependentDensity(), MaterialLib::Fluid::createLinearPressureDependentViscosity(), MaterialLib::Fluid::createLinearTemperatureDependentDensity(), MaterialLib::Fluid::createLiquidDensity(), ProcessLib::LiquidFlow::createLiquidFlowProcess(), ProcessLib::createMeshElementParameter(), ProcessLib::createMeshNodeParameter(), ProcessLib::createNeumannBoundaryCondition(), MaterialLib::createNewtonRaphsonSolverParameters(), ProcessLib::createNodalSourceTerm(), NumLib::createNonlinearSolver(), ProcessLib::createNonuniformDirichletBoundaryCondition(), ProcessLib::createNonuniformNeumannBoundaryCondition(), ProcessLib::createNonuniformVariableDependentNeumannBoundaryCondition(), MaterialLib::PorousMedium::createNonWettingPhaseBrooksCoreyOilGas(), MaterialLib::PorousMedium::createNonWettingPhaseVanGenuchten(), ProcessLib::NormalTractionBoundaryCondition::createNormalTractionBoundaryCondition(), ProcessLib::createOutput(), ProcessLib::createParameter(), MaterialLib::PorousMedium::createPermeabilityModel(), anonymous_namespace{CreatePhase.cpp}::createPhase(), ProcessLib::PhaseField::createPhaseFieldProcess(), MathLib::createPiecewiseLinearCurve(), ProcessLib::HeatTransportBHE::BHE::createPipe(), MaterialLib::PorousMedium::createPorosityModel(), anonymous_namespace{CreateProperty.cpp}::createProperty(), ProcessLib::createPythonBoundaryCondition(), ProcessLib::createPythonSourceTerm(), ProcessLib::HeatTransportBHE::BHE::createRefrigerantProperties(), ProcessLib::RichardsFlow::createRichardsFlowProcess(), ProcessLib::createRobinBoundaryCondition(), ProcessLib::LIE::SmallDeformation::createSmallDeformationProcess(), MaterialLib::Fluid::createSpecificFluidHeatCapacityModel(), MaterialLib::PorousMedium::createStorageModel(), ProcessLib::SurfaceFluxData::createSurfaceFluxData(), MaterialLib::Fluid::createTemperatureDependentViscosity(), ProcessLib::ThermalTwoPhaseFlowWithPP::createThermalTwoPhaseFlowWithPPProcess(), NumLib::createTimeDiscretization(), BaseLib::createTimeInterval(), ProcessLib::TwoPhaseFlowWithPP::createTwoPhaseFlowWithPPProcess(), ProcessLib::TwoPhaseFlowWithPrho::createTwoPhaseFlowWithPrhoProcess(), MaterialLib::PorousMedium::createVanGenuchten(), MaterialLib::Fluid::createViscosityModel(), ProcessLib::createVolumetricSourceTerm(), MaterialLib::PorousMedium::createWettingPhaseBrooksCoreyOilGas(), MaterialLib::PorousMedium::createWettingPhaseVanGenuchten(), anonymous_namespace{ProcessVariable.cpp}::findMeshInConfig(), ProcessLib::findParameter(), ProcessLib::findProcessVariable(), Adsorption::Reaction::newInstance(), operator=(), and anonymous_namespace{ProjectData.cpp}::readMeshes().

41 {
42  if (auto p = getConfigParameterOptional<T>(param))
43  return *p;
44 
45  error("Key <" + param + "> has not been found");
46 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213

◆ getConfigParameter() [2/3]

template<typename T >
T BaseLib::ConfigTree::getConfigParameter ( std::string const &  param,
T const &  default_value 
) const

Get parameter param of type T from the configuration tree or the default_value.

This method has a similar behaviour as getConfigParameter(std::string const&) except the default_value is returned if the attribute has not been found.

Precondition
param must not have been read before from this ConfigTree.

Definition at line 51 of file ConfigTree-impl.h.

52 {
53  if (auto p = getConfigParameterOptional<T>(param))
54  return *p;
55 
56  return default_value;
57 }

◆ getConfigParameter() [3/3]

ConfigTree BaseLib::ConfigTree::getConfigParameter ( std::string const &  param) const

Get parameter param from the configuration tree.

Returns
the subtree representing the requested parameter
Precondition
param must not have been read before from this ConfigTree.

Definition at line 112 of file ConfigTree.cpp.

References error(), getConfigParameterOptional(), and getConfigSubtree().

113 {
114  auto ct = getConfigSubtree(root);
115  if (ct.hasChildren())
116  error("Requested parameter <" + root + "> actually is a subtree.");
117  return ct;
118 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
ConfigTree getConfigSubtree(std::string const &root) const
Definition: ConfigTree.cpp:146

◆ getConfigParameterList() [1/2]

template<typename T >
Range< ConfigTree::ValueIterator< T > > BaseLib::ConfigTree::getConfigParameterList ( std::string const &  param) const

Fetches all parameters with name param from the current level of the tree.

The return value is suitable to be used with range-base for-loops.

Precondition
param must not have been read before from this ConfigTree.

Definition at line 108 of file ConfigTree-impl.h.

References peekConfigParameter().

Referenced by ProcessLib::HeatTransportBHE::createHeatTransportBHEProcess(), ProcessLib::LIE::HydroMechanics::createHydroMechanicsProcess(), ProcessLib::LIE::SmallDeformation::createSmallDeformationProcess(), ProcessLib::findProcessVariables(), getConfigParameterOptional(), getConfigParameterOptionalImpl(), and GeoLib::IO::BoostXmlGmlInterface::readPoints().

109 {
110  checkUnique(param);
111  markVisited<T>(param, Attr::TAG, true);
112 
113  auto p = _tree->equal_range(param);
114  return Range<ValueIterator<T> >(
115  ValueIterator<T>(p.first, param, *this),
116  ValueIterator<T>(p.second, param, *this));
117 }
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUnique(std::string const &key) const
Asserts that the key has not been read yet.
Definition: ConfigTree.cpp:295

◆ getConfigParameterList() [2/2]

Range< ConfigTree::ParameterIterator > BaseLib::ConfigTree::getConfigParameterList ( std::string const &  param) const

Fetches all parameters with name param from the current level of the tree.

The return value is suitable to be used with range-base for-loops.

Precondition
param must not have been read before from this ConfigTree.

Definition at line 132 of file ConfigTree.cpp.

References _tree, checkUnique(), getConfigSubtree(), markVisited(), and TAG.

133 {
134  checkUnique(param);
135  markVisited(param, Attr::TAG, true);
136 
137  auto p = _tree->equal_range(param);
138 
139  return Range<ParameterIterator>(
140  ParameterIterator(p.first, param, *this),
141  ParameterIterator(p.second, param, *this));
142 }
CountType & markVisited(std::string const &key, Attr const is_attr, bool peek_only) const
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUnique(std::string const &key) const
Asserts that the key has not been read yet.
Definition: ConfigTree.cpp:295

◆ getConfigParameterOptional() [1/2]

template<typename T >
boost::optional< T > BaseLib::ConfigTree::getConfigParameterOptional ( std::string const &  param) const

Get parameter param of type T from the configuration tree if present

This method has a similar behaviour as getConfigParameter(std::string const&) except no errors are raised. Rather it can be told from the return value if the parameter could be read.

Precondition
param must not have been read before from this ConfigTree.

Definition at line 60 of file ConfigTree-impl.h.

Referenced by MaterialLib::PorousMedium::createBrooksCorey(), ProcessLib::createCentralDifferencesJacobianAssembler(), ProcessLib::ComponentTransport::createComponentTransportProcess(), ProcessLib::createConstantParameter(), NumLib::createConvergenceCriterionDeltaX(), NumLib::createConvergenceCriterionPerComponentDeltaX(), NumLib::createConvergenceCriterionPerComponentResidual(), NumLib::createConvergenceCriterionResidual(), ProcessLib::HT::createHTProcess(), ProcessLib::HydroMechanics::createHydroMechanicsProcess(), ProcessLib::LIE::HydroMechanics::createHydroMechanicsProcess(), ProcessLib::LiquidFlow::createLiquidFlowProcess(), ProcessLib::createOutput(), ProcessLib::PhaseField::createPhaseFieldProcess(), ProcessLib::RichardsComponentTransport::createRichardsComponentTransportProcess(), ProcessLib::RichardsMechanics::createRichardsMechanicsProcess(), ProcessLib::ThermoMechanics::createThermoMechanicsProcess(), MaterialLib::PorousMedium::createVanGenuchten(), MathLib::ODE::CVodeSolverImpl::CVodeSolverImpl(), anonymous_namespace{ProcessVariable.cpp}::findMeshInConfig(), getConfigParameter(), MathLib::LisOption::LisOption(), ProjectData::ProjectData(), and ProcessLib::TES::TESProcess::TESProcess().

62 {
63  checkUnique(param);
64 
65  return getConfigParameterOptionalImpl(param, static_cast<T*>(nullptr));
66 }
boost::optional< T > getConfigParameterOptionalImpl(std::string const &param, T *) const
Default implementation of reading a value of type T.
void checkUnique(std::string const &key) const
Asserts that the key has not been read yet.
Definition: ConfigTree.cpp:295

◆ getConfigParameterOptional() [2/2]

boost::optional< ConfigTree > BaseLib::ConfigTree::getConfigParameterOptional ( std::string const &  param) const

Get parameter param from the configuration tree if present.

Returns
the subtree representing the requested parameter
Precondition
param must not have been read before from this ConfigTree.

Definition at line 122 of file ConfigTree.cpp.

References error(), getConfigParameterList(), and getConfigSubtreeOptional().

123 {
124  auto ct = getConfigSubtreeOptional(root);
125  if (ct && ct->hasChildren())
126  error("Requested parameter <" + root + "> actually is a subtree.");
127  return ct;
128 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
boost::optional< ConfigTree > getConfigSubtreeOptional(std::string const &root) const
Definition: ConfigTree.cpp:156

◆ getConfigParameterOptionalImpl() [1/2]

template<typename T >
boost::optional< T > BaseLib::ConfigTree::getConfigParameterOptionalImpl ( std::string const &  param,
T *   
) const
private

Default implementation of reading a value of type T.

Definition at line 69 of file ConfigTree-impl.h.

71 {
72  if (auto p = getConfigSubtreeOptional(param)) return p->getValue<T>();
73 
74  return boost::none;
75 }
boost::optional< ConfigTree > getConfigSubtreeOptional(std::string const &root) const
Definition: ConfigTree.cpp:156

◆ getConfigParameterOptionalImpl() [2/2]

template<typename T >
boost::optional< std::vector< T > > BaseLib::ConfigTree::getConfigParameterOptionalImpl ( std::string const &  param,
std::vector< T > *   
) const
private

Implementation of reading a vector of values of type T.

Definition at line 78 of file ConfigTree-impl.h.

References getConfigParameterList().

80 {
81  if (auto p = getConfigSubtreeOptional(param))
82  {
83  std::istringstream sstr{p->getValue<std::string>()};
84  std::vector<T> result;
85  T value;
86  while (sstr >> value)
87  result.push_back(value);
88  if (!sstr.eof()) // The stream is not read until the end, must be an
89  // error. result contains number of read values.
90  {
91  error("Value for key <" + param + "> `" +
92  shortString(sstr.str()) +
93  "' not convertible to a vector of the desired type."
94  " Could not convert token no. " +
95  std::to_string(result.size() + 1) + ".");
96  return boost::none;
97  }
98 
99  return boost::make_optional(result);
100  }
101 
102  return boost::none;
103 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
static std::string shortString(std::string const &s)
returns a short string at suitable for error/warning messages
Definition: ConfigTree.cpp:256
boost::optional< ConfigTree > getConfigSubtreeOptional(std::string const &root) const
Definition: ConfigTree.cpp:156

◆ getConfigSubtree()

ConfigTree BaseLib::ConfigTree::getConfigSubtree ( std::string const &  root) const

Get the subtree rooted at root

If root is not found error() is called.

Precondition
root must not have been read before from this ConfigTree.

Definition at line 146 of file ConfigTree.cpp.

References error(), and getConfigSubtreeOptional().

Referenced by ProcessLib::HeatTransportBHE::BHE::createBHE1U(), MaterialLib::PorousMedium::createCapillaryPressureModel(), ProcessLib::createCompareJacobiansJacobianAssembler(), ProcessLib::ComponentTransport::createComponentTransportProcess(), NumLib::createFixedTimeStepping(), MaterialLib::Fluid::createFluidProperties(), ProcessLib::GroundwaterFlow::createGroundwaterFlowProcess(), ProcessLib::HeatConduction::createHeatConductionProcess(), ProcessLib::HeatTransportBHE::createHeatTransportBHEProcess(), ProcessLib::HT::createHTProcess(), ProcessLib::HydroMechanics::createHydroMechanicsProcess(), ProcessLib::LIE::HydroMechanics::createHydroMechanicsProcess(), ProcessLib::LiquidFlow::createLiquidFlowMaterialProperties(), ProcessLib::LiquidFlow::createLiquidFlowProcess(), MaterialLib::createNewtonRaphsonSolverParameters(), ProcessLib::createOutput(), ProcessLib::PhaseField::createPhaseFieldProcess(), MaterialLib::PorousMedium::createPorousMediaProperties(), MaterialLib::PorousMedium::createRelativePermeabilityModel(), ProcessLib::RichardsComponentTransport::createRichardsComponentTransportProcess(), ProcessLib::RichardsFlow::createRichardsFlowMaterialProperties(), ProcessLib::RichardsFlow::createRichardsFlowProcess(), ProcessLib::RichardsMechanics::createRichardsMechanicsProcess(), ProcessLib::SmallDeformationNonlocal::createSmallDeformationNonlocalProcess(), ProcessLib::SmallDeformation::createSmallDeformationProcess(), ProcessLib::LIE::SmallDeformation::createSmallDeformationProcess(), ProcessLib::TES::createTESProcess(), ProcessLib::ThermalTwoPhaseFlowWithPP::createThermalTwoPhaseFlowWithPPProcess(), ProcessLib::ThermoMechanicalPhaseField::createThermoMechanicalPhaseFieldProcess(), ProcessLib::ThermoMechanics::createThermoMechanicsProcess(), BaseLib::createTimeInterval(), MaterialLib::TwoPhaseFlowWithPP::createTwoPhaseFlowMaterialProperties(), ProcessLib::TwoPhaseFlowWithPrho::createTwoPhaseFlowPrhoMaterialProperties(), ProcessLib::TwoPhaseFlowWithPP::createTwoPhaseFlowWithPPMaterialProperties(), ProcessLib::TwoPhaseFlowWithPP::createTwoPhaseFlowWithPPProcess(), ProcessLib::TwoPhaseFlowWithPrho::createTwoPhaseFlowWithPrhoProcess(), ProcessLib::createUncoupledProcessesTimeLoop(), getConfigParameter(), getConfigParameterList(), ProcessLib::HeatTransportBHE::BHE::parseBHECoaxialConfig(), ProjectData::ProjectData(), Adsorption::ReactionCaOH2::ReactionCaOH2(), and ProcessLib::TES::TESProcess::TESProcess().

147 {
148  if (auto t = getConfigSubtreeOptional(root)) {
149  return std::move(*t);
150  }
151  error("Key <" + root + "> has not been found.");
152 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
boost::optional< ConfigTree > getConfigSubtreeOptional(std::string const &root) const
Definition: ConfigTree.cpp:156

◆ getConfigSubtreeList()

Range< ConfigTree::SubtreeIterator > BaseLib::ConfigTree::getConfigSubtreeList ( std::string const &  root) const

Get all subtrees that have a root root from the current level of the tree.

The return value is suitable to be used with range-base for-loops.

Precondition
root must not have been read before from this ConfigTree.

Definition at line 170 of file ConfigTree.cpp.

References _tree, checkUnique(), markVisited(), and TAG.

Referenced by MaterialLib::Solids::createConstitutiveRelations(), NumLib::createFixedTimeStepping(), ProcessLib::createFunctionParameter(), ProcessLib::createGroupBasedParameter(), ProcessLib::createPerProcessData(), ProcessLib::RichardsComponentTransport::createPorousMediaProperties(), ProcessLib::LIE::SmallDeformation::createSmallDeformationProcess(), getConfigSubtreeOptional(), InSituLib::Initialize(), ProjectData::parseLinearSolvers(), ProjectData::parseNonlinearSolvers(), ProjectData::parseParameters(), ProjectData::parseProcesses(), ProjectData::parseProcessVariables(), GeoLib::IO::BoostXmlGmlInterface::readPolylines(), GeoLib::IO::BoostXmlGmlInterface::readSurfaces(), and ApplicationsLib::TestDefinition::TestDefinition().

171 {
172  checkUnique(root);
173  markVisited(root, Attr::TAG, true);
174 
175  auto p = _tree->equal_range(root);
176 
177  return Range<SubtreeIterator>(
178  SubtreeIterator(p.first, root, *this),
179  SubtreeIterator(p.second, root, *this));
180 }
CountType & markVisited(std::string const &key, Attr const is_attr, bool peek_only) const
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUnique(std::string const &key) const
Asserts that the key has not been read yet.
Definition: ConfigTree.cpp:295

◆ getConfigSubtreeOptional()

boost::optional< ConfigTree > BaseLib::ConfigTree::getConfigSubtreeOptional ( std::string const &  root) const

Get the subtree rooted at root if present

Precondition
root must not have been read before from this ConfigTree.

Definition at line 156 of file ConfigTree.cpp.

References _tree, checkUnique(), ConfigTree(), getConfigSubtreeList(), markVisited(), and TAG.

Referenced by anonymous_namespace{CreateComponent.cpp}::createComponent(), ProcessLib::createDeactivatedSubdomains(), MaterialLib::Fluid::createFluidProperties(), MaterialPropertyLib::createMedium(), ProcessLib::createOutput(), anonymous_namespace{CreatePhase.cpp}::createPhase(), MeshGeoToolsLib::createSearchLengthAlgorithm(), ProcessLib::createSecondaryVariables(), ProcessLib::createUncoupledProcessesTimeLoop(), getConfigParameterOptional(), getConfigSubtree(), MathLib::PETScLinearSolver::PETScLinearSolver(), ProcessLib::ProcessVariable::ProcessVariable(), ProjectData::ProjectData(), anonymous_namespace{ProjectData.cpp}::readMeshes(), and MathLib::EigenLinearSolver::setOption().

157 {
158  checkUnique(root);
159 
160  if (auto subtree = _tree->get_child_optional(root)) {
161  markVisited(root, Attr::TAG, false);
162  return ConfigTree(*subtree, *this, root);
163  }
164  markVisited(root, Attr::TAG, true);
165  return boost::none;
166 }
CountType & markVisited(std::string const &key, Attr const is_attr, bool peek_only) const
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUnique(std::string const &key) const
Asserts that the key has not been read yet.
Definition: ConfigTree.cpp:295
ConfigTree(PTree const &tree, std::string filename, Callback error_cb, Callback warning_cb)
Definition: ConfigTree.cpp:34

◆ getValue()

template<typename T >
T BaseLib::ConfigTree::getValue ( ) const

Get the plain data contained in the current level of the tree.

Returns
the data converted to the type T
Precondition
The data must not have been read before.

Definition at line 167 of file ConfigTree-impl.h.

References getConfigAttribute().

Referenced by checkConfigParameter(), and anonymous_namespace{ProjectData.cpp}::readSingleMesh().

168 {
169  if (_have_read_data) {
170  error("The data of this subtree has already been read.");
171  }
172 
173  _have_read_data = true;
174 
175  if (auto v = _tree->get_value_optional<T>()) {
176  return *v;
177  }
178  error("Value `" + shortString(_tree->data()) +
179  "' is not convertible to the desired type.");
180 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
bool _have_read_data
Indicates if the plain data contained in this tree has already been read.
Definition: ConfigTree.h:627
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
static std::string shortString(std::string const &s)
returns a short string at suitable for error/warning messages
Definition: ConfigTree.cpp:256

◆ hasChildren()

bool BaseLib::ConfigTree::hasChildren ( ) const
private

Checks if this tree has any children.

Definition at line 352 of file ConfigTree.cpp.

References _tree.

353 {
354  auto const& tree = *_tree;
355  if (tree.begin() == tree.end())
356  return false; // no children
357  if (tree.front().first == "<xmlattr>"
358  && (++tree.begin()) == tree.end())
359  return false; // only attributes
360 
361  return true;
362 }
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606

◆ ignoreConfigAttribute()

void BaseLib::ConfigTree::ignoreConfigAttribute ( std::string const &  attr) const

Tell this instance to ignore the XML attribute attr.

This method is used to avoid warning messages.

Precondition
attr must not have been read before from this ConfigTree.

Definition at line 190 of file ConfigTree.cpp.

References _tree, ATTR, checkUniqueAttr(), and markVisited().

191 {
192  checkUniqueAttr(attr);
193 
194  // Exercise: Guess what not! (hint: if not found, peek only)
195  // Btw. (not a hint) _tree->find() does not seem to work here.
196  bool peek_only = !_tree->get_child_optional("<xmlattr>." + attr);
197 
198  markVisited(attr, Attr::ATTR, peek_only);
199 }
CountType & markVisited(std::string const &key, Attr const is_attr, bool peek_only) const
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUniqueAttr(std::string const &attr) const
Asserts that the attribute attr has not been read yet.
Definition: ConfigTree.cpp:304

◆ ignoreConfigParameter()

void BaseLib::ConfigTree::ignoreConfigParameter ( std::string const &  param) const

Tell this instance to ignore parameter param.

This method is used to avoid warning messages.

Precondition
param must not have been read before from this ConfigTree.

Definition at line 182 of file ConfigTree.cpp.

References _tree, checkUnique(), markVisited(), and TAG.

Referenced by NumLib::createTimeStepper(), and MathLib::ignoreOtherLinearSolvers().

183 {
184  checkUnique(param);
185  // if not found, peek only
186  bool peek_only = _tree->find(param) == _tree->not_found();
187  markVisited(param, Attr::TAG, peek_only);
188 }
CountType & markVisited(std::string const &key, Attr const is_attr, bool peek_only) const
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUnique(std::string const &key) const
Asserts that the key has not been read yet.
Definition: ConfigTree.cpp:295

◆ ignoreConfigParameterAll()

void BaseLib::ConfigTree::ignoreConfigParameterAll ( std::string const &  param) const

Tell this instance to ignore all parameters param on the current level of the tree.

This method is used to avoid warning messages.

Precondition
param must not have been read before from this ConfigTree.

Definition at line 201 of file ConfigTree.cpp.

References _tree, checkUnique(), markVisited(), and TAG.

202 {
203  checkUnique(param);
204  auto& ct = markVisited(param, Attr::TAG, true);
205 
206  auto p = _tree->equal_range(param);
207  for (auto it = p.first; it != p.second; ++it) {
208  ++ct.count;
209  }
210 }
CountType & markVisited(std::string const &key, Attr const is_attr, bool peek_only) const
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkUnique(std::string const &key) const
Asserts that the key has not been read yet.
Definition: ConfigTree.cpp:295

◆ joinPaths()

std::string BaseLib::ConfigTree::joinPaths ( std::string const &  p1,
std::string const &  p2 
) const
private

Used to generate the path of a subtree.

Definition at line 284 of file ConfigTree.cpp.

References error(), and pathseparator.

Referenced by checkKeyname().

285 {
286  if (p2.empty()) {
287  error("Second path to be joined is empty.");
288  }
289 
290  if (p1.empty()) return p2;
291 
292  return p1 + pathseparator + p2;
293 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
static const char pathseparator
Character separating two path components.
Definition: ConfigTree.h:633

◆ markVisited() [1/2]

template<typename T >
ConfigTree::CountType & BaseLib::ConfigTree::markVisited ( std::string const &  key,
Attr const  is_attr,
bool  peek_only 
) const
private

Keeps track of the key key and its value type T.

This method asserts that a key is read always with the same type.

param peek_only if true, do not change the read-count of the given key.

Definition at line 229 of file ConfigTree-impl.h.

Referenced by checkUniqueAttr(), getConfigAttributeOptional(), getConfigParameterList(), getConfigSubtreeList(), getConfigSubtreeOptional(), ignoreConfigAttribute(), ignoreConfigParameter(), ignoreConfigParameterAll(), BaseLib::ConfigTree::SubtreeIterator::operator*(), and BaseLib::ConfigTree::ValueIterator< ValueType >::operator*().

231 {
232  auto const type = std::type_index(typeid(T));
233 
234  auto p = _visited_params.emplace(std::make_pair(is_attr, key),
235  CountType{peek_only ? 0 : 1, type});
236 
237  if (!p.second) { // no insertion happened
238  auto& v = p.first->second;
239  if (v.type == type) {
240  if (!peek_only) ++v.count;
241  } else {
242  error("There already was an attempt to obtain key <" + key +
243  "> with type '" + v.type.name() + "' (now: '" + type.name() +
244  "').");
245  }
246  }
247 
248  return p.first->second;
249 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
std::map< KeyType, CountType > _visited_params
Definition: ConfigTree.h:624

◆ markVisited() [2/2]

ConfigTree::CountType & BaseLib::ConfigTree::markVisited ( std::string const &  key,
Attr const  is_attr,
bool const  peek_only 
) const
private

Keeps track of the key key and its value type ConfigTree.

This method asserts that a key is read always with the same type.

param peek_only if true, do not change the read-count of the given key.

Definition at line 331 of file ConfigTree.cpp.

References markVisitedDecrement().

332 {
333  return markVisited<ConfigTree>(key, is_attr, peek_only);
334 }

◆ markVisitedDecrement()

void BaseLib::ConfigTree::markVisitedDecrement ( Attr const  is_attr,
std::string const &  key 
) const
private

Used in the destructor to compute the difference between number of reads of a parameter and the number of times it exists in the ConfigTree

Definition at line 338 of file ConfigTree.cpp.

References _visited_params.

Referenced by checkAndInvalidate(), and markVisited().

339 {
340  auto const type = std::type_index(typeid(nullptr));
341 
342  auto p = _visited_params.emplace(std::make_pair(is_attr, key),
343  CountType{-1, type});
344 
345  if (!p.second) { // no insertion happened
346  auto& v = p.first->second;
347  --v.count;
348  }
349 }
std::map< KeyType, CountType > _visited_params
Definition: ConfigTree.h:624

◆ onerror()

void BaseLib::ConfigTree::onerror ( std::string const &  filename,
std::string const &  path,
std::string const &  message 
)
static

Default error callback function Will throw std::runtime_error

Definition at line 227 of file ConfigTree.cpp.

References OGS_FATAL.

229 {
230  OGS_FATAL("ConfigTree: In file `%s' at path <%s>: %s",
231  filename.c_str(), path.c_str(), message.c_str());
232 }
#define OGS_FATAL(fmt,...)
Definition: Error.h:71

◆ onwarning()

void BaseLib::ConfigTree::onwarning ( std::string const &  filename,
std::string const &  path,
std::string const &  message 
)
static

Default warning callback function Will print a warning message

Definition at line 234 of file ConfigTree.cpp.

236 {
237  WARN("ConfigTree: In file `%s' at path <%s>: %s",
238  filename.c_str(), path.c_str(), message.c_str());
239 }

◆ operator=() [1/2]

ConfigTree& BaseLib::ConfigTree::operator= ( ConfigTree const &  )
delete

copying is not compatible with the semantics of this class

Referenced by ~ConfigTree().

◆ operator=() [2/2]

ConfigTree & BaseLib::ConfigTree::operator= ( ConfigTree &&  other)

After being moved from, other is in an undefined state and must not be used anymore!

Definition at line 94 of file ConfigTree.cpp.

References _filename, _have_read_data, _onerror, _onwarning, _path, _tree, _visited_params, checkAndInvalidate(), and getConfigParameter().

95 {
97 
98  _tree = other._tree;
99  other._tree = nullptr;
100  _path = std::move(other._path);
101  _filename = std::move(other._filename);
102  _visited_params = std::move(other._visited_params);
103  _have_read_data = other._have_read_data;
104  _onerror = std::move(other._onerror);
105  _onwarning = std::move(other._onwarning);
106 
107  return *this;
108 }
std::string _path
A path printed in error/warning messages.
Definition: ConfigTree.h:609
bool _have_read_data
Indicates if the plain data contained in this tree has already been read.
Definition: ConfigTree.h:627
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
std::map< KeyType, CountType > _visited_params
Definition: ConfigTree.h:624
std::string _filename
The path of the file from which this tree has been read.
Definition: ConfigTree.h:612
Callback _onerror
Custom error callback.
Definition: ConfigTree.h:629
Callback _onwarning
Custom warning callback.
Definition: ConfigTree.h:630

◆ peekConfigParameter()

template<typename T >
T BaseLib::ConfigTree::peekConfigParameter ( std::string const &  param) const

Peek at a parameter param of type T from the configuration tree.

This method is an exception to the single-read rule. It is meant to be used to tell from a ConfigTree instance where to pass that instance on for further processing.

But in order that the requested parameter counts as "completely parsed", it has to be read through some other method, too.

Return value and error behaviour are the same as for getConfigParameter<T>(std::string const&).

Definition at line 122 of file ConfigTree-impl.h.

References checkConfigParameter().

Referenced by ProcessLib::createBoundaryCondition(), MaterialLib::PorousMedium::createCapillaryPressureModel(), MaterialLib::Solids::createConstitutiveRelation(), NumLib::createConvergenceCriterion(), ProcessLib::createDeactivatedSubdomain(), ProcessLib::createDirichletBoundaryConditionWithinTimeInterval(), MaterialLib::Fluid::createFluidDensityModel(), ProcessLib::createParameter(), MaterialLib::PorousMedium::createRelativePermeabilityModel(), ProcessLib::LIE::SmallDeformation::createSmallDeformationProcess(), ProcessLib::createSourceTerm(), ProcessLib::ThermoMechanics::createThermoMechanicsProcess(), NumLib::createTimeStepper(), MaterialLib::Fluid::createViscosityModel(), and getConfigParameterList().

123 {
124  checkKeyname(param);
125 
126  if (auto p = _tree->get_child_optional(param))
127  {
128  try
129  {
130  return p->get_value<T>();
131  }
132  catch (boost::property_tree::ptree_bad_data const&)
133  {
134  error("Value for key <" + param + "> `" + shortString(p->data()) +
135  "' not convertible to the desired type.");
136  }
137  }
138  else
139  {
140  error("Key <" + param + "> has not been found");
141  }
142 }
void error(std::string const &message) const
Definition: ConfigTree.cpp:213
boost::property_tree::ptree const * _tree
The wrapped tree.
Definition: ConfigTree.h:606
void checkKeyname(std::string const &key) const
Checks if key complies with the rules [a-z0-9_].
Definition: ConfigTree.cpp:266
static std::string shortString(std::string const &s)
returns a short string at suitable for error/warning messages
Definition: ConfigTree.cpp:256

◆ shortString()

std::string BaseLib::ConfigTree::shortString ( std::string const &  s)
staticprivate

returns a short string at suitable for error/warning messages

Definition at line 256 of file ConfigTree.cpp.

Referenced by checkAndInvalidate().

257 {
258  const std::size_t maxlen = 100;
259 
260  if (s.size() < maxlen) return s;
261 
262  return s.substr(0, maxlen-3) + "...";
263 }

◆ warning()

void BaseLib::ConfigTree::warning ( std::string const &  message) const
private

Called for printing warning messages. Will call the warning callback. This method only acts as a helper method.

Definition at line 221 of file ConfigTree.cpp.

References _filename, _onwarning, and _path.

Referenced by checkAndInvalidate().

222 {
223  _onwarning(_filename, _path, message);
224 }
std::string _path
A path printed in error/warning messages.
Definition: ConfigTree.h:609
std::string _filename
The path of the file from which this tree has been read.
Definition: ConfigTree.h:612
Callback _onwarning
Custom warning callback.
Definition: ConfigTree.h:630

Friends And Related Function Documentation

◆ checkAndInvalidate [1/3]

void checkAndInvalidate ( ConfigTree *const  conf)
friend

Check if conf has been read entirely and invalidate it.

This method can savely be called on nullptr's.

See also
ConfigTree::checkAndInvalidate()

Definition at line 431 of file ConfigTree.cpp.

432 {
433  if (conf) conf->checkAndInvalidate();
434 }

◆ checkAndInvalidate [2/3]

void checkAndInvalidate ( ConfigTree conf)
friend

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 426 of file ConfigTree.cpp.

427 {
428  conf.checkAndInvalidate();
429 }

◆ checkAndInvalidate [3/3]

void checkAndInvalidate ( std::unique_ptr< ConfigTree > const &  conf)
friend

This is an overloaded member function, provided for convenience. It differs from the above function only in what argument(s) it accepts.

Definition at line 436 of file ConfigTree.cpp.

437 {
438  if (conf) conf->checkAndInvalidate();
439 }

Member Data Documentation

◆ _filename

std::string BaseLib::ConfigTree::_filename
private

The path of the file from which this tree has been read.

Definition at line 612 of file ConfigTree.h.

Referenced by error(), operator=(), and warning().

◆ _have_read_data

bool BaseLib::ConfigTree::_have_read_data = false
mutableprivate

Indicates if the plain data contained in this tree has already been read.

Definition at line 627 of file ConfigTree.h.

Referenced by checkAndInvalidate(), and operator=().

◆ _onerror

Callback BaseLib::ConfigTree::_onerror
private

Custom error callback.

Definition at line 629 of file ConfigTree.h.

Referenced by ConfigTree(), error(), and operator=().

◆ _onwarning

Callback BaseLib::ConfigTree::_onwarning
private

Custom warning callback.

Definition at line 630 of file ConfigTree.h.

Referenced by ConfigTree(), operator=(), and warning().

◆ _path

std::string BaseLib::ConfigTree::_path
private

A path printed in error/warning messages.

Definition at line 609 of file ConfigTree.h.

Referenced by error(), operator=(), and warning().

◆ _tree

boost::property_tree::ptree const* BaseLib::ConfigTree::_tree
private

◆ _visited_params

std::map<KeyType, CountType> BaseLib::ConfigTree::_visited_params
mutableprivate

A map KeyType -> (count, type) keeping track which parameters have been read how often and which datatype they have.

This member will be written to when reading from the config tree. Therefore it has to be mutable in order to be able to read from constant instances, e.g., those passed as constant references to temporaries.

Definition at line 624 of file ConfigTree.h.

Referenced by checkAndInvalidate(), checkUnique(), checkUniqueAttr(), markVisitedDecrement(), and operator=().

◆ key_chars

const std::string BaseLib::ConfigTree::key_chars = key_chars_start + "_0123456789"
staticprivate

Set of allowed characters in a key name.

Definition at line 639 of file ConfigTree.h.

Referenced by checkKeyname().

◆ key_chars_start

const std::string BaseLib::ConfigTree::key_chars_start = "abcdefghijklmnopqrstuvwxyz"
staticprivate

Set of allowed characters as the first letter of a key name.

Definition at line 636 of file ConfigTree.h.

Referenced by checkKeyname().

◆ pathseparator

const char BaseLib::ConfigTree::pathseparator = '/'
staticprivate

Character separating two path components.

Definition at line 633 of file ConfigTree.h.

Referenced by joinPaths().


The documentation for this class was generated from the following files: