-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcifa_unit_test.cpp
More file actions
3181 lines (2964 loc) · 108 KB
/
Copy pathcifa_unit_test.cpp
File metadata and controls
3181 lines (2964 loc) · 108 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
#include "../Cifa.h"
#include <filesystem>
#include <cstdio>
#include <print>
#include <numeric>
#include <format>
#include "../CifaBytecode.h"
#include "test_process.h"
namespace cifa {
// A test-only factory runs the same suite with either explicit resource.
static memory::Resource test_resource = memory::default_resource();
class TestBytecode : public CifaBytecode {
public:
TestBytecode() : CifaBytecode(test_resource) {}
};
}
using namespace cifa;
using DirectCifa = Cifa;
static double template_square(double x)
{
return x * x;
}
static double template_add(double a, double b)
{
return a + b;
}
static int template_trunc(double x)
{
return int(x);
}
static void template_set_flag(Object flag)
{
(void)flag;
}
static double template_menu(double x, double y, Object choices, double count)
{
return x + y + count + (choices.hasValue() ? 0.0 : 1.0);
}
template <typename Backend>
struct BackendTests
{
#define Cifa Backend
bool local_array_store_test()
{
Cifa c;
const auto result = c.run_script(R"(
int write_values() {
int values[0];
values[3] = 3.9;
values[1] = -2.9;
return values[3] * 10 + values[1];
}
return write_values();
)");
return result.hasValue() && result.toInt() == 28 && !c.has_runtime_error();
}
bool method_receiver_error_order_test()
{
const auto run_case = [](Cifa& interpreter)
{
interpreter.set_output_error(false);
int touches = 0;
if constexpr (std::same_as<Cifa, TestBytecode>)
{
interpreter.register_native_function("touch", [&touches](TestBytecode::NativeCallContext& context)
{
++touches;
context.set_result(std::int64_t{0});
});
}
else
{
interpreter.register_function("touch", [&touches](ObjectVector&) -> Object
{
++touches;
return 0;
});
}
const auto result = interpreter.run_script("value = 1; value.insert(touch(), touch());");
return result.getSpecialType() == "Error" && interpreter.has_runtime_error() && touches == 0;
};
Cifa interpreter;
return run_case(interpreter);
}
bool register_function_test()
{
Cifa c1;
if constexpr (std::same_as<Cifa, TestBytecode>)
c1.register_native_function("sin", [](TestBytecode::NativeCallContext& context)
{ context.set_result(std::sin(context.to_number(0))); });
else
c1.register_function("sin", [](ObjectVector& d) { return std::sin(d[0].toDouble()); });
const auto o = c1.run_script(R"(
double PI = 3.141592653589793238462643383279;
double return_val = 0;
return_val += sin(0);
return_val += sin(PI * 0.5);
return_val += sin(PI);
return return_val;
)");
return o.hasValue() && o.isNumber() && o.isType<double>()
&& std::fabs(o.ref<double>() - 1.0) <= std::numeric_limits<double>::epsilon();
}
bool register_function_template_test()
{
Cifa c;
if constexpr (std::same_as<Cifa, TestBytecode>)
{
c.register_native_function("square", [](TestBytecode::NativeCallContext& context)
{ const double value = context.to_number(0); context.set_result(value * value); });
c.register_native_function("add", [](TestBytecode::NativeCallContext& context)
{ context.set_result(context.to_number(0) + context.to_number(1)); });
c.register_native_function("trunc", [](TestBytecode::NativeCallContext& context)
{ context.set_result(static_cast<std::int64_t>(context.to_number(0))); });
c.register_native_function("set_flag", [](TestBytecode::NativeCallContext& context)
{ (void)context.argument_count(); context.set_empty_result(); });
}
else
{
c.register_function("square", template_square);
c.register_function("add", template_add);
c.register_function("trunc", template_trunc);
c.register_function("set_flag", template_set_flag);
}
const auto o = c.run_script(R"(
set_flag(1);
return square(3) + add(2, 4) + trunc(1.8);
)");
return o.isNumber() && o.toDouble() == 16.0;
}
bool registration_name_validation_test()
{
Cifa c;
c.set_output_error(false);
int context = 0;
const bool valid_function = [&]()
{
if constexpr (std::same_as<Cifa, TestBytecode>)
return c.register_native_function("valid_function", [](TestBytecode::NativeCallContext& context)
{ context.set_result(context.to_number(0)); });
else return c.register_function("valid_function", template_square);
}();
if (!valid_function || !c.register_parameter("valid_parameter", 1)
|| !c.register_vector("valid_vector", std::vector<int>{1, 2})
|| !c.register_user_data("valid_context", &context))
{
return false;
}
Cifa invalid;
invalid.set_output_error(false);
const bool template_registration_failed = [&]()
{
if constexpr (std::same_as<Cifa, TestBytecode>)
return !invalid.register_native_function("1bad", [](TestBytecode::NativeCallContext&) {});
else return !invalid.register_function("1bad", template_square);
}()
&& invalid.has_runtime_error()
&& invalid.get_runtime_error().find("invalid registration name '1bad'") != std::string::npos;
Cifa default_output;
const bool standard_registration_failed = !default_output.register_parameter("bad-key", 1)
&& default_output.has_runtime_error()
&& default_output.get_runtime_error().find("invalid registration name 'bad-key'") != std::string::npos;
return Cifa::is_valid_key("valid_key") && Cifa::is_valid_key("_value2")
&& !Cifa::is_valid_key("1bad") && !Cifa::is_valid_key("bad-key") && !Cifa::is_valid_key("return")
&& Cifa::revise_key("1bad-key") == "_bad_key" && Cifa::revise_key("return") == "return_"
&& Cifa::revise_key("") == "_" && template_registration_failed && standard_registration_failed;
}
bool exit_function_test()
{
{
Cifa c;
c.run_script("value = 1; exit(); value = 2;");
const auto result = c.run_script("return value;");
if (!result.isNumber() || result.toDouble() != 1.0) return false;
}
{
Cifa c;
c.run_script("count = 0; running = 1; while (running) { count++; exit(); count++; }");
const auto result = c.run_script("return count;");
if (!result.isNumber() || result.toDouble() != 1.0) return false;
}
return true;
}
bool runtime_error_abort_test()
{
const std::vector<std::string> scripts = {
"sum = 0; for (int i = 0; i < 10; i++) { sum += missing_value(i); } return sum;",
"for (int i = !missing_value(); i < 10; i++) { touch(); }", "for (int i = 0; missing_value(); i++) { touch(); }",
"for (int i = 0; i < 10; i += !missing_value()) { }", "while (missing_value()) { touch(); }",
"int i = 0; while (i < 10) { sum += !missing_value(); i++; }", "do { sum += !missing_value(); } while (sum < 10);",
"do { } while (missing_value());", "for (item : missing_value()) { touch(); }",
"values = {1, 2}; for (item : values) { sum += !missing_value(); touch(); }", "bad() { sum += !missing_value(); touch(); } bad();",
"touch(!missing_value());", "sum = !missing_value();", "run_string(\"bad = {1}; return !bad;\");",
"for (int i = 0; i < 10; i++) { run_string(\"bad = {1}; return !bad;\"); touch(); }",
"int i = 0; while (i < 10) { run_string(\"bad = {1}; return !bad;\"); i++; touch(); }",
"do { run_string(\"bad = {1}; return !bad;\"); touch(); } while (1);",
"for (; run_string(\"bad = {1}; return !bad;\");) { touch(); }", "while (run_string(\"bad = {1}; return !bad;\")) { touch(); }",
"do {} while (run_string(\"bad = {1}; return !bad;\"));", "convert({1});"};
for (const auto& script : scripts)
{
Cifa interpreter;
interpreter.set_output_error(false);
int calls = 0;
if constexpr (std::same_as<Cifa, TestBytecode>)
{
interpreter.register_native_function("touch", [&calls](TestBytecode::NativeCallContext& context) { ++calls; context.set_result(std::int64_t{0}); });
interpreter.register_native_function("missing_value", [](TestBytecode::NativeCallContext& context) { context.set_empty_result(); });
interpreter.register_native_function("convert", [&calls](TestBytecode::NativeCallContext& context)
{ const auto value = context.to_number(0); if (!context.is_number(0)) return; ++calls; context.set_result(value); });
}
else
{
interpreter.register_function("touch", [&calls](ObjectVector&) -> Object { ++calls; return 0; });
interpreter.register_function("missing_value", [](ObjectVector&) -> Object { return Object(); });
interpreter.register_function("convert", [&calls, &interpreter](ObjectVector& arguments) -> Object
{ const auto value = arguments[0].toDouble(); if (interpreter.has_runtime_error()) return Object(); ++calls; return value; });
}
auto result = interpreter.run_script("sum = 7; " + script + " touch();");
if (result.getSpecialType() != "Error" || !interpreter.has_runtime_error() || calls != 0)
{
std::println(stderr, "Runtime abort failed: {} (calls={}, result={})\n{}{}",
script, calls, result.getSpecialType(), interpreter.get_errors_str(), interpreter.get_runtime_error());
return false;
}
if (script.find("run_string(") != std::string::npos && interpreter.is_exit_requested())
{
std::println(stderr, "Nested exit flag leaked: {}", script);
return false;
}
result = interpreter.run_script("touch(); return 42;");
if (interpreter.has_error() || interpreter.has_runtime_error()
|| !result.isNumber() || result.toInt() != 42 || calls != 1)
{
return false;
}
}
Cifa interpreter;
interpreter.set_output_error(false);
const auto exit_result = interpreter.run_script("total = 0; for (int i = 0; i < 3; i++) { run_string(\"exit();\"); total++; } return total;");
if (interpreter.has_error() || interpreter.has_runtime_error() || interpreter.is_exit_requested()
|| !exit_result.isNumber() || exit_result.toInt() != 3)
{
return false;
}
for (int attempt = 0; attempt < 2; ++attempt)
{
auto result = interpreter.run_script("stored = 7; bad = {1}; !bad; stored = 9;");
if (result.getSpecialType() != "Error" || !interpreter.has_runtime_error()
|| interpreter.get_runtime_error().find("type conversion failed") == std::string::npos)
{
return false;
}
result = interpreter.run_script("return stored;");
if (interpreter.has_error() || interpreter.has_runtime_error()
|| !result.isNumber() || result.toInt() != 7)
{
return false;
}
}
return true;
}
bool object_conversion_fallback_test()
{
Object value(std::string("not a number"));
auto& invalid = value.ref<ObjectMap>();
if (!invalid.empty())
{
return false;
}
invalid["discarded"] = 1;
const Object& constant = value;
return constant.ref<ObjectMap>().empty() && value.toString() == "not a number";
}
bool typed_function_argument_error_test()
{
Cifa c;
c.set_output_error(false);
if constexpr (std::same_as<Cifa, TestBytecode>)
c.register_native_function("menu", [](TestBytecode::NativeCallContext& context) { context.set_result(context.to_number(3)); });
else
c.register_function("menu", template_menu);
auto o = c.run_script("strs = {1, 2}; menu(85, 100, strs, strs);");
return o.getSpecialType() == "Error"
&& c.get_runtime_error().find("variable 'strs'") != std::string::npos
&& c.get_runtime_error().find("to double") != std::string::npos;
}
bool object_vector_argument_error_test()
{
if constexpr (std::same_as<Cifa, TestBytecode>)
{
const auto expect_conversion_error = [](bool string_conversion)
{
Cifa c;
c.set_output_error(false);
c.register_native_function("menu", [string_conversion](TestBytecode::NativeCallContext& context)
{
if (string_conversion) context.to_string(3);
else context.to_number(3);
});
const auto result = c.run_script("strs = {1, 2}; menu(85, 100, strs, strs);");
return result.getSpecialType() == "Error"
&& c.get_runtime_error().find("variable 'strs'") != std::string::npos;
};
return expect_conversion_error(false) && expect_conversion_error(true);
}
else
{
const auto expect_conversion_error = [](const typename Backend::func_type& menu, const std::string& target_type)
{
Cifa c;
c.set_output_error(false);
c.register_function("menu", menu);
auto result = c.run_script("strs = {1, 2}; menu(85, 100, strs, strs);");
return result.getSpecialType() == "Error"
&& c.get_runtime_error().find("variable 'strs'") != std::string::npos
&& c.get_runtime_error().find(target_type) != std::string::npos;
};
return expect_conversion_error([](ObjectVector& args) -> Object
{
return Object(args[3].toDouble());
}, "to double")
&& expect_conversion_error([](ObjectVector& args) -> Object
{
Object value = args[3];
return Object(value.toDouble());
}, "to double")
&& expect_conversion_error([](ObjectVector& args) -> Object
{
return Object(args[3].toString());
}, "to string")
&& expect_conversion_error([](ObjectVector& args) -> Object
{
return Object(args[3].ref<ObjectMap>().size());
}, typeid(ObjectMap).name());
}
}
bool builtin_math_function_test()
{
Cifa c;
auto o = c.run_script(R"(
double total = 0;
total += cbrt(27);
total += log2(8);
total += atan2(0, -1) > 3;
total += hypot(3, 4);
total += fmod(7, 4);
total += remainder(7, 4);
total += trunc(1.8);
total += copysign(2, -1);
total += fdim(5, 3);
total += fmax(2, 5);
total += fmin(2, 5);
return total;
)");
return o.isNumber() && std::fabs(o.toDouble() - 22.0) < 1e-9;
}
bool builtin_type_function_test()
{
Cifa c;
c.set_output_error(false);
c.run_script("auto pending_value;");
if (!c.has_error() || c.get_errors_str().find("auto variable 'pending_value' requires an initializer") == std::string::npos)
{
return false;
}
auto o = c.run_script(R"(
int empty_value;
auto pending_value = 1;
arr = {1, 2};
m["x"] = 1;
auto string_size = size("abc");
auto array_size = size(arr);
auto pushed_size = arr.push_back(3);
auto array_contains = arr.contains(3);
auto cleared_size = arr.clear();
auto erased_size = m.erase("x");
auto map_contains = m.contains("x");
return type(empty_value) == "int"
&& type(pending_value) == "int"
&& type(1) == "int"
&& type(1.0f) == "double"
&& type(1.0) == "double"
&& type(true) == "bool"
&& type("abc") == "string"
&& type(arr) == "array"
&& type(m) == "map"
&& type(string_size) == "int"
&& type(array_size) == "int"
&& type(pushed_size) == "int"
&& type(cleared_size) == "int"
&& type(erased_size) == "int"
&& type(array_contains) == "bool"
&& type(map_contains) == "bool";
)");
return o.isNumber() && o.toDouble() == 1.0;
}
bool loop_math_test()
{
Cifa c1;
std::string script_code = R"(
int i;
double sum = 0.0, product = 1.0, division = 100.0, difference = 50.0;
double total_result = 0.0;
for (i = 1; i <= 5; i++) {
sum += i;
}
while (i <= 6) {
product *= i;
i++;
}
do {
difference -= i;
i++;
} while (difference > 0);
division /= 5;
total_result = sum + product + division + difference;
return total_result;
)";
auto o = c1.run_script(script_code);
if (o.hasValue() && o.isNumber() && o.isType<double>())
{
return (std::fabs(o.ref<double>() - 34) <= std::numeric_limits<double>::epsilon());
}
else
{
return false;
}
}
bool loop_control_test()
{
Cifa c;
std::string script = R"(
int sum = 0;
for (int i = 0; i < 10; i++) {
if (i % 2 == 0) continue; // 跳过偶数
if (i > 7) break; // 遇到 9 跳出
sum += i;
}
return sum; // 1 + 3 + 5 + 7 = 16
)";
auto o = c.run_script(script);
return o.toInt() == 16;
}
bool control_state_test()
{
Cifa c;
c.set_output_error(false);
auto result = c.run_script(R"(
int sum = 0;
for (int i = 0; i < 5; i++) {
switch (i) {
case 1: continue;
case 3: break;
default: sum += i;
}
sum += 10;
}
{
goto done;
sum = 999;
}
done:
return sum;
)");
if (c.has_error() || c.has_runtime_error() || result.toInt() != 46) return false;
const auto rejects = [](const std::string& script, const std::string& message)
{
Cifa invalid;
invalid.set_output_error(false);
invalid.run_script(script);
const auto error = invalid.get_errors_str();
return invalid.has_error() && error.find(message) != std::string::npos
&& error.find(script) != std::string::npos && error.find('^') != std::string::npos;
};
if (!rejects("break;", "break statement is not within a loop or switch")
|| !rejects("continue;", "continue statement is not within a loop")
|| !rejects("switch (1) { case 1: continue; }", "continue statement is not within a loop"))
{
return false;
}
Cifa switch_break;
switch_break.set_output_error(false);
const auto switch_result = switch_break.run_script("int value = 1; switch (value) { case 1: value = 7; break; default: value = 9; } return value;");
return !switch_break.has_error() && !switch_break.has_runtime_error()
&& switch_result.isNumber() && switch_result.toInt() == 7;
}
bool ternary_operator_test()
{ // 测试嵌套三目运算
Cifa c;
std::string script = R"(
int a = 1, b = 0;
return a > b ? (b > a ? 10 : 20) : 30;
)";
auto o = c.run_script(script);
return o.hasValue() && o.toInt() == 20;
}
bool logical_short_circuit_test()
{
Cifa c;
auto o = c.run_script(R"(
int a = 0, b = 0, c = 0, d = 0;
int first = (0 && a++) || (1 && (b++ == 0)) || c++;
int second = (1 || d++) && (0 || (++d == 1));
return a + b * 10 + c * 100 + d * 1000 + first * 10000 + second * 100000;
)");
return o.isNumber() && o.toInt() == 111010;
}
bool numeric_literal_radix_test()
{
Cifa c;
auto o = c.run_script(R"(
return 42 + 1.5e2 + 0xFF + 0X10 + 0b1010 + 0B11 + 077;
)");
return o.isNumber() && o.toInt() == 539;
}
bool switch_case_test()
{ // Switch-Case 完备性测试
Cifa c;
std::string script = R"(
int x = 2;
int res = 0;
switch(x) {
case 1: res = 10; break;
case 2: res = 20; // 故意不写break看看?
case 3: res = 30; break;
default: res = 40;
}
return res;
)";
auto o = c.run_script(script);
return o.hasValue() && o.toInt() == 30;
}
bool recursion_test()
{ // 递归函数测试
Cifa c;
std::string script = R"(
double factorial(double n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
return factorial(5);
)";
auto o = c.run_script(script);
return o.hasValue() && std::fabs(o.toDouble() - 120.0) < 1e-9;
}
bool script_void_function_test()
{
Cifa c;
const std::string script = R"(
total = 0;
empty();
increment();
add(4);
void empty() {}
void increment() { total += 1; }
void add(int amount) { total += amount; }
return total;
)";
auto result = c.run_script(script);
if (c.has_error() || c.has_runtime_error() || !result.isNumber() || result.toInt() != 5)
{
return false;
}
for (int attempt = 0; attempt < 2; ++attempt)
{
result = c.run_script(script);
if (c.has_error() || c.has_runtime_error() || !result.isNumber() || result.toInt() != 5)
{
return false;
}
}
result = c.run_script("increment(); add(3); return total;");
return !c.has_error() && !c.has_runtime_error() && result.isNumber() && result.toInt() == 9;
}
bool script_function_return_check_test()
{
const std::vector<std::string> invalid_scripts = {
R"(int sum = 0;
int myrandom(int a) {
}
for (int i = 0; i < 10; i++) {
sum += myrandom(i);
}
return sum;)",
"empty() {} empty() + 1;",
"empty() {} value = empty(); return value + 1;",
"empty() {} if (empty()) return 1;",
"empty() {} while (empty()) {}",
"empty() {} do {} while (empty());",
"empty() {} for (int index = 0; empty(); index++) {}",
"empty() {} for (item : empty()) {}",
"empty() {} values = {1, 2}; return values[empty()];",
"empty() {} values = {empty()}; return values[0] + 1;",
"empty() {} return to_number(empty());",
"empty() {} wrapper() { return empty(); } return wrapper() + 1;",
"empty() { 42; } return empty() + 1;",
"empty() { return; } return empty() + 1;",
"empty() {} empty(value) { return value; } return empty() + 1;",
"value(number) { if (number > 0) return number; } return value(-1) + 1;",
"empty() {} addone(value) { return value + 1; } return addone(empty());"
};
for (const auto& script : invalid_scripts)
{
Cifa interpreter;
interpreter.set_output_error(false);
auto result = interpreter.run_script(script);
const auto error = interpreter.get_runtime_error();
if (result.getSpecialType() != "Error" || !interpreter.has_runtime_error() || interpreter.has_error()
|| error.find("has no return value") == std::string::npos || error.find("^") == std::string::npos)
{
std::println(stderr, "NoValue use did not fail: {}\n{}", script, error);
return false;
}
if (&script == &invalid_scripts.front())
{
const std::string header = "<script>:5, col 12: ";
const std::string expected = header + " sum += myrandom(i);\n"
+ std::string(header.size() + 11, ' ') + "^\n";
if (error.find(expected) == std::string::npos)
{
std::print(stderr, "NoValue call position mismatch:\n{}Expected:\n{}", error, expected);
return false;
}
}
}
for (const bool delayed : {false, true})
{
Cifa interpreter;
interpreter.set_output_error(false);
const std::string script = delayed
? "empty() {}\nsaved = empty();\nreturn abs(saved);"
: "empty() {}\nreturn abs(empty());";
auto result = interpreter.run_script(script);
const auto error = interpreter.get_runtime_error();
const std::string origin = delayed ? "<script>:2, col 9:" : "<script>:2, col 12:";
const std::string source_line = delayed ? "saved = empty();" : "return abs(empty());";
const std::string expected_source = "No return value originated at:\n" + origin + " " + source_line
+ "\n" + std::string(origin.size() + 1 + (delayed ? 8 : 11), ' ') + "^\n";
const auto position = error.find(origin);
if (result.getSpecialType() != "Error" || interpreter.has_error() || !interpreter.has_runtime_error()
|| error.find("function 'empty' has no return value") == std::string::npos || position == std::string::npos
|| error.find(expected_source) == std::string::npos
|| error.find("Call Stack (most recent call first):") == std::string::npos
|| error.find(origin, position + origin.size()) != std::string::npos
|| (delayed && error.find("<script>:3, col 12:") == std::string::npos))
{
std::println(stderr, "Invalid NoValue diagnostic frames:\n{}", error);
return false;
}
}
const std::vector<std::string> valid_scripts = {
"empty() {} empty(); return 42;",
"void empty() { return; } empty(); return 42;",
"empty() {} if (true) empty(); else empty(); return 42;",
"empty() {} for (int index = 0; index < 2; index++) empty(); return 42;",
"empty() {} for (empty(); 0; empty()) {} return 42;",
"empty() {} true ? empty() : empty(); return 42;",
"empty() {} (empty()); return 42;",
"empty() {} empty(), empty(); return 42;",
"empty() {} value = empty(); return 42;",
"empty() {} values = {empty()}; return 42;",
"empty() {} ignore(value) { return 42; } return ignore(empty());",
"empty() {} if (0) return empty() + 1; return 42;",
"empty() {} 0 && empty(); 1 || empty(); return 42;",
"empty() {} int i = 0; for (empty(); i < 2; empty()) { i++; } return 42;",
"value() {} value(number) { return number; } value(); return value(42);",
"return value(42); value(number) { return number; }",
"void value() { return 42; } return value();",
"value(number) { if (number > 0) return number; } value(-1); return value(42);"
};
for (const auto& script : valid_scripts)
{
Cifa interpreter;
interpreter.set_output_error(false);
auto result = interpreter.run_script(script);
if (interpreter.has_error() || interpreter.has_runtime_error()
|| !result.isNumber() || result.toInt() != 42)
{
std::println(stderr, "Valid return use rejected: {}\n{}{}", script,
interpreter.get_errors_str(), interpreter.get_runtime_error());
return false;
}
}
const std::vector<std::string> no_value_scripts = {
"empty() {} return empty();",
"empty() { 42; } return empty();",
"empty() { return; } return empty();",
"empty() {} value = empty(); return value;",
"empty() {} values = {empty()}; return values[0];",
"empty() {} wrapper() { return empty(); } return wrapper();",
"inner() { return 42; } outer() { inner(); } return outer();",
"empty() {} return true ? empty() : 1;",
"empty() {} empty(value) { return value; } return empty();",
"value(number) { if (number > 0) return number; } return value(-1);"
};
for (const auto& script : no_value_scripts)
{
Cifa interpreter;
interpreter.set_output_error(false);
auto result = interpreter.run_script(script);
if (interpreter.has_error() || interpreter.has_runtime_error() || result.getSpecialType() != "NoValue"
|| result.isNumber() || result.isType<std::string>())
{
std::println(stderr, "Missing NoValue result: {}\n{}{}", script,
interpreter.get_errors_str(), interpreter.get_runtime_error());
return false;
}
}
Cifa interpreter;
interpreter.set_output_error(false);
interpreter.run_script("saved() {}");
auto result = interpreter.run_script("return saved();");
if (interpreter.has_error() || interpreter.has_runtime_error() || result.getSpecialType() != "NoValue")
{
return false;
}
result = interpreter.run_script("return type(saved());");
if (interpreter.has_error() || interpreter.has_runtime_error()
|| !result.isType<std::string>() || result.toString() != "NoValue")
{
return false;
}
result = interpreter.run_script("value = saved(); return value + 1;");
if (result.getSpecialType() != "Error"
|| interpreter.get_runtime_error().find("function 'saved' has no return value") == std::string::npos)
{
return false;
}
result = interpreter.run_script("saved(); return 42;");
if (interpreter.has_error() || interpreter.has_runtime_error()
|| !result.isNumber() || result.toInt() != 42)
{
std::println(stderr, "Saved function call failed: {}{}", interpreter.get_errors_str(), interpreter.get_runtime_error());
return false;
}
result = interpreter.run_script("saved() { return 42; } return saved();");
if (interpreter.has_error() || interpreter.has_runtime_error() || !result.isNumber() || result.toInt() != 42)
{
return false;
}
interpreter.register_parameter("argument", 42);
for (int argument : {42, -1, 7})
{
interpreter.register_parameter("argument", argument);
result = interpreter.run_script("branch(number) { if (number > 0) return number; } return branch(argument);");
if (interpreter.has_error() || interpreter.has_runtime_error()
|| (argument > 0 && (!result.isNumber() || result.toInt() != argument))
|| (argument <= 0 && result.getSpecialType() != "NoValue"))
{
return false;
}
}
result = interpreter.run_script("stop() { exit(); } return stop() + 1;");
return !interpreter.has_error() && !interpreter.has_runtime_error() && interpreter.is_exit_requested();
}
bool script_function_argument_count_test()
{
const auto expect_runtime_error = [](const char* label, const std::string& script, const std::string& expected)
{
Cifa c;
c.set_output_error(false);
const auto result = c.run_script(script);
const std::string error = c.get_runtime_error();
if (result.getSpecialType() != "Error" || error.find(expected) == std::string::npos)
{
std::println(stderr, " {} failed: expected runtime error: {}\n actual: {}", label, expected, error);
return false;
}
std::println(stderr, " {}: {}", label, error);
return true;
};
{
Cifa c;
auto result = c.run_script(
"describe() { return 0; } "
"describe(value) { return value; } "
"describe(left, right) { return left + right; } "
"return describe() + describe(2) + describe(3, 4);");
if (!result.isNumber() || result.toDouble() != 9.0)
{
return false;
}
}
{
Cifa c;
auto result = c.run_script("same(value) { return value; } same(other) { return other + 10; } return same(1);");
if (!result.isNumber() || result.toDouble() != 11.0 || c.has_error())
{
return false;
}
result = c.run_script("same(number) { return number + 100; } return same(1);");
if (!result.isNumber() || result.toDouble() != 101.0 || c.has_error())
{
return false;
}
}
return expect_runtime_error("missing overload", "add(a, b) { return a + b; } return add(2);",
"no overload for 1 arguments; available: 2")
&& expect_runtime_error("extra argument overload", "add(a, b) { return a + b; } return add(2, 3, 4);",
"no overload for 3 arguments; available: 2")
&& [&]()
{
Cifa c;
c.set_output_error(false);
c.run_script("sqrt(value) { return value; }");
const std::string errors = c.get_errors_str();
return c.has_error() && errors.find("script function 'sqrt' conflicts with a host function") != std::string::npos
&& errors.find("^") != std::string::npos;
}();
}
bool script_function_global_scope_test()
{
Cifa c;
c.set_output_error(false);
int captured_value = 0;
if constexpr (std::same_as<Cifa, TestBytecode>)
c.register_native_function("capture", [&captured_value](TestBytecode::NativeCallContext& context)
{
captured_value = context.argument_count() == 0 ? 0 : static_cast<int>(context.to_integer(0));
context.set_empty_result();
});
else
c.register_function("capture", [&captured_value](ObjectVector& args) -> Object
{
captured_value = args.empty() ? 0 : args[0].toInt();
return Object();
});
auto global_result = c.run_script(R"(
b = 304;
update_b() {
capture(b);
b = b + 1;
return b;
}
result = update_b();
return b * 1000 + result;
)");
if (!global_result.isNumber() || global_result.toInt() != 305305 || captured_value != 304)
{
return false;
}
auto next_script_result = c.run_script("return 7;");
if (!next_script_result.isNumber() || next_script_result.toInt() != 7 || c.has_error())
{
return false;
}
auto persisted_function_result = c.run_script("b = 40; return update_b();");
if (!persisted_function_result.isNumber() || persisted_function_result.toInt() != 41 || c.has_error())
{
return false;
}
c.run_script("broken() { return missing_function(); }");
if (!c.has_error())
{
return false;
}
auto after_failed_definition = c.run_script("return 8;");
if (!after_failed_definition.isNumber() || after_failed_definition.toInt() != 8 || c.has_error())
{
return false;
}
auto shadow_result = c.run_script(R"(
b = 10;
add_one(b) {
b = b + 1;
return b;
}
result = add_one(20);
return b * 100 + result;
)");
return shadow_result.isNumber() && shadow_result.toInt() == 1021;
}
bool string_operation_test()
{ // 字符串操作与拼接测试
Cifa c;
std::string script = R"(
string s1 = "Hello ";
string s2 = "World";
return s1 + s2;
)";
auto o = c.run_script(script);
return o.hasValue() && o.isType<std::string>() && o.toString() == "Hello World";
}
bool string_compare_test()
{ // 字符串比较与跨行逻辑运算测试
Cifa c;
std::string script = R"(
return "abc" == "abc"
&& "abc" != "def";
)";
auto o = c.run_script(script);
return o.isNumber() && o.toDouble() == 1.0;
}
bool bitwise_operator_test()
{ // 位运算测试
Cifa c;
std::string script = R"(
int a = 5; // 0101
int b = 3; // 0011
int res1 = a & b; // 0001 (1)
int res2 = a | b; // 0111 (7)
int res3 = a ^ b; // 0110 (6)
int res4 = a << 1; // 1010 (10)
return res1 + res2 + res3 + res4; // 1 + 7 + 6 + 10 = 24
)";
auto o = c.run_script(script);
return o.toInt() == 24;
}
bool scope_shadowing_test()
{ // 变量作用域遮蔽测试
Cifa c;
std::string script = R"(
int x = 10;
int inner = 0;
{
int x = 15 + 5;
inner = x;
if (x == 20) {
int x = 30;
}
}
return x * 100 + inner;
)";
auto o = c.run_script(script);
return o.toInt() == 1020; // 融合表达式应写入内层声明,外部作用域不应受影响
}
bool complex_math_priority_test()
{ // 复杂算术优先级测试
Cifa c;
std::string script = R"(
return 2 + 3 * 4 / (1 + 1) - 5 % 2; // 2 + 12 / 2 - 1 = 2 + 6 - 1 = 7
)";
auto o = c.run_script(script);
return o.toInt() == 7;
}
bool same_precedence_left_assoc_test()
{ // 同优先级运算符应按 C++ 规则左结合,即 a/b*c == (a/b)*c,而非 a/(b*c)
Cifa c;
bool ok = true;
// 除后乘:100/10*2 == 20
ok = ok && c.run_script("return 100/10*2;").toInt() == 20;
// 乘后除:100*10/2 == 500
ok = ok && c.run_script("return 100*10/2;").toInt() == 500;
// 除后模:100/10%3 == 1