-
Notifications
You must be signed in to change notification settings - Fork 1
/
jsoncpp_impl.py
2894 lines (2453 loc) · 92.4 KB
/
jsoncpp_impl.py
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
"""Generate the implementation of de/serialization from/to Jsoncpp values."""
# pylint: disable=too-many-lines
# pylint: disable=too-many-arguments
import re
import textwrap
from typing import ( # pylint: disable=unused-import
Dict, List, Mapping, MutableMapping, Set, Union)
import icontract
from icontract import ensure
import mapry
import mapry.cpp.generate
import mapry.cpp.jinja2_env
import mapry.cpp.naming
import mapry.indention
def _needs_regex(a_type: mapry.Type) -> bool:
"""
Check if the type needs a regular expression.
For example, types with pattern constraints need to verify the pattern
with the regular expression.
:param a_type: to be inspected
:return: True if the type needs a regular expression
"""
if isinstance(a_type, mapry.String) and a_type.pattern:
return True
if isinstance(a_type, mapry.Path) and a_type.pattern:
return True
if isinstance(a_type, mapry.Duration):
return True
return False
@ensure(lambda result: not result.endswith('\n'))
def _includes(
graph: mapry.Graph, types_header_path: str, parse_header_path: str,
jsoncpp_header_path: str, cpp: mapry.Cpp) -> str:
"""
Generate the include directives of the implementation file.
:param graph: mapry definition of the object graph
:param types_header_path: defines the types of the object graph
:param parse_header_path: defines the general parsing structures
:param jsoncpp_header_path:
defines parsing and serializing functions from/to Jsoncpp
:param cpp: C++ settings
:return: generated code
"""
# yapf: disable
first_party_block = {
'#include "{}"'.format(pth)
for pth in [types_header_path, parse_header_path, jsoncpp_header_path]}
# yapf: enable
third_party_block = set() # type: Set[str]
stl_block = {
"#include <cstring>", "#include <string>", "#include <sstream>",
'#include <stdexcept>', "#include <memory>", "#include <utility>"
}
##
# See if we need any regular expressions
##
include_regex = False
for a_type, _ in mapry.iterate_over_types(graph=graph):
if _needs_regex(a_type=a_type):
include_regex = True
break
for cls in graph.classes.values():
if cls.id_pattern is not None:
include_regex = True
break
if include_regex:
stl_block.add("#include <regex>")
##
# Date/time includes
##
if cpp.datetime_library == 'ctime':
# yapf: disable
if any(mapry.needs_type(a_type=graph, query=query_type)
for query_type in [mapry.Date, mapry.Time, mapry.Datetime]):
# yapf: enable
# needed at least for tm_to_string function
stl_block.add("#include <cstring>")
elif cpp.datetime_library == 'date.h':
# yapf: disable
if any(mapry.needs_type(a_type=graph, query=query_type)
for query_type in [mapry.Date, mapry.Time, mapry.Datetime]):
# yapf: enable
# needed at least to parse the date.h date/times.
stl_block.add("#include <sstream>")
third_party_block.add("#include <date/date.h>")
if mapry.needs_type(a_type=graph, query=mapry.TimeZone):
third_party_block.add("#include <date/tz.h>")
else:
raise NotImplementedError(
"Unhandled datetime library: {}".format(cpp.datetime_library))
if mapry.needs_type(a_type=graph, query=mapry.Duration):
# needed at least for duration_to_string function
stl_block.add("#include <iomanip>")
# needed at least for duration_from_string function
stl_block.add("#include <limits>")
stl_block.add("#include <cmath>")
##
# Assemble
##
# yapf: disable
block_strs = (
['\n'.join(sorted(first_party_block))] +
['\n'.join(sorted(third_party_block))] +
['\n'.join(sorted(stl_block))])
# yapf: enable
return '\n\n'.join(
[block_str for block_str in block_strs if block_str.strip()])
@ensure(lambda result: not result.endswith('\n'))
def _message_function() -> str:
"""
Generate the function that joins strings for error messages.
:return: generated code
"""
return textwrap.dedent(
'''\
/**
* generates an error message.
*
* @param cc char array as the description part of the message
* @param cc_size size of the char array
* @param s string as the detail part of the message
* @return concatenated string
*/
std::string message(const char* cc, size_t cc_size, std::string s) {
std::string result;
result.reserve(cc_size + s.size());
result.append(cc, cc_size);
result.append(s);
return result;
}''')
@ensure(lambda result: not result.endswith('\n'))
def _regex_constants(graph: mapry.Graph) -> str:
"""
Generate the code to define regular expressions as constants.
:param graph: mapry definition of the object graph
:return: generated code
"""
blocks = [] # type: List[str]
# define regular expressions for duration
if mapry.needs_type(a_type=graph, query=mapry.Duration):
re_block = mapry.indention.reindent(
'''\
namespace re {
const std::regex kDuration(
"^(\\\\+|-)?P(((0|[1-9][0-9]*)(\\\\.[0-9]+)?)Y)?"
"(((0|[1-9][0-9]*)(\\\\.[0-9]+)?)M)?"
"(((0|[1-9][0-9]*)(\\\\.[0-9]+)?)W)?"
"(((0|[1-9][0-9]*)(\\\\.[0-9]+)?)D)?"
"(T"
"(((0|[1-9][0-9]*)(\\\\.[0-9]+)?)H)?"
"(((0|[1-9][0-9]*)(\\\\.[0-9]+)?)M)?"
"(((0|[1-9][0-9]*)(\\\\.([0-9]+))?)S)?"
")?$");
} // namespace re''')
blocks.append(re_block)
for cls in graph.classes.values():
if cls.id_pattern is None:
continue
blocks.append(
textwrap.dedent(
'''\
namespace {composite_varname}_re {{
const std::regex kID(
R"v0g0n({regex})v0g0n");
}} // namespace {composite_varname}_re'''.format(
composite_varname=mapry.cpp.naming.as_variable(
identifier=cls.name),
regex=cls.id_pattern.pattern)))
return "\n\n".join(blocks)
@ensure(lambda result: not result.endswith('\n'))
def _duration_from_string() -> str:
"""
Generate the code for parsing durations from strings.
:return: generated code
"""
return textwrap.dedent(
'''\
/**
* adds the left and the right and checks for the overflow.
*
* left and right are expected to be non-negative.
*
* @param[in] left summand
* @param[in] right summand
* @param[out] overflows true if the addition overflows
* @return sum
*/
template <typename rep_t>
rep_t add_rep_double(rep_t left, double right, bool* overflows) {
if (left < 0) {
throw std::invalid_argument("Expected left >= 0");
}
if (right < 0) {
throw std::invalid_argument("Expected right >= 0");
}
// 9223372036854775808 == 2^63, the first double that is
// greater than max int64 (max int64 is 2^63 - 1).
if (right >= 9223372036854775808.0) {
*overflows = true;
return 0;
}
const rep_t rightRep = right;
if (rightRep > std::numeric_limits<rep_t>::max() - left) {
*overflows = true;
return 0;
}
return rightRep + left;
}
/**
* parses the duration from a string.
*
* Following STL chrono library, the following units are counted as:
* - years as 365.2425 days (the average length of a Gregorian year),
* - months as 30.436875 days (exactly 1/12 of years) and
* - weeks as 7 days.
*
* See https://en.cppreference.com/w/cpp/chrono/duration for details.
*
* @param[in] s string to parse
* @param[out] error error message, if any
* @return parsed duration
*/
std::chrono::nanoseconds duration_from_string(
const std::string& s,
std::string* error) {
std::smatch mtch;
const bool matched = std::regex_match(s, mtch, re::kDuration);
if (!matched) {
std::stringstream sserr;
sserr << "failed to match the duration: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
typedef std::chrono::nanoseconds::rep rep_t;
////
// Extract nanoseconds
////
const std::string nanoseconds_str = mtch[31];
rep_t nanoseconds;
if (nanoseconds_str.size() == 0) {
// No nanoseconds specified
nanoseconds = 0;
} else if(nanoseconds_str.size() <= 9) {
size_t first_nonzero = 0;
for (; first_nonzero < nanoseconds_str.size();
++first_nonzero) {
if (nanoseconds_str[first_nonzero] >= '0' and
nanoseconds_str[first_nonzero] <= '9') {
break;
}
}
if (first_nonzero == nanoseconds_str.size()) {
// No non-zero numbers, all zeros behind the seconds comma
nanoseconds = 0;
} else {
const rep_t fraction_as_integer(
std::atol(&nanoseconds_str[first_nonzero]));
const size_t order = 9 - nanoseconds_str.size();
rep_t multiplier = 1;
for (size_t i = 0; i < order; ++i) {
multiplier *= 10;
}
nanoseconds = fraction_as_integer * multiplier;
}
} else {
// Signal that the precision is lost
std::stringstream sserr;
sserr << "converting the duration to nanoseconds "
"results in loss of precision: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
////
// Extract all the other interval counts
////
const std::string sign_str = mtch[1];
const rep_t sign = (sign_str.empty() or sign_str == "+") ? 1 : -1;
const double years(
(mtch[3].length() == 0) ? 0.0 : std::stod(mtch[3]));
const double months(
(mtch[7].length() == 0) ? 0.0 : std::stod(mtch[7]));
const double weeks(
(mtch[11].length() == 0) ? 0.0 : std::stod(mtch[11]));
const double days(
(mtch[15].length() == 0) ? 0.0 : std::stod(mtch[15]));
const double hours(
(mtch[20].length() == 0) ? 0.0 : std::stod(mtch[20]));
const double minutes(
(mtch[24].length() == 0) ? 0.0 : std::stod(mtch[24]));
const rep_t seconds(
(mtch[29].length() == 0) ? 0 : std::stol(mtch[29]));
////
// Sum
////
rep_t sum = nanoseconds;
const rep_t max_seconds(
std::numeric_limits<rep_t>::max() / (1000L * 1000L * 1000L));
if (seconds > max_seconds) {
std::stringstream sserr;
sserr << "seconds in duration overflow as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
const rep_t seconds_as_ns = seconds * 1000L * 1000L * 1000L;
if (sum > std::numeric_limits<rep_t>::max() - seconds_as_ns) {
std::stringstream sserr;
sserr << "duration overflow as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
sum += seconds_as_ns;
bool overflows;
sum = add_rep_double(
sum, minutes * 6e10, &overflows);
if (overflows) {
std::stringstream sserr;
sserr << "duration overflows as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
sum = add_rep_double(
sum, hours * 3.6e12, &overflows);
if (overflows) {
std::stringstream sserr;
sserr << "duration overflows as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
sum = add_rep_double(
sum, days * 24.0 * 3.6e12, &overflows);
if (overflows) {
std::stringstream sserr;
sserr << "duration overflows as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
sum = add_rep_double(
sum, weeks * 7.0 * 24.0 * 3.6e12, &overflows);
if (overflows) {
std::stringstream sserr;
sserr << "duration overflows as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
sum = add_rep_double(
sum, months * 30.436875 * 24.0 * 3.6e12, &overflows);
if (overflows) {
std::stringstream sserr;
sserr << "duration overflows as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
sum = add_rep_double(
sum, years * 365.2425 * 24.0 * 3.6e12, &overflows);
if (overflows) {
std::stringstream sserr;
sserr << "duration overflows as nanoseconds: " << s;
*error = sserr.str();
return std::chrono::nanoseconds();
}
// sum is always positive, so the multiplication by -1 can not
// overflow since |max rep_t| < |min rep_t|
if (sign < 0) {
sum = -sum;
}
return std::chrono::nanoseconds(sum);
}''')
@ensure(lambda result: not result.endswith('\n'))
def _value_type_to_string() -> str:
"""
Generate the function to convert Json::ValueType to a string.
:return: generated code
"""
return textwrap.dedent(
'''\
/**
* converts a JSON value type to a human-readable string representation.
*
* @param value_type to be converted
* @return string representation of the JSON value type
*/
std::string value_type_to_string(Json::ValueType value_type) {
switch (value_type) {
case Json::ValueType::nullValue: return "null";
case Json::ValueType::intValue: return "int";
case Json::ValueType::uintValue: return "uint";
case Json::ValueType::realValue: return "real";
case Json::ValueType::stringValue: return "string";
case Json::ValueType::booleanValue: return "bool";
case Json::ValueType::arrayValue: return "array";
case Json::ValueType::objectValue: return "object";
default:
std::stringstream ss;
ss << "Unhandled value type in value_to_string: "
<< value_type;
throw std::domain_error(ss.str());
}
}''')
class _AutoID:
"""Keep track of parsing identifiers."""
def __init__(self) -> None:
"""Initialize with a zero identifier."""
self._next_id = 0
@ensure(
lambda result: re.match(r'^0|[1-9][0-9]*$', result),
enabled=icontract.SLOW)
def next_identifier(self) -> str:
"""
Generate the next identifier.
:return: the generated identifier
"""
result = self._next_id
self._next_id += 1
return str(result)
_PARSE_BOOLEAN_TPL = mapry.cpp.jinja2_env.ENV.from_string(
'''\
{# Assume `errors` is defined to collect errors. #}
{% if value_expr|is_variable %}
{# short-circuit value as value expression if it is a variable so that
we don't end up with an unnecessary variable1 = variable2 statement.#}
{% set value = value_expr %}
{% else %}
{% set value = "value_%s"|format(uid) %}
const Json::Value& value_{{ uid }} = {{ value_expr }};
{% endif %}
if (!{{ value }}.isBool()) {
constexpr auto expected_but_got(
"Expected a bool, but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
value_type_to_string(
{{ value }}.type())));
} else {
{{ target_expr }} = {{ value }}.asBool();
}''')
@ensure(lambda result: not result.endswith('\n'))
def _parse_boolean(
value_expr: str, target_expr: str, ref_parts: List[str],
auto_id: _AutoID) -> str:
"""
Generate the code to parse a boolean.
The code parses the ``value_expr`` into the ``target_expr``.
:param value_expr: C++ expression of the JSON value
:param target_expr: C++ expression of where to store the parsed value
:param ref_parts: C++ expression of reference path segments to the value
:param auto_id: generator of unique identifiers
:return: C++ code
"""
uid = auto_id.next_identifier()
return _PARSE_BOOLEAN_TPL.render(
uid=uid,
value_expr=value_expr,
ref_parts=ref_parts,
target_expr=target_expr)
_PARSE_INTEGER_TPL = mapry.cpp.jinja2_env.ENV.from_string(
'''\
{# Assume `errors` is defined to collect errors. #}
{% if value_expr|is_variable %}
{# Short-circuit value as value expression if it is a variable so that
we don't end up with an unnecessary variable1 = variable2 statement.#}
{% set value = value_expr %}
{% else %}
{% set value = "value_%s"|format(uid) %}
const Json::Value& value_{{ uid }} = {{ value_expr }};
{% endif %}{# /value_expr|is_variable #}
if (!{{ value }}.isInt64()) {
constexpr auto expected_but_got(
"Expected an int64, but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
value_type_to_string(
{{ value }}.type())));
} else {
{% if a_type.minimum is none and a_type.maximum is none %}
{{ target_expr }} = {{ value }}.asInt64();
{% else %}
const auto cast_{{ uid }} = {{ value }}.asInt64();
bool ok_{{ uid }} = true;
{% if a_type.minimum is not none %}
{% set op = ">" if a_type.exclusive_minimum else ">=" %}
if (!(cast_{{ uid }} {{ op }} {{ a_type.minimum }})) {
constexpr auto expected_but_got(
"Expected "
{{ "%s %d"|format(op, a_type.minimum)|escaped_str }}
", but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
std::to_string(cast_{{ uid }})));
ok_{{ uid }} = false;
}
{% endif %}
{% if a_type.maximum is not none %}
{% set op = "<" if a_type.exclusive_maximum else "<=" %}
if (!(cast_{{ uid }} {{ op }} {{ a_type.maximum }})) {
constexpr auto expected_but_got(
"Expected "
{{ "%s %d"|format(op, a_type.maximum)|escaped_str }}
", but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
std::to_string(cast_{{ uid }})));
ok_{{ uid }} = false;
}
{% endif %}
if (ok_{{ uid }}) {
{{ target_expr }} = cast_{{ uid }};
}
{% endif %}{# /if a_type.minimum is none and a_type.maximum is none #}
}
''')
@ensure(lambda result: not result.endswith('\n'))
def _parse_integer(
value_expr: str, target_expr: str, ref_parts: List[str],
a_type: mapry.Integer, auto_id: _AutoID) -> str:
"""
Generate the code to parse an integer.
The code parses the ``value_expr`` into the ``target_expr``.
:param value_expr: C++ expression of the JSON value
:param target_expr: C++ expression of where to store the parsed value
:param ref_parts: C++ expression of reference path segments to the value
:param a_type: mapry definition of the value type
:param auto_id: generator of unique identifiers
:return: generated code
"""
uid = auto_id.next_identifier()
return _PARSE_INTEGER_TPL.render(
uid=uid,
value_expr=value_expr,
ref_parts=ref_parts,
target_expr=target_expr,
a_type=a_type).rstrip("\n")
_PARSE_FLOAT_TPL = mapry.cpp.jinja2_env.ENV.from_string(
'''\
{# Assume `errors` is defined to collect errors. #}
{% if value_expr|is_variable %}
{# Short-circuit value as value expression if it is a variable so that
we don't end up with an unnecessary variable1 = variable2 statement.#}
{% set value = value_expr %}
{% else %}
{% set value = "value_%s"|format(uid) %}
const Json::Value& value_{{ uid }} = {{ value_expr }};
{% endif %}
if (!{{ value }}.isDouble()) {
constexpr auto expected_but_got(
"Expected a double, but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
value_type_to_string(
{{ value }}.type())));
} else {
{% if a_type.minimum is none and a_type.maximum is none %}
{{ target_expr }} = {{ value }}.asDouble();
{% else %}
const auto cast_{{ uid }} = {{ value }}.asDouble();
bool ok_{{ uid }} = true;
{% if a_type.minimum is not none %}
{% set op = ">" if a_type.exclusive_minimum else ">=" %}
if (!(cast_{{ uid }} {{ op }} {{ a_type.minimum }})) {
constexpr auto expected_but_got(
"Expected "
{{ "%s %f"|format(op, a_type.minimum)|escaped_str }}
", but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
std::to_string(cast_{{ uid }})));
ok_{{ uid }} = false;
}
{% endif %}{# /if a_type.minimum is not none #}
{% if a_type.maximum is not none %}
{% set op = "<" if a_type.exclusive_maximum else "<=" %}
if (!(cast_{{ uid }} {{ op }} {{ a_type.maximum }})) {
constexpr auto expected_but_got(
"Expected "
{{ "%s %f"|format(op, a_type.maximum)|escaped_str }}
", but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
std::to_string(cast_{{ uid }})));
ok_{{ uid }} = false;
}
{% endif %}{# /if a_type.maximum is not none #}
if (ok_{{ uid }}) {
{{ target_expr }} = cast_{{ uid }};
}
{% endif %}{# /if a_type.minimum is none and a_type.maximum is none #}
}''')
@ensure(lambda result: not result.endswith('\n'))
def _parse_float(
value_expr: str, target_expr: str, ref_parts: List[str],
a_type: mapry.Float, auto_id: _AutoID) -> str:
"""
Generate the code to parse a floating-point number.
The code parses the ``value_expr`` into the ``target_expr``.
:param value_expr: C++ expression of the JSON value
:param target_expr: C++ expression of where to store the parsed value
:param ref_parts: C++ expression of reference path segments to the value
:param a_type: mapry definition of the value type
:param auto_id: generator of unique identifiers
:return: generated code
"""
uid = auto_id.next_identifier()
return _PARSE_FLOAT_TPL.render(
uid=uid,
value_expr=value_expr,
ref_parts=ref_parts,
target_expr=target_expr,
a_type=a_type).rstrip("\n")
_PARSE_STRING_TPL = mapry.cpp.jinja2_env.ENV.from_string(
'''\
{# Assume `errors` is defined to collect errors. #}
{% if value_expr|is_variable %}
{# Short-circuit value as value expression if it is a variable so that
we don't end up with an unnecessary variable1 = variable2 statement.#}
{% set value = value_expr %}
{% else %}
{% set value = "value_%s"|format(uid) %}
const Json::Value& value_{{ uid }} = {{ value_expr }};
{% endif %}
if (!{{ value }}.isString()) {
constexpr auto expected_but_got(
"Expected a string, but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
value_type_to_string(
{{ value }}.type())));
} else {
{% if a_type.pattern is none %}
{{ target_expr }} = {{ value }}.asString();
{% else %}
const static std::regex regex_{{ uid }}(
R"v0g0n({{ a_type.pattern.pattern }})v0g0n");
const std::string cast_{{ uid }} = {{ value }}.asString();
bool ok_{{ uid }} = true;
if (!std::regex_match(cast_{{ uid }}, regex_{{ uid }})) {
constexpr auto expected_but_got(
"Expected to match "
{{ a_type.pattern.pattern|escaped_str }}
", but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
cast_{{ uid }}));
ok_{{ uid }} = false;
}
if (ok_{{ uid }}) {
{{ target_expr }} = cast_{{ uid }};
}
{% endif %}{# /if a_type.pattern is none #}
}''')
@ensure(lambda result: not result.endswith('\n'))
def _parse_string(
value_expr: str, target_expr: str, ref_parts: List[str],
a_type: mapry.String, auto_id: _AutoID) -> str:
"""
Generate the code to parse a string.
The code parses the ``value_expr`` into the ``target_expr``.
:param value_expr: C++ expression of the JSON value
:param target_expr: C++ expression of where to store the parsed value
:param ref_parts: C++ expression of reference path segments to the value
:param a_type: mapry definition of the value type
:param auto_id: generator of unique identifiers
:return: generated code
"""
uid = auto_id.next_identifier()
return _PARSE_STRING_TPL.render(
uid=uid,
value_expr=value_expr,
ref_parts=ref_parts,
target_expr=target_expr,
a_type=a_type).rstrip("\n")
_PARSE_PATH_TPL = mapry.cpp.jinja2_env.ENV.from_string(
'''\
{# Assume `errors` is defined to collect errors. #}
{% if value_expr|is_variable %}
{# Short-circuit value as value expression if it is a variable so that
we don't end up with an unnecessary variable1 = variable2 statement.#}
{% set value = value_expr %}
{% else %}
{% set value = "value_%s"|format(uid) %}
const Json::Value& value_{{ uid }} = {{ value_expr }};
{% endif %}
if (!{{ value }}.isString()) {
constexpr auto expected_but_got(
"Expected a string, but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
value_type_to_string(
{{ value }}.type())));
} else {
{% set set_target %}
{% if cpp.path_as == "std::filesystem::path" %}
{{ target_expr }} = std::filesystem::path(
{{ value }}.asString());
{% elif cpp.path_as == "boost::filesystem::path" %}
{{ target_expr }} = boost::filesystem::path(
{{ value }}.asString());
{% else %}
{{ _raise("Unhandled cpp.path_as: %s"|format(cpp.path_as)) }}
{% endif %}
{% endset %}{#
#}
{% if a_type.pattern is none %}
{{ set_target }}
{% else %}
const static std::regex regex(
R"v0g0n({{ a_type.pattern.pattern }})v0g0n");
const std::string cast_{{ uid }} = {{ value }}.asString();
bool ok_{{ uid }} = true;
if (!std::regex_match(cast_{{ uid }}, regex)) {
constexpr auto expected_but_got(
"Expected to match "
{{ a_type.pattern.pattern|escaped_str }}
", but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
cast_{{ uid }}));
ok_{{ uid }} = false;
}
if (ok_{{ uid }}) {
{{ set_target|indent }}
}
{% endif %}{# /if a_type.pattern is none #}
}''')
@ensure(lambda result: not result.endswith('\n'))
def _parse_path(
value_expr: str, target_expr: str, ref_parts: List[str],
a_type: mapry.Path, auto_id: _AutoID, cpp: mapry.Cpp) -> str:
"""
Generate the code to parse a path.
The code parses the ``value_expr`` into the ``target_expr``.
:param value_expr: C++ expression of the JSON value
:param target_expr: C++ expression of where to store the parsed value
:param ref_parts: C++ expression of reference path segments to the value
:param a_type: mapry definition of the value type
:param auto_id: generator of unique identifiers
:param cpp: C++ settings
:return: generated code
"""
uid = auto_id.next_identifier()
return _PARSE_PATH_TPL.render(
uid=uid,
value_expr=value_expr,
ref_parts=ref_parts,
target_expr=target_expr,
a_type=a_type,
cpp=cpp).rstrip("\n")
_PARSE_CTIME_TPL = mapry.cpp.jinja2_env.ENV.from_string(
'''\
{# Assume `errors` is defined to collect errors. #}
{% if value_expr|is_variable %}
{# Short-circuit value as value expression if it is a variable so that
we don't end up with an unnecessary variable1 = variable2 statement.#}
{% set value = value_expr %}
{% else %}
{% set value = "value_%s"|format(uid) %}
const Json::Value& value_{{ uid }} = {{ value_expr }};
{% endif %}
if (!{{ value }}.isString()) {
constexpr auto expected_but_got(
"Expected a string, but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
value_type_to_string(
{{ value }}.type())));
} else {
const std::string cast_{{ uid }} = {{ value }}.asString();
struct tm tm_{{ uid }} = tm{0};
char* ret_{{ uid }} = strptime(
cast_{{ uid }}.c_str(),
{{ a_type.format|escaped_str }},
&tm_{{ uid }});
if (ret_{{ uid }} == nullptr or *ret_{{ uid }} != '\\0') {
constexpr auto expected_but_got(
"Expected to strptime "
{{ a_type.format|escaped_str }}
", but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
cast_{{ uid }}));
} else {
{{ target_expr }} = tm_{{ uid }};
}
}''')
_PARSE_DATE_TPL = mapry.cpp.jinja2_env.ENV.from_string(
'''\
{# Assume `errors` is defined to collect errors. #}
{% if value_expr|is_variable %}
{# Short-circuit value as value expression if it is a variable so that
we don't end up with an unnecessary variable1 = variable2 statement.#}
{% set value = value_expr %}
{% else %}
{% set value = "value_%s"|format(uid) %}
const Json::Value& value_{{ uid }} = {{ value_expr }};
{% endif %}
if (!{{ value }}.isString()) {
constexpr auto expected_but_got(
"Expected a string, but got: ");
errors->add(
{{ ref_parts|join_strings|indent|indent }},
message(
expected_but_got,
strlen(expected_but_got),
value_type_to_string(
{{ value }}.type())));
} else {
std::istringstream iss_{{ uid }}(
{{ value }}.asString());
iss_{{ uid }} >>
date::parse(
{{ a_type.format|escaped_str }},
{{ target_expr }} );
if (iss_{{ uid }}.fail()) {
constexpr auto expected_but_got(
"Expected to date::parse "
{{ a_type.format|escaped_str }}