-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathconfiguru.hpp
3665 lines (3150 loc) · 101 KB
/
configuru.hpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
www.github.com/emilk/configuru
# Configuru
Configuru, an experimental config library for C++, by Emil Ernerfeldt.
# License
This software is in the public domain. Where that dedication is not
recognized, you are granted a perpetual, irrevocable license to copy
and modify this file as you see fit.
That being said, I would appreciate credit!
If you find this library useful, send a tweet to [@ernerfeldt](https://twitter.com/ernerfeldt) or mail me at [email protected].
# Version history
0.0.0: 2014-07-21 - Initial steps
0.1.0: 2015-11-08 - First commit as stand-alone library
0.2.0: 2016-03-25 - check_dangling changes
0.2.1: 2016-04-11 - mark_accessed in dump_string by default
0.2.2: 2016-07-27 - optimizations
0.2.3: 2016-08-09 - optimizations + add Config::emplace(key, value)
0.2.4: 2016-08-18 - fix compilation error for when CONFIGURU_VALUE_SEMANTICS=0
0.3.0: 2016-09-15 - Add option to not align values (object_align_values)
0.3.1: 2016-09-19 - Fix crashes on some compilers/stdlibs
0.3.2: 2016-09-22 - Add support for Config::array(some_container)
0.3.3: 2017-01-10 - Add some missing iterator members
0.3.4: 2017-01-17 - Add cast conversion to std::array
0.4.0: 2017-04-17 - Automatic (de)serialization with serialize/deserialize with https://github.com/cbeck88/visit_struct
0.4.1: 2017-05-21 - Make it compile on VC++
0.4.2: 2018-11-02 - Automatic serialize/deserialize of maps and enums
# Getting started
For using:
`#include <configuru.hpp>`
And in one .cpp file:
#define CONFIGURU_IMPLEMENTATION 1
#include <configuru.hpp>
For more info, please see README.md (at www.github.com/emilk/configuru).
*/
// dP""b8 dP"Yb 88b 88 888888 88 dP""b8 88 88 88""Yb 88 88
// dP `" dP Yb 88Yb88 88__ 88 dP `" 88 88 88__dP 88 88
// Yb Yb dP 88 Y88 88"" 88 Yb "88 Y8 8P 88"Yb Y8 8P
// YboodP YbodP 88 Y8 88 88 YboodP `YbodP' 88 Yb `YbodP'
// Disable all warnings from gcc/clang/msvc:
#if defined(__clang__)
#pragma clang system_header
#elif defined(__GNUC__)
#pragma GCC system_header
#elif defined(_MSC_VER)
#pragma warning( push, 0)
#pragma warning( disable : 4715 )
#endif
#ifndef CONFIGURU_HEADER_HPP
#define CONFIGURU_HEADER_HPP
#include <algorithm>
#include <array>
#include <atomic>
#include <cmath>
#include <cstddef>
#include <cstring>
#include <functional>
#include <initializer_list>
#include <iosfwd>
#include <iterator>
#include <map>
#include <memory>
#include <stdexcept>
#include <string>
#include <type_traits>
#include <utility>
#include <vector>
#ifdef VISITABLE_STRUCT
#include <unordered_map>
#endif
#ifndef CONFIGURU_ONERROR
#define CONFIGURU_ONERROR(message_str) \
throw std::runtime_error(message_str)
#endif // CONFIGURU_ONERROR
#ifndef CONFIGURU_ASSERT
#include <cassert>
#define CONFIGURU_ASSERT(test) assert(test)
#endif // CONFIGURU_ASSERT
#ifndef CONFIGURU_ON_DANGLING
/// CONFIGURU_ON_DANGLING(message_str) is called by check_dangling() if there is any unaccessed keys.
#define CONFIGURU_ON_DANGLING(message_str) \
CONFIGURU_ONERROR(message_str)
#endif // CONFIGURU_ON_DANGLING
#ifdef __GNUC__
#define CONFIGURU_NORETURN __attribute__((noreturn))
#elif __MINGW32__
#define CONFIGURU_NORETURN __attribute__((noreturn))
#elif __clang__
#define CONFIGURU_NORETURN __attribute__((noreturn))
#elif _MSC_VER
#define CONFIGURU_NORETURN
#endif
#ifndef CONFIGURU_IMPLICIT_CONVERSIONS
/// Set to 1 to allow `int x = some_cfg,`
#define CONFIGURU_IMPLICIT_CONVERSIONS 0
#endif
#ifndef CONFIGURU_VALUE_SEMANTICS
/// If set, all copies are deep clones.
/// If 0, all copies of objects and array are shallow (ref-counted).
#define CONFIGURU_VALUE_SEMANTICS 0
#endif
#undef Bool // Needed on Ubuntu 14.04 with GCC 4.8.5
#undef check // Needed on OSX
/// The Configuru namespace.
namespace configuru
{
struct DocInfo;
using DocInfo_SP = std::shared_ptr<DocInfo>;
using Index = unsigned;
const Index BAD_INDEX = static_cast<Index>(-1);
struct Include
{
DocInfo_SP doc;
Index line = BAD_INDEX;
Include() {}
Include(DocInfo_SP d, Index l) : doc(d), line(l) {}
};
/// Helper for describing a document.
struct DocInfo
{
std::vector<Include> includers;
std::string filename;
DocInfo(const std::string& fn) : filename(fn) { }
void append_include_info(std::string& ret, const std::string& indent=" ") const;
};
struct BadLookupInfo;
/// Helper: value in an object.
template<typename Config_T>
struct Config_Entry
{
Config_T _value;
Index _nr = BAD_INDEX; ///< Size of the object prior to adding this entry
mutable bool _accessed = false; ///< Set to true if accessed.
Config_Entry() {}
Config_Entry(Config_T value, Index nr) : _value(std::move(value)), _nr(nr) {}
};
using Comment = std::string;
using Comments = std::vector<Comment>;
/// Captures the comments related to a Config value.
struct ConfigComments
{
/// Comments on preceeding lines.
/// Like this.
Comments prefix;
Comments postfix; ///< After the value, on the same line. Like this.
Comments pre_end_brace; /// Before the closing } or ]
ConfigComments() {}
bool empty() const;
void append(ConfigComments&& other);
};
/// A dynamic config variable.
class Config;
/** Overload this (in cofiguru namespace) for you own types, e.g:
```
namespace configuru {
template<>
inline Vector2f as(const Config& config)
{
auto&& array = config.as_array();
config.check(array.size() == 2, "Expected Vector2f");
return {(float)array[0], (float)array[1]};
}
}
```
*/
template<typename T>
inline T as(const configuru::Config& config);
/// A dynamic config variable.
/// Acts like something out of Python or Lua.
/// If CONFIGURU_VALUE_SEMANTICS all copies of this will be deep copies.
/// If not, it will use reference-counting for objects and arrays,
/// meaning all copies will be shallow copies.
class Config
{
public:
enum Type
{
Uninitialized, ///< Accessing a Config of this type is always an error.
BadLookupType, ///< We are the result of a key-lookup in a Object with no hit. We are in effect write-only.
Null, Bool, Int, Float, String, Array, Object
};
using ObjectEntry = Config_Entry<Config>;
using ConfigArrayImpl = std::vector<Config>;
using ConfigObjectImpl = std::map<std::string, ObjectEntry>;
struct ConfigArray
{
#if !CONFIGURU_VALUE_SEMANTICS
std::atomic<unsigned> _ref_count { 1 };
#endif
ConfigArrayImpl _impl;
};
struct ConfigObject;
// ----------------------------------------
// Constructors:
/// Creates an uninitialized Config.
Config() : _type(Uninitialized) { }
Config(std::nullptr_t) : _type(Null) { }
Config(float f) : _type(Float) { _u.f = f; }
Config(double f) : _type(Float) { _u.f = f; }
Config(bool b) : _type(Bool) { _u.b = b; }
Config(int i) : _type(Int) { _u.i = i; }
Config(unsigned int i) : _type(Int) { _u.i = i; }
Config(long i) : _type(Int) { _u.i = i; }
Config(unsigned long i) : Config(static_cast<unsigned long long>(i)) {}
Config(long long i) : _type(Int) { _u.i = i; }
Config(unsigned long long i) : _type(Int)
{
if ((i & 0x8000000000000000ull) != 0) {
CONFIGURU_ONERROR("Integer too large to fit into 63 bits");
}
_u.i = static_cast<int64_t>(i);
}
Config(const char* str);
Config(std::string str);
/** This constructor is a short-form for Config::object(...).
We have no short-form for Config::array(...),
as that is less common and can lead to ambiguities.
Usage:
```
Config cfg {
{ "key", "value" },
{ "empty_array", Config::array() },
{ "array", Config::array({1, 2, 3}) },
{ "empty_object", Config::object() },
{ "object", Config::object({
{ "nested_key", "nested_value" },
})},
{ "another_object", {
{ "nested_key", "nested_value" },
}},
};
```
*/
Config(std::initializer_list<std::pair<std::string, Config>> values);
/// Array constructor
template<typename T>
Config(const std::vector<T>& values) : _type(Uninitialized)
{
make_array();
_u.array->_impl.reserve(values.size());
for (const auto& v : values) {
push_back(v);
}
}
/// Array constructor
Config(const std::vector<bool>& values) : _type(Uninitialized)
{
make_array();
_u.array->_impl.reserve(values.size());
for (const auto v : values) {
push_back(!!v);
}
}
/// Object constructor
template<typename T>
Config(const std::map<std::string, T>& values) : _type(Uninitialized)
{
make_object();
for (const auto& p : values) {
(*this)[p.first] = p.second;
}
}
/// Used by the parser - no need to use directly.
void make_object();
/// Used by the parser - no need to use directly.
void make_array();
/// Used by the parser - no need to use directly.
void tag(const DocInfo_SP& doc, Index line, Index column);
/// Preferred way to create an empty object.
static Config object();
/// Preferred way to create an object.
static Config object(std::initializer_list<std::pair<std::string, Config>> values);
/// Preferred way to create an empty array.
static Config array();
/// Preferred way to create an array.
static Config array(std::initializer_list<Config> values);
/// Preferred way to create an array from an STL container.
template<typename Container>
static Config array(const Container& container)
{
Config ret;
ret.make_array();
auto& impl = ret._u.array->_impl;
impl.reserve(container.size());
for (auto&& v : container) {
impl.emplace_back(v);
}
return ret;
}
// ----------------------------------------
~Config();
Config(const Config& o);
Config(Config&& o) noexcept;
Config& operator=(const Config& o);
/// Will still remember file/line when assigned an object which has no file/line
Config& operator=(Config&& o) noexcept;
/// Swaps file/line too.
void swap(Config& o) noexcept;
#ifdef CONFIG_EXTENSION
CONFIG_EXTENSION
#endif
// ----------------------------------------
// Inspectors:
Type type() const { return _type; }
bool is_uninitialized() const { return _type == Uninitialized; }
bool is_null() const { return _type == Null; }
bool is_bool() const { return _type == Bool; }
bool is_int() const { return _type == Int; }
bool is_float() const { return _type == Float; }
bool is_string() const { return _type == String; }
bool is_object() const { return _type == Object; }
bool is_array() const { return _type == Array; }
bool is_number() const { return is_int() || is_float(); }
/// Returns file:line iff available.
std::string where() const;
/// BAD_INDEX if not set.
Index line() const { return _line; }
/// Handle to document.
const DocInfo_SP& doc() const { return _doc; }
void set_doc(const DocInfo_SP& doc) { _doc = doc; }
// ----------------------------------------
// Convertors:
#if CONFIGURU_IMPLICIT_CONVERSIONS
/// Explicit casting, for overloads of as<T>
template<typename T>
explicit operator T() const { return as<T>(*this); }
inline operator bool() const { return as_bool(); }
inline operator signed char() const { return as_integer<signed char>(); }
inline operator unsigned char() const { return as_integer<unsigned char>(); }
inline operator signed short() const { return as_integer<signed short>(); }
inline operator unsigned short() const { return as_integer<unsigned short>(); }
inline operator signed int() const { return as_integer<signed int>(); }
inline operator unsigned int() const { return as_integer<unsigned int>(); }
inline operator signed long() const { return as_integer<signed long>(); }
inline operator unsigned long() const { return as_integer<unsigned long>(); }
inline operator signed long long() const { return as_integer<signed long long>(); }
inline operator unsigned long long() const { return as_integer<unsigned long long>(); }
inline operator float() const { return as_float(); }
inline operator double() const { return as_double(); }
inline operator std::string() const { return as_string(); }
inline operator Config::ConfigArrayImpl() const { return as_array(); }
/// Convenience conversion to std::vector
template<typename T>
operator std::vector<T>() const
{
const auto& array = as_array();
std::vector<T> ret;
ret.reserve(array.size());
for (auto&& config : array) {
ret.push_back((T)config);
}
return ret;
}
/// Convenience conversion to std::array
template<typename T, size_t N>
operator std::array<T, N>() const
{
const auto& array = as_array();
check(array.size() == N, "Array size mismatch.");
std::array<T, N> ret;
std::copy(array.begin(), array.end(), ret.begin());
return ret;
}
/// Convenience conversion of an array of length 2 to an std::pair.
/// TODO: generalize for tuples.
template<typename Left, typename Right>
operator std::pair<Left, Right>() const
{
const auto& array = as_array();
check(array.size() == 2u, "Mismatched array length.");
return {(Left)array[0], (Right)array[1]};
}
#else
/// Explicit casting, since C++ handles implicit casts real badly.
template<typename T>
explicit operator T() const { return as<T>(*this); }
/// Convenience conversion to std::vector
template<typename T>
explicit operator std::vector<T>() const
{
const auto& array = as_array();
std::vector<T> ret;
ret.reserve(array.size());
for (auto&& config : array) {
ret.push_back(static_cast<T>(config));
}
return ret;
}
/// Convenience conversion to std::array
template<typename T, size_t N>
explicit operator std::array<T, N>() const
{
const auto& array = as_array();
check(array.size() == N, "Array size mismatch.");
std::array<T, N> ret;
for (size_t i =0; i < N; ++i) {
ret[i] = static_cast<T>(array[i]);
}
return ret;
}
/// Convenience conversion of an array of length 2 to an std::pair.
/// TODO: generalize for tuples.
template<typename Left, typename Right>
explicit operator std::pair<Left, Right>() const
{
const auto& array = as_array();
check(array.size() == 2u, "Mismatched array length.");
return {static_cast<Left>(array[0]), static_cast<Right>(array[1])};
}
#endif
const std::string& as_string() const { assert_type(String); return *_u.str; }
const char* c_str() const { assert_type(String); return _u.str->c_str(); }
/// The Config must be a boolean.
bool as_bool() const
{
assert_type(Bool);
return _u.b;
}
template<typename IntT>
IntT as_integer() const
{
static_assert(std::is_integral<IntT>::value, "Not an integer.");
assert_type(Int);
check(static_cast<int64_t>(static_cast<IntT>(_u.i)) == _u.i, "Integer out of range");
return static_cast<IntT>(_u.i);
}
float as_float() const
{
if (_type == Int) {
return static_cast<float>(_u.i);
} else {
assert_type(Float);
return static_cast<float>(_u.f);
}
}
double as_double() const
{
if (_type == Int) {
return static_cast<double>(_u.i);
} else {
assert_type(Float);
return static_cast<double>(_u.f);
}
}
/// Extract the value of this Config.
template<typename T>
T get() const;
/// Returns the value or `default_value` if this is the result of a bad lookup.
template<typename T>
T get_or(const T& default_value) const
{
if (_type == BadLookupType) {
return default_value;
} else {
return static_cast<T>(*this);
}
}
// ----------------------------------------
// Array:
/// Length of an array
size_t array_size() const
{
return as_array().size();
}
/// Only use this for iterating over an array: `for (Config& e : cfg.as_array()) { ... }`
ConfigArrayImpl& as_array()
{
assert_type(Array);
return _u.array->_impl;
}
/// Only use this for iterating over an array: `for (Config& e : cfg.as_array()) { ... }`
const ConfigArrayImpl& as_array() const
{
assert_type(Array);
return _u.array->_impl;
}
/// Array indexing
Config& operator[](size_t ix)
{
auto&& array = as_array();
check(ix < array.size(), "Array index out of range");
return array[ix];
}
/// Array indexing
const Config& operator[](size_t ix) const
{
auto&& array = as_array();
check(ix < array.size(), "Array index out of range");
return array[ix];
}
/// Append a value to this array.
void push_back(Config value)
{
as_array().push_back(std::move(value));
}
// ----------------------------------------
// Object:
/// Number of elementsi n this object
size_t object_size() const;
/// Only use this for iterating over an object:
/// `for (auto& p : cfg.as_object()) { p.value() = p.key(); }`
ConfigObject& as_object()
{
assert_type(Object);
return *_u.object;
}
/// Only use this for iterating over an object:
/// `for (const auto& p : cfg.as_object()) { cout << p.key() << ": " << p.value(); }`
const ConfigObject& as_object() const
{
assert_type(Object);
return *_u.object;
}
/// Look up a value in an Object. Returns a BadLookupType Config if the key does not exist.
const Config& operator[](const std::string& key) const;
/// Prefer `obj.insert_or_assign(key, value);` to `obj[key] = value;` when inserting and performance is important!
Config& operator[](const std::string& key);
/// For indexing with string literals:
template<std::size_t N>
Config& operator[](const char (&key)[N]) { return operator[](std::string(key)); }
template<std::size_t N>
const Config& operator[](const char (&key)[N]) const { return operator[](std::string(key)); }
/// Check if an object has a specific key.
bool has_key(const std::string& key) const;
/// Like has_key, but STL compatible.
size_t count(const std::string& key) const { return has_key(key) ? 1 : 0; }
/// Returns true iff the value was inserted, false if they key was already there.
bool emplace(std::string key, Config value);
/// Like `foo[key] = value`, but faster.
void insert_or_assign(const std::string& key, Config&& value);
/// Erase a key from an object.
bool erase(const std::string& key);
/// Get the given value in this object.
template<typename T>
T get(const std::string& key) const
{
return as<T>((*this)[key]);
}
/// Look for the given key in this object, and return default_value on failure.
template<typename T>
T get_or(const std::string& key, const T& default_value) const;
/// Look for the given key in this object, and return default_value on failure.
std::string get_or(const std::string& key, const char* default_value) const
{
return get_or<std::string>(key, default_value);
}
/// obj.get_or({"a", "b". "c"}, 42) - like obj["a"]["b"]["c"], but returns 42 if any of the keys are *missing*.
template<typename T>
T get_or(std::initializer_list<std::string> keys, const T& default_value) const;
/// obj.get_or({"a", "b". "c"}, 42) - like obj["a"]["b"]["c"], but returns 42 if any of the keys are *missing*.
std::string get_or(std::initializer_list<std::string> keys, const char* default_value) const
{
return get_or<std::string>(keys, default_value);
}
// --------------------------------------------------------------------------------
/// Compare Config values recursively.
static bool deep_eq(const Config& a, const Config& b);
#if !CONFIGURU_VALUE_SEMANTICS // No need for a deep_clone method when all copies are deep clones.
/// Copy this Config value recursively.
Config deep_clone() const;
#endif
// ----------------------------------------
/// Visit dangling (unaccessed) object keys recursively.
void visit_dangling(const std::function<void(const std::string& key, const Config& value)>& visitor) const;
/// Will check for dangling (unaccessed) object keys recursively and call CONFIGURU_ON_DANGLING on all found.
void check_dangling() const;
/// Set the 'access' flag recursively,
void mark_accessed(bool v) const;
// ----------------------------------------
/// Was there any comments about this value in the input?
bool has_comments() const
{
return _comments && !_comments->empty();
}
/// Read/write of comments.
ConfigComments& comments()
{
if (!_comments) {
_comments.reset(new ConfigComments());
}
return *_comments;
}
/// Read comments.
const ConfigComments& comments() const
{
static const ConfigComments s_empty {};
if (_comments) {
return *_comments;
} else {
return s_empty;
}
}
/// Returns either "true", "false", the constained string, or the type name.
const char* debug_descr() const;
/// Human-readable version of the type ("integer", "bool", etc).
static const char* type_str(Type t);
// ----------------------------------------
// Helper functions for checking the type is what we expect:
inline void check(bool b, const char* msg) const
{
if (!b) {
on_error(msg);
}
}
void assert_type(Type t) const;
void on_error(const std::string& msg) const CONFIGURU_NORETURN;
private:
void free();
using ConfigComments_UP = std::unique_ptr<ConfigComments>;
union {
bool b;
int64_t i;
double f;
const std::string* str;
ConfigObject* object;
ConfigArray* array;
BadLookupInfo* bad_lookup;
} _u;
DocInfo_SP _doc; // So we can name the file
ConfigComments_UP _comments;
Index _line = BAD_INDEX; // Where in the source, or BAD_INDEX. Lines are 1-indexed.
Type _type = Uninitialized;
};
// ------------------------------------------------------------------------
struct Config::ConfigObject
{
#if !CONFIGURU_VALUE_SEMANTICS
std::atomic<unsigned> _ref_count { 1 };
#endif
ConfigObjectImpl _impl;
class iterator
{
public:
iterator() = default;
explicit iterator(ConfigObjectImpl::iterator it) : _it(std::move(it)) {}
const iterator& operator*() const {
_it->second._accessed = true;
return *this;
}
iterator& operator++() {
++_it;
return *this;
}
friend bool operator==(const iterator& a, const iterator& b) {
return a._it == b._it;
}
friend bool operator!=(const iterator& a, const iterator& b) {
return a._it != b._it;
}
const std::string& key() const { return _it->first; }
Config& value() const { return _it->second._value; }
private:
ConfigObjectImpl::iterator _it;
};
class const_iterator
{
public:
const_iterator() = default;
explicit const_iterator(ConfigObjectImpl::const_iterator it) : _it(std::move(it)) {}
const const_iterator& operator*() const {
_it->second._accessed = true;
return *this;
}
const_iterator& operator++() {
++_it;
return *this;
}
friend bool operator==(const const_iterator& a, const const_iterator& b) {
return a._it == b._it;
}
friend bool operator!=(const const_iterator& a, const const_iterator& b) {
return a._it != b._it;
}
const std::string& key() const { return _it->first; }
const Config& value() const { return _it->second._value; }
private:
ConfigObjectImpl::const_iterator _it;
};
iterator begin() { return iterator{_impl.begin()}; }
iterator end() { return iterator{_impl.end()}; }
const_iterator begin() const { return const_iterator{_impl.cbegin()}; }
const_iterator end() const { return const_iterator{_impl.cend()}; }
const_iterator cbegin() const { return const_iterator{_impl.cbegin()}; }
const_iterator cend() const { return const_iterator{_impl.cend()}; }
};
// ------------------------------------------------------------------------
inline bool operator==(const Config& a, const Config& b)
{
return Config::deep_eq(a, b);
}
inline bool operator!=(const Config& a, const Config& b)
{
return !Config::deep_eq(a, b);
}
// ------------------------------------------------------------------------
template<> inline bool Config::get() const { return as_bool(); }
template<> inline signed char Config::get() const { return as_integer<signed char>(); }
template<> inline unsigned char Config::get() const { return as_integer<unsigned char>(); }
template<> inline signed short Config::get() const { return as_integer<signed short>(); }
template<> inline unsigned short Config::get() const { return as_integer<unsigned short>(); }
template<> inline signed int Config::get() const { return as_integer<signed int>(); }
template<> inline unsigned int Config::get() const { return as_integer<unsigned int>(); }
template<> inline signed long Config::get() const { return as_integer<signed long>(); }
template<> inline unsigned long Config::get() const { return as_integer<unsigned long>(); }
template<> inline signed long long Config::get() const { return as_integer<signed long long>(); }
template<> inline unsigned long long Config::get() const { return as_integer<unsigned long long>(); }
template<> inline float Config::get() const { return as_float(); }
template<> inline double Config::get() const { return as_double(); }
template<> inline const std::string& Config::get() const { return as_string(); }
template<> inline std::string Config::get() const { return as_string(); }
template<> inline const Config::ConfigArrayImpl& Config::get() const { return as_array(); }
// template<> inline std::vector<std::string> Config::get() const { return as_vector<T>(); }
// ------------------------------------------------------------------------
template<typename T>
inline T as(const configuru::Config& config)
{
return config.get<T>();
}
template<typename T>
T Config::get_or(const std::string& key, const T& default_value) const
{
auto&& object = as_object()._impl;
auto it = object.find(key);
if (it == object.end()) {
return default_value;
} else {
const auto& entry = it->second;
entry._accessed = true;
return as<T>(entry._value);
}
}
template<typename T>
T Config::get_or(std::initializer_list<std::string> keys, const T& default_value) const
{
const Config* obj = this;
for (const auto& key : keys)
{
if (obj->has_key(key)) {
obj = &(*obj)[key];
} else {
return default_value;
}
}
return as<T>(*obj);
}
// ------------------------------------------------------------------------
/// Prints in JSON but in a fail-safe manner, allowing uninitialized keys and inf/nan.
std::ostream& operator<<(std::ostream& os, const Config& cfg);
// ------------------------------------------------------------------------
/// Recursively visit all values in a config.
template<class Config, class Visitor>
void visit_configs(Config&& config, Visitor&& visitor)
{
visitor(config);
if (config.is_object()) {
for (auto&& p : config.as_object()) {
visit_configs(p.value(), visitor);
}
} else if (config.is_array()) {
for (auto&& e : config.as_array()) {
visit_configs(e, visitor);
}
}
}
inline void clear_doc(Config& root) // TODO: shouldn't be needed. Replace with some info of whether a Config is the root of the document it is in.
{
visit_configs(root, [&](Config& cfg){ cfg.set_doc(nullptr); });
}
/*
inline void replace_doc(Config& root, DocInfo_SP find, DocInfo_SP replacement)
{
visit_configs(root, [&](Config& config){
if (config.doc() == find) {
config.set_doc(replacement);
}
});
}
// Will try to merge from 'src' do 'dst', replacing with 'src' on any conflict.
inline void merge_replace(Config& dst, const Config& src)
{
if (dst.is_object() && src.is_object()) {
for (auto&& p : src.as_object()) {
merge_replace(dst[p.key()], p.value());
}
} else {
dst = src;
}
}
*/
// ----------------------------------------------------------
/// Thrown on a syntax error.
class ParseError : public std::exception
{
public:
ParseError(const DocInfo_SP& doc, Index line, Index column, const std::string& msg)
: _line(line), _column(column)
{
_what = doc->filename + ":" + std::to_string(line) + ":" + std::to_string(column);
doc->append_include_info(_what);
_what += ": " + msg;
}
/// Will name the file name, line number, column and description.
const char* what() const noexcept override
{
return _what.c_str();
}
Index line() const noexcept { return _line; }
Index column() const noexcept { return _column; }
private:
Index _line, _column;
std::string _what;
};
// ----------------------------------------------------------
/// This struct basically contain all the way we can tweak the file format.
struct FormatOptions
{
/// Indentation should be a single tab,
/// multiple spaces or an empty string.
/// An empty string means the output will be compact.
std::string indentation = "\t";
bool enforce_indentation = true; ///< Must have correct indentation?
bool end_with_newline = true; ///< End each file with a newline (unless compact).
// Top file:
bool empty_file = false; ///< If true, an empty file is an empty object.
bool implicit_top_object = true; ///< Ok with key-value pairs top-level?
bool implicit_top_array = true; ///< Ok with several values top-level?
// Comments:
bool single_line_comments = true; ///< Allow this?
bool block_comments = true; /* Allow this? */
bool nesting_block_comments = true; ///< /* Allow /* this? */ */