-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCifa.cpp
More file actions
4620 lines (4443 loc) · 161 KB
/
Copy pathCifa.cpp
File metadata and controls
4620 lines (4443 loc) · 161 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 <algorithm>
#include <bit>
#include <cerrno>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <limits>
#include <print>
#include <sstream>
namespace cifa
{
template <typename F>
class RaiiGuard
{
public:
explicit RaiiGuard(F finish) : finish_(std::move(finish)) { }
~RaiiGuard() { finish_(); }
RaiiGuard(const RaiiGuard&) = delete;
RaiiGuard& operator=(const RaiiGuard&) = delete;
private:
F finish_;
};
template <typename F>
RaiiGuard(F) -> RaiiGuard<F>;
static std::string normalize_path(const std::string& path);
static std::unordered_set<std::string> make_token_set(const std::vector<std::string>& tokens)
{
return std::unordered_set<std::string>(tokens.begin(), tokens.end());
}
static std::unordered_set<std::string> make_token_set(const std::vector<std::vector<std::string>>& token_groups)
{
std::unordered_set<std::string> tokens;
for (const auto& group : token_groups)
{
tokens.insert(group.begin(), group.end());
}
return tokens;
}
bool Cifa::parse_number_literal(const std::string& text, Object& value)
{
std::string normalized = text;
const bool has_hex_prefix = normalized.size() > 2 && normalized[0] == '0'
&& (normalized[1] == 'x' || normalized[1] == 'X');
const bool is_float_literal = (normalized.ends_with('f') || normalized.ends_with('F'))
&& (!has_hex_prefix || normalized.find_first_of(".pP") != std::string::npos);
if (is_float_literal)
{
normalized.pop_back();
}
const bool is_hex = normalized.size() > 2 && normalized[0] == '0' && (normalized[1] == 'x' || normalized[1] == 'X');
const bool is_binary = normalized.size() > 2 && normalized[0] == '0' && (normalized[1] == 'b' || normalized[1] == 'B');
const bool is_octal = normalized.size() > 1 && normalized[0] == '0'
&& normalized.find_first_of(".eE") == std::string::npos;
if (is_hex || is_binary || is_octal)
{
const char* digits = normalized.c_str() + (is_hex || is_binary ? 2 : 0);
const int base = is_hex ? 16 : (is_binary ? 2 : 8);
char* end = nullptr;
errno = 0;
const auto integer = std::strtoull(digits, &end, base);
if (errno == ERANGE || end == digits || *end != '\0')
{
return false;
}
if (integer > static_cast<unsigned long long>(std::numeric_limits<std::int64_t>::max())) { return false; }
value = Object(static_cast<std::int64_t>(integer));
return true;
}
const bool has_fraction_or_exponent = normalized.find_first_of(".eE") != std::string::npos;
if (!has_fraction_or_exponent)
{
char* end = nullptr;
errno = 0;
const auto integer = std::strtoll(normalized.c_str(), &end, 10);
if (errno == ERANGE || end == normalized.c_str() || *end != '\0')
{
return false;
}
value = is_float_literal ? Object(static_cast<double>(integer)) : Object(static_cast<std::int64_t>(integer));
return true;
}
char* end = nullptr;
errno = 0;
const double parsed = std::strtod(normalized.c_str(), &end);
if (errno == ERANGE || end == normalized.c_str() || *end != '\0')
{
return false;
}
value = Object(parsed);
return true;
}
static std::string object_to_display_string(const Object& value)
{
if (value.isType<bool>()) { return value.toBool() ? "true" : "false"; }
if (value.isInteger()) { return std::format("{}", value.toInt64()); }
if (value.isType<double>()) { return std::format("{}", value.toDouble()); }
if (value.isType<std::string>()) { return value.toString(); }
return {};
}
static std::int64_t wrap_int64(std::uint64_t value)
{
return std::bit_cast<std::int64_t>(value);
}
static bool numeric_less(const Object& left, const Object& right)
{
return left.isInteger() && right.isInteger()
? left.toInt64() < right.toInt64() : left.toDouble() < right.toDouble();
}
//构造函数:注册内置函数(print, println, 数学函数等)
Cifa::Cifa()
{
register_type<std::int64_t>("int");
register_type<double>("double");
register_type<bool>("bool");
register_type<std::string>("string");
type_names.emplace(typeid(ObjectVector), "array");
type_names.emplace(typeid(ObjectMap), "map");
register_type<double>("float");
register_type<std::int64_t>("char");
//输出辅助:先检查数字再检查字符串,不可输出类型调 toString 使报错显示 "<empty> to string"
//返回 false 表示遇到了不可输出的类型(已触发 runtime error)
auto print_object = [](const Object& d1) -> bool
{
if (d1.isNumber())
{
std::print("{}", object_to_display_string(d1));
return true;
}
if (d1.isType<std::string>())
{
std::print("{}", d1.toString());
return true;
}
//不可输出类型:触发运行时错误,不输出值
d1.toString();
return false;
};
register_function("print", [print_object](ObjectVector& d)
{
for (auto& d1 : d)
{
if (!print_object(d1)) { break; }
}
return Object(double(d.size()));
});
register_function("println", [print_object](ObjectVector& d)
{
bool ok = true;
for (auto& d1 : d)
{
if (!print_object(d1))
{
ok = false;
break;
}
}
//只有全部成功才输出换行,避免出错后多出空行
if (ok) { std::print("\n"); }
return Object(double(d.size()));
});
register_function("to_string", [](ObjectVector& d)
{
if (d.empty())
{
return Object("");
}
std::ostringstream stream;
if (d[0].isNumber())
{
stream << object_to_display_string(d[0]);
}
else
{
stream << d[0].toString();
}
return Object(stream.str());
});
register_function("to_number", [](ObjectVector& d)
{
if (d.empty())
{
return Object();
}
return Object(atof(d[0].toString().c_str()));
});
register_function("type", [this](ObjectVector& d)
{
if (d.empty())
{
return Object(std::string("empty"));
}
if (!d[0].hasValue())
{
if (d[0].isTyped() && d[0].getDeclaredTypeName() != "auto")
{
return Object(d[0].getDeclaredTypeName());
}
return Object(std::string("empty"));
}
if (find_struct_definition(d[0].getDeclaredTypeName()) != nullptr)
{
return Object(d[0].getDeclaredTypeName());
}
if (!d[0].getSpecialType().empty())
{
return Object(d[0].getSpecialType());
}
if (d[0].isNumber())
{
return Object(registered_type_name(d[0]));
}
if (d[0].isType<std::string>())
{
return Object(std::string("string"));
}
if (d[0].isType<std::vector<Object>>())
{
return Object(std::string("array"));
}
if (d[0].isType<ObjectMap>())
{
return Object(std::string("map"));
}
return Object(registered_type_name(d[0]));
});
register_function("run_string", [this](ObjectVector& d) -> Object
{
if (d.size() != 1)
{
set_runtime_error("function 'run_string' expects 1 argument, got " + std::to_string(d.size()));
return Object();
}
return run_script(d[0].toString());
});
register_function("run_file", [this](ObjectVector& d) -> Object
{
if (d.size() != 1)
{
set_runtime_error("function 'run_file' expects 1 argument, got " + std::to_string(d.size()));
return Object();
}
return run_file(d[0].toString());
});
register_function("exit", [this](ObjectVector&) -> Object
{
request_exit();
return Object();
});
auto ifv = [](ObjectVector& x) -> Object
{
if (x.size() != 3) { return cifa::Object(); }
return x[0].toBool() ? x[1] : x[2];
};
register_function("ifv", ifv);
register_function("ifvalue", ifv);
const auto extremum = []<bool maximum>(ObjectVector& arguments) -> Object
{
if (arguments.empty()) return Object();
if (arguments.size() == 1) return arguments[0];
if (!arguments[0].isNumber()) return arguments[0].to<double>();
bool floating = arguments[0].isType<double>();
size_t best = 0;
for (size_t index = 1; index < arguments.size(); ++index)
{
if (!arguments[index].isNumber()) return arguments[index].to<double>();
floating = floating || arguments[index].isType<double>();
if constexpr (maximum)
{
if (numeric_less(arguments[best], arguments[index])) best = index;
}
else
{
if (numeric_less(arguments[index], arguments[best])) best = index;
}
}
return floating ? Object(arguments[best].toDouble()) : Object(arguments[best].toInt64());
};
register_function("max", [extremum](ObjectVector& arguments)
{ return extremum.operator()<true>(arguments); });
register_function("min", [extremum](ObjectVector& arguments)
{ return extremum.operator()<false>(arguments); });
register_function("random", [this](ObjectVector& x) -> Object
{
if (x.size() == 0) { return Object(double(rand()) / RAND_MAX); }
if (x.size() == 1)
{
return Object(double(rand()) / RAND_MAX * x[0].toDouble());
}
if (x.size() == 2)
{
double min_val = x[0].toDouble();
double max_val = x[1].toDouble();
return Object(min_val + double(rand()) / RAND_MAX * (max_val - min_val));
}
set_runtime_error("function 'random' expects 0 to 2 arguments, got " + std::to_string(x.size()));
return Object();
});
register_function("size", [this](ObjectVector& x) -> Object
{
if (x.size() == 0) { return 0; }
if (x.size() == 1)
{
if (x[0].isType<std::string>())
{
return Object(double(x[0].toString().size()));
}
if (x[0].isType<std::vector<Object>>())
{
return Object(double(x[0].ref<std::vector<Object>>().size()));
}
if (x[0].isType<ObjectMap>())
{
return Object(double(x[0].ref<ObjectMap>().size()));
}
set_runtime_error("function 'size' requires a string, array, or map", &x[0]);
return Object();
}
set_runtime_error("function 'size' expects 0 or 1 arguments, got " + std::to_string(x.size()));
return Object();
});
// 按 printf 格式说明符将一个 Object 转为字符串
// spec 含用户原始长度修饰符(如 %llu),此处统一剥离后按类型重新添加
auto sprintf_sub = [](const Object& arg, const std::string& spec, char tc) -> std::string
{
char buf[512] = { };
// 剥离用户写的长度修饰符(hlLzjtq),保留 %、flags、width、.prec
static const std::string len_mods = "hlLzjtq";
std::string base; // '%' + flags + width + .prec,不含长度修饰符和类型字符
base += spec[0]; // '%'
for (size_t k = 1; k + 1 < spec.size(); ++k)
{
if (len_mods.find(spec[k]) == std::string::npos)
{
base += spec[k];
}
}
if (tc == 's')
{
snprintf(buf, sizeof(buf), (base + 's').c_str(), arg.toString().c_str());
}
else if (tc == 'd' || tc == 'i')
{
snprintf(buf, sizeof(buf), (base + (tc == 'd' ? "lld" : "lli")).c_str(), static_cast<long long>(arg.toInt64()));
}
else if (tc == 'u' || tc == 'o' || tc == 'x' || tc == 'X')
{
snprintf(buf, sizeof(buf), (base + "ll" + tc).c_str(), static_cast<unsigned long long>(arg.toInt64()));
}
else // %f %e %E %g %G %a;整数类型和 float 会按 C 的默认提升传给 printf
{
snprintf(buf, sizeof(buf), (base + tc).c_str(), arg.toDouble());
}
return buf;
};
register_function("sprintf", [sprintf_sub](ObjectVector& x) -> Object
{
if (x.empty())
{
return Object(std::string(""));
}
std::string fmt = x[0].toString();
std::string result;
size_t arg_idx = 1;
for (size_t i = 0; i < fmt.size();)
{
if (fmt[i] != '%')
{
result += fmt[i++];
continue;
}
// %% -> 字面 %
if (i + 1 < fmt.size() && fmt[i + 1] == '%')
{
result += '%';
i += 2;
continue;
}
// 解析: %[flags][width][.prec]type
size_t spec_start = i++;
while (i < fmt.size() && std::string("-+ #0").find(fmt[i]) != std::string::npos)
{
++i; // flags
}
while (i < fmt.size() && fmt[i] >= '0' && fmt[i] <= '9')
{
++i; // width
}
if (i < fmt.size() && fmt[i] == '.')
{
++i;
while (i < fmt.size() && fmt[i] >= '0' && fmt[i] <= '9')
{
++i;
}
} // .prec
// 跳过长度修饰符(h hh l ll L z j t q),tc 取真正的转换字符
while (i < fmt.size() && std::string("hlLzjtq").find(fmt[i]) != std::string::npos)
{
++i;
}
if (i >= fmt.size())
{
break;
}
char tc = fmt[i++];
if (arg_idx < x.size())
{
result += sprintf_sub(x[arg_idx++], fmt.substr(spec_start, i - spec_start), tc);
}
}
return Object(result);
});
// 将 Object 转为字符串
// fspec 为空:按对象真实数值类型格式化
// fspec 非空:格式字串是运行时値,必须用 std::vformat;按末尾字符选择传入的原生类型
auto format_sub = [](const Object& arg, const std::string& fspec = { }) -> std::string
{
if (fspec.empty())
{
if (arg.isNumber())
{
if (arg.isType<std::int64_t>())
{
return std::format("{}", arg.toInt64());
}
if (arg.isType<bool>())
{
return arg.toBool() ? "true" : "false";
}
return std::format("{}", arg.toDouble());
}
std::string s = arg.toString();
return std::format("{}", s);
}
std::string fmt_str = "{:" + fspec + "}";
char last = fspec.back();
if (!arg.isNumber() || last == 's')
{
std::string sv = arg.toString();
return std::vformat(fmt_str, std::make_format_args(sv));
}
if (std::string_view("diouxXbB").find(last) != std::string_view::npos)
{
long long iv = arg.toInt64();
return std::vformat(fmt_str, std::make_format_args(iv));
}
double dv = arg.toDouble();
return std::vformat(fmt_str, std::make_format_args(dv));
};
register_function("format", [format_sub](ObjectVector& x) -> Object
{
if (x.empty())
{
return Object(std::string(""));
}
std::string fmt = x[0].toString();
std::string result;
size_t auto_idx = 0;
for (size_t i = 0; i < fmt.size();)
{
if (fmt[i] == '{')
{
// {{ -> 字面 {
if (i + 1 < fmt.size() && fmt[i + 1] == '{')
{
result += '{';
i += 2;
continue;
}
size_t end = fmt.find('}', i + 1);
if (end == std::string::npos)
{
result += fmt[i++];
continue;
}
std::string inner = fmt.substr(i + 1, end - i - 1);
// 分离 [index][:format_spec]
std::string idx_part = inner;
std::string fspec;
size_t colon = inner.find(':');
if (colon != std::string::npos)
{
idx_part = inner.substr(0, colon);
fspec = inner.substr(colon + 1);
}
size_t idx;
if (idx_part.empty())
{
idx = auto_idx++;
}
else
{
bool is_num = true;
for (char c : idx_part)
{
if (c < '0' || c > '9')
{
is_num = false;
break;
}
}
if (!is_num)
{
result += fmt[i++];
continue;
} // 未知说明符,逐字输出
idx = (size_t)std::stoul(idx_part);
}
size_t arg_pos = idx + 1;
if (arg_pos < x.size())
{
result += format_sub(x[arg_pos], fspec);
}
i = end + 1;
}
else if (fmt[i] == '}' && i + 1 < fmt.size() && fmt[i + 1] == '}')
{
// }} -> 字面 }
result += '}';
i += 2;
}
else
{
result += fmt[i++];
}
}
return Object(result);
});
register_function("abs", [](ObjectVector& x) -> Object
{
if (x.size() != 1) { return Object(); }
if (x[0].isInteger())
{
const auto value = x[0].toInt64();
if (value == std::numeric_limits<std::int64_t>::min())
{
return Object();
}
return Object(value < 0 ? -value : value);
}
if (x[0].isType<double>())
{
return Object(std::fabs(x[0].toDouble()));
}
return x[0].to<double>();
});
#define REGISTER_MATH1(func) register_function(#func, static_cast<double (*)(double)>(&std::func))
#define REGISTER_MATH2(func) register_function(#func, static_cast<double (*)(double, double)>(&std::func))
REGISTER_MATH1(sqrt);
REGISTER_MATH1(cbrt);
REGISTER_MATH1(round);
REGISTER_MATH1(trunc);
REGISTER_MATH1(nearbyint);
REGISTER_MATH1(rint);
REGISTER_MATH1(ceil);
REGISTER_MATH1(floor);
REGISTER_MATH1(sin);
REGISTER_MATH1(cos);
REGISTER_MATH1(tan);
REGISTER_MATH1(asin);
REGISTER_MATH1(acos);
REGISTER_MATH1(atan);
REGISTER_MATH2(atan2);
REGISTER_MATH1(sinh);
REGISTER_MATH1(cosh);
REGISTER_MATH1(tanh);
REGISTER_MATH1(exp);
REGISTER_MATH1(log);
REGISTER_MATH1(log2);
REGISTER_MATH1(log10);
REGISTER_MATH2(pow);
REGISTER_MATH2(hypot);
REGISTER_MATH2(fmod);
REGISTER_MATH2(remainder);
REGISTER_MATH1(erf);
REGISTER_MATH1(erfc);
REGISTER_MATH1(tgamma);
REGISTER_MATH1(lgamma);
REGISTER_MATH2(copysign);
REGISTER_MATH2(fdim);
REGISTER_MATH2(fmax);
REGISTER_MATH2(fmin);
#undef REGISTER_MATH2
#undef REGISTER_MATH1
builtin_function_generations = function_generations;
}
const std::unordered_set<std::string>& Cifa::keyword_tokens()
{
static const auto tokens = []()
{
std::unordered_set<std::string> result;
for (const auto& group : keys)
{
result.insert(group.begin(), group.end());
}
return result;
}();
return tokens;
}
const std::unordered_set<std::string>& Cifa::operator_tokens()
{
static const auto tokens = make_token_set(ops);
return tokens;
}
const std::vector<std::unordered_set<std::string>>& Cifa::operator_precedence_token_groups()
{
static const auto groups = []()
{
std::vector<std::unordered_set<std::string>> result;
result.reserve(ops.size());
for (const auto& group : ops)
{
result.push_back(make_token_set(group));
}
return result;
}();
return groups;
}
Cifa::ErrorSet& Cifa::active_errors()
{
return execution_contexts.empty() ? errors : execution_contexts.back().errors;
}
const Cifa::ErrorSet& Cifa::active_errors() const
{
return execution_contexts.empty() ? errors : execution_contexts.back().errors;
}
const std::vector<SourceLineInfo>& Cifa::active_source_line_infos() const
{
static const std::vector<SourceLineInfo> empty;
if (compiling)
{
return compilation_source_line_infos;
}
if (execution_contexts.empty())
{
return empty;
}
return execution_contexts.back().source_line_infos;
}
void Cifa::record_error(ErrorMessage error)
{
active_errors().emplace(std::move(error));
if (compiling)
{
compile_failed = true;
}
}
FunctionOverloads* Cifa::find_script_function(const std::string& name)
{
if (compiling)
{
auto function = compilation_functions.find(name);
if (function != compilation_functions.end())
{
return &function->second;
}
if (compile_visible_functions != nullptr)
{
const auto visible = compile_visible_functions->find(name);
if (visible != compile_visible_functions->end()) return const_cast<FunctionOverloads*>(&visible->second);
}
}
else if (!execution_contexts.empty())
{
auto& context = execution_contexts.back();
auto function = context.functions.find(name);
if (function != context.functions.end())
{
return &function->second;
}
}
auto function = functions2.find(name);
return function != functions2.end() ? &function->second : nullptr;
}
const std::vector<StructField>* Cifa::find_struct_definition(const std::string& name) const
{
if (compiling)
{
auto definition = compilation_struct_defs.find(name);
if (definition != compilation_struct_defs.end())
{
return &definition->second;
}
if (compile_visible_struct_defs != nullptr)
{
definition = compile_visible_struct_defs->find(name);
if (definition != compile_visible_struct_defs->end()) return &definition->second;
}
}
else if (!execution_contexts.empty())
{
const auto& context = execution_contexts.back();
auto definition = context.struct_defs.find(name);
if (definition != context.struct_defs.end())
{
return &definition->second;
}
}
auto definition = struct_defs.find(name);
return definition != struct_defs.end() ? &definition->second : nullptr;
}
bool Cifa::has_error() const
{
return !active_errors().empty();
}
void Cifa::request_exit()
{
if (!execution_contexts.empty())
{
execution_contexts.back().exit_requested = true;
}
else
{
last_exit_requested = true;
}
}
bool Cifa::is_exit_requested() const
{
return execution_contexts.empty() ? last_exit_requested : execution_contexts.back().exit_requested;
}
bool Cifa::has_runtime_error() const
{
return execution_contexts.empty() ? !runtime_error_message.empty() : !execution_contexts.back().runtime_error_message.empty();
}
//从局部作用域栈的最内层向外查找变量,最后查找实例全局变量表
Object* Cifa::find_object_from_inner(ScopeStack& scopes, const std::string& name)
{
for (auto it = scopes.rbegin(); it != scopes.rend(); ++it)
{
auto it_obj = it->find(name);
if (it_obj != it->end())
{
return &it_obj->second;
}
}
auto global = global_variables.find(name);
if (global != global_variables.end())
{
return &global->second;
}
return nullptr;
}
//返回值属于执行/函数调用控制状态,不存放在变量作用域栈中
bool Cifa::has_return_value() const
{
const auto& return_states = execution_contexts.back().return_states;
return !return_states.empty() && return_states.back().has_value;
}
void Cifa::set_control_flow(ControlFlow flow, std::string label)
{
auto& context = execution_contexts.back();
context.control_flow = flow;
context.goto_label = std::move(label);
}
bool Cifa::consume_control_flow(ControlFlow flow)
{
auto& context = execution_contexts.back();
if (context.control_flow != flow) return false;
context.control_flow = ControlFlow::None;
context.goto_label.clear();
return true;
}
//获取当前执行或函数调用的返回值引用
Object& Cifa::return_value()
{
auto& return_states = execution_contexts.back().return_states;
if (return_states.empty())
{
return_states.emplace_back();
}
return_states.back().has_value = true;
return return_states.back().value;
}
//对数组或 map 对象执行内置方法(push_back / erase / contains 等)
//obj 必须是对原始变量的引用;args 是已展开的参数列表(CalUnit)
Object Cifa::eval_builtin_method(const CalUnit& method, Object& obj, std::vector<CalUnit>& args, ScopeStack& scopes)
{
const auto& method_name = method.str;
if (obj.isType<std::vector<Object>>())
{
auto& arr = obj.ref<std::vector<Object>>();
if (method_name == "push_back")
{
for (auto& a : args)
{
Object value = eval_scoped(a, scopes);
if (!obj.element_type_name.empty())
{
value = convert_object_type(value, obj.element_type_name, &a);
if (has_runtime_error()) { return Object(); }
}
arr.push_back(std::move(value));
}
return Object(double(arr.size()));
}
if (method_name == "pop_back")
{
if (!arr.empty()) { arr.pop_back(); }
return Object(double(arr.size()));
}
if (method_name == "resize")
{
if (!args.empty())
{
arr.resize(size_t(eval_scoped(args[0], scopes).toInt()));
if (!obj.element_type_name.empty()) { set_array_element_type(obj, obj.element_type_name); }
}
return Object(double(arr.size()));
}
if (method_name == "reserve")
{
if (!args.empty()) { arr.reserve(size_t(eval_scoped(args[0], scopes).toInt())); }
return Object(double(arr.size()));
}
if (method_name == "insert")
{
if (args.size() >= 2)
{
int idx = eval_scoped(args[0], scopes).toInt();
if (idx < 0)
{
idx = 0;
}
if (idx > (int)arr.size())
{
idx = (int)arr.size();
}
Object value = eval_scoped(args[1], scopes);
if (!obj.element_type_name.empty())
{
value = convert_object_type(value, obj.element_type_name, &args[1]);
if (has_runtime_error()) { return Object(); }
}
arr.insert(arr.begin() + idx, std::move(value));
}
return Object(double(arr.size()));
}
if (method_name == "erase")
{
if (!args.empty())
{
int idx = eval_scoped(args[0], scopes).toInt();
if (idx >= 0 && idx < (int)arr.size())
{
arr.erase(arr.begin() + idx);
}
}
return Object(double(arr.size()));
}
if (method_name == "clear")
{
arr.clear();
return Object(0.0);
}
if (method_name == "contains")
{
if (!args.empty())
{
auto val = eval_scoped(args[0], scopes);
for (auto& e : arr)
{
if (equal(e, val)) { return Object(1.0); }
}
}
return Object(0.0);
}
if (method_name == "keys")
{
set_runtime_error("keys() is not supported on arrays", nullptr, &method);
return Object();
}
}
else if (obj.isType<ObjectMap>())
{
auto& m = obj.ref<ObjectMap>();
if (method_name == "erase")
{
if (!args.empty())
{
auto key = eval_scoped(args[0], scopes).toString();
m.erase(key);
}
return Object(double(m.size()));
}
if (method_name == "clear")
{
m.clear();
return Object(0.0);
}
if (method_name == "contains")
{
if (!args.empty())
{
auto key = eval_scoped(args[0], scopes).toString();
return Object(m.count(key) ? 1.0 : 0.0);
}
return Object(0.0);
}
if (method_name == "keys")
{
std::vector<Object> keys;
for (auto& [k, v] : m)
{
keys.push_back(Object(k));
}
return Object(std::move(keys));
}
if (method_name == "push_back" || method_name == "pop_back"
|| method_name == "resize" || method_name == "reserve" || method_name == "insert")
{
set_runtime_error(method_name + "() is not supported on maps", nullptr, &method);
return Object();
}
}
else
{
set_runtime_error(method_name + "() requires an array or map", nullptr, &method);
}
return Object();
}
//核心求值函数:递归遍历语法树节点并执行对应操作
bool Cifa::eval_condition(CalUnit& c, ScopeStack& scopes)
{
auto value = eval_scoped(c, scopes);
if (should_stop_execution()) { return false; }
Object::set_runtime_error_reporter([this, &c](const std::string& message, const Object* source)
{ set_runtime_error(message, source, &c); });
RaiiGuard reporter_guard([]() { Object::clear_runtime_error_reporter(); });
const bool result = value.toBool();
return !should_stop_execution() && result;
}
Object Cifa::eval_scoped(CalUnit& c, ScopeStack& scopes)
{
if (should_stop_execution())
{
return Object("RuntimeError", "Error");
}
//Union(代码块/数组字面量)不入调用栈,避免根块的行号污染错误报告
const bool push_frame = (c.type != CalUnitType::Union);
auto& runtime_stack = execution_contexts.back().runtime_call_stack;
if (push_frame)
{
runtime_stack.push_back({ &c, &execution_contexts.back().source_line_infos, {} });
}
RaiiGuard frame_guard([&runtime_stack, push_frame]()
{
if (push_frame)
{
runtime_stack.pop_back();
}
});
if (has_return_value())
{
return return_value();
}