-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcifa_unit_test.cpp
More file actions
2482 lines (2270 loc) · 74.8 KB
/
Copy pathcifa_unit_test.cpp
File metadata and controls
2482 lines (2270 loc) · 74.8 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 <chrono>
#include <filesystem>
#include <iostream>
#include <numeric>
#include <sstream>
using namespace 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);
}
bool register_function_test()
{
Cifa c1;
c1.register_function("sin", [](ObjectVector& d)
{
return sin(d[0]);
});
std::string script_code = 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;
)";
auto o = c1.run_script(script_code);
if (o.hasValue() && o.isNumber() && o.isType<double>())
{
return (std::fabs(o.ref<double>() - 1.0) <= std::numeric_limits<double>::epsilon());
}
else
{
return false;
}
}
bool register_function_template_test()
{
Cifa c;
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);
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;
if (!c.register_function("valid_function", template_square)
|| !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 = !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;");
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++; }");
auto result = c.run_script("return count;");
if (!result.isNumber() || result.toDouble() != 1.0)
{
return false;
}
}
return true;
}
bool typed_function_argument_error_test()
{
Cifa c;
c.set_output_error(false);
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()
{
const auto expect_conversion_error = [](const Cifa::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;
};
const auto expect_ref_error = []()
{
Cifa c;
c.set_output_error(false);
c.register_function("menu", [](ObjectVector& args) -> Object
{
return Object(args[3].ref<ObjectMap>().size());
});
try
{
c.run_script("strs = {1, 2}; menu(85, 100, strs, strs);");
}
catch (const std::bad_any_cast&)
{
return c.get_runtime_error().find("variable 'strs'") != std::string::npos
&& c.get_runtime_error().find(typeid(ObjectMap).name()) != std::string::npos;
}
return false;
};
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_ref_error();
}
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;
auto o = c.run_script(R"(
int empty_value;
arr = {1, 2};
m["x"] = 1;
return type(empty_value) == "empty"
&& type(1) == "number"
&& type("abc") == "string"
&& type(arr) == "array"
&& type(m) == "map";
)");
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 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_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::cerr << " " << label << " failed: expected runtime error: " << expected << "\n";
std::cerr << " actual: " << error << "\n";
return false;
}
std::cerr << " " << label << ": " << error << "\n";
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;
c.register_function("capture", [&captured_value](ObjectVector& args) -> Object
{
captured_value = args.empty() ? 0 : args[0].toInt();
return Object();
});
auto program = c.compile_script(R"(
b = 304;
update_b() {
capture(b);
b = b + 1;
return b;
}
result = update_b();
return b * 1000 + result;
)");
if (!program)
{
return false;
}
auto global_result = c.run(program);
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;
}
auto broken = c.compile_script("broken() { return missing_function(); }");
if (broken || !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 x = 20;
if (x == 20) {
int x = 30;
}
}
return x;
)";
auto o = c.run_script(script);
return o.toInt() == 10; // 外部作用域不应受内部干扰
}
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
ok = ok && c.run_script("return 100/10%3;").toInt() == 1;
// 模后除:10%4/2 == 1
ok = ok && c.run_script("return 10%4/2;").toInt() == 1;
// 减后加:10-3+1 == 8
ok = ok && c.run_script("return 10-3+1;").toInt() == 8;
// lW/2*lH/2 应等于 (lW/2*lH)/2,即 8/2*6/2==12
ok = ok && c.run_script("double lW=8; double lH=6; return lW/2*lH/2;").toInt() == 12;
return ok;
}
bool unary_minus_test()
{
Cifa c;
bool ok = true;
ok = ok && c.run_script("return -5;").toDouble() == -5; // 前置负号 + 常量
ok = ok && c.run_script("return -(2+3);").toDouble() == -5; // 前置负号 + 括号表达式
ok = ok && c.run_script("return -(-3);").toDouble() == 3; // 双重前置负号
ok = ok && c.run_script("return 1 - -2;").toDouble() == 3; // 二元减 + 前置负号
ok = ok && c.run_script("return 10 - 3 - 2;").toDouble() == 5; // 二元减左结合
ok = ok && c.run_script("return -3 + 5;").toDouble() == 2; // 前置负号 + 加法
ok = ok && c.run_script("return 2 * -3;").toDouble() == -6; // 乘以前置负号
ok = ok && c.run_script("x = 7; return x * -1;").toDouble() == -7; // 变量乘以前置负号
ok = ok && c.run_script("x = 7; x = x * -1; return x;").toDouble() == -7; // 赋值语境中的前置负号
ok = ok && c.run_script("x = 7; return x * -1 + x * -2;").toDouble() == -21; // 连续乘法项
ok = ok && c.run_script("return -(2*3);").toDouble() == -6; // 前置负号 + 乘法括号
ok = ok && c.run_script("return -2 + -3;").toDouble() == -5; // 两个前置负号相加
ok = ok && c.run_script("return +5;").toDouble() == 5; // 前置正号 + 常量
ok = ok && c.run_script("return +(2+3);").toDouble() == 5; // 前置正号 + 括号表达式
ok = ok && c.run_script("return 2 * +3;").toDouble() == 6; // 乘以前置正号
ok = ok && c.run_script("return 1 + +2;").toDouble() == 3; // 二元加 + 前置正号
return ok;
}
bool array_access_test()
{ // 数组/集合模拟测试 (假设Cifa支持类似[]的操作)
Cifa c;
std::string script = R"(
//int arr[3];
arr[0] = 10;
{arr[1] = 20;}
arr[2] = arr[0] + arr[1];
return arr[2];
)";
auto o = c.run_script(script);
return o.hasValue() && o.toInt() == 30;
}
bool array_literal_assignment_test()
{ // 数组字面量赋值测试
Cifa c;
std::string script = R"(
array = {1,2,3,4,5};
return array[0] + array[4];
)";
auto o = c.run_script(script);
return o.hasValue() && o.toInt() == 6;
}
bool size_of_array_test()
{ // 数组大小测试
Cifa c;
std::string script = R"(
array = {1,2,3,4,5};
return size(array);
)";
auto o = c.run_script(script);
return o.hasValue() && o.toInt() == 5;
}
bool register_vector_test()
{
std::vector<double> v = { 1.2, 1.45, 77.3 };
Cifa c;
c.register_vector("v", v);
std::string script = R"(
return v[0] + v[1] + v[2];
)";
auto o = c.run_script(script);
return o.hasValue() && o.toDouble() == std::accumulate(v.begin(), v.end(), 0.0);
}
bool register_map_test()
{
Cifa c;
c.register_parameter("cfg", std::map<std::string, double>{ { "width", 640 }, { "height", 480 } });
// m["key"] syntax
{
auto o = c.run_script(R"( return cfg["width"] * cfg["height"]; )");
if (!o.hasValue() || o.toDouble() != 640 * 480)
{
return false;
}
}
// m::key syntax
{
auto o = c.run_script(R"( return cfg::width + cfg::height; )");
if (!o.hasValue() || o.toDouble() != 640 + 480)
{
return false;
}
}
return true;
}
bool type_promotion_test()
{
//不区分整数和浮点数,此测试不增加特别处理不可能通过
Cifa c;
std::string script = R"(
int a = 5;
int b = 2;
double res = floor(a / b); // 整数除法,结果可能是 2.0
double res2 = a / 2.0; // 提升为浮点,结果应该是 2.5
return res + res2; // 4.5
)";
auto o = c.run_script(script);
return std::fabs(o.toDouble() - 4.5) < 1e-9;
}
bool empty_statement_test()
{
Cifa c;
std::string script = R"(
int x = 10;;; // 多重分号
if (x > 5) {}
else ;
while(false){;}
for(;false;);
return x;
)";
auto o = c.run_script(script);
return o.toInt() == 10;
}
bool else_if_chain_test()
{
Cifa c;
const auto run_branch = [&c](int value)
{
return c.run_script(std::format(R"(
int value = {};
if (value == 3) {{ return 30; }}
else if (value == 2) {{ return 20; }}
else if (value == 1) {{ return 10; }}
else {{ return 0; }}
)", value));
};
return run_branch(3).toInt() == 30
&& run_branch(2).toInt() == 20
&& run_branch(1).toInt() == 10
&& run_branch(0).toInt() == 0;
}
bool multi_dimensional_array_test()
{
Cifa c;
std::string script = R"(
grid = {{1, 2}, {3, 4}};
grid[2][1] = 5;
return grid[1][0] + grid[2][1];
)";
auto o = c.run_script(script);
return o.toInt() == 8;
}
bool compound_assignment_test()
{
Cifa c;
std::string script = R"(
int x = 10;
x *= 2 + 3; // 应该是 10 * (2 + 3) = 50,而不是 10 * 2 + 3 = 23
x %= 7; // 50 % 7 = 1
return x;
)";
auto o = c.run_script(script);
return o.toInt() == 1;
}
bool c_string_library_test()
{
Cifa c1;
// 1. 注册 strlen: 返回字符串长度
c1.register_function("strlen", [](ObjectVector& d) -> Object
{
if (d.empty() || !d[0].isType<std::string>())
{
return 0;
}
return (double)d[0].toString().length();
});
// 2. 注册 strcmp: 比较字符串
c1.register_function("strcmp", [](ObjectVector& d) -> Object
{
if (d.size() < 2)
{
return 0;
}
int res = d[0].toString().compare(d[1].toString());
// 标准化为 C 风格的 -1, 0, 1
return (double)((res > 0) - (res < 0));
});
// 3. 注册 strcat: 拼接字符串
c1.register_function("strcat", [](ObjectVector& d) -> Object
{
if (d.size() < 2)
{
return "";
}
return d[0].toString() + d[1].toString();
});
// 4. 注册 strcpy: 模拟赋值
c1.register_function("strcpy", [](ObjectVector& d) -> Object
{
if (d.size() < 2)
{
return "";
}
return d[1]; // 将第二个参数赋值给第一个
});
std::string script_code = R"(
string s1 = "Cifa";
string s2 = "Language";
// 测试 strlen
int len = strlen(s1); // 4
// 测试 strcmp
int cmp_res = strcmp(s1, "Cifa"); // 0
// 测试 strcat
string combined = strcat(s1, s2); // "CifaLanguage"
// 测试 strcpy 逻辑
string target = "old";
target = strcpy(target, "new");
// 期望: 4 + 0 + 12 (combined长度) + 3 (new长度) = 19
return len + cmp_res + strlen(combined) + strlen(target);
)";
auto o = c1.run_script(script_code);
if (o.hasValue() && o.isNumber())
{
// 预期 4 + 0 + 12 + 3 = 19
return o.toInt() == 19;
}
return false;
}
bool runtime_error_stack_test()
{ // 多层脚本函数调用中的运行时错误应传播到顶层。
Cifa c;
c.set_output_error(false);
std::string script = R"(
string bad = "abc";
inner(value) { return sqrt(value); }
middle(value) { return inner(value); }
outer(value) { return middle(value); }
return outer(bad);
)";
auto o = c.run_script(script);
const std::string error = c.get_runtime_error();
return o.getSpecialType() == "Error"
&& error.find("type conversion failed") != std::string::npos
&& error.find("Call Stack (most recent call last):") != std::string::npos
&& error.find("func inner()") != std::string::npos
&& error.find("func middle()") != std::string::npos
&& error.find("func outer()") != std::string::npos;
}
bool uninitialized_variable_runtime_test()
{
Cifa c;
auto o = c.run_script("double x; return x * 2;");
return o.getSpecialType() == "Error"
&& c.get_runtime_error().find("variable 'x' has not been initialized") != std::string::npos;
}
bool nested_execution_state_test()
{
Cifa c;
c.set_output_error(false);
auto success = c.run_script("shared = 10; run_string(\"shared += 1; return shared;\"); run_file(\"unit_test/test_data/nested_increment.cifa\"); return shared;");
if (!success.isNumber() || success.toInt() != 21 || c.has_error())
{
return false;
}
c.run_script("run_string(\"return missing_nested_value;\"); return 1;");
if (!c.has_error() || c.get_errors_str().find("missing_nested_value") == std::string::npos)
{
return false;
}
c.run_script("run_file(\"unit_test/test_data/not_present_nested.cifa\"); double outer_value; return outer_value;");
return c.has_error()
&& c.get_errors_str().find("cannot open file") != std::string::npos
&& !c.get_runtime_error().empty()
&& c.get_runtime_error().find("double outer_value; return outer_value;") != std::string::npos;
}
bool nested_error_preservation_test()
{
Cifa c;
c.set_output_error(false);
c.register_function("run_first", [&c](ObjectVector&) -> Object
{
return c.run_script("first_missing_function();");
});
c.register_function("run_second", [&c](ObjectVector&) -> Object
{
return c.run_script("second_missing_function();");
});
c.run_script("run_first(); run_second();");
const std::string errors = c.get_errors_str();
return c.get_errors().size() == 2
&& errors.find("first_missing_function") != std::string::npos
&& errors.find("second_missing_function") != std::string::npos;
}
bool nested_static_error_source_test()
{
Cifa c;
c.set_output_error(false);
c.run_script("run_string(\"missing_nested_function();\");");
const auto errors = c.get_errors();
return errors.size() == 1
&& errors.front().message == "function 'missing_nested_function' is not defined"
&& errors.front().source_text == "missing_nested_function();"
&& c.get_errors_str().find("missing_nested_function();") != std::string::npos;
}
bool mixed_array_literal_test()
{ // 混合类型数组字面量:数字、字符串混存
Cifa c;
std::string script = R"(
arr = {1, "hello", 3.14, "world"};
int i = 2;
double n = arr[0];
string s = arr[1];
double f = arr[i];
string s2 = arr[3];
println(s + " " + s2, " ", to_string(f)); // 输出 "hello world 3.14"
return n + f; // 1 + 3.14 = 4.14
)";
auto o = c.run_script(script);
return o.hasValue() && std::fabs(o.toDouble() - 4.14) < 1e-9;
}
// ---- 共用测试辅助函数 ----
// 断言脚本产生语法错误,且错误信息包含 keyword;同时验证输出带行号和 ^ 箭头
static bool expect_syntax_error(const std::string& label, const std::string& script, const std::string& keyword)
{
Cifa c;
c.set_output_error(false);
c.run_script(script);
std::string err = c.get_errors_str();
std::cerr << " [" << label << "]:\n";
if (err.find("Syntax Error:") == std::string::npos || err.find(keyword) == std::string::npos)
{
std::cerr << " FAIL: expected keyword \"" << keyword << "\" in error output\n";
if (!err.empty()) { std::cerr << " Got:\n"
<< err; }
else { std::cerr << " (no error produced)\n"; }
return false;
}
if (err.find("^") == std::string::npos)
{
std::cerr << " FAIL: missing caret (^) in error output\n";
return false;
}
std::cerr << err;
return true;
}
// 断言脚本不产生任何语法错误
static bool expect_no_syntax_error(const std::string& label, const std::string& script)
{
Cifa c;
c.set_output_error(false);
c.run_script(script);
std::string err = c.get_errors_str();
std::cerr << " [" << label << "]: ";
if (!err.empty())
{
std::cerr << "FAIL unexpected error:\n"
<< err;
return false;
}
std::cerr << "OK\n";
return true;
}
bool static_syntax_error_test()
{
// 委托到文件级辅助函数
auto expect_error = [](const std::string& label, const std::string& script, const std::string& keyword) -> bool
{
return expect_syntax_error(label, script, keyword);
};
auto expect_no_error = [](const std::string& label, const std::string& script) -> bool
{
return expect_no_syntax_error(label, script);
};
bool ok = true;
// ==== 应触发静态错误的场景 ====
// 1. 赋值右侧使用未初始化变量
ok &= expect_error("uninitialized var in assign",
R"(int y = undef;)",
"not been initialized");
// 2. 赋值右侧使用未初始化变量(多行,验证行号定位)
ok &= expect_error("uninitialized var multiline",
"int x = 10;\nint y = undef;\n",
"not been initialized");
// 3. 调用未定义的函数
ok &= expect_error("undefined function",
R"(return foo(1, 2);)",
"not defined");
// 4. 括号不匹配(右括号多余)
ok &= expect_error("unpaired right paren",
R"(int x = (1 + 2));)",
"unpaired");
// 5. 括号不匹配(左括号多余)
ok &= expect_error("unpaired left paren",
R"(int x = ((1 + 2);)",
"unpaired");
// 6. 赋值给常量
ok &= expect_error("assign to constant",
R"(123 = 5;)",
"cannot be assigned");
// 7. 赋值给字符串字面量
ok &= expect_error("assign to string literal",
"\"hello\" = 5;",
"cannot be assigned");
// 8. 独立的 else(没有对应的 if)
ok &= expect_error("else without if",
R"(else { int x = 1; })",
"else has no if");
// 9. 三元运算符缺少 :
ok &= expect_error("ternary missing colon",
R"(int x = 1; int y = x ? 10;)",
"no :");