forked from CleverRaven/Cataclysm-DDA
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgeneric_factory.h
1322 lines (1191 loc) · 50.6 KB
/
generic_factory.h
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
#pragma once
#ifndef CATA_SRC_GENERIC_FACTORY_H
#define CATA_SRC_GENERIC_FACTORY_H
#include <algorithm>
#include <bitset>
#include <set>
#include <unordered_map>
#include <vector>
#include "assign.h"
#include "cached_options.h"
#include "catacharset.h"
#include "cata_void.h"
#include "debug.h"
#include "enum_bitset.h"
#include "init.h"
#include "int_id.h"
#include "json.h"
#include "mod_tracker.h"
#include "output.h"
#include "string_id.h"
#include "units.h"
#include "wcwidth.h"
/**
A generic class to store objects identified by a `string_id`.
The class handles loading (including overriding / replacing existing objects) and
querying for specific objects. The class is designed to work with @ref string_id and
can be by it to implement its interface.
----
@tparam T The type of the managed objects. The type must have:
- a default constructor,
- a `load( JsonObject & )` function,
- an `id` member of type `string_id<T>`,
- a `was_loaded` member of type `bool`, which must have the value `false` before
the first call to `load`.
The type can also have:
- a 'check()' function (to run `generic_factory::check()` on all objects)
Those things must be visible from the factory, you may have to add this class as
friend if necessary.
`T::load` should load all the members of `T`, except `id` and `was_loaded` (they are
set by the `generic_factory` before calling `load`). Failures should be reported by
throwing an exception (e.g. via `JsonObject::throw_error`).
----
Usage:
- Create an instance, it can be static, or packed into another object.
- Implement `string_id::load` as simply forwarding to `generic_factory::load`.
Register `string_id::load` in the @ref DynamicDataLoader (init.cpp) to be called when
an object of the matching type is encountered.
- Similar: implement and register `string_id::reset` and let it call `generic_factory::reset`.
The functions can contain more code:
- `load` typically does nothing special beside forwarding to `generic_factory`.
- `reset` removes the loaded objects. It usually needs to remove the additional data that was set
up in `finalize`. It must call `generic_factory::reset`.
Optional: implement the other functions used by the DynamicDataLoader: `finalize`,
`check_consistency`. There is no implementation of them in the generic factory.
`check_consistency` typically goes over all loaded items and checks them somehow.
`finalize` typically populates some other data (e.g. some cache) or sets up connection between
loaded objects of different type.
A sample implementation looks like this:
\code
class my_class { ... }
namespace {
generic_factory<my_class> my_class_factory( "my class" );
std::map<...> some_cache;
}
template<>
void string_id<my_class>::load( const JsonObject &jo ) {
my_class_factory.load( jo );
}
template<>
void string_id<my_class>::reset() {
some_cache.clear();
my_class_factory.reset();
}
template<>
void string_id<my_class>::finalize() {
for( auto &ptr : my_class_factory.all() )
// populate a cache just as an example
some_cache.insert( ... );
}
}
// Implementation of the string_id functions:
template<>
const my_class &string_id<my_class>::obj() const
{
return my_class_factory.obj( *this );
}
// ... more functions of string_id, similar to the above.
\endcode
*/
template<typename T>
class string_id_reader;
template<typename T>
class generic_factory
{
public:
virtual ~generic_factory() = default;
private:
DynamicDataLoader::deferred_json deferred;
// generation or "modification count" of this factory
// it's incremented when any changes to the inner id containers occur
// version value corresponds to the string_id::_version,
// so incrementing the version here effectively invalidates all cached string_id::_cid
int64_t version = 0;
void inc_version() {
do {
version++;
} while( version == INVALID_VERSION );
}
protected:
std::vector<T> list;
std::unordered_map<string_id<T>, int_id<T>> map;
std::unordered_map<std::string, T> abstracts;
std::string type_name;
std::string id_member_name;
std::string alias_member_name;
// TEMPORARY until 0.G: Remove "ident" support
const std::string legacy_id_member_name = "ident";
bool find_id( const string_id<T> &id, int_id<T> &result ) const {
if( id._version == version ) {
result = int_id<T>( id._cid );
return is_valid( result );
}
const auto iter = map.find( id );
// map lookup happens at most once per string_id instance per generic_factory::version
// id was not found, explicitly marking it as "invalid"
if( iter == map.end() ) {
id.set_cid_version( INVALID_CID, version );
return false;
}
result = iter->second;
id.set_cid_version( result.to_i(), version );
return true;
}
void remove_aliases( const string_id<T> &id ) {
int_id<T> i_id;
if( !find_id( id, i_id ) ) {
return;
}
auto iter = map.begin();
const auto end = map.end();
while( iter != end ) {
if( iter->second == i_id && iter->first != id ) {
map.erase( iter++ );
} else {
++iter;
}
}
}
const T dummy_obj;
public:
const bool initialized;
/**
* @param type_name A string used in debug messages as the name of `T`,
* for example "vehicle type".
* @param id_member_name The name of the JSON member that contains the id(s) of the
* loaded object(s).
* @param alias_member_name Alternate names of the JSON member that contains the id(s) of the
* loaded object alias(es).
*/
explicit generic_factory( const std::string &type_name, const std::string &id_member_name = "id",
const std::string &alias_member_name = "alias" )
: type_name( type_name ),
id_member_name( id_member_name ),
alias_member_name( alias_member_name ),
dummy_obj(),
initialized( true ) {
}
/**
* Perform JSON inheritance handling for `T def` and returns true if JsonObject is real.
*
* If the object contains a "copy-from" member the corresponding abstract gets copied if found.
* If abstract is not found, object is added to deferred.
* If the object is abstract, it is loaded via `T::load` and added to `abstracts`
*
* @return true if `jo` is loaded and false if loading is deferred.
* @throws JsonError If `jo` is both abstract and real. (contains "abstract" and "id" members)
*/
bool handle_inheritance( T &def, const JsonObject &jo, const std::string &src ) {
static const std::string copy_from_member_name( "copy-from" );
static const std::string abstract_member_name( "abstract" );
if( jo.has_string( copy_from_member_name ) ) {
const std::string source = jo.get_string( copy_from_member_name );
auto base = map.find( string_id<T>( source ) );
if( base != map.end() ) {
def = obj( base->second );
} else {
auto ab = abstracts.find( source );
if( ab != abstracts.end() ) {
def = ab->second;
} else {
def.was_loaded = false;
deferred.emplace_back( jo.get_source_location(), src );
jo.allow_omitted_members();
return false;
}
}
def.was_loaded = true;
}
if( jo.has_string( abstract_member_name ) ) {
if( jo.has_string( id_member_name ) || jo.has_string( legacy_id_member_name ) ) {
jo.throw_error( string_format( "cannot specify both '%s' and '%s'/'%s'",
abstract_member_name, id_member_name, legacy_id_member_name ) );
}
restore_on_out_of_scope<check_plural_t> restore_check_plural( check_plural );
check_plural = check_plural_t::none;
def.load( jo, src );
abstracts[jo.get_string( abstract_member_name )] = def;
}
return true;
}
/**
* Load an object of type T with the data from the given JSON object.
*
* The id of the object is taken from the JSON object. The object data is loaded by
* calling `T::load(jo)` (either on a new object or on an existing object).
* See class documentation for intended behavior of that function.
*
* @throws JsonError If loading fails for any reason (thrown by `T::load`).
*/
void load( const JsonObject &jo, const std::string &src ) {
bool strict = src == "dda";
static const std::string abstract_member_name( "abstract" );
T def;
if( !handle_inheritance( def, jo, src ) ) {
return;
}
if( jo.has_string( id_member_name ) ) {
def.id = string_id<T>( jo.get_string( id_member_name ) );
mod_tracker::assign_src( def, src );
def.load( jo, src );
insert( def );
if( jo.has_member( alias_member_name ) ) {
std::set<string_id<T>> aliases;
assign( jo, alias_member_name, aliases, strict );
const int_id<T> ref = map[def.id];
for( const auto &e : aliases ) {
map[e] = ref;
}
}
} else if( jo.has_array( id_member_name ) ) {
for( JsonValue e : jo.get_array( id_member_name ) ) {
T def;
if( !handle_inheritance( def, jo, src ) ) {
break;
}
def.id = string_id<T>( e );
mod_tracker::assign_src( def, src );
def.load( jo, src );
insert( def );
}
if( jo.has_member( alias_member_name ) ) {
jo.throw_error( string_format( "can not specify '%s' when '%s' is array",
alias_member_name, id_member_name ) );
}
} else if( jo.has_string( legacy_id_member_name ) ) {
def.id = string_id<T>( jo.get_string( legacy_id_member_name ) );
mod_tracker::assign_src( def, src );
def.load( jo, src );
insert( def );
if( jo.has_member( alias_member_name ) ) {
std::set<string_id<T>> aliases;
assign( jo, alias_member_name, aliases, strict );
const int_id<T> ref = map[def.id];
for( const auto &e : aliases ) {
map[e] = ref;
}
}
} else if( jo.has_array( legacy_id_member_name ) ) {
for( const JsonValue e : jo.get_array( legacy_id_member_name ) ) {
T def;
if( !handle_inheritance( def, jo, src ) ) {
break;
}
def.id = string_id<T>( e );
mod_tracker::assign_src( def, src );
def.load( jo, src );
insert( def );
}
if( jo.has_member( alias_member_name ) ) {
jo.throw_error( string_format( "can not specify '%s' when '%s' is array",
alias_member_name, legacy_id_member_name ) );
}
} else if( !jo.has_string( abstract_member_name ) ) {
jo.throw_error( string_format( "must specify either '%s' or '%s'/'%s'",
abstract_member_name, id_member_name, legacy_id_member_name ) );
}
}
/**
* Add an object to the factory, without loading from JSON.
* The new object replaces any existing object of the same id.
* The function returns the actual object reference.
*/
T &insert( const T &obj ) {
// this invalidates `_cid` cache for all previously added string_ids,
// but! it's necessary to invalidate cache for all possibly cached "missed" lookups
// (lookups for not-yet-inserted elements)
// in the common scenario there is no loss of performance, as `finalize` will make cache
// for all ids valid again
inc_version();
const auto iter = map.find( obj.id );
if( iter != map.end() ) {
mod_tracker::check_duplicate_entries( obj, list[iter->second.to_i()] );
T &result = list[iter->second.to_i()];
result = obj;
result.id.set_cid_version( iter->second.to_i(), version );
return result;
}
const int_id<T> cid( list.size() );
list.push_back( obj );
T &result = list.back();
result.id.set_cid_version( cid.to_i(), version );
map[result.id] = cid;
return result;
}
/** Finalize all entries (derived classes should chain to this method) */
virtual void finalize() {
DynamicDataLoader::get_instance().load_deferred( deferred );
abstracts.clear();
inc_version();
for( size_t i = 0; i < list.size(); i++ ) {
list[i].id.set_cid_version( static_cast<int>( i ), version );
}
}
/**
* Checks loaded/inserted objects for consistency
*/
void check() const {
for( const T &obj : list ) {
obj.check();
}
}
/**
* Returns the number of loaded objects.
*/
size_t size() const {
return list.size();
}
/**
* Returns whether factory is empty.
*/
bool empty() const {
return list.empty();
}
/**
* Removes all loaded objects.
* Postcondition: `size() == 0`
*/
void reset() {
list.clear();
map.clear();
inc_version();
}
/**
* Returns all the loaded objects. It can be used to iterate over them.
*/
const std::vector<T> &get_all() const {
return list;
}
/**
* @name `string_id/int_id` interface functions
*
* The functions here are supposed to be used by the id classes, they have the
* same behavior as described in the id classes and can be used directly by
* forwarding the parameters to them and returning their result.
*/
/**@{*/
/**
* Returns the object with the given id.
* The input id should be valid, otherwise a debug message is issued.
* This function can be used to implement @ref int_id::obj().
* Note: If the id was valid, the returned object can be modified (after
* casting the const away).
*/
const T &obj( const int_id<T> &id ) const {
if( !is_valid( id ) ) {
debugmsg( "invalid %s id \"%d\"", type_name, id.to_i() );
return dummy_obj;
}
return list[id.to_i()];
}
/**
* Returns the object with the given id.
* The input id should be valid, otherwise a debug message is issued.
* This function can be used to implement @ref string_id::obj().
* Note: If the id was valid, the returned object can be modified (after
* casting the const away).
*/
const T &obj( const string_id<T> &id ) const {
int_id<T> i_id;
if( !find_id( id, i_id ) ) {
debugmsg( "invalid %s id \"%s\"", type_name, id.c_str() );
return dummy_obj;
}
return list[i_id.to_i()];
}
/**
* Checks whether the factory contains an object with the given id.
* This function can be used to implement @ref int_id::is_valid().
*/
bool is_valid( const int_id<T> &id ) const {
return static_cast<size_t>( id.to_i() ) < list.size();
}
/**
* Checks whether the factory contains an object with the given id.
* This function can be used to implement @ref string_id::is_valid().
*/
bool is_valid( const string_id<T> &id ) const {
int_id<T> dummy;
return find_id( id, dummy );
}
/**
* Converts string_id<T> to int_id<T>. Returns null_id on failure.
* When optional flag warn is true, issues a warning if `id` is not found and null_id was returned.
*/
int_id<T> convert( const string_id<T> &id, const int_id<T> &null_id,
const bool warn = true ) const {
int_id<T> result;
if( find_id( id, result ) ) {
return result;
}
if( warn ) {
debugmsg( "invalid %s id \"%s\"", type_name, id.c_str() );
}
return null_id;
}
/**
* Converts int_id<T> to string_id<T>. Returns null_id on failure.
*/
const string_id<T> &convert( const int_id<T> &id ) const {
return obj( id ).id;
}
/**@}*/
/**
* Wrapper around generic_factory::version.
* Allows to have local caches that invalidate when corresponding generic factory invalidates.
* Note: when created using it's default constructor, Version is guaranteed to be invalid.
*/
class Version
{
friend generic_factory<T>;
public:
Version() = default;
private:
explicit Version( int64_t version ) : version( version ) {}
int64_t version = -1;
public:
bool operator==( const Version &rhs ) const {
return version == rhs.version;
}
bool operator!=( const Version &rhs ) const {
return !( rhs == *this );
}
};
// current version of this generic_factory
Version get_version() {
return Version( version );
}
// checks whether given version is the same as current version of this generic_factory
bool is_valid( const Version &v ) {
return v.version == version;
}
};
/**
@file
Helper for loading from JSON
Loading (inside a `T::load(JsonObject &jo)` function) can be done with two functions
(defined here):
- `mandatory` loads required data and throws an error if the JSON data does not contain
the required data.
- `optional` is for optional data, it has the same parameters and an additional default
value that will be used if the JSON data does not contain the requested data. It may
throw an error if the existing data is not valid (e.g. string instead of requested int).
The functions are designed to work with the `generic_factory` and therefore support the
`was_loaded` parameter (set by `generic_factory::load`). If that parameter is `true`, it
is assumed the object has already been loaded and missing JSON data is simply ignored
(the default value is not applied and no error is thrown upon missing mandatory data).
The parameters are this:
- `JsonObject jo` the object to load from.
- `bool was_loaded` whether the object had already been loaded completely.
- `std::string member_name` the name of the JSON member to load from.
- `T &member` a reference to the C++ object to store the loaded data.
- (for `optional`) a default value of any type that can be assigned to `member`.
Both functions use the native `read` functions of `JsonIn` (see there) to load the value.
Example:
\code
class Dummy {
bool was_loaded = false;
int a;
std::string b;
void load(JsonObject &jo) {
mandatory(jo, was_loaded, "a", a);
optional(jo, was_loaded, "b", b, "default value of b");
}
};
\endcode
This only works if there is function with the matching type defined in `JsonIn`. For other
types, or if the loaded value needs to be converted (e.g. to `nc_color`), one can use the
reader classes/functions. `mandatory` and `optional` have an overload that requires the same
parameters and an additional reference to such a reader object.
\code
class Dummy2 {
bool was_loaded = false;
int b;
nc_color c;
void load(JsonObject &jo) {
mandatory(jo, was_loaded, "b", b); // uses JsonIn::read(int&)
}
};
\endcode
Both versions of `optional` have yet another overload that does not require an explicit default
value, a default initialized object of the member type will be used instead.
----
Readers must provide the following function:
`bool operator()( const JsonObject &jo, const std::string &member_name, T &member, bool was_loaded ) const
(This can be implemented as free function or as operator in a class.)
The parameters are the same as the for the `mandatory` function (see above). The `function shall
return `true` if the loading was done, or `false` if the JSON data did
not contain the requested member. If loading fails because of invalid data (but not missing
data), it should throw.
*/
/** @name Implementation of `mandatory` and `optional`. */
/**@{*/
template<typename MemberType>
inline void mandatory( const JsonObject &jo, const bool was_loaded, const std::string &name,
MemberType &member )
{
if( !jo.read( name, member ) ) {
if( !was_loaded ) {
if( jo.has_member( name ) ) {
jo.throw_error( "failed to read mandatory member \"" + name + "\"" );
} else {
jo.throw_error( "missing mandatory member \"" + name + "\"" );
}
}
}
}
template<typename MemberType, typename ReaderType>
inline void mandatory( const JsonObject &jo, const bool was_loaded, const std::string &name,
MemberType &member, const ReaderType &reader )
{
if( !reader( jo, name, member, was_loaded ) ) {
if( !was_loaded ) {
if( jo.has_member( name ) ) {
jo.throw_error( "failed to read mandatory member \"" + name + "\"" );
} else {
jo.throw_error( "missing mandatory member \"" + name + "\"" );
}
}
}
}
/*
* Template vodoo:
* The compiler will construct the appropriate one of these based on if the
* type can support the operations being done.
* So, it defaults to the false_type, but if it can use the *= operator
* against a float, it then supports proportional, and the handle_proportional
* template that isn't just a dummy is constructed.
* Similarly, if it can use a += operator against it's own type, the non-dummy
* handle_relative template is constructed.
*/
template<typename T, typename = cata::void_t<>>
struct supports_proportional : std::false_type { };
template<typename T>
struct supports_proportional<T, cata::void_t<decltype( std::declval<T &>() *= std::declval<float>() )>> :
std::true_type {};
template<typename T, typename = cata::void_t<>>
struct supports_relative : std::false_type { };
template<typename T>
struct supports_relative < T, cata::void_t < decltype( std::declval<T &>() += std::declval<T &>() )
>> : std::true_type {};
// Explicitly specialize these templates for a couple types
// So the compiler does not attempt to use a template that it should not
template<>
struct supports_proportional<bool> : std::false_type {};
template<>
struct supports_relative<bool> : std::false_type {};
template<>
struct supports_relative<std::string> : std::false_type {};
// This checks that all units:: types will support relative and proportional
static_assert( supports_relative<units::energy>::value, "units should support relative" );
static_assert( supports_proportional<units::energy>::value, "units should support proportional" );
static_assert( supports_relative<int>::value, "ints should support relative" );
static_assert( supports_proportional<int>::value, "ints should support proportional" );
static_assert( !supports_relative<bool>::value, "bools should not support relative" );
static_assert( !supports_proportional<bool>::value, "bools should not support proportional" );
// Using string ids with ints doesn't make sense in practice, but it doesn't matter here
// The type that it is templated with does not change it's behavior
static_assert( !supports_relative<string_id<int>>::value,
"string ids should not support relative" );
static_assert( !supports_proportional<string_id<int>>::value,
"string ids should not support proportional" );
// Using int ids with ints doesn't make sense in practice, but it doesn't matter here
// The type that it is templated with does not change it's behavior
static_assert( !supports_relative<int_id<int>>::value,
"int ids should not support relative" );
static_assert( !supports_proportional<int_id<int>>::value,
"int ids should not support proportional" );
static_assert( !supports_relative<std::string>::value, "strings should not support relative" );
static_assert( !supports_proportional<std::string>::value,
"strings should not support proportional" );
// Grab an enum class from debug.h
static_assert( !supports_relative<DebugOutput>::value, "enum classes should not support relative" );
static_assert( !supports_proportional<DebugOutput>::value,
"enum classes should not support proportional" );
// Grab a normal enum from there too
static_assert( !supports_relative<DebugLevel>::value, "enums should not support relative" );
static_assert( !supports_proportional<DebugLevel>::value, "enums should not support relative" );
// Dummy template:
// Warn if it's trying to use proportional where it cannot, but otherwise just
// return.
template < typename MemberType, std::enable_if_t < !supports_proportional<MemberType>::value > * =
nullptr >
inline bool handle_proportional( const JsonObject &jo, const std::string &name, MemberType & )
{
if( jo.has_object( "proportional" ) ) {
JsonObject proportional = jo.get_object( "proportional" );
proportional.allow_omitted_members();
if( proportional.has_member( name ) ) {
debugmsg( "Member %s of type %s does not support proportional", name,
demangle( typeid( MemberType ).name() ) );
}
}
return false;
}
// Real template:
// Copy-from makes it so the thing we're inheriting from is used to construct
// this, so member will contain the value of the thing we inherit from
// So, check if there is a proportional entry, check if it's got a valid value
// and if it does, multiply the member by it.
template<typename MemberType, std::enable_if_t<supports_proportional<MemberType>::value>* = nullptr>
inline bool handle_proportional( const JsonObject &jo, const std::string &name, MemberType &member )
{
if( jo.has_object( "proportional" ) ) {
JsonObject proportional = jo.get_object( "proportional" );
proportional.allow_omitted_members();
// We need to check this here, otherwise we get problems with unvisited members
if( !proportional.has_member( name ) ) {
return false;
}
if( proportional.has_float( name ) ) {
double scalar = proportional.get_float( name );
if( scalar <= 0 || scalar == 1 ) {
debugmsg( "Invalid scalar %g for %s", scalar, name );
return false;
}
member *= scalar;
return true;
} else {
jo.throw_error_at( name, "Invalid scalar for " + name );
}
}
return false;
}
// Dummy template:
// Warn when trying to use relative when it's not supported, but otherwise,
// return
template < typename MemberType,
std::enable_if_t < !supports_relative<MemberType>::value > * = nullptr
>
inline bool handle_relative( const JsonObject &jo, const std::string &name, MemberType & )
{
if( jo.has_object( "relative" ) ) {
JsonObject relative = jo.get_object( "relative" );
relative.allow_omitted_members();
if( !relative.has_member( name ) ) {
return false;
}
debugmsg( "Member %s of type %s does not support relative", name,
demangle( typeid( MemberType ).name() ) );
}
return false;
}
// Real template:
// Copy-from makes it so the thing we're inheriting from is used to construct
// this, so member will contain the value of the thing we inherit from
// So, check if there is a relative entry, then add it to our member
template<typename MemberType, std::enable_if_t<supports_relative<MemberType>::value>* = nullptr>
inline bool handle_relative( const JsonObject &jo, const std::string &name, MemberType &member )
{
if( jo.has_object( "relative" ) ) {
JsonObject relative = jo.get_object( "relative" );
relative.allow_omitted_members();
// This needs to happen here, otherwise we get unvisited members
if( !relative.has_member( name ) ) {
return false;
}
MemberType adder;
if( relative.read( name, adder ) ) {
member += adder;
return true;
} else {
jo.throw_error_at( name, "Invalid adder for " + name );
}
}
return false;
}
// No template magic here, yay!
template<typename MemberType>
inline void optional( const JsonObject &jo, const bool was_loaded, const std::string &name,
MemberType &member )
{
if( !jo.read( name, member ) && !handle_proportional( jo, name, member ) &&
!handle_relative( jo, name, member ) ) {
if( !was_loaded ) {
member = MemberType();
}
}
}
/*
Template trickery, not for the faint of heart. It is required because there are two functions
with 5 parameters. The first 4 are always the same: JsonObject, bool, member name, member reference.
The last one is different: in one case it's the default value, in the other case it's the reader
and there is no explicit default value there.
The enable_if stuff assumes that a `MemberType` can not be constructed from a `ReaderType`, in other
words: `MemberType foo( ReaderType(...) );` does not work. This is what `is_constructible` checks.
If the 5. parameter can be used to construct a `MemberType`, it is assumed to be the default value,
otherwise it is assumed to be the reader.
*/
template<typename MemberType, typename DefaultType = MemberType,
typename = typename std::enable_if<std::is_constructible<MemberType, const DefaultType &>::value>::type>
inline void optional( const JsonObject &jo, const bool was_loaded, const std::string &name,
MemberType &member, const DefaultType &default_value )
{
if( !jo.read( name, member ) && !handle_proportional( jo, name, member ) &&
!handle_relative( jo, name, member ) ) {
if( !was_loaded ) {
member = default_value;
}
}
}
template < typename MemberType, typename ReaderType, typename DefaultType = MemberType,
typename = typename std::enable_if <
!std::is_constructible<MemberType, const ReaderType &>::value >::type >
inline void optional( const JsonObject &jo, const bool was_loaded, const std::string &name,
MemberType &member, const ReaderType &reader )
{
if( !reader( jo, name, member, was_loaded ) ) {
if( !was_loaded ) {
member = MemberType();
}
}
}
template<typename MemberType, typename ReaderType, typename DefaultType = MemberType>
inline void optional( const JsonObject &jo, const bool was_loaded, const std::string &name,
MemberType &member, const ReaderType &reader, const DefaultType &default_value )
{
if( !reader( jo, name, member, was_loaded ) ) {
if( !was_loaded ) {
member = default_value;
}
}
}
/**@}*/
/**
* Reads a string and stores the first byte of it in `sym`. Throws if the input contains more
* or less than one byte.
*/
bool one_char_symbol_reader( const JsonObject &jo, const std::string &member_name, int &sym,
bool );
/**
* Reads a UTF-8 string (or int as legacy fallback) and stores Unicode codepoint of it in `symbol`.
* Throws if the inputs width is more than one console cell wide.
*/
bool unicode_codepoint_from_symbol_reader(
const JsonObject &jo, const std::string &member_name, uint32_t &member, bool );
namespace reader_detail
{
template<typename T>
struct handler {
static constexpr bool is_container = false;
};
template<typename T>
struct handler<std::set<T>> {
void clear( std::set<T> &container ) const {
container.clear();
}
void insert( std::set<T> &container, const T &data ) const {
container.insert( data );
}
void erase( std::set<T> &container, const T &data ) const {
container.erase( data );
}
static constexpr bool is_container = true;
};
template<size_t N>
struct handler<std::bitset<N>> {
void clear( std::bitset<N> &container ) const {
container.reset();
}
template<typename T>
void insert( std::bitset<N> &container, const T &data ) const {
container.set( data );
}
template<typename T>
void erase( std::bitset<N> &container, const T &data ) const {
container.reset( data );
}
static constexpr bool is_container = true;
};
template<typename E>
struct handler<enum_bitset<E>> {
void clear( enum_bitset<E> &container ) const {
container.reset();
}
template<typename T>
void insert( enum_bitset<E> &container, const T &data ) const {
container.set( data );
}
template<typename T>
void erase( enum_bitset<E> &container, const T &data ) const {
container.reset( data );
}
static constexpr bool is_container = true;
};
template<typename T>
struct handler<std::vector<T>> {
void clear( std::vector<T> &container ) const {
container.clear();
}
void insert( std::vector<T> &container, const T &data ) const {
container.push_back( data );
}
template<typename E>
void erase( std::vector<T> &container, const E &data ) const {
erase_if( container, [&data]( const T & e ) {
return e == data;
} );
}
template<typename P>
void erase_if( std::vector<T> &container, const P &predicate ) const {
const auto iter = std::find_if( container.begin(), container.end(), predicate );
if( iter != container.end() ) {
container.erase( iter );
}
}
static constexpr bool is_container = true;
};
} // namespace reader_detail
/**
* Base class for reading generic objects from JSON.
* It can load members being certain containers or being a single value.
* The function get_next() needs to be implemented to read and convert the data from JSON.
* It uses the curiously recurring template pattern, you have to derive your new class
* `MyReader` from `generic_typed_reader<MyReader>` and implement `get_next` and
* optionally `erase_next`.
* Most function calls here are done on a `Derived`, which means it can "override" them.
* This even allows changing their signature and return type.
*
* - If the object is new (`was_loaded` is `false`), only the given JSON member is read
* and assigned, overriding any existing content of it.
* - If the object is not new and the member exists, it is read and assigned as well.
* - If the object is not new and the member does not exists, two further members are examined:
* entries from `"extend"` are added to the set and entries from `"delete"`
* are removed. This only works if the member is actually a container, not just a single value.
*
* Example:
* The JSON `{ "f": ["a","b","c"] }` would be loaded as the set `{"a","b","c"}`.
* Loading the set again from the JSON `{ "delete": { "f": ["c","x"] }, "extend": { "f": ["h"] } }`
* would add the "h" flag and removes the "c" and the "x" flag, resulting in `{"a","b","h"}`.
*
* @tparam Derived The class that inherits from this. It must implement the following:
* - `Foo get_next( V ) const`: reads the next value from JSON, converts it into some
* type `Foo` and returns it. The returned value is assigned to the loaded member (see reader
* interface above), or is inserted into the member (if it's a container). The type `Foo` must
* be compatible with those uses (read: it should be the same type). V is a type convertible from
* JsonValue.
* - (optional) `erase_next( V v, C &container ) const`, the default implementation here
* reads a value from JSON via `get_next` and removes the matching value in the container.
* The value in the container must match *exactly*. You may override this function to allow
* a different matching algorithm, e.g. reading a simple id from JSON and remove entries with
* the same id from the container. V is a value convertible from JsonValue.
*/
template<typename Derived>
class generic_typed_reader
{
public:
template<typename C>
void insert_values_from( const JsonObject &jo, const std::string &member_name,
C &container ) const {
const Derived &derived = static_cast<const Derived &>( *this );
if( !jo.has_member( member_name ) ) {
return;
}
JsonValue jv = jo.get_member( member_name );
// We allow either a single value or an array of values. Note that this will not work
// correctly if the thing we load from JSON is itself an array.
if( jv.test_array() ) {
for( JsonValue jav : jv.get_array() ) {
derived.insert_next( jav, container );
}
} else {
derived.insert_next( jv, container );
}
}
template<typename C>
void insert_next( JsonValue &jv, C &container ) const {
const Derived &derived = static_cast<const Derived &>( *this );
reader_detail::handler<C>().insert( container, derived.get_next( jv ) );