Logo ROOT  
Reference Guide
 
Loading...
Searching...
No Matches
JSONInterface.cxx
Go to the documentation of this file.
1/*
2 * Project: RooFit
3 * Authors:
4 * Carsten D. Burgard, DESY/ATLAS, Dec 2021
5 *
6 * Copyright (c) 2022, CERN
7 *
8 * Redistribution and use in source and binary forms,
9 * with or without modification, are permitted according to the terms
10 * listed in LICENSE (http://roofit.sourceforge.net/license.txt)
11 */
12
14
15#include "JSONReadRecorder.h"
16
17#include <nlohmann/json.hpp>
18
19#include <algorithm>
20#include <cstdlib>
21#include <deque>
22#include <iomanip>
23#include <istream>
24#include <iterator>
25#include <limits>
26#include <memory>
27#include <sstream>
28
29// This is the only translation unit where the JSON parsing library is used.
30// Hence, the JSON engine backing the RooFit::Detail::JSONTree could in
31// principle be swapped out by changing only this file.
32
33namespace RooFit {
34namespace Detail {
35
36namespace {
37
38nlohmann::json &json(void *value)
39{
40 return *static_cast<nlohmann::json *>(value);
41}
42
43// Receives the events of a parse that only looks for the syntax error, see parse().
44class SyntaxErrorRecorder : public nlohmann::json_sax<nlohmann::json> {
45public:
46 bool null() override { return true; }
47 bool boolean(bool) override { return true; }
48 bool number_integer(number_integer_t) override { return true; }
49 bool number_unsigned(number_unsigned_t) override { return true; }
50 bool number_float(number_float_t, const string_t &) override { return true; }
51 bool string(string_t &) override { return true; }
52 bool binary(binary_t &) override { return true; }
53 bool start_object(std::size_t) override { return true; }
54 bool key(string_t &) override { return true; }
55 bool end_object() override { return true; }
56 bool start_array(std::size_t) override { return true; }
57 bool end_array() override { return true; }
58 bool parse_error(std::size_t, const std::string &, const nlohmann::json::exception &ex) override
59 {
60 message = ex.what();
61 return false;
62 }
63
64 std::string message;
65};
66
67// Parse without exceptions of the JSON library. For invalid input, the input is parsed again to get the message.
68nlohmann::json parse(std::string const &input)
69{
70 nlohmann::json out = nlohmann::json::parse(input, nullptr, /*allow_exceptions=*/false);
71 if (out.is_discarded()) {
72 SyntaxErrorRecorder recorder;
73 nlohmann::json::sax_parse(input, &recorder);
74 throw std::runtime_error(recorder.message);
75 }
76 return out;
77}
78
79// Reading a value with the wrong type throws an std::runtime_error, not an exception of the JSON library.
80[[noreturn]] void throwTypeError(std::string const &key, const char *expected, nlohmann::json const &value)
81{
82 throw std::runtime_error("node \"" + key + "\": expected " + expected + ", but the value is of type " +
83 value.type_name());
84}
85
86// Makes a value a map or an array. Only a value that has no type yet or is an empty string, which is what
87// append_child() creates, can change its type.
88void setContainerType(nlohmann::json &value, nlohmann::json::value_t type, std::string const &key)
89{
90 if (value.type() == type) {
91 return;
92 }
93 if (!value.is_null() && !(value.is_string() && value.get_ref<std::string const &>().empty())) {
94 throw std::runtime_error("cannot declare \"" + key + "\" to be of " +
95 (type == nlohmann::json::value_t::object ? "map" : "seq") + " - type, already of type " +
96 value.type_name());
97 }
98 // Not with braces, which would create an array with one element.
99 value = nlohmann::json(type);
100}
101
102} // namespace
103
104// The nodes live as long as the tree, because the interface hands out references to them.
106public:
107 // Not root{value}, which would be an array that contains the value.
108 explicit Storage(nlohmann::json value) : root(std::move(value)), rootNode{*this, &root, ""} {}
109
110 JSONNode &makeNode(nlohmann::json &value, std::string key)
111 {
112 nodes.push_back(std::unique_ptr<JSONNode>{new JSONNode{*this, &value, std::move(key)}});
113 return *nodes.back();
114 }
115
116 // The children are created up front, such that the iterators can be pointers into this list.
117 std::vector<JSONNode *> const &makeChildren(nlohmann::json &value)
118 {
119 childLists.emplace_back();
120 std::vector<JSONNode *> &list = childLists.back();
121 if (!value.is_structured()) {
122 return list;
123 }
124 list.reserve(value.size());
125 for (auto it = value.begin(); it != value.end(); ++it) {
126 list.push_back(&makeNode(it.value(), value.is_array() ? "" : it.key()));
127 }
128 return list;
129 }
130
131 // Tells the recorders that the component `key` of `value` is read, where nullptr means all components.
132 void recordRead(void const *value, std::string const *key)
133 {
134 for (JSONReadRecorder *recorder : recorders) {
135 recorder->record(value, key);
136 }
137 }
138
139 nlohmann::json root;
141 std::vector<std::unique_ptr<JSONNode>> nodes;
142 std::deque<std::vector<JSONNode *>> childLists;
143 std::vector<JSONReadRecorder *> recorders;
144};
145
146// JSONNode
147
148JSONNode::JSONNode(Storage &storage, void *value, std::string key)
149 : _storage{&storage}, _value{value}, _key{std::move(key)}
150{
151}
152
153void JSONNode::writeJSON(std::ostream &os) const
154{
155 _storage->recordRead(_value, nullptr);
156 os << json(_value);
157}
158
159JSONNode &JSONNode::operator<<(std::string const &s)
160{
161 json(_value) = s;
162 return *this;
163}
164
166{
167 json(_value) = i;
168 return *this;
169}
170
172{
173 json(_value) = d;
174 return *this;
175}
176
178{
179 json(_value) = b;
180 return *this;
181}
182
183JSONNode &JSONNode::operator[](std::string const &k)
184{
185 return _storage->makeNode(json(_value)[k], k);
186}
187
188const JSONNode &JSONNode::operator[](std::string const &k) const
189{
191 return _storage->makeNode(json(_value)[k], k);
192}
193
195{
196 return json(_value).is_array() || json(_value).is_object();
197}
198
200{
201 return json(_value).is_object();
202}
203
205{
206 return json(_value).is_array();
207}
208
210{
211 return json(_value).is_null();
212}
213
215{
216 return json(_value).is_number();
217}
218
220{
221 setContainerType(json(_value), nlohmann::json::value_t::object, _key);
222 return *this;
223}
224
226{
227 setContainerType(json(_value), nlohmann::json::value_t::array, _key);
228 return *this;
229}
230
232{
233 json(_value) = nullptr;
234 return *this;
235}
236
238{
239 json(_value).clear();
240}
241
242void JSONNode::erase(std::string const &key)
243{
244 json(_value).erase(key);
245}
246
247std::string JSONNode::key() const
248{
249 return _key;
250}
251
252std::string JSONNode::val() const
253{
254 nlohmann::json const &value = json(_value);
255 switch (value.type()) {
256 case nlohmann::json::value_t::string: return value.get<std::string>();
257 case nlohmann::json::value_t::boolean: return value.get<bool>() ? "true" : "false";
258 case nlohmann::json::value_t::number_integer: return std::to_string(value.get<nlohmann::json::number_integer_t>());
259 case nlohmann::json::value_t::number_unsigned: return std::to_string(value.get<nlohmann::json::number_unsigned_t>());
260 case nlohmann::json::value_t::number_float: {
261 // The string has to read back as the same number. Start with the default precision of the streams, so that the
262 // numbers that six digits spell exactly keep their short spelling, and add digits as long as it takes.
263 const double number = value.get<double>();
264 std::stringstream ss;
265 for (int precision = 6; precision <= std::numeric_limits<double>::max_digits10; ++precision) {
266 ss.str("");
267 ss << std::setprecision(precision) << number;
268 if (std::strtod(ss.str().c_str(), nullptr) == number) {
269 break;
270 }
271 }
272 return ss.str();
273 }
274 default:
275 throw std::runtime_error("node \"" + _key + "\": implicit string conversion for type " + value.type_name() +
276 " not supported!");
277 }
278}
279
281{
282 auto const &nd = json(_value);
283 if (!nd.is_number() && !nd.is_boolean()) {
284 throwTypeError(_key, "a number", nd);
285 }
286 return nd.get<int>();
287}
289{
290 auto const &nd = json(_value);
291 if (!nd.is_number() && !nd.is_boolean()) {
292 throwTypeError(_key, "a number", nd);
293 }
294 return nd.get<double>();
295}
297{
298 std::optional<bool> out = try_val_bool();
299 if (!out) {
300 throwTypeError(_key, "a boolean", json(_value));
301 }
302 return *out;
303}
304
305std::optional<bool> JSONNode::try_val_bool() const
306{
307 auto const &nd = json(_value);
308 if (nd.is_boolean()) {
309 return nd.get<bool>();
310 }
311 // Attempting to convert zeroes and ones to bools.
312 if (nd.is_number_unsigned() && nd.get<nlohmann::json::number_unsigned_t>() <= 1) {
313 return nd.get<nlohmann::json::number_unsigned_t>() == 1;
314 }
315 return std::nullopt;
316}
317
319{
320 return json(_value).is_primitive();
321}
322
323bool JSONNode::has_child(std::string const &c) const
324{
326 return json(_value).find(c) != json(_value).end();
327}
328
330{
331 json(_value).push_back("");
332 return _storage->makeNode(json(_value).back(), "");
333}
334
336{
337 return json(_value).size();
338}
339
341{
342 return _storage->makeNode(json(_value).at(pos), "");
343}
344
345const JSONNode &JSONNode::child(size_t pos) const
346{
347 _storage->recordRead(_value, nullptr);
348 return _storage->makeNode(json(_value).at(pos), "");
349}
350
352{
353 std::vector<JSONNode *> const &list = _storage->makeChildren(json(_value));
354 return {child_iterator{list.data()}, child_iterator{list.data() + list.size()}};
355}
356
358{
359 _storage->recordRead(_value, nullptr);
360 std::vector<JSONNode *> const &list = _storage->makeChildren(json(_value));
361 return {const_child_iterator{list.data()}, const_child_iterator{list.data() + list.size()}};
362}
363
364// JSONTree
365
366JSONTree::JSONTree(std::unique_ptr<JSONNode::Storage> storage) : _storage{std::move(storage)} {}
367
368JSONTree::~JSONTree() = default;
369
371{
372 return _storage->rootNode;
373}
374
375std::unique_ptr<JSONTree> JSONTree::create()
376{
377 return std::unique_ptr<JSONTree>{new JSONTree{std::make_unique<JSONNode::Storage>(nlohmann::json{})}};
378}
379
380std::unique_ptr<JSONTree> JSONTree::create(std::istream &is)
381{
382 return JSONTree::create(std::string{std::istreambuf_iterator<char>{is}, std::istreambuf_iterator<char>{}});
383}
384
385std::unique_ptr<JSONTree> JSONTree::create(std::string const &str)
386{
387 return std::unique_ptr<JSONTree>{new JSONTree{std::make_unique<JSONNode::Storage>(parse(str))}};
388}
389
390// JSONReadRecorder
391
393{
394 _node._storage->recorders.push_back(this);
395}
396
398{
399 auto &recorders = _node._storage->recorders;
400 recorders.erase(std::find(recorders.begin(), recorders.end(), this));
401}
402
403void JSONReadRecorder::record(void const *value, std::string const *key)
404{
405 if (value != _node._value) {
406 return;
407 }
408 if (key) {
409 _read.insert(*key);
410 } else {
411 _readAll = true;
412 }
413}
414
415std::vector<std::string> JSONReadRecorder::unreadComponents() const
416{
417 std::vector<std::string> out;
418 nlohmann::json const &value = json(_node._value);
419 if (!value.is_object() || _readAll) {
420 return out;
421 }
422 for (auto const &item : value.items()) {
423 if (_read.count(item.key()) == 0) {
424 out.push_back(item.key());
425 }
426 }
427 return out;
428}
429
430} // namespace Detail
431} // namespace RooFit
std::string message
nlohmann::json json
#define d(i)
Definition RSha256.hxx:102
#define b(i)
Definition RSha256.hxx:100
#define c(i)
Definition RSha256.hxx:101
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void input
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void value
Option_t Option_t TPoint TPoint const char GetTextMagnitude GetFillStyle GetLineColor GetLineWidth GetMarkerStyle GetTextAlign GetTextColor GetTextSize void char Point_t Rectangle_t WindowAttributes_t Float_t Float_t Float_t Int_t Int_t UInt_t UInt_t Rectangle_t Int_t Int_t Window_t TString Int_t GCValues_t GetPrimarySelectionOwner GetDisplay GetScreen GetColormap GetNativeEvent const char const char dpyName wid window const char font_name cursor keysym reg const char only_if_exist regb h Point_t winding char text const char depth char const char Int_t count const char ColorStruct_t color const char Pixmap_t Pixmap_t PictureAttributes_t attr const char char ret_data h unsigned char height h Atom_t Int_t ULong_t ULong_t unsigned char prop_list Atom_t Atom_t Atom_t Time_t type
JSONNode & makeNode(nlohmann::json &value, std::string key)
std::vector< JSONReadRecorder * > recorders
std::vector< JSONNode * > const & makeChildren(nlohmann::json &value)
void recordRead(void const *value, std::string const *key)
std::deque< std::vector< JSONNode * > > childLists
std::vector< std::unique_ptr< JSONNode > > nodes
JSONNode & operator[](std::string const &k)
void erase(std::string const &key)
Remove a child of a map, if it exists.
void writeJSON(std::ostream &os) const
JSONNode & operator<<(std::string const &s)
std::string val() const
JSONNode(JSONNode const &)=delete
bool has_child(std::string const &) const
std::string key() const
std::optional< bool > try_val_bool() const
The value as a boolean, or std::nullopt if it is none. Like val_bool(), the integers 0 and 1 are acce...
JSONNode & child(size_t pos)
Records which components of a JSON map are read while it is alive, through any node of the tree.
std::set< std::string > _read
void record(void const *value, std::string const *key)
Called by the tree for every read of the component key of value, where nullptr means all components.
JSONReadRecorder(JSONNode const &node)
std::vector< std::string > unreadComponents() const
The components of the map that were not read.
static std::unique_ptr< JSONTree > create()
JSONTree(std::unique_ptr< JSONNode::Storage > storage)
std::unique_ptr< JSONNode::Storage > _storage
Double_t ex[n]
Definition legend1.C:17
The namespace RooFit contains mostly switches that change the behaviour of functions of PDFs (or othe...
Definition CodegenImpl.h:73
null_t< F > null()