Line data Source code
1 : /* JSON trees
2 : Copyright (C) 2017-2026 Free Software Foundation, Inc.
3 : Contributed by David Malcolm <dmalcolm@redhat.com>.
4 :
5 : This file is part of GCC.
6 :
7 : GCC is free software; you can redistribute it and/or modify it under
8 : the terms of the GNU General Public License as published by the Free
9 : Software Foundation; either version 3, or (at your option) any later
10 : version.
11 :
12 : GCC is distributed in the hope that it will be useful, but WITHOUT ANY
13 : WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 : FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
15 : for more details.
16 :
17 : You should have received a copy of the GNU General Public License
18 : along with GCC; see the file COPYING3. If not see
19 : <http://www.gnu.org/licenses/>. */
20 :
21 : #define INCLUDE_STRING
22 : #include "config.h"
23 : #include "system.h"
24 : #include "coretypes.h"
25 : #include "json.h"
26 : #include "pretty-print.h"
27 : #include "math.h"
28 : #include "selftest.h"
29 :
30 : using namespace json;
31 :
32 : /* Print a JSON string to PP, escaping '"', control characters,
33 : and embedded null bytes.
34 : The string is required to be UTF-8 encoded. */
35 :
36 : static void
37 1384455 : print_escaped_json_string (pretty_printer *pp,
38 : const char *utf8_str,
39 : size_t len)
40 : {
41 1384455 : pp_character (pp, '"');
42 20411287 : for (size_t i = 0; i != len; ++i)
43 : {
44 17642377 : char ch = utf8_str[i];
45 17642377 : switch (ch)
46 : {
47 3054 : case '"':
48 3054 : pp_string (pp, "\\\"");
49 3054 : break;
50 1609 : case '\\':
51 1609 : pp_string (pp, "\\\\");
52 1609 : break;
53 8 : case '\b':
54 8 : pp_string (pp, "\\b");
55 8 : break;
56 8 : case '\f':
57 8 : pp_string (pp, "\\f");
58 8 : break;
59 54736 : case '\n':
60 54736 : pp_string (pp, "\\n");
61 54736 : break;
62 8 : case '\r':
63 8 : pp_string (pp, "\\r");
64 8 : break;
65 3218 : case '\t':
66 3218 : pp_string (pp, "\\t");
67 3218 : break;
68 4 : case '\0':
69 4 : pp_string (pp, "\\0");
70 4 : break;
71 17579732 : default:
72 17579732 : pp_character (pp, ch);
73 : }
74 : }
75 1384455 : pp_character (pp, '"');
76 1384455 : }
77 :
78 : /* class pointer::token. */
79 :
80 4221054 : pointer::token::token ()
81 : {
82 4221054 : m_parent = nullptr;
83 4221054 : m_data.u_member = nullptr;
84 4221054 : m_kind = kind::root_value;
85 4221054 : }
86 :
87 3403423 : pointer::token::token (json::object &parent, const char *member)
88 : {
89 3403423 : m_parent = &parent;
90 3403423 : m_data.u_member = xstrdup (member); // ideally we'd share
91 3403423 : m_kind = kind::object_member;
92 3403423 : }
93 :
94 811433 : pointer::token::token (json::array &parent, size_t index)
95 : {
96 811433 : m_parent = &parent;
97 811433 : m_data.u_index = index;
98 811433 : m_kind = kind::array_index;
99 811433 : }
100 :
101 8434402 : pointer::token::~token ()
102 : {
103 8434402 : if (m_kind == kind::object_member)
104 : {
105 3402156 : gcc_assert (m_data.u_member);
106 3402156 : free (m_data.u_member);
107 : }
108 8434402 : }
109 :
110 : pointer::token &
111 4214856 : pointer::token::operator= (pointer::token &&other)
112 : {
113 4214856 : m_parent = other.m_parent;
114 4214856 : m_data = other.m_data;
115 4214856 : m_kind = other.m_kind;
116 :
117 4214856 : other.m_parent = nullptr;
118 4214856 : other.m_data.u_member = nullptr;
119 4214856 : other.m_kind = kind::root_value;
120 :
121 4214856 : return *this;
122 : }
123 :
124 : /* Print this to PP as an RFC 6901 section 3 reference-token. */
125 :
126 : void
127 92 : pointer::token::print (pretty_printer *pp) const
128 : {
129 92 : switch (m_kind)
130 : {
131 : case kind::root_value:
132 : break;
133 :
134 24 : case kind::object_member:
135 24 : {
136 96 : for (const char *ch = m_data.u_member; *ch; ++ch)
137 : {
138 72 : switch (*ch)
139 : {
140 4 : case '~':
141 4 : pp_string (pp, "~0");
142 4 : break;
143 4 : case '/':
144 4 : pp_string (pp, "~1");
145 4 : break;
146 64 : default:
147 64 : pp_character (pp, *ch);
148 64 : break;
149 : }
150 : }
151 : }
152 : break;
153 :
154 8 : case kind::array_index:
155 8 : pp_scalar (pp, HOST_SIZE_T_PRINT_UNSIGNED, (fmt_size_t) m_data.u_index);
156 8 : break;
157 : }
158 92 : }
159 :
160 : /* class json::value. */
161 :
162 : /* Dump this json::value tree to OUTF.
163 :
164 : The key/value pairs of json::objects are printed in the order
165 : in which the keys were originally inserted. */
166 :
167 : void
168 115 : value::dump (FILE *outf, bool formatted) const
169 : {
170 115 : pretty_printer pp;
171 115 : pp_buffer (&pp)->m_stream = outf;
172 115 : print (&pp, formatted);
173 115 : pp_flush (&pp);
174 115 : }
175 :
176 : /* A convenience function for debugging.
177 : Dump to stderr with formatting, and a trailing newline. */
178 :
179 : void
180 0 : value::dump () const
181 : {
182 0 : dump (stderr, true);
183 0 : fprintf (stderr, "\n");
184 0 : }
185 :
186 : /* A deterministic total ordering for comparing json values, so that we
187 : can e.g. put them in std::map.
188 :
189 : This is intended to follow the condition for equality described in
190 : the JSON Schema standard (§4.3, “Instance equality”), as referenced
191 : by SARIF v2.1.0 (§3.7.3 "Array properties with unique values"), but has
192 : the following limitations:
193 : - numbers are supposed to be checked for "the same mathematical value",
194 : but in this implementation int vs float numbers won't compare as equal,
195 : and float number comparison is bitwise
196 : - strings are supposed to be "the same codepoint-for-codepoint", but
197 : this implementation doesn't take into account canonicalization issues. */
198 :
199 : int
200 17138 : value::compare (const value &val_a, const value &val_b)
201 : {
202 17138 : enum kind kind_a = val_a.get_kind ();
203 17138 : enum kind kind_b = val_b.get_kind ();
204 17138 : if (kind_a != kind_b)
205 32 : return (int)kind_a - (int)kind_b;
206 :
207 17106 : switch (kind_a)
208 : {
209 0 : default:
210 0 : gcc_unreachable ();
211 :
212 5470 : case JSON_OBJECT:
213 5470 : {
214 5470 : const object &obj_a = (const object &)val_a;
215 5470 : const object &obj_b = (const object &)val_b;
216 5470 : return object::compare (obj_a, obj_b);
217 : }
218 56 : break;
219 :
220 56 : case JSON_ARRAY:
221 56 : {
222 56 : const array &arr_a = (const array &)val_a;
223 56 : const array &arr_b = (const array &)val_b;
224 128 : if (int cmp_size = (int)arr_a.size () - (int)arr_b.size ())
225 : return cmp_size;
226 64 : for (size_t idx = 0; idx < arr_a.size (); ++idx)
227 24 : if (int cmp_element = compare (*arr_a[idx], *arr_b[idx]))
228 : return cmp_element;
229 : return 0;
230 : }
231 81 : break;
232 :
233 81 : case JSON_INTEGER:
234 81 : {
235 81 : const integer_number &int_a = (const integer_number &)val_a;
236 81 : const integer_number &int_b = (const integer_number &)val_b;
237 81 : return int_a.get () - int_b.get ();
238 : }
239 32 : break;
240 :
241 32 : case JSON_FLOAT:
242 32 : {
243 32 : const float_number &float_a = (const float_number &)val_a;
244 32 : const float_number &float_b = (const float_number &)val_b;
245 32 : union u
246 : {
247 : double u_double;
248 : char u_buf[sizeof(double)];
249 : };
250 32 : union u u_a, u_b;
251 32 : u_a.u_double = float_a.get ();
252 32 : u_b.u_double = float_b.get ();
253 32 : return memcmp (&u_a, &u_b, sizeof(double));
254 : }
255 11427 : break;
256 :
257 11427 : case JSON_STRING:
258 11427 : {
259 11427 : const string &str_a = (const string &)val_a;
260 11427 : const string &str_b = (const string &)val_b;
261 11427 : return strcmp (str_a.get_string (), str_b.get_string ());
262 : }
263 : break;
264 :
265 : case JSON_TRUE:
266 : case JSON_FALSE:
267 : case JSON_NULL:
268 : /* All instances of literals compare equal to instances
269 : of the same literal. */
270 : return 0;
271 : }
272 : }
273 :
274 : /* Print this value's JSON Pointer to PP. */
275 :
276 : void
277 60 : value::print_pointer (pretty_printer *pp) const
278 : {
279 : /* Get path from this value to root. */
280 60 : auto_vec<const pointer::token *> ancestry;
281 152 : for (auto *iter = this; iter; iter = iter->m_pointer_token.m_parent)
282 92 : ancestry.safe_push (&iter->m_pointer_token);
283 :
284 : /* Walk backward, going from root to this value. */
285 60 : ancestry.reverse ();
286 60 : bool first = true;
287 272 : for (auto iter : ancestry)
288 : {
289 92 : if (first)
290 : first = false;
291 : else
292 32 : pp_character (pp, '/');
293 92 : iter->print (pp);
294 : }
295 60 : }
296 :
297 : /* class json::object, a subclass of json::value, representing
298 : an ordered collection of key/value pairs. */
299 :
300 : /* json:object's dtor. */
301 :
302 1539040 : object::~object ()
303 : {
304 4180934 : for (map_t::iterator it = m_map.begin (); it != m_map.end (); ++it)
305 : {
306 3402078 : free (const_cast <char *>((*it).first));
307 3402078 : delete ((*it).second);
308 : }
309 1539040 : }
310 :
311 : /* Implementation of json::value::print for json::object. */
312 :
313 : void
314 265837 : object::print (pretty_printer *pp, bool formatted) const
315 : {
316 265837 : pp_character (pp, '{');
317 265837 : if (formatted)
318 12413 : pp_indentation (pp) += 1;
319 :
320 : /* Iterate in the order that the keys were inserted. */
321 265837 : unsigned i;
322 265837 : const char *key;
323 1389167 : FOR_EACH_VEC_ELT (m_keys, i, key)
324 : {
325 857507 : if (i > 0)
326 : {
327 591684 : pp_string (pp, ",");
328 591684 : if (formatted)
329 : {
330 18234 : pp_newline (pp);
331 18234 : pp_indent (pp);
332 : }
333 : else
334 573450 : pp_space (pp);
335 : }
336 857507 : map_t &mut_map = const_cast<map_t &> (m_map);
337 857507 : value *value = *mut_map.get (key);
338 857507 : print_escaped_json_string (pp, key, strlen (key));
339 857507 : pp_string (pp, ": ");
340 857507 : const int indent = strlen (key) + 4;
341 857507 : if (formatted)
342 30633 : pp_indentation (pp) += indent;
343 857507 : value->print (pp, formatted);
344 857507 : if (formatted)
345 30633 : pp_indentation (pp) -= indent;
346 : }
347 265837 : if (formatted)
348 12413 : pp_indentation (pp) -= 1;
349 265837 : pp_character (pp, '}');
350 265837 : }
351 :
352 : std::unique_ptr<value>
353 1320 : object::clone () const
354 : {
355 1320 : return clone_as_object ();
356 : }
357 :
358 : std::unique_ptr<object>
359 1320 : object::clone_as_object () const
360 : {
361 1320 : auto result = std::make_unique<object> ();
362 :
363 : /* Iterate in the order that the keys were inserted. */
364 1320 : unsigned i;
365 1320 : const char *key;
366 6688 : FOR_EACH_VEC_ELT (m_keys, i, key)
367 : {
368 4048 : map_t &mut_map = const_cast<map_t &> (m_map);
369 4048 : value *value = *mut_map.get (key);
370 4048 : result->set (key, value->clone ());
371 : }
372 :
373 1320 : return result;
374 : }
375 :
376 : /* Set the json::value * for KEY, taking ownership of V
377 : (and taking a copy of KEY if necessary). */
378 :
379 : void
380 3403423 : object::set (const char *key, value *v)
381 : {
382 3403423 : gcc_assert (key);
383 3403423 : gcc_assert (v);
384 :
385 3403423 : value **ptr = m_map.get (key);
386 3403423 : if (ptr)
387 : {
388 : /* If the key is already present, delete the existing value
389 : and overwrite it. */
390 78 : delete *ptr;
391 78 : *ptr = v;
392 : }
393 : else
394 : {
395 : /* If the key wasn't already present, take a copy of the key,
396 : and store the value. */
397 3403345 : char *owned_key = xstrdup (key);
398 3403345 : m_map.put (owned_key, v);
399 3403345 : m_keys.safe_push (owned_key);
400 : }
401 :
402 3403423 : v->m_pointer_token = pointer::token (*this, key);
403 3403423 : }
404 :
405 : /* Get the json::value * for KEY.
406 :
407 : The object retains ownership of the value. */
408 :
409 : value *
410 26231 : object::get (const char *key) const
411 : {
412 26231 : gcc_assert (key);
413 :
414 26231 : value **ptr = const_cast <map_t &> (m_map).get (key);
415 26231 : if (ptr)
416 23629 : return *ptr;
417 : else
418 : return NULL;
419 : }
420 :
421 : /* Set value of KEY within this object to a JSON
422 : string value based on UTF8_VALUE.
423 : Return a borrowed ptr to the new json::string. */
424 :
425 : const json::string *
426 1373491 : object::set_string (const char *key, const char *utf8_value)
427 : {
428 1373491 : json::string *str = new json::string (utf8_value);
429 1373491 : set (key, str);
430 1373491 : return str;
431 : }
432 :
433 : /* As above, but taking a std::string. */
434 :
435 : const json::string *
436 5750 : object::set_string (const char *key, std::string utf8_value)
437 : {
438 5750 : json::string *str = new json::string (utf8_value.c_str ());
439 5750 : set (key, str);
440 5750 : return str;
441 : }
442 :
443 : /* Set value of KEY within this object to a JSON
444 : integer value based on V.
445 : Return a borrowed ptr to the new json::integer_number. */
446 :
447 : const json::integer_number *
448 690269 : object::set_integer (const char *key, long v)
449 : {
450 690269 : json::integer_number *js_int = new json::integer_number (v);
451 690269 : set (key, js_int);
452 690269 : return js_int;
453 : }
454 :
455 : /* Set value of KEY within this object to a JSON
456 : floating point value based on V. */
457 :
458 : void
459 16 : object::set_float (const char *key, double v)
460 : {
461 16 : set (key, new json::float_number (v));
462 16 : }
463 :
464 : /* Set value of KEY within this object to the JSON
465 : literal true or false, based on V. */
466 :
467 : void
468 548 : object::set_bool (const char *key, bool v)
469 : {
470 1096 : set (key, new json::literal (v));
471 548 : }
472 :
473 : void
474 180 : object::set_string (const string_property &property, const char *utf8_value)
475 : {
476 180 : set_string (property.m_key.get (), utf8_value);
477 180 : }
478 :
479 : void
480 240 : object::set_integer (const integer_property &property, long value)
481 : {
482 240 : set_integer (property.m_key.get (), value);
483 240 : }
484 :
485 : void
486 0 : object::set_bool (const bool_property &property, bool value)
487 : {
488 0 : set_bool (property.m_key.get (), value);
489 0 : }
490 :
491 : void
492 780 : object::set_array_of_string (const array_of_string_property &property,
493 : std::unique_ptr<json::array> value)
494 : {
495 780 : set<array> (property.m_key.get (), std::move (value));
496 780 : }
497 :
498 : /* Subroutine of json::compare for comparing a pairs of objects. */
499 :
500 : int
501 5470 : object::compare (const json::object &obj_a, const json::object &obj_b)
502 : {
503 16334 : if (int cmp_size = (int)obj_a.m_keys.length () - (int)obj_b.m_keys.length ())
504 : return cmp_size;
505 :
506 12026 : for (auto iter_a : obj_a.m_map)
507 : {
508 11380 : const char *key = iter_a.first;
509 11380 : const value *value_a = iter_a.second;
510 11380 : gcc_assert (value_a);
511 :
512 11380 : const value *value_b = obj_b.get (key);
513 11380 : if (!value_b)
514 : /* Key is in OBJ_A but not in OBJ_B. */
515 4623 : return 1;
516 : /* If key is OBJ_B but not in OBJ_A, then the
517 : count of keys will have been different, or
518 : OBJ_A would have had a key not in OBJ_B. */
519 11380 : if (int cmp_value = value::compare (*value_a, *value_b))
520 : /* Values for key are non-equal. */
521 : return cmp_value;
522 : }
523 :
524 : /* Objects are equal. */
525 646 : return 0;
526 : }
527 :
528 : /* class json::array, a subclass of json::value, representing
529 : an ordered collection of values. */
530 :
531 : /* json::array's dtor. */
532 :
533 1254440 : array::~array ()
534 : {
535 627668 : unsigned i;
536 627668 : value *v;
537 1439022 : FOR_EACH_VEC_ELT (m_elements, i, v)
538 811354 : delete v;
539 1254440 : }
540 :
541 : /* Implementation of json::value::print for json::array. */
542 :
543 : void
544 97735 : array::print (pretty_printer *pp, bool formatted) const
545 : {
546 97735 : pp_character (pp, '[');
547 97735 : if (formatted)
548 3177 : pp_indentation (pp) += 1;
549 97735 : unsigned i;
550 97735 : value *v;
551 317589 : FOR_EACH_VEC_ELT (m_elements, i, v)
552 : {
553 219854 : if (i)
554 : {
555 137220 : pp_string (pp, ",");
556 137220 : if (formatted)
557 : {
558 6953 : pp_newline (pp);
559 6953 : pp_indent (pp);
560 : }
561 : else
562 130267 : pp_space (pp);
563 : }
564 219854 : v->print (pp, formatted);
565 : }
566 97735 : if (formatted)
567 3177 : pp_indentation (pp) -= 1;
568 97735 : pp_character (pp, ']');
569 97735 : }
570 :
571 : std::unique_ptr<value>
572 755 : array::clone () const
573 : {
574 755 : auto result = std::make_unique<array> ();
575 755 : unsigned i;
576 755 : value *v;
577 2735 : FOR_EACH_VEC_ELT (m_elements, i, v)
578 1225 : result->append (v->clone ());
579 755 : return result;
580 755 : }
581 :
582 : /* Append non-NULL value V to a json::array, taking ownership of V. */
583 :
584 : void
585 811433 : array::append (value *v)
586 : {
587 811433 : gcc_assert (v);
588 1422448 : v->m_pointer_token = pointer::token (*this, m_elements.length ());
589 811433 : m_elements.safe_push (v);
590 811433 : }
591 :
592 : /* Append UTF8_VALUE to this array, returning a borrowed pointer to the
593 : new json::string. */
594 :
595 : const json::string *
596 182846 : array::append_string (const char *utf8_value)
597 : {
598 182846 : gcc_assert (utf8_value);
599 182846 : auto js_str = new json::string (utf8_value);
600 182846 : append (js_str);
601 182846 : return js_str;
602 : }
603 :
604 : /* class json::float_number, a subclass of json::value, wrapping a double. */
605 :
606 : /* Implementation of json::value::print for json::float_number. */
607 :
608 : void
609 32 : float_number::print (pretty_printer *pp,
610 : bool formatted ATTRIBUTE_UNUSED) const
611 : {
612 32 : char tmp[1024];
613 32 : snprintf (tmp, sizeof (tmp), "%g", m_value);
614 32 : pp_string (pp, tmp);
615 32 : }
616 :
617 : std::unique_ptr<value>
618 4 : float_number::clone () const
619 : {
620 4 : return std::make_unique<float_number> (m_value);
621 : }
622 :
623 : /* class json::integer_number, a subclass of json::value, wrapping a long. */
624 :
625 : /* Implementation of json::value::print for json::integer_number. */
626 :
627 : void
628 186907 : integer_number::print (pretty_printer *pp,
629 : bool formatted ATTRIBUTE_UNUSED) const
630 : {
631 186907 : char tmp[1024];
632 186907 : snprintf (tmp, sizeof (tmp), "%ld", m_value);
633 186907 : pp_string (pp, tmp);
634 186907 : }
635 :
636 : std::unique_ptr<value>
637 1265 : integer_number::clone () const
638 : {
639 1265 : return std::make_unique<integer_number> (m_value);
640 : }
641 :
642 : /* class json::string, a subclass of json::value. */
643 :
644 : /* json::string's ctor. */
645 :
646 2116232 : string::string (const char *utf8)
647 : {
648 2116232 : gcc_assert (utf8);
649 2116232 : m_utf8 = xstrdup (utf8);
650 2116232 : m_len = strlen (utf8);
651 2116232 : }
652 :
653 5296 : string::string (const char *utf8, size_t len)
654 : {
655 5296 : gcc_assert (utf8);
656 5296 : m_utf8 = XNEWVEC (char, len + 1);
657 5296 : m_len = len;
658 5296 : memcpy (m_utf8, utf8, len);
659 5296 : m_utf8[len] = '\0';
660 5296 : }
661 :
662 : /* Implementation of json::value::print for json::string. */
663 :
664 : void
665 526948 : string::print (pretty_printer *pp,
666 : bool formatted ATTRIBUTE_UNUSED) const
667 : {
668 526948 : print_escaped_json_string (pp, m_utf8, m_len);
669 526948 : }
670 :
671 : std::unique_ptr<value>
672 5058 : string::clone () const
673 : {
674 5058 : return std::make_unique<string> (m_utf8, m_len);
675 : }
676 :
677 : /* class json::literal, a subclass of json::value. */
678 :
679 : /* Implementation of json::value::print for json::literal. */
680 :
681 : void
682 284 : literal::print (pretty_printer *pp,
683 : bool formatted ATTRIBUTE_UNUSED) const
684 : {
685 284 : switch (m_kind)
686 : {
687 155 : case JSON_TRUE:
688 155 : pp_string (pp, "true");
689 155 : break;
690 121 : case JSON_FALSE:
691 121 : pp_string (pp, "false");
692 121 : break;
693 8 : case JSON_NULL:
694 8 : pp_string (pp, "null");
695 8 : break;
696 0 : default:
697 0 : gcc_unreachable ();
698 : }
699 284 : }
700 :
701 : std::unique_ptr<value>
702 62 : literal::clone () const
703 : {
704 62 : return std::make_unique<literal> (m_kind);
705 : }
706 :
707 :
708 : #if CHECKING_P
709 :
710 : namespace selftest {
711 :
712 : /* Selftests. */
713 :
714 : /* Verify that JV->print () prints EXPECTED_JSON. */
715 :
716 : void
717 168 : assert_json_print_eq (const location &loc,
718 : const json::value &jv,
719 : bool formatted,
720 : const char *expected_json)
721 : {
722 168 : pretty_printer pp;
723 168 : jv.print (&pp, formatted);
724 168 : ASSERT_STREQ_AT (loc, expected_json, pp_formatted_text (&pp));
725 168 : }
726 :
727 : /* Verify that object::get works as expected. */
728 :
729 : static void
730 4 : test_object_get ()
731 : {
732 4 : object obj;
733 4 : value *val = new json::string ("value");
734 4 : obj.set ("foo", val);
735 4 : ASSERT_EQ (obj.get ("foo"), val);
736 4 : ASSERT_EQ (obj.get ("not-present"), NULL);
737 4 : }
738 :
739 : /* Verify that JSON objects are written correctly. */
740 :
741 : static void
742 4 : test_writing_objects ()
743 : {
744 4 : object obj;
745 4 : obj.set_string ("foo", "bar");
746 4 : obj.set_string ("baz", "quux");
747 4 : obj.set_string ("\"\\\b\f\n\r\t", "value for awkward key");
748 :
749 : /* This test relies on json::object writing out key/value pairs
750 : in key-insertion order. */
751 4 : ASSERT_JSON_PRINT_EQ
752 : (obj, true,
753 : "{\"foo\": \"bar\",\n"
754 : " \"baz\": \"quux\",\n"
755 : " \"\\\"\\\\\\b\\f\\n\\r\\t\": \"value for awkward key\"}");
756 4 : ASSERT_JSON_PRINT_EQ
757 : (obj, false,
758 : "{\"foo\": \"bar\", \"baz\": \"quux\""
759 : ", \"\\\"\\\\\\b\\f\\n\\r\\t\": \"value for awkward key\"}");
760 4 : }
761 :
762 : /* Verify that JSON arrays are written correctly. */
763 :
764 : static void
765 4 : test_writing_arrays ()
766 : {
767 4 : array arr;
768 4 : ASSERT_JSON_PRINT_EQ (arr, true, "[]");
769 :
770 4 : arr.append (new json::string ("foo"));
771 4 : ASSERT_JSON_PRINT_EQ (arr, true, "[\"foo\"]");
772 :
773 4 : arr.append_string ("bar");
774 4 : ASSERT_JSON_PRINT_EQ (arr, true,
775 : "[\"foo\",\n"
776 : " \"bar\"]");
777 4 : ASSERT_JSON_PRINT_EQ (arr, false,
778 : "[\"foo\", \"bar\"]");
779 4 : }
780 :
781 : /* Verify that JSON numbers are written correctly. */
782 :
783 : static void
784 4 : test_writing_float_numbers ()
785 : {
786 4 : ASSERT_JSON_PRINT_EQ (float_number (0), true, "0");
787 4 : ASSERT_JSON_PRINT_EQ (float_number (42), true, "42");
788 4 : ASSERT_JSON_PRINT_EQ (float_number (-100), true, "-100");
789 4 : ASSERT_JSON_PRINT_EQ (float_number (123456789), true, "1.23457e+08");
790 4 : }
791 :
792 : static void
793 4 : test_writing_integer_numbers ()
794 : {
795 4 : ASSERT_JSON_PRINT_EQ (integer_number (0), true, "0");
796 4 : ASSERT_JSON_PRINT_EQ (integer_number (42), true, "42");
797 4 : ASSERT_JSON_PRINT_EQ (integer_number (-100), true, "-100");
798 4 : ASSERT_JSON_PRINT_EQ (integer_number (123456789), true, "123456789");
799 4 : ASSERT_JSON_PRINT_EQ (integer_number (-123456789), true, "-123456789");
800 4 : }
801 :
802 : /* Verify that JSON strings are written correctly. */
803 :
804 : static void
805 4 : test_writing_strings ()
806 : {
807 4 : string foo ("foo");
808 4 : ASSERT_JSON_PRINT_EQ (foo, true, "\"foo\"");
809 :
810 4 : string contains_quotes ("before \"quoted\" after");
811 4 : ASSERT_JSON_PRINT_EQ (contains_quotes, true,
812 : "\"before \\\"quoted\\\" after\"");
813 :
814 4 : const char data[] = {'a', 'b', 'c', 'd', '\0', 'e', 'f'};
815 4 : string not_terminated (data, 3);
816 4 : ASSERT_JSON_PRINT_EQ (not_terminated, true, "\"abc\"");
817 4 : string embedded_null (data, sizeof data);
818 4 : ASSERT_JSON_PRINT_EQ (embedded_null, true, "\"abcd\\0ef\"");
819 4 : }
820 :
821 : /* Verify that JSON literals are written correctly. */
822 :
823 : static void
824 4 : test_writing_literals ()
825 : {
826 4 : ASSERT_JSON_PRINT_EQ (literal (JSON_TRUE), true, "true");
827 4 : ASSERT_JSON_PRINT_EQ (literal (JSON_FALSE), true, "false");
828 4 : ASSERT_JSON_PRINT_EQ (literal (JSON_NULL), true, "null");
829 :
830 4 : ASSERT_JSON_PRINT_EQ (literal (true), true, "true");
831 4 : ASSERT_JSON_PRINT_EQ (literal (false), true, "false");
832 4 : }
833 :
834 : /* Verify that nested values are formatted correctly when written.
835 :
836 : Also, make use of array::append(std::unique_ptr<value>) and
837 : object::set (const char *key, std::unique_ptr<value> v).*/
838 :
839 : static void
840 4 : test_formatting ()
841 : {
842 4 : object obj;
843 4 : object *child = new object;
844 4 : std::unique_ptr<object> grandchild = std::make_unique<object> ();
845 :
846 4 : obj.set_string ("str", "bar");
847 4 : obj.set ("child", child);
848 4 : obj.set_integer ("int", 42);
849 :
850 4 : array *arr = new array;
851 16 : for (int i = 0; i < 3; i++)
852 12 : arr->append (std::make_unique<integer_number> (i));
853 4 : grandchild->set ("arr", arr);
854 4 : grandchild->set_integer ("int", 1066);
855 :
856 4 : child->set ("grandchild", std::move (grandchild));
857 4 : child->set_integer ("int", 1776);
858 :
859 : /* This test relies on json::object writing out key/value pairs
860 : in key-insertion order. */
861 4 : ASSERT_JSON_PRINT_EQ (obj, true,
862 : ("{\"str\": \"bar\",\n"
863 : " \"child\": {\"grandchild\": {\"arr\": [0,\n"
864 : " 1,\n"
865 : " 2],\n"
866 : " \"int\": 1066},\n"
867 : " \"int\": 1776},\n"
868 : " \"int\": 42}"));
869 4 : ASSERT_JSON_PRINT_EQ (obj, false,
870 : ("{\"str\": \"bar\", \"child\": {\"grandchild\":"
871 : " {\"arr\": [0, 1, 2], \"int\": 1066},"
872 : " \"int\": 1776}, \"int\": 42}"));
873 4 : }
874 :
875 : /* Helper function for reporting failure of JSON comparisons. */
876 :
877 : static void
878 0 : fail_comparison (const location &loc,
879 : const char *desc,
880 : const value &val_a, const value &val_b,
881 : const char *desc_expected_value,
882 : int actual_value)
883 : {
884 0 : fprintf (stderr, "val_a: ");
885 0 : val_a.dump ();
886 :
887 0 : fprintf (stderr, "val_b: ");
888 0 : val_b.dump ();
889 :
890 0 : selftest::fail_formatted (loc,
891 : "%s: failed JSON comparison:"
892 : " expected: %s got: %i\n",
893 : desc,
894 : desc_expected_value, actual_value);
895 : }
896 :
897 : /* Implementation of ASSERT_JSON_EQ. */
898 :
899 : static void
900 100 : assert_json_equal (const location &loc,
901 : const char *desc,
902 : const value &val_a, const value &val_b)
903 : {
904 : /* Comparison should return zero, both ways, indicating no differences. */
905 100 : const int a_vs_b = value::compare (val_a, val_b);
906 100 : if (a_vs_b != 0)
907 0 : fail_comparison (loc, desc, val_a, val_b, "zero", a_vs_b);
908 :
909 100 : const int b_vs_a = value::compare (val_b, val_a);
910 100 : if (b_vs_a != 0)
911 0 : fail_comparison (loc, desc, val_b, val_a, "zero", b_vs_a);
912 100 : }
913 :
914 : /* Verify that json::value::compare returns 0 ("no differences") on
915 : VAL1 and VAL2, in both orders. */
916 :
917 : #define ASSERT_JSON_EQ(VAL1, VAL2) \
918 : SELFTEST_BEGIN_STMT \
919 : assert_json_equal ((SELFTEST_LOCATION), \
920 : "ASSERT_JSON_EQ", \
921 : (VAL1), (VAL2)); \
922 : SELFTEST_END_STMT
923 :
924 : /* Implementation of ASSERT_JSON_NE. */
925 :
926 : static void
927 48 : assert_json_non_equal (const location &loc,
928 : const char *desc,
929 : const value &val_a, const value &val_b)
930 : {
931 : /* Comparison should be non-zero, indicating differences. */
932 48 : const int a_vs_b = value::compare (val_a, val_b);
933 48 : if (a_vs_b == 0)
934 0 : fail_comparison (loc, desc, val_a, val_b, "non-zero", a_vs_b);
935 :
936 48 : const int b_vs_a = value::compare (val_b, val_a);
937 48 : ASSERT_NE_AT (loc, b_vs_a, 0);
938 48 : if (b_vs_a == 0)
939 : fail_comparison (loc, desc, val_b, val_a, "non-zero", b_vs_a);
940 :
941 : /* Swapping the args should swap the sign of the result
942 : (but isn't necessarily the negation). */
943 48 : if ( (a_vs_b > 0) == (b_vs_a > 0) )
944 0 : fail_comparison (loc, desc, val_b, val_a, "opposite signs", 1);
945 48 : }
946 :
947 : /* Verify that json::value::compare returns non-zero ("different") on
948 : VAL1 and VAL2, in both orders, and that they have opposite
949 : sign. */
950 :
951 : #define ASSERT_JSON_NE(VAL1, VAL2) \
952 : SELFTEST_BEGIN_STMT \
953 : assert_json_non_equal ((SELFTEST_LOCATION), \
954 : "ASSERT_JSON_NE", \
955 : (VAL1), (VAL2)); \
956 : SELFTEST_END_STMT
957 :
958 : /* Verify that json::value::compare works as expected. */
959 :
960 : static void
961 4 : test_comparisons ()
962 : {
963 : /* Literals. */
964 :
965 4 : literal null_lit (JSON_NULL);
966 4 : ASSERT_JSON_EQ (null_lit, null_lit);
967 :
968 4 : literal other_null_lit (JSON_NULL);
969 4 : ASSERT_JSON_EQ (null_lit, other_null_lit);
970 :
971 4 : literal true_lit (JSON_TRUE);
972 4 : ASSERT_JSON_EQ (true_lit, true_lit);
973 4 : ASSERT_JSON_NE (true_lit, null_lit);
974 :
975 4 : literal false_lit (JSON_FALSE);
976 4 : ASSERT_JSON_EQ (false_lit, false_lit);
977 4 : ASSERT_JSON_NE (false_lit, true_lit);
978 4 : ASSERT_JSON_NE (false_lit, null_lit);
979 :
980 : /* Strings. */
981 4 : string str_foo_1 ("foo");
982 4 : ASSERT_JSON_EQ (str_foo_1, str_foo_1);
983 :
984 4 : string str_foo_2 ("foo");
985 4 : ASSERT_JSON_EQ (str_foo_1, str_foo_2);
986 :
987 4 : string str_bar ("bar");
988 4 : ASSERT_JSON_NE (str_bar, str_foo_1);
989 :
990 : /* Numbers. */
991 4 : integer_number i_42 (42);
992 4 : ASSERT_JSON_EQ (i_42, i_42);
993 4 : integer_number i_42_2 (42);
994 4 : ASSERT_JSON_EQ (i_42, i_42_2);
995 4 : integer_number i_43 (43);
996 4 : ASSERT_JSON_NE (i_42, i_43);
997 :
998 4 : float_number f_zero (0.0);
999 4 : ASSERT_JSON_EQ (f_zero, f_zero);
1000 4 : float_number f_zero_2 (0.0);
1001 4 : ASSERT_JSON_EQ (f_zero, f_zero_2);
1002 4 : float_number f_one (1.0);
1003 4 : ASSERT_JSON_NE (f_zero, f_one);
1004 : /* We don't yet test the more awkward cases e.g. NaN. */
1005 :
1006 : /* Objects. */
1007 :
1008 : // Empty object
1009 : // Self comparison should be 0
1010 4 : object empty_obj_a;
1011 4 : ASSERT_JSON_EQ (empty_obj_a, empty_obj_a);
1012 :
1013 : // Instances of empty objects should compare equal to each other
1014 4 : object empty_obj_b;
1015 4 : ASSERT_JSON_EQ (empty_obj_a, empty_obj_b);
1016 :
1017 : // Object with one field:
1018 4 : object obj_1;
1019 4 : obj_1.set_string ("foo", "bar");
1020 : // Self comparison should be 0
1021 4 : ASSERT_JSON_EQ (obj_1, obj_1);
1022 :
1023 : // but should be different to an empty object:
1024 4 : ASSERT_JSON_NE (obj_1, empty_obj_a);
1025 :
1026 : // Another with one field, with same key/value:
1027 4 : object obj_2;
1028 4 : obj_2.set_string ("foo", "bar");
1029 4 : ASSERT_JSON_EQ (obj_1, obj_2);
1030 :
1031 : // Same key, different value:
1032 4 : object obj_3;
1033 4 : obj_3.set_string ("foo", "baz");
1034 4 : ASSERT_JSON_NE (obj_1, obj_3);
1035 :
1036 : // Adding an extra property:
1037 4 : obj_2.set_integer ("year", 1066);
1038 4 : ASSERT_JSON_NE (obj_1, obj_2);
1039 :
1040 : /* Different insertion order, but same k-v pairs should be equal,
1041 : despite having different serialization. */
1042 4 : object obj_4;
1043 4 : obj_4.set_integer ("year", 1066);
1044 4 : obj_4.set_string ("foo", "bar");
1045 4 : ASSERT_JSON_EQ (obj_2, obj_4);
1046 4 : ASSERT_JSON_PRINT_EQ (obj_2, false, "{\"foo\": \"bar\", \"year\": 1066}");
1047 4 : ASSERT_JSON_PRINT_EQ (obj_4, false, "{\"year\": 1066, \"foo\": \"bar\"}");
1048 :
1049 : /* Arrays. */
1050 :
1051 : // Empty array
1052 4 : array empty_arr_a;
1053 : // Self comparison should be 0
1054 4 : ASSERT_JSON_EQ (empty_arr_a, empty_arr_a);
1055 :
1056 : // Objects and arrays are different
1057 4 : ASSERT_JSON_NE (empty_obj_a, empty_arr_a);
1058 :
1059 : // Instances of empty arrays should compare equal to each other
1060 4 : array empty_arr_b;
1061 4 : ASSERT_JSON_EQ (empty_arr_a, empty_arr_b);
1062 :
1063 : // Array with one element:
1064 4 : array arr_1;
1065 4 : arr_1.append (std::make_unique<string> ("foo"));
1066 : // Self comparison should be 0
1067 4 : ASSERT_JSON_EQ (arr_1, arr_1);
1068 :
1069 : // but should be different to an empty array:
1070 4 : ASSERT_JSON_NE (arr_1, empty_arr_a);
1071 :
1072 : // Another with one element:
1073 4 : array arr_2;
1074 4 : arr_2.append (std::make_unique<string> ("foo"));
1075 4 : ASSERT_JSON_EQ (arr_1, arr_2);
1076 :
1077 : // Adding an extra element:
1078 4 : arr_2.append (std::make_unique<string> ("bar"));
1079 4 : ASSERT_JSON_NE (arr_1, arr_2);
1080 4 : }
1081 :
1082 : /* Ensure that json::string's get_string is usable as a C-style string. */
1083 :
1084 : static void
1085 4 : test_strcmp ()
1086 : {
1087 4 : string str ("foobar", 3);
1088 4 : ASSERT_EQ (strcmp (str.get_string (), "foo"), 0);
1089 4 : }
1090 :
1091 : static void
1092 4 : test_cloning ()
1093 : {
1094 : // Objects
1095 4 : {
1096 4 : object obj;
1097 4 : obj.set_string ("foo", "bar");
1098 :
1099 4 : auto obj_clone = obj.clone ();
1100 4 : ASSERT_JSON_EQ (obj, *obj_clone);
1101 4 : }
1102 :
1103 : // Arrays
1104 4 : {
1105 4 : array arr;
1106 4 : arr.append (std::make_unique<string> ("foo"));
1107 :
1108 4 : auto arr_clone = arr.clone ();
1109 4 : ASSERT_JSON_EQ (arr, *arr_clone);
1110 4 : }
1111 :
1112 : // float_number
1113 4 : {
1114 4 : float_number f_one (1.0);
1115 4 : auto f_clone = f_one.clone ();
1116 4 : ASSERT_JSON_EQ (f_one, *f_clone);
1117 4 : }
1118 :
1119 : // integer_number
1120 4 : {
1121 4 : integer_number num (42);
1122 4 : auto num_clone = num.clone ();
1123 4 : ASSERT_JSON_EQ (num, *num_clone);
1124 4 : }
1125 :
1126 : // string
1127 4 : {
1128 4 : string str ("foo");
1129 4 : auto str_clone = str.clone ();
1130 4 : ASSERT_JSON_EQ (str, *str_clone);
1131 4 : }
1132 :
1133 : // literal
1134 4 : {
1135 4 : literal lit (JSON_TRUE);
1136 4 : auto lit_clone = lit.clone ();
1137 4 : ASSERT_JSON_EQ (lit, *lit_clone);
1138 4 : }
1139 4 : }
1140 :
1141 : /* Run all of the selftests within this file. */
1142 :
1143 : void
1144 4 : json_cc_tests ()
1145 : {
1146 4 : test_object_get ();
1147 4 : test_writing_objects ();
1148 4 : test_writing_arrays ();
1149 4 : test_writing_float_numbers ();
1150 4 : test_writing_integer_numbers ();
1151 4 : test_writing_strings ();
1152 4 : test_writing_literals ();
1153 4 : test_formatting ();
1154 4 : test_comparisons ();
1155 4 : test_strcmp ();
1156 4 : test_cloning ();
1157 4 : }
1158 :
1159 : } // namespace selftest
1160 :
1161 : #endif /* #if CHECKING_P */
|