-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmod.rs
More file actions
5547 lines (4872 loc) · 215 KB
/
mod.rs
File metadata and controls
5547 lines (4872 loc) · 215 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
// File: src/interpreter/native_functions/mod.rs
//
// Module organization for native (built-in) function implementations.
// This module is part of Phase 3 modularization to split the massive
// call_native_function_impl into manageable category-based modules.
pub mod async_ops;
pub mod collections;
pub mod concurrency;
pub mod crypto;
pub mod database;
pub mod filesystem;
pub mod http;
pub mod io;
pub mod json;
pub mod math;
pub mod network;
pub mod strings;
pub mod system;
pub mod type_ops;
use super::{Interpreter, Value};
/// Main dispatcher that routes native function calls to appropriate category modules
pub fn call_native_function(interp: &mut Interpreter, name: &str, arg_values: &[Value]) -> Value {
// Try async operations first (high priority for async functions)
if let Some(result) = async_ops::handle(interp, name, arg_values) {
return result;
}
// Try each category in order
if let Some(result) = io::handle(interp, name, arg_values) {
return result;
}
if let Some(result) = math::handle(name, arg_values) {
return result;
}
if let Some(result) = strings::handle(name, arg_values) {
return result;
}
if let Some(result) = collections::handle(interp, name, arg_values) {
return result;
}
if let Some(result) = type_ops::handle(name, arg_values) {
return result;
}
if let Some(result) = filesystem::handle(interp, name, arg_values) {
return result;
}
if let Some(result) = http::handle(name, arg_values) {
return result;
}
if let Some(result) = json::handle(name, arg_values) {
return result;
}
if let Some(result) = crypto::handle(name, arg_values) {
return result;
}
if let Some(result) = system::handle(name, arg_values) {
return result;
}
if let Some(result) = concurrency::handle(interp, name, arg_values) {
return result;
}
if let Some(result) = database::handle(name, arg_values) {
return result;
}
if let Some(result) = network::handle(interp, name, arg_values) {
return result;
}
// Unknown function
Value::Error(format!("Unknown native function: {}", name))
}
#[cfg(test)]
mod tests {
use super::call_native_function;
use crate::interpreter::{AsyncRuntime, Interpreter, LeakyFunctionBody, Value};
use std::sync::Arc;
fn available_tcp_port() -> i64 {
let listener =
std::net::TcpListener::bind("127.0.0.1:0").expect("ephemeral tcp listener should bind");
listener.local_addr().expect("ephemeral tcp listener should have local addr").port() as i64
}
fn available_udp_port() -> i64 {
let socket =
std::net::UdpSocket::bind("127.0.0.1:0").expect("ephemeral udp socket should bind");
socket.local_addr().expect("ephemeral udp socket should have local addr").port() as i64
}
fn tmp_test_path(file_name: &str) -> String {
let mut path = std::env::current_dir().expect("current_dir should resolve");
path.push("tmp");
path.push("native_zip_dispatch_tests");
std::fs::create_dir_all(&path).expect("zip test tmp dir should be created");
path.push(file_name);
path.to_string_lossy().to_string()
}
fn is_unknown_native_error(value: &Value) -> bool {
if let Value::Error(message) = value {
message.starts_with("Unknown native function:")
} else {
false
}
}
fn await_native_promise(value: Value) -> Result<Value, String> {
match value {
Value::Promise { receiver, .. } => AsyncRuntime::block_on(async {
let rx = {
let mut receiver_guard = receiver.lock().unwrap();
let (dummy_tx, dummy_rx) = tokio::sync::oneshot::channel();
drop(dummy_tx);
std::mem::replace(&mut *receiver_guard, dummy_rx)
};
match rx.await {
Ok(result) => result,
Err(_) => Err("Promise channel closed before resolution".to_string()),
}
}),
other => panic!("Expected Promise value, got {:?}", other),
}
}
fn noop_spawnable_function() -> Value {
Value::Function(vec![], LeakyFunctionBody::new(Vec::<crate::ast::Stmt>::new()), None)
}
#[test]
fn test_unknown_native_function_returns_explicit_error() {
let mut interpreter = Interpreter::new();
let result = call_native_function(&mut interpreter, "__unknown_native_test__", &[]);
match result {
Value::Error(message) => {
assert_eq!(message, "Unknown native function: __unknown_native_test__");
}
other => panic!("Expected Value::Error, got {:?}", other),
}
}
#[test]
fn test_release_hardening_builtin_dispatch_coverage_for_recent_apis() {
let mut interpreter = Interpreter::new();
let critical_builtin_names = [
"len",
"type",
"is_int",
"is_float",
"is_string",
"is_bool",
"is_array",
"is_dict",
"is_null",
"is_function",
"parse_int",
"parse_float",
"to_int",
"to_float",
"to_string",
"to_bool",
"bytes",
"Set",
"ssg_render_pages",
"ssg_build_output_paths",
"ssg_render_and_write_pages",
"ssg_read_render_and_write_pages",
"upper",
"lower",
"replace",
"append",
"push",
"pop",
"insert",
"remove",
"remove_at",
"clear",
"slice",
"concat",
"map",
"filter",
"reduce",
"find",
"sort",
"reverse",
"unique",
"sum",
"any",
"all",
"chunk",
"flatten",
"zip",
"enumerate",
"take",
"skip",
"windows",
"starts_with",
"ends_with",
"repeat",
"char_at",
"is_empty",
"count_chars",
"pad_left",
"pad_right",
"lines",
"words",
"str_reverse",
"slugify",
"truncate",
"to_camel_case",
"to_snake_case",
"to_kebab_case",
"substring",
"capitalize",
"trim",
"trim_start",
"trim_end",
"split",
"join",
"Promise.all",
"parallel_map",
"par_map",
"channel",
"async_sleep",
"async_timeout",
"async_http_get",
"async_http_post",
"async_read_file",
"async_write_file",
"spawn_task",
"await_task",
"cancel_task",
"sleep",
"execute",
"contains",
"index_of",
"io_read_bytes",
"io_write_bytes",
"io_append_bytes",
"io_read_at",
"io_write_at",
"io_seek_read",
"io_file_metadata",
"io_truncate",
"io_copy_range",
"http_get",
"http_post",
"http_put",
"http_delete",
"http_get_binary",
"parallel_http",
"jwt_encode",
"jwt_decode",
"oauth2_auth_url",
"oauth2_get_token",
"http_get_stream",
"http_server",
"http_response",
"json_response",
"html_response",
"redirect_response",
"set_header",
"set_headers",
"db_connect",
"db_execute",
"db_query",
"db_close",
"db_pool",
"db_pool_acquire",
"db_pool_release",
"db_pool_stats",
"db_pool_close",
"db_begin",
"db_commit",
"db_rollback",
"db_last_insert_id",
"join_path",
"path_join",
"set_add",
"set_has",
"set_remove",
"set_union",
"set_intersect",
"set_difference",
"set_to_array",
"Queue",
"queue_enqueue",
"queue_dequeue",
"queue_peek",
"queue_is_empty",
"queue_to_array",
"Stack",
"stack_push",
"stack_pop",
"stack_peek",
"stack_is_empty",
"stack_to_array",
"queue_size",
"stack_size",
"shared_set",
"shared_get",
"shared_has",
"shared_delete",
"shared_add_int",
"async_read_files",
"async_write_files",
"promise_all",
"await_all",
"par_each",
"set_task_pool_size",
"get_task_pool_size",
"spawn_process",
"pipe_commands",
"load_image",
"zip_create",
"zip_add_file",
"zip_add_dir",
"zip_close",
"unzip",
"tcp_listen",
"tcp_accept",
"tcp_connect",
"tcp_send",
"tcp_receive",
"tcp_close",
"tcp_set_nonblocking",
"udp_bind",
"udp_send_to",
"udp_receive_from",
"udp_close",
"sha256",
"md5",
"md5_file",
"hash_password",
"verify_password",
"aes_encrypt",
"aes_decrypt",
"aes_encrypt_bytes",
"aes_decrypt_bytes",
"rsa_generate_keypair",
"rsa_encrypt",
"rsa_decrypt",
"rsa_sign",
"rsa_verify",
"random",
"random_int",
"random_choice",
"set_random_seed",
"clear_random_seed",
"now",
"current_timestamp",
"performance_now",
"time_us",
"time_ns",
"format_duration",
"elapsed",
"format_date",
"parse_date",
"abs",
"sqrt",
"pow",
"floor",
"ceil",
"round",
"min",
"max",
"sin",
"cos",
"tan",
"log",
"exp",
"range",
"keys",
"values",
"items",
"has_key",
"get",
"merge",
"invert",
"update",
"get_default",
"format",
"parse_json",
"to_json",
"parse_toml",
"to_toml",
"parse_yaml",
"to_yaml",
"parse_csv",
"to_csv",
"encode_base64",
"decode_base64",
"regex_match",
"regex_find_all",
"regex_replace",
"regex_split",
"assert",
"debug",
"assert_equal",
"assert_true",
"assert_false",
"assert_contains",
"read_file",
"write_file",
"append_file",
"file_exists",
"read_lines",
"list_dir",
"create_dir",
"file_size",
"delete_file",
"rename_file",
"copy_file",
"read_binary_file",
"write_binary_file",
"env",
"env_or",
"env_int",
"env_float",
"env_bool",
"env_required",
"env_set",
"env_list",
"args",
"arg_parser",
"os_getcwd",
"os_chdir",
"os_rmdir",
"os_environ",
"dirname",
"basename",
"path_exists",
"path_absolute",
"path_is_dir",
"path_is_file",
"path_extension",
];
for builtin_name in critical_builtin_names {
let result = call_native_function(&mut interpreter, builtin_name, &[]);
assert!(
!is_unknown_native_error(&result),
"Builtin '{}' unexpectedly hit unknown-native fallback with result {:?}",
builtin_name,
result
);
}
}
#[test]
fn test_release_hardening_builtin_dispatch_coverage_for_declared_builtins() {
let mut interpreter = Interpreter::new();
let mut unknown_builtin_names = Vec::new();
let expected_known_legacy_dispatch_gaps: Vec<String> = vec![];
for builtin_name in Interpreter::get_builtin_names() {
let probe_args = match builtin_name {
"input" => vec![Value::Int(1)],
"exit" => vec![Value::Str(Arc::new("non-numeric".to_string()))],
_ => vec![],
};
let result = call_native_function(&mut interpreter, builtin_name, &probe_args);
if is_unknown_native_error(&result) {
unknown_builtin_names.push(builtin_name.to_string());
}
}
assert_eq!(
unknown_builtin_names,
expected_known_legacy_dispatch_gaps,
"Declared builtin dispatch drift changed. If a gap was fixed, remove it from expected list; if a new gap appeared, investigate and either fix dispatch or explicitly acknowledge it here."
);
}
#[test]
fn test_release_hardening_async_sleep_timeout_contracts() {
let mut interpreter = Interpreter::new();
let sleep_missing_args = call_native_function(&mut interpreter, "async_sleep", &[]);
assert!(
matches!(sleep_missing_args, Value::Error(message) if message.contains("expects 1 argument"))
);
let sleep_negative =
call_native_function(&mut interpreter, "async_sleep", &[Value::Int(-1)]);
assert!(
matches!(sleep_negative, Value::Error(message) if message.contains("requires non-negative milliseconds"))
);
let timeout_wrong_first_arg = call_native_function(
&mut interpreter,
"async_timeout",
&[Value::Int(1), Value::Int(5)],
);
assert!(
matches!(timeout_wrong_first_arg, Value::Error(message) if message.contains("requires a Promise as first argument"))
);
let timeout_non_positive_sleep =
call_native_function(&mut interpreter, "async_sleep", &[Value::Int(1)]);
let timeout_non_positive = call_native_function(
&mut interpreter,
"async_timeout",
&[timeout_non_positive_sleep, Value::Int(0)],
);
assert!(
matches!(timeout_non_positive, Value::Error(message) if message.contains("requires positive timeout_ms"))
);
let quick_sleep = call_native_function(&mut interpreter, "async_sleep", &[Value::Int(2)]);
let timeout_success =
call_native_function(&mut interpreter, "async_timeout", &[quick_sleep, Value::Int(50)]);
let timeout_success_result = await_native_promise(timeout_success);
assert!(matches!(timeout_success_result, Ok(Value::Null)));
let slow_sleep = call_native_function(&mut interpreter, "async_sleep", &[Value::Int(30)]);
let timeout_failure =
call_native_function(&mut interpreter, "async_timeout", &[slow_sleep, Value::Int(1)]);
let timeout_failure_result = await_native_promise(timeout_failure);
assert!(
matches!(timeout_failure_result, Err(message) if message.contains("Timeout after"))
);
}
#[test]
fn test_release_hardening_async_http_argument_contracts() {
let mut interpreter = Interpreter::new();
let http_get_wrong_arity = call_native_function(
&mut interpreter,
"async_http_get",
&[Value::Str(Arc::new("https://example.com".to_string())), Value::Int(1)],
);
assert!(
matches!(http_get_wrong_arity, Value::Error(message) if message.contains("expects 1 argument"))
);
let http_get_wrong_type =
call_native_function(&mut interpreter, "async_http_get", &[Value::Int(1)]);
assert!(
matches!(http_get_wrong_type, Value::Error(message) if message.contains("requires a string URL argument"))
);
let http_post_wrong_arity = call_native_function(
&mut interpreter,
"async_http_post",
&[Value::Str(Arc::new("https://example.com".to_string()))],
);
assert!(
matches!(http_post_wrong_arity, Value::Error(message) if message.contains("expects 2-3 arguments"))
);
let http_post_bad_headers = call_native_function(
&mut interpreter,
"async_http_post",
&[
Value::Str(Arc::new("https://example.com".to_string())),
Value::Str(Arc::new("payload".to_string())),
Value::Int(1),
],
);
assert!(
matches!(http_post_bad_headers, Value::Error(message) if message.contains("headers must be a dictionary"))
);
}
#[test]
fn test_release_hardening_async_file_wrapper_contracts() {
let mut interpreter = Interpreter::new();
let file_path = tmp_test_path("release_hardening_async_file_wrapper.txt");
let async_read_bad_arg =
call_native_function(&mut interpreter, "async_read_file", &[Value::Int(1)]);
assert!(
matches!(async_read_bad_arg, Value::Error(message) if message.contains("requires a string path argument"))
);
let async_write_bad_arg = call_native_function(
&mut interpreter,
"async_write_file",
&[Value::Str(Arc::new(file_path.clone())), Value::Int(1)],
);
assert!(
matches!(async_write_bad_arg, Value::Error(message) if message.contains("requires a string content argument"))
);
let write_promise = call_native_function(
&mut interpreter,
"async_write_file",
&[
Value::Str(Arc::new(file_path.clone())),
Value::Str(Arc::new("release-hardening-async".to_string())),
],
);
let write_result = await_native_promise(write_promise);
assert!(matches!(write_result, Ok(Value::Bool(true))));
let read_promise = call_native_function(
&mut interpreter,
"async_read_file",
&[Value::Str(Arc::new(file_path.clone()))],
);
let read_result = await_native_promise(read_promise);
assert!(
matches!(read_result, Ok(Value::Str(content)) if content.as_ref() == "release-hardening-async")
);
let _ = std::fs::remove_file(file_path);
}
#[test]
fn test_release_hardening_channel_and_task_handle_contracts() {
let mut interpreter = Interpreter::new();
let channel_with_args = call_native_function(&mut interpreter, "channel", &[Value::Int(1)]);
assert!(
matches!(channel_with_args, Value::Error(message) if message.contains("channel() expects 0 arguments"))
);
let channel_value = call_native_function(&mut interpreter, "channel", &[]);
assert!(matches!(channel_value, Value::Channel(_)));
let await_task_missing = call_native_function(&mut interpreter, "await_task", &[]);
assert!(
matches!(await_task_missing, Value::Error(message) if message.contains("await_task() expects 1 argument"))
);
let await_task_bad_type =
call_native_function(&mut interpreter, "await_task", &[Value::Int(1)]);
assert!(
matches!(await_task_bad_type, Value::Error(message) if message.contains("await_task() requires a TaskHandle argument"))
);
let cancel_task_missing = call_native_function(&mut interpreter, "cancel_task", &[]);
assert!(
matches!(cancel_task_missing, Value::Error(message) if message.contains("cancel_task() expects 1 argument"))
);
let cancel_task_bad_type =
call_native_function(&mut interpreter, "cancel_task", &[Value::Int(1)]);
assert!(
matches!(cancel_task_bad_type, Value::Error(message) if message.contains("cancel_task() requires a TaskHandle argument"))
);
let spawn_bad_arg = call_native_function(&mut interpreter, "spawn_task", &[Value::Int(1)]);
assert!(
matches!(spawn_bad_arg, Value::Error(message) if message.contains("requires an async function argument"))
);
let task_handle =
call_native_function(&mut interpreter, "spawn_task", &[noop_spawnable_function()]);
assert!(matches!(task_handle, Value::TaskHandle { .. }));
let await_task_promise =
call_native_function(&mut interpreter, "await_task", &[task_handle.clone()]);
let await_task_result = await_native_promise(await_task_promise);
assert!(matches!(await_task_result, Ok(Value::Null)));
let await_task_consumed =
call_native_function(&mut interpreter, "await_task", &[task_handle.clone()]);
let await_task_consumed_result = await_native_promise(await_task_consumed);
assert!(
matches!(await_task_consumed_result, Err(message) if message.contains("already consumed"))
);
let cancel_target =
call_native_function(&mut interpreter, "spawn_task", &[noop_spawnable_function()]);
let cancel_result =
call_native_function(&mut interpreter, "cancel_task", &[cancel_target.clone()]);
assert!(matches!(cancel_result, Value::Bool(true)));
let cancel_again_result =
call_native_function(&mut interpreter, "cancel_task", &[cancel_target.clone()]);
assert!(matches!(cancel_again_result, Value::Bool(false)));
let await_cancelled =
call_native_function(&mut interpreter, "await_task", &[cancel_target]);
let await_cancelled_result = await_native_promise(await_cancelled);
assert!(
matches!(await_cancelled_result, Err(message) if message.contains("already consumed"))
);
}
#[test]
fn test_release_hardening_system_operation_contracts() {
let mut interpreter = Interpreter::new();
let sleep_missing_args = call_native_function(&mut interpreter, "sleep", &[]);
assert!(
matches!(sleep_missing_args, Value::Error(message) if message.contains("expects 1 argument"))
);
let sleep_wrong_type = call_native_function(
&mut interpreter,
"sleep",
&[Value::Str(Arc::new("1".to_string()))],
);
assert!(
matches!(sleep_wrong_type, Value::Error(message) if message.contains("requires a number argument"))
);
let sleep_negative = call_native_function(&mut interpreter, "sleep", &[Value::Int(-1)]);
assert!(
matches!(sleep_negative, Value::Error(message) if message.contains("non-negative milliseconds"))
);
let sleep_success = call_native_function(&mut interpreter, "sleep", &[Value::Int(0)]);
assert!(matches!(sleep_success, Value::Int(0)));
let execute_missing_args = call_native_function(&mut interpreter, "execute", &[]);
assert!(
matches!(execute_missing_args, Value::Error(message) if message.contains("expects 1 argument"))
);
let execute_wrong_type =
call_native_function(&mut interpreter, "execute", &[Value::Int(1)]);
assert!(
matches!(execute_wrong_type, Value::Error(message) if message.contains("requires a string command"))
);
let execute_extra_arg = call_native_function(
&mut interpreter,
"execute",
&[Value::Str(Arc::new("echo release-hardening-system".to_string())), Value::Int(1)],
);
assert!(
matches!(execute_extra_arg, Value::Error(message) if message.contains("expects 1 argument"))
);
let execute_success = call_native_function(
&mut interpreter,
"execute",
&[Value::Str(Arc::new("echo release-hardening-system".to_string()))],
);
assert!(
matches!(execute_success, Value::Str(output) if output.as_ref().contains("release-hardening-system"))
);
let input_wrong_type = call_native_function(&mut interpreter, "input", &[Value::Int(1)]);
assert!(
matches!(input_wrong_type, Value::Error(message) if message.contains("requires a string prompt"))
);
let input_extra_arg = call_native_function(
&mut interpreter,
"input",
&[
Value::Str(Arc::new("prompt".to_string())),
Value::Str(Arc::new("extra".to_string())),
],
);
assert!(
matches!(input_extra_arg, Value::Error(message) if message.contains("expects 0-1 arguments"))
);
let exit_extra_arg =
call_native_function(&mut interpreter, "exit", &[Value::Int(1), Value::Int(2)]);
assert!(
matches!(exit_extra_arg, Value::Error(message) if message.contains("expects 0-1 arguments"))
);
let exit_wrong_type = call_native_function(
&mut interpreter,
"exit",
&[Value::Str(Arc::new("bad".to_string()))],
);
assert!(
matches!(exit_wrong_type, Value::Error(message) if message.contains("requires a numeric exit code"))
);
}
#[test]
fn test_release_hardening_contains_index_of_argument_and_polymorphic_contracts() {
let mut interpreter = Interpreter::new();
let contains_missing_args = call_native_function(&mut interpreter, "contains", &[]);
assert!(
matches!(contains_missing_args, Value::Error(message) if message.contains("contains() requires two arguments"))
);
let index_of_missing_args = call_native_function(&mut interpreter, "index_of", &[]);
assert!(
matches!(index_of_missing_args, Value::Error(message) if message.contains("index_of() requires two arguments"))
);
let contains_array = call_native_function(
&mut interpreter,
"contains",
&[Value::Array(std::sync::Arc::new(vec![Value::Int(1), Value::Int(2)])), Value::Int(2)],
);
assert!(matches!(contains_array, Value::Bool(true)));
let index_of_array = call_native_function(
&mut interpreter,
"index_of",
&[
Value::Array(std::sync::Arc::new(vec![Value::Int(10), Value::Int(20)])),
Value::Int(20),
],
);
assert!(matches!(index_of_array, Value::Int(1)));
}
#[test]
fn test_release_hardening_len_polymorphic_contracts() {
let mut interpreter = Interpreter::new();
let string_len = call_native_function(
&mut interpreter,
"len",
&[Value::Str(Arc::new("ruff".to_string()))],
);
assert!(matches!(string_len, Value::Int(4)));
let array_len = call_native_function(
&mut interpreter,
"len",
&[Value::Array(Arc::new(vec![Value::Int(1), Value::Int(2)]))],
);
assert!(matches!(array_len, Value::Int(2)));
let mut dict = crate::interpreter::DictMap::default();
dict.insert("a".into(), Value::Int(1));
dict.insert("b".into(), Value::Int(2));
let dict_len =
call_native_function(&mut interpreter, "len", &[Value::Dict(Arc::new(dict))]);
assert!(matches!(dict_len, Value::Int(2)));
let bytes_len =
call_native_function(&mut interpreter, "len", &[Value::Bytes(vec![1, 2, 3])]);
assert!(matches!(bytes_len, Value::Int(3)));
let set_len = call_native_function(
&mut interpreter,
"len",
&[Value::Set(vec![Value::Int(1), Value::Int(2), Value::Int(3)])],
);
assert!(matches!(set_len, Value::Int(3)));
let queue_len = call_native_function(
&mut interpreter,
"len",
&[Value::Queue(std::collections::VecDeque::from(vec![Value::Int(1), Value::Int(2)]))],
);
assert!(matches!(queue_len, Value::Int(2)));
let stack_len = call_native_function(
&mut interpreter,
"len",
&[Value::Stack(vec![Value::Int(1), Value::Int(2), Value::Int(3), Value::Int(4)])],
);
assert!(matches!(stack_len, Value::Int(4)));
let fallback_len = call_native_function(&mut interpreter, "len", &[Value::Null]);
assert!(matches!(fallback_len, Value::Int(0)));
let missing_args_len = call_native_function(&mut interpreter, "len", &[]);
assert!(matches!(missing_args_len, Value::Int(0)));
}
#[test]
fn test_release_hardening_type_and_is_introspection_contracts() {
let mut interpreter = Interpreter::new();
let type_string = call_native_function(
&mut interpreter,
"type",
&[Value::Str(Arc::new("ruff".to_string()))],
);
assert!(matches!(type_string, Value::Str(name) if name.as_ref() == "string"));
let type_array = call_native_function(
&mut interpreter,
"type",
&[Value::Array(Arc::new(vec![Value::Int(1)]))],
);
assert!(matches!(type_array, Value::Str(name) if name.as_ref() == "array"));
let type_null = call_native_function(&mut interpreter, "type", &[Value::Null]);
assert!(matches!(type_null, Value::Str(name) if name.as_ref() == "null"));
let type_missing = call_native_function(&mut interpreter, "type", &[]);
assert!(
matches!(type_missing, Value::Error(message) if message.contains("type() requires one argument"))
);
let type_extra =
call_native_function(&mut interpreter, "type", &[Value::Int(1), Value::Int(2)]);
assert!(
matches!(type_extra, Value::Error(message) if message.contains("type() requires one argument"))
);
let is_int_true = call_native_function(&mut interpreter, "is_int", &[Value::Int(7)]);
assert!(matches!(is_int_true, Value::Bool(true)));
let is_int_false = call_native_function(&mut interpreter, "is_int", &[Value::Float(7.0)]);
assert!(matches!(is_int_false, Value::Bool(false)));
let is_int_missing = call_native_function(&mut interpreter, "is_int", &[]);
assert!(matches!(is_int_missing, Value::Bool(false)));
let is_int_extra =
call_native_function(&mut interpreter, "is_int", &[Value::Int(7), Value::Int(8)]);
assert!(
matches!(is_int_extra, Value::Error(message) if message.contains("is_int() expects 1 argument"))
);
let is_float_true =
call_native_function(&mut interpreter, "is_float", &[Value::Float(7.5)]);
assert!(matches!(is_float_true, Value::Bool(true)));
let is_float_false = call_native_function(&mut interpreter, "is_float", &[Value::Int(7)]);
assert!(matches!(is_float_false, Value::Bool(false)));
let is_float_extra =
call_native_function(&mut interpreter, "is_float", &[Value::Float(7.5), Value::Int(8)]);
assert!(
matches!(is_float_extra, Value::Error(message) if message.contains("is_float() expects 1 argument"))
);
let is_string_true = call_native_function(
&mut interpreter,
"is_string",
&[Value::Str(Arc::new("x".to_string()))],
);
assert!(matches!(is_string_true, Value::Bool(true)));
let is_string_false =
call_native_function(&mut interpreter, "is_string", &[Value::Bool(true)]);
assert!(matches!(is_string_false, Value::Bool(false)));
let is_string_extra = call_native_function(
&mut interpreter,
"is_string",
&[Value::Str(Arc::new("x".to_string())), Value::Int(1)],
);
assert!(
matches!(is_string_extra, Value::Error(message) if message.contains("is_string() expects 1 argument"))
);
let is_bool_true = call_native_function(&mut interpreter, "is_bool", &[Value::Bool(true)]);
assert!(matches!(is_bool_true, Value::Bool(true)));
let is_bool_false = call_native_function(
&mut interpreter,
"is_bool",
&[Value::Str(Arc::new("true".to_string()))],
);
assert!(matches!(is_bool_false, Value::Bool(false)));
let is_bool_extra = call_native_function(
&mut interpreter,
"is_bool",
&[Value::Bool(true), Value::Bool(false)],
);
assert!(
matches!(is_bool_extra, Value::Error(message) if message.contains("is_bool() expects 1 argument"))
);
let is_array_true =
call_native_function(&mut interpreter, "is_array", &[Value::Array(Arc::new(vec![]))]);
assert!(matches!(is_array_true, Value::Bool(true)));
let is_array_false = call_native_function(&mut interpreter, "is_array", &[Value::Null]);
assert!(matches!(is_array_false, Value::Bool(false)));
let is_array_extra = call_native_function(
&mut interpreter,
"is_array",
&[Value::Array(Arc::new(vec![])), Value::Int(1)],
);
assert!(
matches!(is_array_extra, Value::Error(message) if message.contains("is_array() expects 1 argument"))
);
let mut dict = crate::interpreter::DictMap::default();
dict.insert("k".into(), Value::Int(1));
let is_dict_true =
call_native_function(&mut interpreter, "is_dict", &[Value::Dict(Arc::new(dict))]);
assert!(matches!(is_dict_true, Value::Bool(true)));
let is_dict_false =
call_native_function(&mut interpreter, "is_dict", &[Value::Array(Arc::new(vec![]))]);
assert!(matches!(is_dict_false, Value::Bool(false)));
let is_dict_extra = call_native_function(
&mut interpreter,
"is_dict",
&[Value::Dict(Arc::new(crate::interpreter::DictMap::default())), Value::Int(1)],
);
assert!(
matches!(is_dict_extra, Value::Error(message) if message.contains("is_dict() expects 1 argument"))
);
let is_null_true = call_native_function(&mut interpreter, "is_null", &[Value::Null]);
assert!(matches!(is_null_true, Value::Bool(true)));
let is_null_false = call_native_function(&mut interpreter, "is_null", &[Value::Int(0)]);
assert!(matches!(is_null_false, Value::Bool(false)));
let is_null_extra =
call_native_function(&mut interpreter, "is_null", &[Value::Null, Value::Int(0)]);
assert!(
matches!(is_null_extra, Value::Error(message) if message.contains("is_null() expects 1 argument"))
);
let is_function_true = call_native_function(
&mut interpreter,
"is_function",
&[Value::NativeFunction("len".to_string())],