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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
//
// Copyright 2024 Formata, Inc. All rights reserved.
//
// 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.
//
use std::{cmp::Ordering, collections::{BTreeMap, HashMap, HashSet}, ops::Deref, sync::Arc};
use crate::{lang::SError, IntoNodeRef, Library, SData, SDoc, SField, SFunc, SMutex, SNodeRef, SNum, SPrototype, SVal};
#[derive(Default, Debug)]
pub struct ObjectLibrary;
impl ObjectLibrary {
/// Call object operation.
pub fn operate(&self, pid: &str, doc: &mut SDoc, name: &str, obj: &SNodeRef, parameters: &mut Vec<SVal>) -> Result<SVal, SError> {
match name {
"len" => {
if let Some(node) = obj.node(&doc.graph) {
let refs = node.data_refs::<SField>(&doc.graph);
return Ok(SVal::Number(SNum::I64(refs.len() as i64)));
}
Ok(SVal::Number(SNum::I64(0)))
},
"at" => {
if parameters.len() == 1 {
match ¶meters[0] {
SVal::String(index) => {
if let Some(field) = SField::field(&doc.graph, &index, '.', Some(obj)) {
return Ok(field.value.clone());
} else if let Some(func) = SFunc::func_ref(&doc.graph, &index, '.', Some(obj)) {
return Ok(SVal::FnPtr(func));
}
return Ok(SVal::Null); // Not found
},
SVal::Number(val) => {
let mut fields = SField::fields(&doc.graph, obj);
let index = val.int() as usize;
if index < fields.len() {
let field = fields.remove(index);
let value = field.value.clone();
let key = SVal::String(field.name.clone());
return Ok(SVal::Tuple(vec![key, value]));
}
},
_ => {}
}
}
if parameters.len() > 1 {
let mut array = Vec::new();
for param in parameters.drain(..) {
match param {
SVal::String(index) => {
if let Some(field) = SField::field(&doc.graph, &index, '.', Some(obj)) {
array.push(field.value.clone());
} else if let Some(func) = SFunc::func_ref(&doc.graph, &index, '.', Some(obj)) {
array.push(SVal::FnPtr(func));
}
},
SVal::Number(val) => {
let mut fields = SField::fields(&doc.graph, obj);
let index = val.int() as usize;
if index < fields.len() {
let field = fields.remove(index);
let value = field.value.clone();
let key = SVal::String(field.name.clone());
array.push(SVal::Tuple(vec![key, value]));
}
},
_ => {}
}
}
return Ok(SVal::Array(array));
}
Err(SError::obj(pid, &doc, "at", "invalid arguments - index must be a string or number"))
},
"reference" => {
if parameters.len() == 1 {
let field_path = parameters[0].to_string();
if let Some(field_ref) = SField::field_ref(&doc.graph, &field_path, '.', Some(obj)) {
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
self.operate(pid, doc, "removeField", obj, &mut vec![SVal::String(field.name.clone())])?;
}
SData::attach_existing(&mut doc.graph, obj, field_ref);
return Ok(SVal::Bool(true));
} else if let Some(field_ref) = SField::field_ref(&doc.graph, &field_path, '.', None) {
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
self.operate(pid, doc, "removeField", obj, &mut vec![SVal::String(field.name.clone())])?;
}
SData::attach_existing(&mut doc.graph, obj, field_ref);
return Ok(SVal::Bool(true));
} else if let Some(func) = SFunc::func_ref(&doc.graph, &field_path, '.', Some(obj)) {
SData::attach_existing(&mut doc.graph, obj, func);
return Ok(SVal::Bool(true));
} else if let Some(func) = SFunc::func_ref(&doc.graph, &field_path, '.', None) {
SData::attach_existing(&mut doc.graph, obj, func);
return Ok(SVal::Bool(true));
}
return Ok(SVal::Bool(false));
} else if parameters.len() == 2 {
match ¶meters[0] {
SVal::Object(context) => {
let field_path = parameters[1].to_string();
if let Some(field_ref) = SField::field_ref(&doc.graph, &field_path, '.', Some(&context)) {
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
self.operate(pid, doc, "removeField", obj, &mut vec![SVal::String(field.name.clone())])?;
}
SData::attach_existing(&mut doc.graph, obj, field_ref);
return Ok(SVal::Bool(true));
} else if let Some(func) = SFunc::func_ref(&doc.graph, &field_path, '.', Some(&context)) {
SData::attach_existing(&mut doc.graph, obj, func);
return Ok(SVal::Bool(true));
}
return Ok(SVal::Bool(false));
},
_ => {}
}
}
Err(SError::obj(pid, &doc, "reference", "path argument not found"))
},
"fields" => {
let fields = SField::fields(&doc.graph, obj);
let mut map = BTreeMap::new();
for field in fields {
let value = field.value.clone();
let key = SVal::String(field.name.clone());
map.insert(key, value);
}
Ok(SVal::Map(map))
},
"attributes" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "attributes", "invalid arguments - path not found"));
}
match ¶meters[0] {
SVal::String(index) => {
if let Some(field) = SField::field(&doc.graph, &index, '.', Some(obj)) {
let mut attrs = BTreeMap::new();
for (key, value) in &field.attributes {
attrs.insert(SVal::String(key.clone()), value.clone());
}
return Ok(SVal::Map(attrs));
} else if let Some(func_ref) = SFunc::func_ref(&doc.graph, &index, '.', Some(obj)) {
let mut attrs = BTreeMap::new();
if let Some(func) = SData::get::<SFunc>(&doc.graph, &func_ref) {
for (key, value) in &func.attributes {
attrs.insert(SVal::String(key.clone()), value.clone());
}
}
return Ok(SVal::Map(attrs));
}
return Ok(SVal::Null); // Not found
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::String(index) => {
if let Some(field) = SField::field(&doc.graph, &index, '.', Some(obj)) {
let mut attrs = BTreeMap::new();
for (key, value) in &field.attributes {
attrs.insert(SVal::String(key.clone()), value.clone());
}
return Ok(SVal::Map(attrs));
} else if let Some(func_ref) = SFunc::func_ref(&doc.graph, &index, '.', Some(obj)) {
let mut attrs = BTreeMap::new();
if let Some(func) = SData::get::<SFunc>(&doc.graph, &func_ref) {
for (key, value) in &func.attributes {
attrs.insert(SVal::String(key.clone()), value.clone());
}
}
return Ok(SVal::Map(attrs));
}
return Ok(SVal::Null); // Not found
},
_ => {
Err(SError::obj(pid, &doc, "attributes", "invalid arguments - path must be a string"))
}
}
},
_ => {
Err(SError::obj(pid, &doc, "attributes", "invalid arguments - path must be a string"))
}
}
},
"funcs" |
"functions" => {
let funcs = SFunc::func_refs(&doc.graph, obj);
let mut map = BTreeMap::new();
for func_ref in funcs {
if let Some(func) = SData::get::<SFunc>(&doc.graph, &func_ref) {
let value = SVal::FnPtr(func_ref);
let key = SVal::String(func.name.clone());
map.insert(key, value);
}
}
Ok(SVal::Map(map))
},
"keys" => {
let fields = SField::fields(&doc.graph, obj);
let mut array = Vec::new();
for field in fields {
array.push(SVal::String(field.name.clone()));
}
Ok(SVal::Array(array))
},
"values" => {
let fields = SField::fields(&doc.graph, obj);
let mut array = Vec::new();
for field in fields {
array.push(field.value.clone());
}
Ok(SVal::Array(array))
},
// Unbox a field without an assign operation.
// Can be used like "set", but with an unbox operation in the middle.
"unbox" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "unbox", "invalid arguments - expecing a string path to a field that should be unboxed on this object"));
}
let path = parameters[0].to_string();
let mut value = None;
if parameters.len() > 1 {
value = Some(parameters.pop().unwrap());
}
// Look for an existing field to unbox
if let Some(field_ref) = SField::field_ref(&doc.graph, &path, '.', Some(obj)) {
if !doc.perms.can_write_field(&doc.graph, &field_ref, Some(obj)) {
return Ok(SVal::Bool(false));
}
if let Some(field) = SData::get_mut::<SField>(&mut doc.graph, &field_ref) {
if let Some(value) = value {
field.value = value.unbox();
} else {
field.value.unbox_ref();
}
return Ok(SVal::Bool(true));
}
return Ok(SVal::Bool(false));
}
if let Some(value) = value {
// val is a dot separated path!
let mut path = path.split('.').collect::<Vec<&str>>();
let name = path.pop().unwrap().to_string();
// Ensure the path exists if we need to add objects
let mut fref = obj.clone();
if path.len() > 0 {
fref = doc.graph.ensure_nodes(&path.join("/"), '/', true, Some(obj.clone()));
}
// Create the field on fref with the unboxed value
let field = SField::new(&name, value.unbox());
SData::insert_new(&mut doc.graph, &fref, Box::new(field));
return Ok(SVal::Bool(true));
}
Ok(SVal::Bool(false))
},
// Box a field without an assign operation.
// Can be used like "set", but with a box operation in the middle.
"box" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "box", "invalid arguments - expecing a string path to a field that should be boxed on this object"));
}
let path = parameters[0].to_string();
let mut value = None;
if parameters.len() > 1 {
value = Some(parameters.pop().unwrap());
}
// Look for an existing field to box
if let Some(field_ref) = SField::field_ref(&doc.graph, &path, '.', Some(obj)) {
if !doc.perms.can_write_field(&doc.graph, &field_ref, Some(obj)) {
return Ok(SVal::Bool(false));
}
if let Some(field) = SData::get_mut::<SField>(&mut doc.graph, &field_ref) {
if let Some(value) = value {
field.value = value.to_box();
} else {
field.value.to_box_ref();
}
return Ok(SVal::Bool(true));
}
return Ok(SVal::Bool(false));
}
// val is a dot separated path!
let mut path = path.split('.').collect::<Vec<&str>>();
let name = path.pop().unwrap().to_string();
// Ensure the path exists if we need to add objects
let mut fref = obj.clone();
if path.len() > 0 {
fref = doc.graph.ensure_nodes(&path.join("/"), '/', true, Some(obj.clone()));
}
// Create the field on fref
let mut field = SField::new(&name, SVal::Null.to_box());
if let Some(value) = value {
field.value = value.to_box();
}
SData::insert_new(&mut doc.graph, &fref, Box::new(field));
Ok(SVal::Bool(true))
},
"set" => {
if parameters.len() == 2 {
let value = parameters.pop().unwrap();
let name = parameters.pop().unwrap().to_string();
// Check for an existing field at this location
if let Some(field_ref) = SField::field_ref(&doc.graph, &name, '.', Some(obj)) {
if !doc.perms.can_write_field(&doc.graph, &field_ref, Some(obj)) {
return Ok(SVal::Bool(false));
}
if let Some(field) = SData::get_mut::<SField>(&mut doc.graph, &field_ref) {
field.value = value;
return Ok(SVal::Bool(true));
}
return Ok(SVal::Bool(false));
}
// val is a dot separated path!
let mut path = name.split('.').collect::<Vec<&str>>();
let name = path.pop().unwrap().to_string();
// Ensure the path exists if we need to add objects
let mut fref = obj.clone();
if path.len() > 0 {
fref = doc.graph.ensure_nodes(&path.join("/"), '/', true, Some(obj.clone()));
}
// Create the field on fref
let field = SField::new(&name, value);
SData::insert_new(&mut doc.graph, &fref, Box::new(field));
return Ok(SVal::Bool(true));
}
Err(SError::obj(pid, &doc, "set", "invalid arguments - requires a name and value to set a field"))
},
// Take a map and do rename/moves with all entries.
// Signature: Object.mapFields(obj, map: map): map
"mapFields" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "mapFields", "invalid arguments - requires a map argument"));
}
match ¶meters[0] {
SVal::Map(map) => {
let mut mapped_values = BTreeMap::new();
for (k, v) in map {
let res = self.operate(pid, doc, "renameField", obj, &mut vec![k.clone(), v.clone()])?;
if res.truthy() {
mapped_values.insert(k.clone(), v.clone());
}
}
Ok(SVal::Map(mapped_values))
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Map(map) => {
let mut mapped_values = BTreeMap::new();
for (k, v) in map {
let res = self.operate(pid, doc, "renameField", obj, &mut vec![k.clone(), v.clone()])?;
if res.truthy() {
mapped_values.insert(k.clone(), v.clone());
}
}
Ok(SVal::Map(mapped_values))
},
_ => {
Err(SError::obj(pid, &doc, "mapFields", "invalid arguments - map argument not found"))
}
}
},
_ => {
Err(SError::obj(pid, &doc, "mapFields", "invalid arguments - map argument not found"))
}
}
},
// Rename/Move a field if this object has it and permissions allow.
// Signature: Object.renameField(obj, field_path: str, new_path: str): bool
"moveField" |
"renameField" => {
if parameters.len() < 2 {
return Err(SError::obj(pid, &doc, "moveField", "invalid arguments - requires two paths, a source and a destination"));
}
let dest = parameters.pop().unwrap().to_string();
let source = parameters.pop().unwrap().to_string();
if let Some(field_ref) = SField::field_ref(&doc.graph, &source, '.', Some(obj)) {
if !doc.perms.can_write_field(&doc.graph, &field_ref, Some(obj)) {
return Ok(SVal::Bool(false));
}
// union the destination field if one already exists...
if let Some(existing_ref) = SField::field_ref(&doc.graph, &dest, '.', Some(obj)) {
// Clone the field
let clone;
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
clone = field.clone();
} else {
return Ok(SVal::Bool(false));
}
// remove this field from the graph (everywhere, I know... no way to be sure that field is on obj)
doc.graph.remove_data(&field_ref, None);
if let Some(existing) = SData::get_mut::<SField>(&mut doc.graph, existing_ref) {
existing.merge(&clone)?;
}
} else {
// Get the new field name from the destination path
let mut dest_path = dest.split('.').collect::<Vec<&str>>();
let new_field_name = dest_path.pop().unwrap();
// If there is a new destination node, do that
if dest_path.len() > 0 {
// Clone the field
let mut clone;
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
clone = field.clone();
} else {
return Ok(SVal::Bool(false));
}
// remove this field from the graph (everywhere, I know... no way to be sure that field is on obj)
doc.graph.remove_data(&field_ref, None);
clone.name = new_field_name.to_owned();
let dest_node_path = dest_path.join(".");
let dest_ref = doc.graph.ensure_nodes(&dest_node_path, '.', true, Some(obj.clone()));
// If field is an object, move the object to the destination also and rename
match &clone.value {
SVal::Object(nref) => {
doc.graph.rename_node(nref, new_field_name);
let id_path: HashSet<String> = HashSet::from_iter(nref.id_path(&doc.graph).into_iter());
if !id_path.contains(&dest_ref.id) && !dest_ref.is_child_of(&doc.graph, &nref) {
doc.graph.move_node(nref, &dest_ref);
}
},
_ => {}
}
SData::insert_new_id(&mut doc.graph, &dest_ref, Box::new(clone), &field_ref.id); // keep same id
} else {
// We've only renamed the field, so do that only
let mut rename_node = None;
if let Some(field) = SData::get_mut::<SField>(&mut doc.graph, field_ref) {
field.name = new_field_name.to_owned();
// If field is an object, rename
match &field.value {
SVal::Object(nref) => {
rename_node = Some(nref.clone());
},
_ => {}
}
}
if let Some(rename_node) = rename_node {
doc.graph.rename_node(&rename_node, new_field_name);
}
}
}
return Ok(SVal::Bool(true));
}
Ok(SVal::Bool(false))
},
// Delete a field (path), starting at this object.
// Signature: Object.removeField(obj, path: str, remove_obj: bool): bool
"removeField" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "removeField", "invalid arguments - field path not found"));
}
let mut remove_obj = false;
if parameters.len() > 1 {
remove_obj = parameters.pop().unwrap().truthy();
}
let path = parameters.pop().unwrap().to_string();
if let Some(field_ref) = SField::field_ref(&doc.graph, &path, '.', Some(obj)) {
if !doc.perms.can_write_field(&doc.graph, &field_ref, Some(obj)) {
return Ok(SVal::Bool(false));
}
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
if remove_obj && field.value.is_object() {
match field.value.clone().unbox() {
SVal::Object(nref) => {
doc.types.drop_types_for(&nref, &doc.graph);
doc.graph.remove_node(nref);
},
_ => {}
}
}
}
if path.contains('.') {
// remove from everywhere
doc.graph.remove_data(field_ref, None);
} else {
// remove only from this node (potentially everywhere)
doc.graph.remove_data(field_ref, Some(obj));
}
return Ok(SVal::Bool(true));
}
Ok(SVal::Bool(false))
},
// Delete a function (path), starting at this object.
// Signature: Object.removeFunc(obj, path: str): bool
"removeFunc" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "removeFunc", "invalid arguments - func path not found"));
}
let path = parameters.pop().unwrap().to_string();
if let Some(func_ref) = SFunc::func_ref(&doc.graph, &path, '.', Some(obj)) {
if !doc.perms.can_write_func(&doc.graph, &func_ref, Some(obj)) {
return Ok(SVal::Bool(false));
}
if path.contains('.') {
doc.graph.remove_data(func_ref, None);
} else {
doc.graph.remove_data(func_ref, Some(obj));
}
return Ok(SVal::Bool(true));
}
Ok(SVal::Bool(false))
},
"name" => {
if let Some(node) = obj.node(&doc.graph) {
return Ok(SVal::String(node.name.clone()));
}
Err(SError::obj(pid, &doc, "name", "could not find object"))
},
"id" => {
Ok(SVal::String(obj.id.clone()))
},
"parent" => {
if let Some(node) = obj.node(&doc.graph) {
if let Some(parent) = &node.parent {
return Ok(SVal::Object(parent.clone()));
}
}
Ok(SVal::Null)
},
// Return this objects prototype object (if any)
"prototype" => {
if let Some(prototype) = SPrototype::get(&doc.graph, obj) {
return Ok(SVal::Object(prototype.node_ref()));
}
Ok(SVal::Null)
},
// Set this objects prototype explicitly.
"setPrototype" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "setPrototype", "invalid arguments - object prototype not found"));
}
match ¶meters[0] {
SVal::Object(nref) => {
if let Some(prototype_ref) = SPrototype::get_ref(&doc.graph, obj) {
if let Some(prototype) = SData::get_mut::<SPrototype>(&mut doc.graph, prototype_ref) {
prototype.prototype = nref.id.clone();
}
} else {
let prototype = SPrototype::new(nref);
SData::insert_new(&mut doc.graph, obj, Box::new(prototype));
}
return Ok(SVal::Void);
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Object(nref) => {
if let Some(prototype_ref) = SPrototype::get_ref(&doc.graph, obj) {
if let Some(prototype) = SData::get_mut::<SPrototype>(&mut doc.graph, prototype_ref) {
prototype.prototype = nref.id.clone();
}
} else {
let prototype = SPrototype::new(nref);
SData::insert_new(&mut doc.graph, obj, Box::new(prototype));
}
return Ok(SVal::Void);
},
_ => {}
}
},
_ => {}
}
Err(SError::obj(pid, &doc, "setPrototype", "invalid arguments - object prototype not found"))
},
// Get the attributes for the prototype of this object (if any)
"prototypeAttributes" => {
if let Some(prototype) = SPrototype::get(&doc.graph, obj) {
let attributes = prototype.attributes(&doc);
let mut map = BTreeMap::new();
for (k, v) in attributes {
map.insert(SVal::String(k), v);
}
return Ok(SVal::Map(map));
}
Ok(SVal::Null)
}
// Return this objects root object.
// Signature: Object.root(obj): obj
"root" => {
if let Some(root) = obj.root(&doc.graph) {
return Ok(SVal::Object(root.node_ref()));
}
Ok(SVal::Null)
},
// Is this object a root object?
"isRoot" => {
if let Some(node) = obj.node(&doc.graph) {
Ok(SVal::Bool(node.parent.is_none()))
} else {
Ok(SVal::Bool(true)) // unreachable case
}
},
"path" => {
Ok(SVal::String(obj.path(&doc.graph).replace('/', ".")))
},
"children" => {
if let Some(node) = obj.node(&doc.graph) {
let mut children = Vec::new();
for child in &node.children {
children.push(SVal::Object(child.clone()));
}
return Ok(SVal::Array(children));
}
Ok(SVal::Array(vec![]))
},
"typename" => {
let typename = SVal::Object(obj.clone()).type_name(&doc.graph);
Ok(SVal::String(typename))
},
"typestack" => {
let typestack = SVal::Object(obj.clone()).type_stack(&doc.graph);
Ok(SVal::Array(typestack.into_iter().map(|x| SVal::String(x)).collect()))
},
"instanceOf" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "instanceOf", "invalid arguments - type string not found"));
}
let iof = SVal::Object(obj.clone()).instance_of(&doc.graph, ¶meters[0].to_string());
Ok(SVal::Bool(iof))
},
"upcast" => {
if let Some(prototype_ref) = SPrototype::get_ref(&doc.graph, obj) {
let mut parent_id = String::default();
if let Some(prototype) = SData::get::<SPrototype>(&doc.graph, &prototype_ref) {
if let Some(node) = prototype.node_ref().node(&doc.graph) {
if let Some(parent_ref) = &node.parent {
if let Some(parent) = parent_ref.node(&doc.graph) {
if parent.name != "__stof__" && parent.name != "prototypes" {
parent_id = parent.id.clone();
}
}
}
}
}
if parent_id.len() > 0 {
if let Some(prototype) = SData::get_mut::<SPrototype>(&mut doc.graph, prototype_ref) {
prototype.prototype = parent_id;
return Ok(SVal::Bool(true));
}
}
}
Ok(SVal::Bool(false))
},
// Remove the prototype for this object if any, returning whether one was removed or not.
"removePrototype" => {
if let Some(prototype) = SPrototype::get_ref(&doc.graph, obj) {
doc.graph.remove_data(prototype, Some(obj));
return Ok(SVal::Bool(true));
}
Ok(SVal::Bool(false))
},
// dump this object (testing)
"dbg_dump" => {
if let Some(node) = obj.node(&doc.graph) {
let dump = node.dump(&doc.graph, 0, true);
println!("{dump}");
}
Ok(SVal::Void)
},
/*****************************************************************************
* Search for fields.
*****************************************************************************/
// Searches both up and down, looking for the closest field with a given name.
// Returns null if not found, otherwise the value and distance from this object.
// Signature: Object.search(obj, field_name: str, search_parent_children: bool = true, obj_ignore_set: vec = []): null | (unknown, int)
"search" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "search", "invalid arguments - field name not found"));
}
let up = self.operate(pid, doc, "searchUp", obj, parameters)?;
let mut down_parameters = vec![parameters[0].clone(), SVal::Number(SNum::I64(0))];
if parameters.len() > 2 { down_parameters.push(parameters[2].clone()); }
let down = self.operate(pid, doc, "searchDown", obj, &mut down_parameters)?;
if !up.is_empty() && !down.is_empty() {
match up {
SVal::Tuple(up) => {
match down {
SVal::Tuple(down) => {
let down_lte_up = down.last().unwrap().lte(up.last().unwrap())?;
if down_lte_up.truthy() {
// down is closer (or equal) - return down
return Ok(SVal::Tuple(down));
} else {
// up is closer
return Ok(SVal::Tuple(up));
}
},
_ => {}
}
},
_ => {}
}
} else if !up.is_empty() {
return Ok(up);
} else if !down.is_empty() {
return Ok(down);
}
Ok(SVal::Null)
},
// Search upwards through our parents to find the closest field with a name.
// Returns null if not found, otherwise the value and distance from this object.
// Signature: Object.searchUp(obj, field_name: str, search_parent_children: bool = true, obj_ignore_set: vec = []): null | (unknown, int)
"searchUp" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "searchUp", "invalid arguments - field name not found"));
}
let mut obj_ignore_set = HashSet::new();
if parameters.len() > 2 {
match ¶meters[2] {
SVal::Array(vals) => {
for v in vals {
match v {
SVal::Object(nref) => {
obj_ignore_set.insert(nref.id.clone());
},
_ => {}
}
}
},
_ => {}
}
}
let field_name = parameters[0].to_string();
if !obj_ignore_set.contains(&obj.id) {
if let Some(field_ref) = SField::field_ref(&doc.graph, &field_name, '.', Some(obj)) {
if doc.perms.can_read_field(&doc.graph, &field_ref, Some(obj)) {
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
return Ok(SVal::Tuple(vec![field.value.clone(), SVal::Number(SNum::I64(0))]));
}
}
}
}
obj_ignore_set.insert(obj.id.clone()); // already searched in this object
// Search up, through parent nodes
let mut allow_parent_children = true;
let mut child_finds = Vec::new();
if parameters.len() > 1 {
allow_parent_children = parameters[1].truthy();
}
let mut parent = None;
let mut parent_field = None;
let mut parent_field_ref = None;
if let Some(node) = obj.node(&doc.graph) {
parent = node.parent.clone();
}
let mut parent_distance = 1;
while parent.is_some() {
if let Some(parent) = &parent {
if !obj_ignore_set.contains(&parent.id) {
if let Some(field_ref) = SField::field_ref(&doc.graph, &field_name, '.', Some(parent)) {
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
parent_field = Some(field);
}
parent_field_ref = Some(field_ref);
break;
}
obj_ignore_set.insert(parent.id.clone()); // just searched this parent
}
}
if allow_parent_children {
let mut params = vec![parameters[0].clone(), SVal::Number(SNum::I64(parent_distance))];
if obj_ignore_set.len() > 0 {
let vals = obj_ignore_set.iter().map(|id| SVal::Object(SNodeRef::new(id))).collect();
params.push(SVal::Array(vals));
}
let val = self.operate(pid, doc, "searchDown", &parent.clone().unwrap(), &mut params)?;
if !val.is_empty() {
child_finds.push(val);
}
}
if let Some(node) = parent.unwrap().node(&doc.graph) {
parent = node.parent.clone();
} else {
parent = None;
}
parent_distance += 1;
}
// sort child finds by distance if any
if child_finds.len() > 0 {
child_finds.sort_by(|a, b| {
match a {
SVal::Tuple(a) => {
match b {
SVal::Tuple(b) => {
let a_lt = a.last().unwrap().lt(b.last().unwrap()).unwrap();
if a_lt.truthy() {
return Ordering::Less;
}
let a_gt = a.last().unwrap().gt(b.last().unwrap()).unwrap();
if a_gt.truthy() {
return Ordering::Greater;
}
},
_ => {}
}
},
_ => {}
}
Ordering::Equal
});
}
if let Some(field) = parent_field { // will be the first in-line value found if any
if child_finds.len() > 0 {
// compare the closest child find to this parent find, preferring the parent find when equal
let first_child = child_finds.remove(0);
let mut return_child = false;
match &first_child {
SVal::Tuple(tup) => {
match &tup.last().unwrap() {
SVal::Number(num) => {
let dist = num.int();
if dist < parent_distance {
return_child = true;
}
},
_ => {}
}
},
_ => {}
}
if return_child {
return Ok(first_child);
}
}
if let Some(parent_ref) = parent_field_ref {
if doc.perms.can_read_field(&doc.graph, &parent_ref, Some(obj)) {
return Ok(SVal::Tuple(vec![field.value.clone(), SVal::Number(SNum::I64(parent_distance))]));
}
}
} else if child_finds.len() > 0 {
return Ok(child_finds.remove(0));
}
Ok(SVal::Null)
},
// Search downwards through our children to find the closest field with a name.
// Returns null if not found, otherwise the value and distance from this object.
// Signature: Object.searchDown(obj, field_name: str, current_dist: int = 0, obj_ignore_set: vec = []): null | (unknown, int)
"searchDown" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "searchDown", "invalid arguments - field name not found"));
}
let mut current_distance = 0;
if parameters.len() > 1 {
match ¶meters[1] {
SVal::Number(num) => {
current_distance = num.int();
},
_ => {}
}
}
let mut obj_ignore_set = HashSet::new();
if parameters.len() > 2 {
match ¶meters[2] {
SVal::Array(vals) => {
for v in vals {
match v {
SVal::Object(nref) => {
obj_ignore_set.insert(nref.id.clone());
},
_ => {}
}
}
},
_ => {}
}
}
let field_name = parameters[0].to_string();
if !obj_ignore_set.contains(&obj.id) {
if let Some(field_ref) = SField::field_ref(&doc.graph, &field_name, '.', Some(obj)) {
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
if doc.perms.can_read_field(&doc.graph, &field_ref, Some(obj)) {
return Ok(SVal::Tuple(vec![field.value.clone(), SVal::Number(SNum::I64(current_distance))]));
}
}
}
}
let children;
if let Some(node) = obj.node(&doc.graph) {
children = node.children.clone();
} else {
return Ok(SVal::Null); // no children to consider
}
let mut params = vec![parameters[0].clone(), SVal::Number(SNum::I64(current_distance + 1))];
if obj_ignore_set.len() > 0 {
params.push(parameters[2].clone());
}
let mut child_finds = Vec::new();
for child in children {
let val = self.operate(pid, doc, "searchDown", &child, &mut params)?;
if !val.is_empty() {
child_finds.push(val);
}
}
if child_finds.len() > 0 {
child_finds.sort_by(|a, b| {
match a {
SVal::Tuple(a) => {
match b {
SVal::Tuple(b) => {
let a_lt = a.last().unwrap().lt(b.last().unwrap()).unwrap();
if a_lt.truthy() {
return Ordering::Less;
}
let a_gt = a.last().unwrap().gt(b.last().unwrap()).unwrap();
if a_gt.truthy() {
return Ordering::Greater;
}
},
_ => {}
}
},
_ => {}
}
Ordering::Equal
});
return Ok(child_finds.remove(0));
}
Ok(SVal::Null)
},
/*****************************************************************************
* Schemafy another object with this object (as a schema).
*****************************************************************************/
// Use fields defined on this object with the #[schema(..)] attribute to control the same
// fields on a target object.
// Signature: Object.schemafy(schema: obj, target: obj, remove_invalid_fields: bool = true, remove_undefined: bool = false): bool
"schemafy" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "schemafy", "invalid arguments - expecting a target object to apply this schema on"));
}
let target;
match ¶meters[0] {
SVal::Object(nref) => target = nref.clone(),
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Object(nref) => target = nref.clone(),
_ => {
return Err(SError::obj(pid, &doc, "schemafy", "invalid arguments - expecting a target object to apply this schema on"));
}
}
},
_ => {
return Err(SError::obj(pid, &doc, "schemafy", "invalid arguments - expecting a target object to apply this schema on"));
}
}
let mut remove_invalid_fields = true;
if parameters.len() > 1 {
remove_invalid_fields = parameters[1].truthy();
}
let mut remove_undefined_fields = false;
if parameters.len() > 2 {
remove_undefined_fields = parameters[2].truthy();
}
// Get all of the fields on this schema to apply on the target object
// Field name -> #[schema] attribute value
let mut schema_fields: HashMap<String, SVal> = HashMap::new();
let mut schema_field_names = HashSet::new();
for schema_field in SField::fields(&doc.graph, obj) {
if let Some(schema_val) = schema_field.attributes.get("schema") {
schema_fields.insert(schema_field.name.clone(), schema_val.clone());
}
if remove_undefined_fields {
schema_field_names.insert(schema_field.name.clone());
}
}
// Iterate over all schema fields, applying them to the target object as needed
let mut valid = true;
for (field, value) in schema_fields {
if !self.schemafy_field(doc, pid, &obj, &target, &field, value, remove_invalid_fields, remove_undefined_fields) {
valid = false;
if remove_invalid_fields {
// remove this field, removing the object as well if present
self.operate(pid, doc, "removeField", &target, &mut vec![SVal::String(field), SVal::Bool(true)])?;
}
}
}
// Remove all fields on the target that are not defined in the schema fields
// Make sure to do this after all validations of course...
if remove_undefined_fields {
let mut to_remove = Vec::new();
for field_ref in SField::field_refs(&doc.graph, &target) {
if let Some(field) = SData::get::<SField>(&doc.graph, &field_ref) {
if !schema_field_names.contains(&field.name) {
to_remove.push(field.name.clone());
}
}
}
for field_name in to_remove {
// remove this field, removing the object as well if present
self.operate(pid, doc, "removeField", &target, &mut vec![SVal::String(field_name), SVal::Bool(true)])?;
}
}
Ok(SVal::Bool(valid))
},
/*****************************************************************************
* Copy object helpers.
*****************************************************************************/
// Make this object a shallow copy of the referenced object by attaching all of its fields.
// Signature: Object.shallowCopy(obj, to_copy: obj): void
"shallowCopy" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "shallowCopy", "invalid arguments - object to copy not found"));
}
match ¶meters[0] {
SVal::Object(to_copy) => {
let data;
if let Some(copy_node) = to_copy.node(&doc.graph) {
data = copy_node.data.clone();
} else {
return Err(SError::obj(pid, &doc, "shallowCopy", "invalid arguments - object to copy does not exist"));
}
for data in data {
doc.graph.put_data_ref(obj, data);
}
Ok(SVal::Void)
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Object(to_copy) => {
let data;
if let Some(copy_node) = to_copy.node(&doc.graph) {
data = copy_node.data.clone();
} else {
return Err(SError::obj(pid, &doc, "shallowCopy", "invalid arguments - object to copy does not exist"));
}
for data in data {
doc.graph.put_data_ref(obj, data);
}
Ok(SVal::Void)
},
_ => {
Err(SError::obj(pid, &doc, "shallowCopy", "invalid arguments - object to copy not found"))
}
}
},
_ => {
Err(SError::obj(pid, &doc, "shallowCopy", "invalid arguments - object to copy not found"))
}
}
},
// Make this object a deep copy of the referenced object (fields only).
// Captures attributes, deep copies sub objects, etc.. as well.
// Signature: Object.deepCopyFields(obj, to_copy: obj): void
"deepCopyFields" => {
if parameters.len() < 1 {
return Err(SError::obj(pid, &doc, "deepCopyFields", "invalid arguments - object to copy not found"));
}
match ¶meters[0] {
SVal::Object(to_copy) => {
let mut fields = Vec::new();
for field in SField::fields(&doc.graph, to_copy) {
fields.push(field.clone());
}
for field in fields {
if field.is_object() {
match field.value.clone().unbox() {
SVal::Object(nref) => {
let deep_copy = SField::new_object(&mut doc.graph, &field.name, obj);
let to_copy = SVal::Object(nref);
self.operate(pid, doc, "deepCopyFields", &deep_copy, &mut vec![to_copy])?;
},
_ => {}
}
} else {
SData::insert_new(&mut doc.graph, obj, Box::new(field));
}
}
Ok(SVal::Void)
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Object(to_copy) => {
let mut fields = Vec::new();
for field in SField::fields(&doc.graph, to_copy) {
fields.push(field.clone());
}
for field in fields {
if field.is_object() {
match field.value.clone().unbox() {
SVal::Object(nref) => {
let deep_copy = SField::new_object(&mut doc.graph, &field.name, obj);
let to_copy = SVal::Object(nref);
self.operate(pid, doc, "deepCopyFields", &deep_copy, &mut vec![to_copy])?;
},
_ => {}
}
} else {
SData::insert_new(&mut doc.graph, obj, Box::new(field));
}
}
Ok(SVal::Void)
},
_ => {
Err(SError::obj(pid, &doc, "deepCopyFields", "invalid arguments - object to copy not found"))
}
}
},
_ => {
Err(SError::obj(pid, &doc, "deepCopyFields", "invalid arguments - object to copy not found"))
}
}
},
_ => {
Err(SError::obj(pid, &doc, "NotFound", &format!("{} is not a function in the Object Library", name)))
}
}
}
/// Schemafy an individual field on a target object.
fn schemafy_field(&self, doc: &mut SDoc, pid: &str, schema: &SNodeRef, target: &SNodeRef, field: &str, value: SVal, remove_invalid: bool, remove_undefined: bool) -> bool {
match value {
SVal::Void |
SVal::Null => {
// if the field is an object on the schema and on the target, use the object to "schemafy" with
let mut schema_field_object = None;
let mut target_field_object = None;
if let Some(field) = SField::field(&doc.graph, field, '.', Some(schema)) {
match &field.value {
SVal::Object(nref) => {
schema_field_object = Some(nref.clone());
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Object(nref) => {
schema_field_object = Some(nref.clone());
},
_ => {}
}
},
_ => {}
}
}
if let Some(field) = SField::field(&doc.graph, field, '.', Some(target)) {
match &field.value {
SVal::Object(nref) => {
target_field_object = Some(nref.clone());
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Object(nref) => {
target_field_object = Some(nref.clone());
},
_ => {}
}
},
_ => {}
}
}
if let Some(schema_object) = schema_field_object {
if let Some(target_object) = target_field_object {
if let Ok(res) = self.operate(pid, doc, "schemafy", &schema_object, &mut vec![SVal::Object(target_object), SVal::Bool(remove_invalid), SVal::Bool(remove_undefined)]) {
return res.truthy();
}
return false;
}
}
true
},
SVal::Object(another_schema) => {
let mut another_value = None;
if let Some(field) = SField::field(&doc.graph, field, '.', Some(&another_schema)) {
if let Some(schema_val) = field.attributes.get("schema") {
another_value = Some(schema_val.clone());
}
}
if let Some(value) = another_value {
return self.schemafy_field(doc, pid, &another_schema, target, field, value, remove_invalid, remove_undefined);
}
false // other schema does not implement/define this field as a schema
},
SVal::FnPtr(func_ref) => {
let mut parameters = Vec::new();
let mut valid_check = false; // func result treated as truthy valid or a value to set on the field..
let mut value_index = None;
let mut box_target_field_value = false;
let mut boxed_field_name = None;
if let Some(func) = SData::get::<SFunc>(&doc.graph, &func_ref) {
if func.rtype.is_bool() { valid_check = true; }
let mut added_target = false;
let mut added_schema = false;
let mut added_field = false;
let mut added_value = false;
for param_index in 0..func.params.len() {
let mut done = false;
let param = &func.params[param_index];
// First two objects in parameters are the target, then the schema
if param.ptype.is_object() && param.name != "value" && (!added_target || !added_schema) {
if param.name == "target" || (param.name != "schema" && !added_target) {
added_target = true;
parameters.push(SVal::Object(target.clone()));
} else if param.name == "schema" || !added_schema {
parameters.push(SVal::Object(schema.clone()));
added_schema = true;
}
done = true;
}
// First string parameter is the field name
if !done && !added_field && param.name != "value" && param.ptype.is_string() {
if param.ptype.is_boxed() {
let val = SVal::String(field.to_string());
let boxed = SVal::Boxed(Arc::new(SMutex::new(val)));
parameters.push(boxed.clone());
boxed_field_name = Some(boxed);
} else {
parameters.push(SVal::String(field.to_string()));
}
added_field = true;
done = true;
}
// Any other value is the target's current field value
if !done && !added_value {
value_index = Some(param_index);
added_value = true;
// If parameter is boxed, go ahead and box the target object's field
if param.ptype.is_boxed() {
box_target_field_value = true;
}
}
}
}
// Add the target's field value if needed, boxing the field if specified
if let Some(value_index) = value_index {
if let Some(field_ref) = SField::field_ref(&doc.graph, field, '.', Some(target)) {
if let Some(field) = SData::get_mut::<SField>(&mut doc.graph, &field_ref) {
if box_target_field_value {
field.value.to_box_ref();
}
parameters.insert(value_index, field.value.clone());
}
} else {
// no field, so insert null in place of it
parameters.insert(value_index, SVal::Null);
}
}
if let Ok(res) = SFunc::call(&func_ref, pid, doc, parameters, true) {
if let Some(field_ref) = SField::field_ref(&doc.graph, field, '.', Some(target)) {
if let Some(field) = SData::get_mut::<SField>(&mut doc.graph, &field_ref) {
if let Some(new_name) = boxed_field_name {
field.name = new_name.to_string();
}
if valid_check {
return res.truthy();
} else if !res.is_empty() {
field.value = res;
}
}
} else if valid_check {
return res.truthy();
} else if !res.is_empty() {
// create a new field since one doesn't exist, but we have a new value for it!
let mut field = SField::new(field, res);
if let Some(new_name) = boxed_field_name {
field.name = new_name.to_string();
}
SData::insert_new(&mut doc.graph, target, Box::new(field));
}
return true;
}
false
},
SVal::Tuple(vals) |
SVal::Array(vals) => {
for val in vals {
if !self.schemafy_field(doc, pid, schema, target, field, val, remove_invalid, remove_undefined) {
return false;
}
}
true
},
SVal::Set(set) => {
for val in set {
if !self.schemafy_field(doc, pid, schema, target, field, val, remove_invalid, remove_undefined) {
return false;
}
}
true
},
SVal::Boxed(val) => {
let cloned;
{
let val = val.lock().unwrap();
cloned = val.deref().clone();
}
self.schemafy_field(doc, pid, schema, target, field, cloned, remove_invalid, remove_undefined)
},
_ => false, // no other value is valid as a schema attribute
}
}
}
impl Library for ObjectLibrary {
fn scope(&self) -> String {
"Object".into()
}
fn call(&self, pid: &str, doc: &mut SDoc, name: &str, parameters: &mut Vec<SVal>) -> Result<SVal, SError> {
if parameters.len() > 0 {
match name {
"toString" => {
return Ok(SVal::String(parameters[0].print(doc)));
},
"or" => {
for param in parameters.drain(..) {
if !param.is_empty() {
return Ok(param);
}
}
return Ok(SVal::Null);
},
_ => {}
}
let mut params;
if parameters.len() > 1 {
params = parameters.drain(1..).collect();
} else {
params = Vec::new();
}
match ¶meters[0] {
SVal::Object(nref) => {
return self.operate(pid, doc, name, nref, &mut params);
},
SVal::Boxed(val) => {
let val = val.lock().unwrap();
let val = val.deref();
match val {
SVal::Object(nref) => {
return self.operate(pid, doc, name, nref, &mut params);
},
_ => {
return Err(SError::obj(pid, &doc, "InvalidArgument", "object argument not found"));
}
}
},
_ => {
return Err(SError::obj(pid, &doc, "InvalidArgument", "object argument not found"));
}
}
} else {
return Err(SError::obj(pid, &doc, "InvalidArgument", "object argument not found"));
}
}
}