-
Notifications
You must be signed in to change notification settings - Fork 34
Expand file tree
/
Copy pathgoldfish.hpp
More file actions
5568 lines (4908 loc) · 180 KB
/
goldfish.hpp
File metadata and controls
5568 lines (4908 loc) · 180 KB
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
//
// Copyright (C) 2024 The Goldfish Scheme Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations
// under the License.
//
#include <algorithm>
#include <argh.h>
#include <chrono>
#include <cctype>
#include <cmath>
#include <cstdint>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <fstream>
#include <iostream>
#include <limits>
#include <memory>
#include <mutex>
#include <sstream>
#include <stdexcept>
#include "s7.h"
#include <string>
#include <unordered_map>
#include <vector>
#include <thread>
#include <tbox/platform/file.h>
#include <tbox/platform/path.h>
#include <tbox/tbox.h>
#ifdef TB_CONFIG_OS_WINDOWS
#include <io.h>
#include <windows.h>
#elif TB_CONFIG_OS_MACOSX
#include <limits.h>
#include <mach-o/dyld.h>
#elif defined(__EMSCRIPTEN__)
#include <limits.h>
#else
#include <linux/limits.h>
#endif
#if !defined(TB_CONFIG_OS_WINDOWS)
#include <errno.h>
#include <pwd.h>
#include <unistd.h>
#if !defined(__EMSCRIPTEN__)
#include <wordexp.h>
#endif
#endif
#include <cpr/cpr.h>
#include <nlohmann/json.hpp>
#include <nlohmann/json-schema.hpp>
#ifdef GOLDFISH_WITH_REPL
#include <functional>
#include <isocline.h>
#endif
#define GOLDFISH_VERSION "17.11.38"
#define GOLDFISH_PATH_MAXN TB_PATH_MAXN
static std::vector<std::string> command_args= std::vector<std::string> ();
// Declare environ for non-Windows platforms (needed for f_getenvs)
#if !defined(TB_CONFIG_OS_WINDOWS)
extern char **environ;
#endif
namespace goldfish {
using std::cerr;
using std::cout;
using std::endl;
using std::string;
using std::vector;
namespace fs = std::filesystem;
using nlohmann::json;
inline void
glue_define (s7_scheme* sc, const char* name, const char* desc, s7_function f, s7_int required, s7_int optional);
static s7_pointer
f_function_libraries (s7_scheme* sc, s7_pointer args);
static bool
split_library_query (const string& query, string& group, string& library);
static vector<string>
find_function_libraries_in_load_path (s7_scheme* sc, const string& function_name);
static const char* NJSON_HANDLE_TAG = "njson-handle";
struct NjsonState {
std::thread::id owner_thread_id;
std::vector<std::unique_ptr<json>> handle_store;
std::vector<s7_int> handle_generations;
std::vector<s7_int> handle_free_ids;
std::vector<std::vector<std::string>> keys_cache_values;
std::vector<bool> keys_cache_valid;
NjsonState ()
: owner_thread_id (std::this_thread::get_id ()),
handle_store (1),
handle_generations (1, 0),
keys_cache_values (1),
keys_cache_valid (1, false) {}
};
static std::mutex njson_state_registry_mutex;
static std::unordered_map<s7_scheme*, std::unique_ptr<NjsonState>> njson_state_registry;
static NjsonState&
njson_get_or_create_state (s7_scheme* sc) {
std::lock_guard<std::mutex> lock (njson_state_registry_mutex);
auto it = njson_state_registry.find (sc);
if (it == njson_state_registry.end ()) {
auto inserted = njson_state_registry.emplace (sc, std::make_unique<NjsonState> ());
return *(inserted.first->second);
}
return *(it->second);
}
static void
njson_register_state (s7_scheme* sc) {
(void) njson_get_or_create_state (sc);
}
static bool
scheme_json_key_to_string (s7_scheme* sc, s7_pointer key, std::string& out, std::string& error_msg) {
(void) sc;
if (s7_is_string (key)) {
out = s7_string (key);
return true;
}
error_msg = "json object key must be string?";
return false;
}
static s7_pointer
njson_error (s7_scheme* sc, const char* type_name, const std::string& msg, s7_pointer culprit) {
return s7_error (sc, s7_make_symbol (sc, type_name),
s7_list (sc, 2, s7_make_string (sc, msg.c_str ()), culprit));
}
static s7_pointer
njson_require_owner_thread (s7_scheme* sc, const char* api_name, s7_pointer culprit) {
NjsonState& state = njson_get_or_create_state (sc);
if (state.owner_thread_id == std::this_thread::get_id ()) {
return nullptr;
}
return njson_error (sc, "thread-error",
std::string (api_name) + ": must be called from the thread that created this VM", culprit);
}
static s7_pointer
make_njson_handle (s7_scheme* sc, s7_int id) {
NjsonState& state = njson_get_or_create_state (sc);
s7_int generation = 0;
if (id > 0) {
size_t index = static_cast<size_t> (id);
if (index < state.handle_generations.size ()) {
generation = state.handle_generations[index];
}
}
return s7_cons (
sc, s7_make_symbol (sc, NJSON_HANDLE_TAG), s7_cons (sc, s7_make_integer (sc, id), s7_make_integer (sc, generation)));
}
static bool
is_njson_handle (s7_pointer x, s7_int* id_out = nullptr, s7_int* generation_out = nullptr) {
if (!s7_is_pair (x)) return false;
s7_pointer tag = s7_car (x);
s7_pointer payload = s7_cdr (x);
if (!s7_is_symbol (tag)) return false;
if (strcmp (s7_symbol_name (tag), NJSON_HANDLE_TAG) != 0) return false;
if (!s7_is_pair (payload)) return false;
s7_pointer id = s7_car (payload);
s7_pointer generation = s7_cdr (payload);
if (!s7_is_integer (id) || !s7_is_integer (generation)) return false;
if (id_out) *id_out = s7_integer (id);
if (generation_out) *generation_out = s7_integer (generation);
return true;
}
static bool
extract_njson_handle_id (s7_scheme* sc, s7_pointer handle, s7_int& id, std::string& error_msg) {
NjsonState& state = njson_get_or_create_state (sc);
s7_int generation = 0;
if (!is_njson_handle (handle, &id, &generation)) {
error_msg = "expected njson handle";
return false;
}
if (id <= 0) {
error_msg = "invalid njson handle id";
return false;
}
if (generation <= 0) {
error_msg = "invalid njson handle generation";
return false;
}
size_t index = static_cast<size_t> (id);
if (index >= state.handle_generations.size ()) {
error_msg = "njson handle does not exist (may have been freed)";
return false;
}
if (state.handle_generations[index] != generation) {
error_msg = "njson handle generation mismatch (stale handle)";
return false;
}
if (static_cast<size_t> (id) >= state.handle_store.size () || !state.handle_store[static_cast<size_t> (id)]) {
error_msg = "njson handle does not exist (may have been freed)";
return false;
}
return true;
}
static json*
njson_value_by_id (s7_scheme* sc, s7_int id) {
NjsonState& state = njson_get_or_create_state (sc);
if (id <= 0) return nullptr;
size_t index = static_cast<size_t> (id);
if (index >= state.handle_store.size ()) return nullptr;
return state.handle_store[index].get ();
}
static const json*
njson_value_by_id_const (s7_scheme* sc, s7_int id) {
NjsonState& state = njson_get_or_create_state (sc);
if (id <= 0) return nullptr;
size_t index = static_cast<size_t> (id);
if (index >= state.handle_store.size ()) return nullptr;
return state.handle_store[index].get ();
}
static void
njson_ensure_keys_cache_size (s7_scheme* sc, size_t n) {
NjsonState& state = njson_get_or_create_state (sc);
if (state.keys_cache_values.size () < n) {
state.keys_cache_values.resize (n);
state.keys_cache_valid.resize (n, false);
}
}
static void
njson_ensure_generations_size (s7_scheme* sc, size_t n) {
NjsonState& state = njson_get_or_create_state (sc);
if (state.handle_generations.size () < n) {
state.handle_generations.resize (n, 0);
}
}
static void
njson_clear_keys_cache_slot (s7_scheme* sc, s7_int id) {
NjsonState& state = njson_get_or_create_state (sc);
if (id <= 0) return;
size_t index = static_cast<size_t> (id);
if (index >= state.keys_cache_valid.size ()) return;
state.keys_cache_values[index].clear ();
state.keys_cache_valid[index] = false;
}
static void
njson_collect_keys (const json& root, std::vector<std::string>& out) {
out.clear ();
if (!root.is_object ()) {
return;
}
out.reserve (root.size ());
for (auto it = root.begin (); it != root.end (); ++it) {
out.push_back (it.key ());
}
}
static s7_pointer
njson_build_keys_list (s7_scheme* sc, const std::vector<std::string>& keys) {
s7_pointer out = s7_nil (sc);
for (auto it = keys.rbegin (); it != keys.rend (); ++it) {
const std::string& key = *it;
out = s7_cons (sc, s7_make_string_with_length (sc, key.data (), static_cast<s7_int> (key.size ())), out);
}
return out;
}
static void
njson_store_keys_cache (s7_scheme* sc, s7_int id, std::vector<std::string>&& keys) {
NjsonState& state = njson_get_or_create_state (sc);
if (id <= 0) return;
size_t index = static_cast<size_t> (id);
njson_ensure_keys_cache_size (sc, index + 1);
njson_clear_keys_cache_slot (sc, id);
state.keys_cache_values[index] = std::move (keys);
state.keys_cache_valid[index] = true;
}
static bool
njson_try_get_keys_cache (s7_scheme* sc, s7_int id, const std::vector<std::string>*& out) {
NjsonState& state = njson_get_or_create_state (sc);
if (id <= 0) return false;
size_t index = static_cast<size_t> (id);
if (index >= state.keys_cache_valid.size ()) return false;
if (!state.keys_cache_valid[index]) return false;
out = &state.keys_cache_values[index];
return true;
}
static void
njson_invalidate_keys_cache_if_present (s7_scheme* sc, s7_int id) {
NjsonState& state = njson_get_or_create_state (sc);
if (id <= 0) return;
size_t index = static_cast<size_t> (id);
if (index >= state.keys_cache_valid.size () || !state.keys_cache_valid[index]) return;
njson_clear_keys_cache_slot (sc, id);
}
static s7_int
store_njson_value (s7_scheme* sc, json&& value) {
NjsonState& state = njson_get_or_create_state (sc);
if (!state.handle_free_ids.empty ()) {
s7_int id = state.handle_free_ids.back ();
state.handle_free_ids.pop_back ();
size_t index = static_cast<size_t> (id);
njson_ensure_generations_size (sc, index + 1);
s7_int generation = state.handle_generations[index];
if (generation <= 0 || generation == (std::numeric_limits<s7_int>::max) ()) {
generation = 1;
}
else {
generation += 1;
}
state.handle_generations[index] = generation;
state.handle_store[index] = std::make_unique<json> (std::move (value));
njson_ensure_keys_cache_size (sc, state.handle_store.size ());
return id;
}
state.handle_store.push_back (std::make_unique<json> (std::move (value)));
state.handle_generations.push_back (1);
njson_ensure_keys_cache_size (sc, state.handle_store.size ());
s7_int id = static_cast<s7_int> (state.handle_store.size () - 1);
return id;
}
static s7_int
store_njson_value (s7_scheme* sc, const json& value) {
json copied = value;
return store_njson_value (sc, std::move (copied));
}
static bool
scheme_json_index (s7_pointer key, size_t& out, std::string& error_msg) {
if (!s7_is_integer (key)) {
error_msg = "array index must be integer?";
return false;
}
s7_int idx = s7_integer (key);
if (idx < 0) {
error_msg = "array index must be non-negative";
return false;
}
out = static_cast<size_t> (idx);
return true;
}
static bool
collect_path_keys (s7_scheme* sc, s7_pointer list, std::vector<s7_pointer>& out, std::string& error_msg) {
s7_pointer iter = list;
while (s7_is_pair (iter)) {
out.push_back (s7_car (iter));
iter = s7_cdr (iter);
}
if (!s7_is_null (sc, iter)) {
error_msg = "path keys must be a proper list";
return false;
}
return true;
}
template <typename JsonPtr>
static bool
njson_lookup_core (s7_scheme* sc, JsonPtr root, const std::vector<s7_pointer>& path, size_t steps,
JsonPtr& out, std::string& error_msg) {
JsonPtr cur = root;
for (size_t i = 0; i < steps; i++) {
s7_pointer key = path[i];
if (cur->is_object ()) {
std::string name;
if (!scheme_json_key_to_string (sc, key, name, error_msg)) {
return false;
}
auto it = cur->find (name);
if (it == cur->end ()) {
error_msg = "path not found: missing object key '" + name + "'";
return false;
}
cur = &(*it);
}
else if (cur->is_array ()) {
size_t idx = 0;
if (!scheme_json_index (key, idx, error_msg)) {
return false;
}
if (idx >= cur->size ()) {
error_msg = "path not found: array index out of range (index=" + std::to_string (idx)
+ ", size=" + std::to_string (cur->size ()) + ")";
return false;
}
cur = &(*cur)[idx];
}
else {
char* key_repr_c = s7_object_to_c_string (sc, key);
if (key_repr_c) {
std::string key_repr (key_repr_c);
free (key_repr_c);
if (key_repr.size () >= 2 && key_repr.front () == '"' && key_repr.back () == '"') {
key_repr = key_repr.substr (1, key_repr.size () - 2);
}
error_msg = "path not found: missing object key '" + key_repr + "'";
}
else {
error_msg = "path not found: missing object key '<unknown>'";
}
return false;
}
}
out = cur;
return true;
}
static bool
lookup_path_const (s7_scheme* sc, const json& root, const std::vector<s7_pointer>& path, const json*& out,
std::string& error_msg) {
return njson_lookup_core (sc, &root, path, path.size (), out, error_msg);
}
static bool
lookup_path_parent_mutable (s7_scheme* sc, json& root, const std::vector<s7_pointer>& path, json*& parent,
s7_pointer& last_key, std::string& error_msg) {
if (path.empty ()) {
error_msg = "path cannot be empty";
return false;
}
if (!njson_lookup_core (sc, &root, path, path.size () - 1, parent, error_msg)) {
return false;
}
last_key = path.back ();
return true;
}
static bool
lookup_path_mutable (s7_scheme* sc, json& root, const std::vector<s7_pointer>& path, json*& out, std::string& error_msg) {
return njson_lookup_core (sc, &root, path, path.size (), out, error_msg);
}
static bool
scheme_to_njson_scalar_or_handle (s7_scheme* sc, s7_pointer value, json& out, std::string& error_msg) {
if (is_njson_handle (value)) {
s7_int id = 0;
if (!extract_njson_handle_id (sc, value, id, error_msg)) {
return false;
}
const json* source = njson_value_by_id_const (sc, id);
if (!source) {
error_msg = "njson handle does not exist (may have been freed)";
return false;
}
out = *source;
return true;
}
if (s7_is_string (value)) {
out = s7_string (value);
return true;
}
if (s7_is_boolean (value)) {
out = s7_boolean (sc, value);
return true;
}
if (s7_is_integer (value)) {
out = static_cast<long long> (s7_integer (value));
return true;
}
if (s7_is_real (value)) {
double real_value = s7_number_to_real (sc, value);
if (!std::isfinite (real_value)) {
error_msg = "number must be finite (NaN/Inf are not valid JSON numbers)";
return false;
}
out = real_value;
return true;
}
if (s7_is_number (value)) {
error_msg = "number must be real and finite";
return false;
}
if (s7_is_symbol (value)) {
const char* symbol_name = s7_symbol_name (value);
if (strcmp (symbol_name, "null") == 0) {
out = nullptr;
return true;
}
error_msg = "symbol value must be null; use boolean? for true/false and string? for text";
return false;
}
error_msg = "value must be njson handle, string?, number?, boolean?, or null symbol";
return false;
}
static s7_pointer
njson_scalar_value_to_scheme (s7_scheme* sc, const json& value) {
if (value.is_null ()) {
return s7_make_symbol (sc, "null");
}
if (value.is_boolean ()) {
return s7_make_boolean (sc, value.get<bool> ());
}
if (value.is_number_integer ()) {
return s7_make_integer (sc, static_cast<s7_int> (value.get<long long> ()));
}
if (value.is_number_unsigned ()) {
unsigned long long v = value.get<unsigned long long> ();
if (v > static_cast<unsigned long long> ((std::numeric_limits<s7_int>::max) ())) {
return s7_make_real (sc, static_cast<double> (v));
}
return s7_make_integer (sc, static_cast<s7_int> (v));
}
if (value.is_number_float ()) {
return s7_make_real (sc, value.get<double> ());
}
if (value.is_string ()) {
const auto& text = value.get_ref<const std::string&> ();
return s7_make_string (sc, text.c_str ());
}
return s7_nil (sc);
}
enum class njson_scheme_tree_mode {
alist_list,
hash_vector
};
static s7_pointer njson_value_to_scheme_tree (s7_scheme* sc, const json& value, njson_scheme_tree_mode mode);
static s7_pointer
njson_object_to_alist_tree (s7_scheme* sc, const json& value, njson_scheme_tree_mode mode) {
// Match (liii json): empty object is '(()) so {} stays distinct from [].
if (value.empty ()) {
return s7_cons (sc, s7_nil (sc), s7_nil (sc));
}
s7_pointer out = s7_nil (sc);
for (auto it = value.begin (); it != value.end (); ++it) {
const std::string& key = it.key ();
s7_pointer key_s7 = s7_make_string_with_length (sc, key.data (), static_cast<s7_int> (key.size ()));
s7_pointer val_s7 = njson_value_to_scheme_tree (sc, it.value (), mode);
out = s7_cons (sc, s7_cons (sc, key_s7, val_s7), out);
}
return s7_reverse (sc, out);
}
static s7_pointer
njson_array_to_list_tree (s7_scheme* sc, const json& value, njson_scheme_tree_mode mode) {
s7_pointer out = s7_nil (sc);
for (auto it = value.begin (); it != value.end (); ++it) {
out = s7_cons (sc, njson_value_to_scheme_tree (sc, *it, mode), out);
}
return s7_reverse (sc, out);
}
static s7_pointer
njson_object_to_hash_table_tree (s7_scheme* sc, const json& value, njson_scheme_tree_mode mode) {
s7_pointer out = s7_make_hash_table (sc, static_cast<s7_int> (value.size ()));
for (auto it = value.begin (); it != value.end (); ++it) {
const std::string& key = it.key ();
s7_hash_table_set (sc, out, s7_make_string_with_length (sc, key.data (), static_cast<s7_int> (key.size ())),
njson_value_to_scheme_tree (sc, it.value (), mode));
}
return out;
}
static s7_pointer
njson_array_to_vector_tree (s7_scheme* sc, const json& value, njson_scheme_tree_mode mode) {
s7_pointer out = s7_make_vector (sc, static_cast<s7_int> (value.size ()));
for (size_t i = 0; i < value.size (); i++) {
s7_vector_set (sc, out, static_cast<s7_int> (i), njson_value_to_scheme_tree (sc, value[i], mode));
}
return out;
}
static s7_pointer
njson_value_to_scheme_tree (s7_scheme* sc, const json& value, njson_scheme_tree_mode mode) {
if (value.is_object ()) {
return (mode == njson_scheme_tree_mode::alist_list) ? njson_object_to_alist_tree (sc, value, mode)
: njson_object_to_hash_table_tree (sc, value, mode);
}
if (value.is_array ()) {
return (mode == njson_scheme_tree_mode::alist_list) ? njson_array_to_list_tree (sc, value, mode)
: njson_array_to_vector_tree (sc, value, mode);
}
return njson_scalar_value_to_scheme (sc, value);
}
enum class njson_structure_root_kind {
object,
array
};
static s7_pointer
njson_run_structure_conversion (s7_scheme* sc, s7_pointer args, const char* api_name, njson_structure_root_kind root_kind,
njson_scheme_tree_mode mode) {
s7_pointer thread_err = njson_require_owner_thread (sc, api_name, s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer handle = s7_car (args);
s7_int id = 0;
std::string error_msg;
if (!extract_njson_handle_id (sc, handle, id, error_msg)) {
return njson_error (sc, "type-error", std::string (api_name) + ": " + error_msg, handle);
}
const json* root = njson_value_by_id_const (sc, id);
if (!root) {
return njson_error (sc, "type-error",
std::string (api_name) + ": njson handle does not exist (may have been freed)", handle);
}
if ((root_kind == njson_structure_root_kind::object) && !root->is_object ()) {
return njson_error (sc, "type-error", std::string (api_name) + ": json root must be object", handle);
}
if ((root_kind == njson_structure_root_kind::array) && !root->is_array ()) {
return njson_error (sc, "type-error", std::string (api_name) + ": json root must be array", handle);
}
return njson_value_to_scheme_tree (sc, *root, mode);
}
static s7_pointer
njson_value_to_scheme_or_handle (s7_scheme* sc, const json& value) {
if (value.is_object () || value.is_array ()) {
s7_int id = store_njson_value (sc, value);
return make_njson_handle (sc, id);
}
return njson_scalar_value_to_scheme (sc, value);
}
static s7_pointer
f_njson_string_to_json (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-string->json", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer input = s7_car (args);
if (!s7_is_string (input)) {
return njson_error (sc, "type-error", "g_njson-string->json: input must be string", input);
}
try {
json parsed = json::parse (s7_string (input));
return make_njson_handle (sc, store_njson_value (sc, std::move (parsed)));
}
catch (const json::parse_error& err) {
return njson_error (sc, "parse-error", err.what (), input);
}
}
static s7_pointer
f_njson_json_to_string (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-json->string", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer input = s7_car (args);
json encoded;
std::string error_msg;
if (!scheme_to_njson_scalar_or_handle (sc, input, encoded, error_msg)) {
return njson_error (sc, "type-error", "g_njson-json->string: " + error_msg, input);
}
std::string dumped = encoded.dump ();
return s7_make_string (sc, dumped.c_str ());
}
static s7_pointer
f_njson_format_string (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-format-string", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer input = s7_car (args);
if (!s7_is_string (input)) {
return njson_error (sc, "type-error", "g_njson-format-string: input must be string", input);
}
s7_int indent = 2;
s7_pointer rest = s7_cdr (args);
if (!s7_is_null (sc, rest)) {
s7_pointer indent_arg = s7_car (rest);
if (!s7_is_integer (indent_arg)) {
return njson_error (sc, "type-error", "g_njson-format-string: indent must be integer?", indent_arg);
}
indent = s7_integer (indent_arg);
if (indent < 0) {
return njson_error (sc, "value-error", "g_njson-format-string: indent must be >= 0", indent_arg);
}
}
try {
json parsed = json::parse (s7_string (input));
std::string dumped = parsed.dump (static_cast<int> (indent));
return s7_make_string (sc, dumped.c_str ());
}
catch (const json::parse_error& err) {
return njson_error (sc, "parse-error", err.what (), input);
}
}
static s7_pointer
f_njson_handle_p (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-handle?", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer input = s7_car (args);
return s7_make_boolean (sc, is_njson_handle (input));
}
template <typename HandlePredicate, typename ScalarPredicate>
static s7_pointer
njson_run_value_type_predicate (s7_scheme* sc, s7_pointer args, const char* api_name, HandlePredicate handle_pred,
ScalarPredicate scalar_pred) {
s7_pointer thread_err = njson_require_owner_thread (sc, api_name, s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer input = s7_car (args);
if (!is_njson_handle (input)) {
return s7_make_boolean (sc, scalar_pred (input));
}
s7_int id = 0;
std::string error_msg;
if (!extract_njson_handle_id (sc, input, id, error_msg)) {
return njson_error (sc, "type-error", std::string (api_name) + ": " + error_msg, input);
}
const json* value = njson_value_by_id_const (sc, id);
if (!value) {
return njson_error (sc, "type-error",
std::string (api_name) + ": njson handle does not exist (may have been freed)", input);
}
return s7_make_boolean (sc, handle_pred (*value));
}
static s7_pointer
f_njson_null_p (s7_scheme* sc, s7_pointer args) {
return njson_run_value_type_predicate (
sc, args, "g_njson-null?", [] (const json& value) { return value.is_null (); }, [] (s7_pointer value) {
return s7_is_symbol (value) && strcmp (s7_symbol_name (value), "null") == 0;
});
}
static s7_pointer
f_njson_object_p (s7_scheme* sc, s7_pointer args) {
return njson_run_value_type_predicate (sc, args, "g_njson-object?", [] (const json& value) { return value.is_object (); },
[] (s7_pointer value) {
(void) value;
return false;
});
}
static s7_pointer
f_njson_array_p (s7_scheme* sc, s7_pointer args) {
return njson_run_value_type_predicate (sc, args, "g_njson-array?", [] (const json& value) { return value.is_array (); },
[] (s7_pointer value) {
(void) value;
return false;
});
}
static s7_pointer
f_njson_string_p (s7_scheme* sc, s7_pointer args) {
return njson_run_value_type_predicate (
sc, args, "g_njson-string?", [] (const json& value) { return value.is_string (); },
[] (s7_pointer value) { return s7_is_string (value); });
}
static s7_pointer
f_njson_number_p (s7_scheme* sc, s7_pointer args) {
return njson_run_value_type_predicate (
sc, args, "g_njson-number?", [] (const json& value) { return value.is_number (); },
[] (s7_pointer value) { return s7_is_number (value); });
}
static s7_pointer
f_njson_integer_p (s7_scheme* sc, s7_pointer args) {
return njson_run_value_type_predicate (
sc, args, "g_njson-integer?",
[] (const json& value) { return value.is_number_integer () || value.is_number_unsigned (); },
[] (s7_pointer value) { return s7_is_integer (value); });
}
static s7_pointer
f_njson_boolean_p (s7_scheme* sc, s7_pointer args) {
return njson_run_value_type_predicate (
sc, args, "g_njson-boolean?", [] (const json& value) { return value.is_boolean (); },
[] (s7_pointer value) { return s7_is_boolean (value); });
}
static s7_pointer
f_njson_free (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-free", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer handle = s7_car (args);
s7_int id = 0;
std::string error_msg;
if (!extract_njson_handle_id (sc, handle, id, error_msg)) {
return njson_error (sc, "type-error", "g_njson-free: " + error_msg, handle);
}
NjsonState& state = njson_get_or_create_state (sc);
njson_clear_keys_cache_slot (sc, id);
state.handle_store[static_cast<size_t> (id)].reset ();
state.handle_free_ids.push_back (id);
return s7_t (sc);
}
static s7_pointer
f_njson_size (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-size", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer handle = s7_car (args);
s7_int id = 0;
std::string error_msg;
if (!extract_njson_handle_id (sc, handle, id, error_msg)) {
return njson_error (sc, "type-error", "g_njson-size: " + error_msg, handle);
}
const json* root = njson_value_by_id_const (sc, id);
if (!root) {
return njson_error (sc, "type-error", "g_njson-size: njson handle does not exist (may have been freed)", handle);
}
if (root->is_object () || root->is_array ()) {
return s7_make_integer (sc, static_cast<s7_int> (root->size ()));
}
return s7_make_integer (sc, 0);
}
static s7_pointer
f_njson_empty_p (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-empty?", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer handle = s7_car (args);
s7_int id = 0;
std::string error_msg;
if (!extract_njson_handle_id (sc, handle, id, error_msg)) {
return njson_error (sc, "type-error", "g_njson-empty?: " + error_msg, handle);
}
const json* root = njson_value_by_id_const (sc, id);
if (!root) {
return njson_error (sc, "type-error",
"g_njson-empty?: njson handle does not exist (may have been freed)", handle);
}
if (root->is_object () || root->is_array ()) {
return s7_make_boolean (sc, root->empty ());
}
return s7_t (sc);
}
static s7_pointer
f_njson_ref (s7_scheme* sc, s7_pointer args) {
s7_pointer thread_err = njson_require_owner_thread (sc, "g_njson-ref", s7_car (args));
if (thread_err) {
return thread_err;
}
s7_pointer handle = s7_car (args);
s7_int id = 0;
std::string error_msg;
if (!extract_njson_handle_id (sc, handle, id, error_msg)) {
return njson_error (sc, "type-error", "g_njson-ref: " + error_msg, handle);
}
std::vector<s7_pointer> path;
if (!collect_path_keys (sc, s7_cdr (args), path, error_msg)) {
return njson_error (sc, "key-error", "g_njson-ref: " + error_msg, handle);
}
if (path.empty ()) {
return njson_error (sc, "key-error", "g_njson-ref: missing key arguments", handle);
}
const json* root = njson_value_by_id_const (sc, id);
if (!root) {
return njson_error (sc, "type-error", "g_njson-ref: njson handle does not exist (may have been freed)", handle);
}
const json* found_value = nullptr;
if (!lookup_path_const (sc, *root, path, found_value, error_msg)) {
return njson_error (sc, "key-error", "g_njson-ref: " + error_msg, handle);
}
return njson_value_to_scheme_or_handle (sc, *found_value);
}
enum class njson_update_op {
set,
append,
drop
};
static bool
njson_update_needs_value (njson_update_op op) {
return op != njson_update_op::drop;
}
static const char*
njson_update_expected_argv (njson_update_op op) {
if (op == njson_update_op::drop) {
return "expected (json key ...)";
}
if (op == njson_update_op::append) {
return "expected (json [key ...] value)";
}
return "expected (json key ... value)";
}
static s7_pointer
njson_parse_update_request (s7_scheme* sc, s7_pointer args, const char* api_name, njson_update_op op,
s7_pointer& handle, s7_int& id, std::vector<s7_pointer>& path, json& value_json) {
handle = s7_car (args);
std::string error_msg;
if (!extract_njson_handle_id (sc, handle, id, error_msg)) {
return njson_error (sc, "type-error", std::string (api_name) + ": " + error_msg, handle);
}
std::vector<s7_pointer> tokens;
if (!collect_path_keys (sc, s7_cdr (args), tokens, error_msg)) {
return njson_error (sc, "key-error", std::string (api_name) + ": " + error_msg, handle);
}
if (njson_update_needs_value (op)) {
size_t min_tokens = (op == njson_update_op::append) ? 1 : 2;
if (tokens.size () < min_tokens) {
return njson_error (sc, "key-error", std::string (api_name) + ": " + njson_update_expected_argv (op), handle);
}
path.assign (tokens.begin (), tokens.end () - 1);
s7_pointer value_token = tokens.back ();
if (!scheme_to_njson_scalar_or_handle (sc, value_token, value_json, error_msg)) {
return njson_error (sc, "type-error", std::string (api_name) + ": " + error_msg, value_token);
}
}
else {
if (tokens.empty ()) {
return njson_error (sc, "key-error", std::string (api_name) + ": " + njson_update_expected_argv (op), handle);
}
path = std::move (tokens);
}
return nullptr;
}
static s7_pointer
njson_apply_update_on_root (s7_scheme* sc, json& root, const std::vector<s7_pointer>& path, const json& value_json,
njson_update_op op, const char* api_name, s7_pointer handle) {
if (op == njson_update_op::append) {
std::string error_msg;
json* target = &root;
if (!path.empty ()) {
if (!lookup_path_mutable (sc, root, path, target, error_msg)) {
return njson_error (sc, "key-error", std::string (api_name) + ": " + error_msg, handle);
}
}
if (!target->is_array ()) {
return njson_error (sc, "key-error", std::string (api_name) + ": append target must be array", handle);
}
target->push_back (value_json);
return nullptr;
}
std::string error_msg;
json* parent = nullptr;