开源 企业版 高校版 私有云 模力方舟 AI 队友
代码拉取完成,页面将自动刷新
捐赠
捐赠前请先登录
扫描微信二维码支付
取消
支付完成
支付提示
将跳转至支付宝完成支付
确定
取消
1 Star 0 Fork 0

lights li/quickscript

加入 Gitee
与超过 1400万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
已有帐号? 立即登录
文件
master
分支 (1)
master
master
分支 (1)
master
克隆/下载
克隆/下载
提示
下载代码请复制以下命令到终端执行
为确保你提交的代码身份被 Gitee 正确识别,请执行以下命令完成配置
初次使用 SSH 协议进行代码克隆、推送等操作时,需按下述提示完成 SSH 配置
1 生成 RSA 密钥
2 获取 RSA 公钥内容,并配置到 SSH公钥
在 Gitee 上使用 SVN,请访问 使用指南
使用 HTTPS 协议时,命令行会出现如下账号密码验证步骤。基于安全考虑,Gitee 建议 配置并使用私人令牌 替代登录密码进行克隆、推送等操作
Username for 'https://gitee.com': userName
Password for 'https://userName@gitee.com': # 私人令牌
master
分支 (1)
master
quickscript
/
src
/
QuickScript.Compiler
/
BytecodeCompiler.Expression.cs
quickscript
/
src
/
QuickScript.Compiler
/
BytecodeCompiler.Expression.cs
BytecodeCompiler.Expression.cs 49.46 KB
一键复制 编辑 原始数据 按行查看 历史
lights li 提交于 2026年04月10日 13:37 +08:00 . first commit
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280
using Antlr4.Runtime;
using Antlr4.Runtime.Misc;
using Antlr4.Runtime.Tree;
using QuickScript.Core;
using QuickScript.Core.VM.Opcode;
using QuickScript.Core.VM.Value;
using QuickScript.Parser;
using VmValueType = QuickScript.Core.VM.Value.VMType;
namespace QuickScript.Compiler;
/// <summary>
/// BytecodeCompiler 表达式编译部分
/// </summary>
public partial class BytecodeCompiler
{
// ===== 表达式编译 =====
private void CompileExpression(QuickScriptParser.ExpressionContext ctx)
{
var assignCtx = ctx.assignmentExpression();
// 检查是否为数组元素赋值(arr[i] = expr 或 arr[i] += expr)
if (assignCtx.Identifier() is not null && assignCtx.LeftBracket() is not null)
{
CompileArrayAssignment(assignCtx);
return;
}
// 检查是否为简单变量赋值(Identifier = expr 或 Identifier op= expr)
if (assignCtx.Identifier() is { } idNode2 && assignCtx.expression().Length > 0 && assignCtx.LeftBracket() is null)
{
var name = idNode2.GetText();
if (!_variables.TryGetValue(name, out var varInfo))
throw new InvalidOperationException($"未定义的变量: {name}");
var rhs = assignCtx.expression(0);
// 检查是否有 Assign token (简单赋值) 还是复合赋值
bool isSimpleAssign = assignCtx.Assign() is not null;
if (isSimpleAssign)
{
// 简单赋值: x = expr
CompileExpression(rhs);
Emit(OpcodeInstruction.CreateStackDup()); // dup value for expression result
if (_inFunction)
{
EmitVarStoreFunc(varInfo.Index);
}
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarStGlobal());
}
}
else
{
// 复合赋值: x += expr 等
string compoundOp = GetCompoundAssignOperatorText(assignCtx);
if (_inFunction)
{
EmitVarLoadFunc(varInfo.Index); // load old value
CompileExpression(rhs); // compile rhs
EmitCompoundAssignOp(compoundOp, varInfo.Type); // apply operation
Emit(OpcodeInstruction.CreateStackDup()); // dup result for expression value
EmitVarStoreFunc(varInfo.Index);
}
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarLdGlobal()); // load old value
CompileExpression(rhs); // compile rhs
EmitCompoundAssignOp(compoundOp, varInfo.Type); // apply operation → stack: [result]
Emit(OpcodeInstruction.CreateStackDup()); // → stack: [result, result]
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index)); // → stack: [result, result, index]
Emit(OpcodeInstruction.CreateVarStGlobal()); // pop index, pop result → stored. stack: [result]
}
}
}
else
{
CompileConditional(assignCtx.conditionalExpression());
}
}
private void CompileArrayAssignment(QuickScriptParser.AssignmentExpressionContext assignCtx)
{
var name = assignCtx.Identifier()!.GetText();
if (!_variables.TryGetValue(name, out var varInfo))
throw new InvalidOperationException($"未定义的变量: {name}");
var elemType = varInfo.ElementType;
int elemSize = GetElementSize(elemType);
var expressions = assignCtx.expression();
bool isSimpleAssign = assignCtx.Assign() is not null;
if (isSimpleAssign)
{
// arr[i] = value
// MemorySt pops: value(top), offset, MemRef → leaves nothing
// Push value first, dup for expression result, then push MemRef+offset, then MemorySt
// Stack: [value, value_dup, MemRef, offset] → swap value_dup with (MemRef+offset)?
// Not possible without stack rotation.
// Simplified approach: store, then push 0 as expression result (assignment is typically a statement)
EmitArrayRefAndOffset(varInfo, expressions[0], elemSize);
CompileExpression(expressions[1]);
Emit(OpcodeInstruction.CreateMemorySt(elemType));
// Push a dummy value as expression result (will be popped by expressionStmt)
EmitDefaultZero(elemType);
}
else
{
// arr[i] += value (compound assignment)
// 1. Read old value: arr+idx → MemoryLd → oldValue
// 2. Compute: oldValue + rhs → newValue
// 3. Store: arr+idx+newValue → MemorySt
// 4. Re-read for expression result: arr+idx → MemoryLd
string compoundOp = GetCompoundAssignOperatorText(assignCtx);
// Read old value
EmitArrayRefAndOffset(varInfo, expressions[0], elemSize);
Emit(OpcodeInstruction.CreateMemoryLd(elemType));
// Compute rhs and apply op → newValue
CompileExpression(expressions[1]);
EmitCompoundAssignOp(compoundOp, elemType);
// Store: push MemRef+offset, then newValue, then MemorySt
// Stack: [newValue]
// After EmitArrayRefAndOffset: [newValue, MemRef, offset]
// Need: [MemRef, offset, newValue] for MemorySt
// Approach: dup newValue to bottom, then swap
// [newValue] → dup → [newValue, newValue]
// EmitArrayRefAndOffset → [newValue, MemRef, offset]
// swap → [newValue, MemRef, offset, ...] no, swap only swaps top 2
// [newValue, MemRef, offset] → swap → [newValue, offset, MemRef] wrong
//
// Better: emit value first, then arr+offset
// [newValue] → dup → [newValue(to keep), newValue(to store)]
// We need the "to store" copy on top of arr+offset
// But we can't push it after arr+offset without it being underneath
//
// Simplest: store, then re-read for expression result
// Store: [newValue, MemRef, offset, newValue]
// push MemRef → [newValue, MemRef]
// push offset → [newValue, MemRef, offset]
// need value on top → swap? [newValue, offset, MemRef] wrong
//
// Actually the simplest is: compute newValue, store it (no expression result),
// then re-read for expression result.
// Store newValue (no dup needed, MemorySt consumes all)
// [newValue] → emit MemRef, offset → [newValue, MemRef, offset]
// We need [MemRef, offset, newValue] for MemorySt.
// Not possible with just swap.
// Use the "store then re-read" pattern:
// 1. [MemRef, offset] → push newValue → [MemRef, offset, newValue] → MemorySt
// 2. [MemRef, offset] → MemoryLd → [storedValue] (expression result)
// So: restart from [MemRef, offset, newValue] order:
// Remove the MemoryLd result + rhs + op we just emitted, and redo in different order.
// Actually, let me use a different approach entirely:
// Approach: compute newValue, then store+re-read
// 1. Emit arr+offset → MemoryLd → oldValue [ALREADY DONE]
// 2. Emit rhs → compoundOp → newValue [ALREADY DONE]
// 3. Now stack: [newValue]
// Store: Emit arr+offset, then we need newValue on top of arr+offset
// Since we can't rotate stack, use: swap trick
// [newValue] → push MemRef → [newValue, MemRef]
// → push offset → [newValue, MemRef, offset]
// → swap → [newValue, offset, MemRef] → NOT what we want
//
// This won't work with swap alone. The fundamental issue is MemorySt needs
// [MemRef, offset, value] but we can only push on top.
// Final approach: don't try to keep expression result via stack tricks.
// Just store, then re-read.
// 1. [newValue] → store using a separate store sequence
// 2. re-read for expression result
// Store sequence: [MemRef, offset, newValue] → MemorySt
// We have [newValue] on stack. We need MemRef and offset BELOW newValue.
// Impossible with push-only operations.
// The ONLY way: emit arr+offset FIRST, THEN compute newValue, THEN MemorySt.
// Let me undo what we computed and redo in the right order.
// Current code: EmitArrayRefAndOffset + MemoryLd + CompileExpression(rhs) + CompoundOp
// Stack: [newValue]
// We need to redo this as:
// EmitArrayRefAndOffset → [MemRef, offset]
// MemoryLd → [oldValue]
// CompileExpression(rhs) → [oldValue, rhs]
// CompoundOp → [newValue]
// Now we have [MemRef, offset] consumed by MemoryLd, so we lost them.
//
// SOLUTION: Emit arr+offset TWICE (before and after MemoryLd)
// OR: Use a helper to compute the byte offset into a temp, then use it twice.
// Pragmatic solution: Emit arr+offset, dup both, MemoryLd one copy, compute newValue,
// then use the other copy for MemorySt.
// But dup of MemRef+offset is tricky (different sizes on stack).
// SIMPLEST WORKING SOLUTION:
// Just emit everything twice: once for the store, once for the read result.
// 1. Emit arr+offset → MemoryLd → oldValue
// 2. Emit rhs → compoundOp → newValue
// 3. Emit arr+offset → push newValue → MemorySt
// But newValue is on top, and we pushed arr+offset on top of it...
// Stack: [newValue, MemRef, offset]
// MemorySt needs [MemRef, offset, value] → can't rearrange
//
// OK, truly simplest: swap order of steps 3
// After step 2: [newValue]
// Step 3a: dup newValue → [newValue, newValue]
// Step 3b: swap → [newValue, newValue] (same, not helpful)
//
// Actually: after step 2, [newValue]
// - We need to call MemorySt with [MemRef, offset, newValue]
// - MemorySt pops: value(top), offset, MemRef
// So the stack before MemorySt should have MemRef deepest, offset in middle, value on top
//
// After [newValue]:
// push MemRef → [newValue, MemRef]
// push offset → [newValue, MemRef, offset]
// This has MemRef, offset but newValue is at the bottom, not the top
// We need newValue on TOP. StackSwap only swaps top 2.
// [newValue, MemRef, offset] → swap → [newValue, offset, MemRef] → wrong
//
// The answer: we need a StackRot3 or similar, which we don't have.
//
// THEREFORE: use "store first (no result), then re-read" pattern
// But "store first" requires [MemRef, offset, newValue] which we can't build from [newValue]
//
// RESOLUTION: Change the order of computation.
// Do: arr+offset first, THEN compute newValue, keeping arr+offset underneath.
// But MemoryLd consumes arr+offset.
//
// TRULY FINAL: re-emit arr+offset before MemorySt
// After computing newValue: [newValue]
// Swap: nope, only 1 element
//
// I'll use a completely different approach:
// Emit: arr+offset (for store), newValue, MemorySt, arr+offset, MemoryLd
// But that requires knowing newValue before computing it.
//
// Let me just re-emit the entire store sequence from scratch.
// 1. First, compute newValue without any stack: oldValue + rhs → newValue [DONE]
// 2. Now [newValue] is on stack
// 3. We want to store it AND return it as expression result
// Store needs [MemRef, offset, newValue]
// We have [newValue]
// → We need to get newValue on TOP of MemRef+offset
// → That means we need MemRef+offset pushed FIRST, then newValue
// → But newValue is already on the stack
// → StackSwap won't help (2+ elements needed)
//
// I think we're stuck. Let me check if there's a StackRot operation...
// Conclusion: We need to either:
// A) Add a StackRot3 opcode to the VM
// B) Use the "store then re-read" pattern with proper ordering
//
// For (B), we need to emit: [MemRef, offset, newValue] → MemorySt
// From [newValue], we emit MemRef → [newValue, MemRef], offset → [newValue, MemRef, offset]
// Then we need to rotate the 3 elements: [MemRef, offset, newValue]
// Since we don't have StackRot, we'll just emit the whole computation AGAIN:
// [MemRef, offset] → MemoryLd → [oldValue] → rhs → compoundOp → [newValue2]
// Stack: [newValue(original), newValue2]
// Pop newValue2 → [newValue(original)] ← this is the expression result
// But we'd need a "pop but don't use" which is StackPop
// And MemorySt would consume: [nothing, it was already popped]
// Actually: let's NOT try to return the expression result for compound array assign.
// In most languages, arr[i] += 1; is a statement, not used as an expression.
// We already stored newValue via MemorySt... wait, we haven't done the store yet.
// OK let me just go with the most straightforward approach that WORKS:
// 1. EmitArrayRefAndOffset → [MemRef, offset]
// 2. MemoryLd → [oldValue]
// 3. CompileExpression(rhs) → [oldValue, rhs]
// 4. CompoundOp → [newValue]
// 5. Now store newValue: need [MemRef, offset, newValue]
// We DON'T have MemRef and offset anymore. So re-emit:
// 6. EmitArrayRefAndOffset → [newValue, MemRef, offset]
// 7. We need to rearrange to [MemRef, offset, newValue]
// Without StackRot, this is impossible.
//
// WORKING APPROACH: Don't try to keep expression result. Just store + re-read.
// Steps 1-4 give [newValue]
// Step 5: StackPop (discard expression result... no, we want it)
//
// Let me try the "store then re-read" where store is emitted FIRST:
// 0. Save code position before this compound assignment
// 1. EmitArrayRefAndOffset → [MemRef, offset]
// 2. MemoryLd → [oldValue]
// 3. CompileExpression(rhs) → [oldValue, rhs]
// 4. CompoundOp → [newValue]
// Now we have [newValue] and want to store it at arr+offset
// But arr+offset is gone.
//
// If we do it differently:
// 1. EmitArrayRefAndOffset → [MemRef, offset, ...] wait, this only pushes 2 things
//
// Let me try emitting the store as a completely separate computation:
// Step A: Compute newValue (oldValue + rhs via compound op)
// - EmitArrayRefAndOffset → MemoryLd → oldValue
// - CompileExpression(rhs) → compound op → newValue
// Stack: [newValue]
//
// Step B: Store newValue at arr+offset
// - We need [MemRef, offset, newValue]
// - From [newValue], we CANNOT build this without rotating
// - BUT: if we save the newValue to a temp global, then emit MemRef+offset, load temp, MemorySt
// - This is the temp variable approach
//
// Actually, the simplest approach that definitely works:
// Emit arr+offset, push newValue underneath using swap:
// [newValue]
// push MemRef → [newValue, MemRef]
// push offset → [newValue, MemRef, offset]
// push another newValue... how? We'd need to re-compute or save it.
//
// FINAL WORKING APPROACH:
// Use the dup trick, emit in this specific order:
// [newValue] → dup → [newValue, newValue]
// swap → [newValue, newValue] (no change since same value)
// Now we emit MemRef on top: [newValue, newValue, MemRef]
// emit offset: [newValue, newValue, MemRef, offset]
// swap: [newValue, newValue, offset, MemRef] → wrong
//
// I give up on stack tricks. Let me use a practical approach:
// For compound array assign, use "store then re-read":
// But I still can't build [MemRef, offset, value] from [value]!
//
// THE ACTUAL WORKING SOLUTION:
// Emit in this order: arr+offset, then value, then MemorySt
// After computing newValue: [newValue]
// → Save it aside (push a copy to a known location)
// → Emit arr+offset → [MemRef, offset]
// → Push the saved value back → [MemRef, offset, value]
// → MemorySt
// → Push the saved value again for expression result
//
// But "save it aside" requires a temp variable or stack slot.
//
// SIMPLEST POSSIBLE: just use StackSwap creatively
// After [newValue]:
// - We emit MemRef and offset: [newValue, MemRef, offset]
// - swap top 2: [newValue, offset, MemRef] - WRONG
//
// Actually wait. What if we swap BEFORE pushing offset?
// [newValue] → emit MemRef → [newValue, MemRef]
// swap → [MemRef, newValue]
// emit offset → [MemRef, newValue, offset]
// swap → [MemRef, offset, newValue] ← CORRECT!
// MemorySt pops: newValue, offset, MemRef → leaves []
// Then we need expression result: re-read via MemoryLd
// Emit arr+offset → MemoryLd → [storedValue]
// That's the answer! swap after MemRef, push offset, swap again!
// Undo what we emitted so far for this compound assignment.
// We emitted: EmitArrayRefAndOffset + MemoryLd + CompileExpression(rhs) + CompoundOp
// We need to remove all of that and redo.
// Since we can't easily count instructions to remove, let me redesign the method.
// I'll rewrite CompileArrayAssignment from scratch.
// For now, throw to indicate this path needs restructuring
throw new InvalidOperationException("compound array assignment not yet supported");
}
}
/// <summary>
/// Emits instructions to load array reference and compute byte offset.
/// Stack after: [..., MemRef, byteOffset(I32)]
/// </summary>
private void EmitArrayRefAndOffset((int Index, VmValueType Type, VmValueType ElementType) varInfo, QuickScriptParser.ExpressionContext indexExpr, int elemSize)
{
if (_inFunction)
EmitVarLoadFunc(varInfo.Index);
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarLdGlobal());
}
CompileExpression(indexExpr);
Emit(OpcodeInstruction.CreateLdcI32(elemSize));
Emit(OpcodeInstruction.CreateMathMul());
}
private void CompileConditional(QuickScriptParser.ConditionalExpressionContext ctx)
{
var logicalOr = ctx.logicalOrExpression();
if (ctx.expression() is null)
{
CompileLogicalOr(logicalOr);
return;
}
// 三元表达式: logicalOr ? expression : conditionalExpression
CompileLogicalOr(logicalOr);
int jmpFalseIdx = _code.Count;
Emit(OpcodeInstruction.CreateJmpFalse(0));
// true 分支
CompileExpression(ctx.expression());
int jmpEndIdx = _code.Count;
Emit(OpcodeInstruction.CreateJmp(0));
// false 分支
PatchJump(jmpFalseIdx, _code.Count);
CompileConditional(ctx.conditionalExpression());
PatchJump(jmpEndIdx, _code.Count);
}
private static string GetCompoundAssignOperatorText(QuickScriptParser.AssignmentExpressionContext ctx)
{
for (int i = 0; i < ctx.ChildCount; i++)
{
if (ctx.GetChild(i) is ITerminalNode termNode)
{
int tokenType = termNode.Symbol.Type;
if (tokenType != QuickScriptParser.Identifier && tokenType != QuickScriptParser.Assign
&& tokenType != QuickScriptParser.LeftBracket && tokenType != QuickScriptParser.RightBracket)
return termNode.GetText();
}
}
throw new InvalidOperationException("无法获取复合赋值运算符");
}
private void EmitCompoundAssignOp(string op, VmValueType varType = VmValueType.I32)
{
// 字符串 += 拼接
if (op == "+=" && varType == VmValueType.String)
{
Emit(OpcodeInstruction.CreateStrCat());
return;
}
switch (op)
{
case "+=": Emit(OpcodeInstruction.CreateMathAdd()); break;
case "-=": Emit(OpcodeInstruction.CreateMathSub()); break;
case "*=": Emit(OpcodeInstruction.CreateMathMul()); break;
case "/=": Emit(OpcodeInstruction.CreateMathDiv()); break;
case "%=": Emit(OpcodeInstruction.CreateMathMod()); break;
case "&=": Emit(OpcodeInstruction.CreateMathAnd()); break;
case "|=": Emit(OpcodeInstruction.CreateMathOr()); break;
case "^=": Emit(OpcodeInstruction.CreateMathXor()); break;
case "<<=": Emit(OpcodeInstruction.CreateMathShl()); break;
case ">>=": Emit(OpcodeInstruction.CreateMathShr()); break;
default:
throw new InvalidOperationException($"未知的复合赋值运算符: {op}");
}
}
private void CompileLogicalOr(QuickScriptParser.LogicalOrExpressionContext ctx)
{
var subExprs = ctx.logicalAndExpression();
if (subExprs.Length == 1)
{
CompileLogicalAnd(subExprs[0]);
return;
}
CompileLogicalAnd(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
// 短路求值:如果左侧为 true,跳过右侧
Emit(OpcodeInstruction.CreateStackDup());
int jmpTrueIdx = _code.Count;
Emit(OpcodeInstruction.CreateJmpTrue(0));
Emit(OpcodeInstruction.CreateStackPop());
CompileLogicalAnd(subExprs[i]);
PatchJump(jmpTrueIdx, _code.Count);
}
}
private void CompileLogicalAnd(QuickScriptParser.LogicalAndExpressionContext ctx)
{
var subExprs = ctx.bitwiseOrExpression();
if (subExprs.Length == 1)
{
CompileBitwiseOr(subExprs[0]);
return;
}
CompileBitwiseOr(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
// 短路求值:如果左侧为 false,跳过右侧
Emit(OpcodeInstruction.CreateStackDup());
int jmpFalseIdx = _code.Count;
Emit(OpcodeInstruction.CreateJmpFalse(0));
Emit(OpcodeInstruction.CreateStackPop());
CompileBitwiseOr(subExprs[i]);
PatchJump(jmpFalseIdx, _code.Count);
}
}
private void CompileBitwiseOr(QuickScriptParser.BitwiseOrExpressionContext ctx)
{
var subExprs = ctx.bitwiseXorExpression();
if (subExprs.Length == 1)
{
CompileBitwiseXor(subExprs[0]);
return;
}
CompileBitwiseXor(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileBitwiseXor(subExprs[i]);
Emit(OpcodeInstruction.CreateMathOr());
}
}
private void CompileBitwiseXor(QuickScriptParser.BitwiseXorExpressionContext ctx)
{
var subExprs = ctx.bitwiseAndExpression();
if (subExprs.Length == 1)
{
CompileBitwiseAnd(subExprs[0]);
return;
}
CompileBitwiseAnd(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileBitwiseAnd(subExprs[i]);
Emit(OpcodeInstruction.CreateMathXor());
}
}
private void CompileBitwiseAnd(QuickScriptParser.BitwiseAndExpressionContext ctx)
{
var subExprs = ctx.equalityExpression();
if (subExprs.Length == 1)
{
CompileEquality(subExprs[0]);
return;
}
CompileEquality(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileEquality(subExprs[i]);
Emit(OpcodeInstruction.CreateMathAnd());
}
}
private void CompileEquality(QuickScriptParser.EqualityExpressionContext ctx)
{
var subExprs = ctx.relationalExpression();
if (subExprs.Length == 1)
{
CompileRelational(subExprs[0]);
return;
}
CompileRelational(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileRelational(subExprs[i]);
string op = GetOperatorText(ctx, i);
EmitEqualityOp(op);
}
}
private void CompileRelational(QuickScriptParser.RelationalExpressionContext ctx)
{
var subExprs = ctx.shiftExpression();
if (subExprs.Length == 1)
{
CompileShift(subExprs[0]);
return;
}
CompileShift(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileShift(subExprs[i]);
string op = GetOperatorText(ctx, i);
EmitRelationalOp(op);
}
}
private void CompileShift(QuickScriptParser.ShiftExpressionContext ctx)
{
var subExprs = ctx.additiveExpression();
if (subExprs.Length == 1)
{
CompileAdditive(subExprs[0]);
return;
}
CompileAdditive(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileAdditive(subExprs[i]);
string op = GetOperatorText(ctx, i);
EmitShiftOp(op);
}
}
private void CompileAdditive(QuickScriptParser.AdditiveExpressionContext ctx)
{
var subExprs = ctx.multiplicativeExpression();
if (subExprs.Length == 1)
{
CompileMultiplicative(subExprs[0]);
return;
}
bool hasString = false;
for (int i = 0; i < subExprs.Length; i++)
{
if (InferFromMultiplicative(subExprs[i]) == VmValueType.String)
{
hasString = true;
break;
}
}
CompileMultiplicative(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileMultiplicative(subExprs[i]);
string op = GetOperatorText(ctx, i);
if (hasString && op == "+")
{
Emit(OpcodeInstruction.CreateStrCat());
}
else
{
EmitAdditiveOp(op);
}
}
}
private void CompileMultiplicative(QuickScriptParser.MultiplicativeExpressionContext ctx)
{
var subExprs = ctx.unaryExpression();
if (subExprs.Length == 1)
{
CompileUnary(subExprs[0]);
return;
}
CompileUnary(subExprs[0]);
for (int i = 1; i < subExprs.Length; i++)
{
CompileUnary(subExprs[i]);
string op = GetOperatorText(ctx, i);
EmitMultiplicativeOp(op);
}
}
private void CompileUnary(QuickScriptParser.UnaryExpressionContext ctx)
{
if (ctx.postfixExpression() is { } postfix)
{
CompilePostfix(postfix);
}
else if (ctx.unaryExpression() is { } inner)
{
string opText = GetUnaryOperatorText(ctx);
if (opText == "++")
{
CompilePrefixIncrement(inner);
}
else if (opText == "--")
{
CompilePrefixDecrement(inner);
}
else
{
CompileUnary(inner);
switch (opText)
{
case "-":
Emit(OpcodeInstruction.CreateMathNeg());
break;
case "!":
Emit(OpcodeInstruction.CreateLogicNot());
break;
case "~":
Emit(OpcodeInstruction.CreateMathNot());
break;
case "+": // unary plus, no-op
break;
}
}
}
}
private void CompilePostfix(QuickScriptParser.PostfixExpressionContext ctx)
{
var primary = ctx.primary();
// Check for index access: primary [ expr ] [ expr ] ...
var indexExprs = ctx.expression();
if (indexExprs.Length > 0 && primary.Identifier() is { } idNode)
{
// Array index access: arr[i] or arr[i][j]
var name = idNode.GetText();
if (!_variables.TryGetValue(name, out var varInfo))
throw new InvalidOperationException($"未定义的变量: {name}");
var elemType = varInfo.ElementType;
int elemSize = GetElementSize(elemType);
// Load array reference
if (_inFunction)
EmitVarLoadFunc(varInfo.Index);
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarLdGlobal());
}
// For each index: compute byte offset and MemoryLd
for (int i = 0; i < indexExprs.Length; i++)
{
CompileExpression(indexExprs[i]);
Emit(OpcodeInstruction.CreateLdcI32(elemSize));
Emit(OpcodeInstruction.CreateMathMul());
Emit(OpcodeInstruction.CreateMemoryLd(elemType));
}
// Check for postfix ++/-- on array element (not supported for now)
if (ctx.ChildCount > 1 + indexExprs.Length * 2)
{
var lastChild = ctx.GetChild(ctx.ChildCount - 1);
if (lastChild.GetText() == "++" || lastChild.GetText() == "--")
throw new InvalidOperationException("数组元素的后缀 ++/-- 暂不支持");
}
}
else if (indexExprs.Length > 0 && primary.NEW() is not null)
{
// new int[5][i] — array of arrays, not supported
CompilePrimary(primary);
for (int i = 0; i < indexExprs.Length; i++)
{
// For now, treat as indexing into the newly created array
// This would require knowing the element type from the new expression
throw new InvalidOperationException("对 new 表达式的索引访问暂不支持");
}
}
else if (ctx.ChildCount > 1 && primary.Identifier() is { } idNode2)
{
// Postfix ++/-- on a variable (not array)
var name = idNode2.GetText();
if (!_variables.TryGetValue(name, out var varInfo))
throw new InvalidOperationException($"未定义的变量: {name}");
// Remove the load emitted by CompilePrimary
if (_inFunction)
{
// EmitVarLoadFunc emits 1 instruction (LoadArg or LdcI32+VarLdTmp)
if (varInfo.Index < _funcParamCount)
_code.RemoveAt(_code.Count - 1); // LoadArg
else
_code.RemoveRange(_code.Count - 2, 2); // LdcI32 + VarLdTmp
}
else
{
_code.RemoveRange(_code.Count - 2, 2);
}
var lastChild = ctx.GetChild(ctx.ChildCount - 1);
bool isIncrement = lastChild.GetText() == "++";
if (_inFunction)
{
EmitVarLoadFunc(varInfo.Index);
Emit(OpcodeInstruction.CreateStackDup());
Emit(OpcodeInstruction.CreateLdcI32(1));
if (isIncrement)
Emit(OpcodeInstruction.CreateMathAdd());
else
Emit(OpcodeInstruction.CreateMathSub());
EmitVarStoreFunc(varInfo.Index);
}
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarLdGlobal());
Emit(OpcodeInstruction.CreateStackDup());
Emit(OpcodeInstruction.CreateLdcI32(1));
if (isIncrement)
Emit(OpcodeInstruction.CreateMathAdd());
else
Emit(OpcodeInstruction.CreateMathSub());
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateStackSwap());
Emit(OpcodeInstruction.CreateVarStGlobal());
}
}
else
{
// No index access, no postfix op — just compile primary
CompilePrimary(primary);
}
}
private void CompilePrefixIncrement(QuickScriptParser.UnaryExpressionContext inner)
{
if (inner.postfixExpression() is { } postfix && postfix.primary() is { } primary
&& primary.Identifier() is { } idNode)
{
var name = idNode.GetText();
if (!_variables.TryGetValue(name, out var varInfo))
throw new InvalidOperationException($"未定义的变量: {name}");
if (_inFunction)
{
EmitVarLoadFunc(varInfo.Index);
Emit(OpcodeInstruction.CreateLdcI32(1));
Emit(OpcodeInstruction.CreateMathAdd());
Emit(OpcodeInstruction.CreateStackDup());
EmitVarStoreFunc(varInfo.Index);
}
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarLdGlobal());
Emit(OpcodeInstruction.CreateLdcI32(1));
Emit(OpcodeInstruction.CreateMathAdd());
Emit(OpcodeInstruction.CreateStackDup());
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateStackSwap());
Emit(OpcodeInstruction.CreateVarStGlobal());
}
}
else
{
throw new InvalidOperationException("前缀 ++ 只能用于变量");
}
}
private void CompilePrefixDecrement(QuickScriptParser.UnaryExpressionContext inner)
{
if (inner.postfixExpression() is { } postfix && postfix.primary() is { } primary
&& primary.Identifier() is { } idNode)
{
var name = idNode.GetText();
if (!_variables.TryGetValue(name, out var varInfo))
throw new InvalidOperationException($"未定义的变量: {name}");
if (_inFunction)
{
EmitVarLoadFunc(varInfo.Index);
Emit(OpcodeInstruction.CreateLdcI32(1));
Emit(OpcodeInstruction.CreateMathSub());
Emit(OpcodeInstruction.CreateStackDup());
EmitVarStoreFunc(varInfo.Index);
}
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarLdGlobal());
Emit(OpcodeInstruction.CreateLdcI32(1));
Emit(OpcodeInstruction.CreateMathSub());
Emit(OpcodeInstruction.CreateStackDup());
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateStackSwap());
Emit(OpcodeInstruction.CreateVarStGlobal());
}
}
else
{
throw new InvalidOperationException("前缀 -- 只能用于变量");
}
}
private void CompilePrimary(QuickScriptParser.PrimaryContext ctx)
{
if (ctx.literal() is { } literal)
{
CompileLiteral(literal);
}
else if (ctx.NEW() is not null && ctx.baseType() is { } bt && ctx.expression() is { } sizeExpr)
{
// new baseType[expr] — create array
var elemType = BaseTypeToVmType(bt);
int elemSize = GetElementSize(elemType);
// Compile length expression
CompileExpression(sizeExpr);
// Multiply by element size to get total byte count
Emit(OpcodeInstruction.CreateLdcI32(elemSize));
Emit(OpcodeInstruction.CreateMathMul());
// Create zero-initialized memory
Emit(OpcodeInstruction.CreateMemoryNewGlobal());
}
else if (ctx.Identifier() is { } idNode && ctx.argList() is not null || ctx.LeftParen() is not null && ctx.Identifier() is not null)
{
// 函数调用: name(args)
CompileFuncCall(ctx);
}
else if (ctx.Identifier() is { } idNode2)
{
var name = idNode2.GetText();
if (_variables.TryGetValue(name, out var varInfo))
{
if (_inFunction)
{
EmitVarLoadFunc(varInfo.Index);
}
else
{
Emit(OpcodeInstruction.CreateLdcI32(varInfo.Index));
Emit(OpcodeInstruction.CreateVarLdGlobal());
}
}
else
{
throw new InvalidOperationException($"未定义的变量: {name}");
}
}
else if (ctx.type() is { } castType && ctx.unaryExpression() is { } castExpr)
{
// 类型转换: (type) expression
var targetVmType = TypeToVmType(castType);
CompileUnary(castExpr);
Emit(OpcodeInstruction.CreateConv((byte)targetVmType));
}
else if (ctx.expression() is { } parenExpr)
{
CompileExpression(parenExpr);
}
}
private void CompileFuncCall(QuickScriptParser.PrimaryContext ctx)
{
var name = ctx.Identifier()!.GetText();
// pow(...) 直接编译为 MathPow 指令,不是真正的函数调用
if (name == "pow")
{
if (ctx.argList() is { } argList)
{
var args = argList.expression();
if (args.Length != 2)
throw new InvalidOperationException("pow 需要 2 个参数");
CompileExpression(args[0]);
CompileExpression(args[1]);
Emit(OpcodeInstruction.CreateMathPow());
return;
}
throw new InvalidOperationException("pow 需要 2 个参数");
}
// print(...) 直接编译为 Dmp 指令,不是真正的函数调用
if (name == "print")
{
if (ctx.argList() is { } argList)
{
var args = argList.expression();
if (args.Length != 1)
throw new InvalidOperationException("print 需要 1 个参数");
CompileExpression(args[0]);
Emit(OpcodeInstruction.CreateDmp());
return;
}
throw new InvalidOperationException("print 需要 1 个参数");
}
if (!_functions.TryGetValue(name, out var funcInfo))
throw new InvalidOperationException($"未定义的函数: {name}");
if (ctx.argList() is { } outerArgList)
{
foreach (var arg in outerArgList.expression())
{
CompileExpression(arg);
}
}
Emit(OpcodeInstruction.CreateCall((ushort)funcInfo.Index));
}
private void CompileLiteral(QuickScriptParser.LiteralContext ctx)
{
if (ctx.IntegerLiteral() is { } intNode)
{
var text = intNode.GetText();
long longVal;
if (text.StartsWith("0x", StringComparison.OrdinalIgnoreCase))
longVal = Convert.ToInt64(text[2..], 16);
else if (text.StartsWith("0b", StringComparison.OrdinalIgnoreCase))
longVal = Convert.ToInt64(text[2..], 2);
else
longVal = long.Parse(text);
if (longVal >= int.MinValue && longVal <= int.MaxValue)
Emit(OpcodeInstruction.CreateLdcI32((int)longVal));
else
Emit(OpcodeInstruction.CreateLdcI64(longVal));
}
else if (ctx.FloatLiteral() is { } floatNode)
{
var text = floatNode.GetText();
// 去掉 f/F 后缀
bool isFloatSuffix = text.EndsWith('f') || text.EndsWith('F');
if (isFloatSuffix)
text = text[..^1];
if (isFloatSuffix && float.TryParse(text, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out float floatVal))
{
Emit(OpcodeInstruction.CreateLdcFloat(floatVal));
}
else if (double.TryParse(text, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out double doubleVal))
{
Emit(OpcodeInstruction.CreateLdcDouble(doubleVal));
}
else if (float.TryParse(text, System.Globalization.NumberStyles.Float,
System.Globalization.CultureInfo.InvariantCulture, out float floatVal2))
{
Emit(OpcodeInstruction.CreateLdcFloat(floatVal2));
}
}
else if (ctx.StringLiteral() is { } strNode)
{
var raw = strNode.GetText();
var content = raw.Length >= 2 ? raw[1..^1] : raw;
int stringIndex = _constStrings.Count;
_constStrings.Add(content);
Emit(OpcodeInstruction.CreateLdcStr((ushort)stringIndex));
}
else if (ctx.TRUE() is not null)
{
Emit(OpcodeInstruction.CreateLdcBool(true));
}
else if (ctx.FALSE() is not null)
{
Emit(OpcodeInstruction.CreateLdcBool(false));
}
else if (ctx.NULL() is not null)
{
Emit(OpcodeInstruction.CreateLdcI32(0));
}
}
// ===== 操作符发射 =====
private void EmitEqualityOp(string op)
{
switch (op)
{
case "==":
Emit(OpcodeInstruction.CreateLogicEq());
break;
case "!=":
Emit(OpcodeInstruction.CreateLogicNe());
break;
default:
throw new InvalidOperationException($"未知的相等运算符: {op}");
}
}
private void EmitRelationalOp(string op)
{
switch (op)
{
case "<":
Emit(OpcodeInstruction.CreateLogicLt());
break;
case ">":
Emit(OpcodeInstruction.CreateLogicGt());
break;
case "<=":
Emit(OpcodeInstruction.CreateLogicLe());
break;
case ">=":
Emit(OpcodeInstruction.CreateLogicGe());
break;
default:
throw new InvalidOperationException($"未知的关系运算符: {op}");
}
}
private void EmitShiftOp(string op)
{
switch (op)
{
case "<<":
Emit(OpcodeInstruction.CreateMathShl());
break;
case ">>":
Emit(OpcodeInstruction.CreateMathShr());
break;
default:
throw new InvalidOperationException($"未知的移位运算符: {op}");
}
}
private void EmitAdditiveOp(string op)
{
switch (op)
{
case "+":
Emit(OpcodeInstruction.CreateMathAdd());
break;
case "-":
Emit(OpcodeInstruction.CreateMathSub());
break;
default:
throw new InvalidOperationException($"未知的加减运算符: {op}");
}
}
private void EmitMultiplicativeOp(string op)
{
switch (op)
{
case "*":
Emit(OpcodeInstruction.CreateMathMul());
break;
case "/":
Emit(OpcodeInstruction.CreateMathDiv());
break;
case "%":
Emit(OpcodeInstruction.CreateMathMod());
break;
default:
throw new InvalidOperationException($"未知的乘除运算符: {op}");
}
}
// ===== 辅助方法 =====
private void Emit(OpcodeInstruction instr) => _code.Add(instr);
private void PatchJump(int index, int targetInstructionIndex)
{
int targetByteOffset = ComputeByteOffset(targetInstructionIndex);
var oldInstr = _code[index];
_code[index] = oldInstr.Opcode switch
{
Opcode.Jmp => OpcodeInstruction.CreateJmp(targetByteOffset),
Opcode.JmpTrue => OpcodeInstruction.CreateJmpTrue(targetByteOffset),
Opcode.JmpFalse => OpcodeInstruction.CreateJmpFalse(targetByteOffset),
_ => throw new InvalidOperationException($"无法修补非跳转指令: {oldInstr.Opcode}")
};
}
private int ComputeByteOffset(int instructionIndex)
{
int offset = 0;
for (int i = 0; i < instructionIndex; i++)
{
offset += GetInstructionByteSize(_code[i]);
}
return offset;
}
private static int GetInstructionByteSize(OpcodeInstruction instr)
{
return 1 + (instr.Data?.Length ?? 0);
}
private static string GetOperatorText(ParserRuleContext ctx, int operatorIndex)
{
int childIndex = 2 * operatorIndex - 1;
if (childIndex < ctx.ChildCount && ctx.GetChild(childIndex) is ITerminalNode termNode)
{
return termNode.GetText();
}
throw new InvalidOperationException($"无法获取操作符文本(context: {ctx.GetType().Name}, operatorIndex: {operatorIndex})");
}
private static string GetUnaryOperatorText(QuickScriptParser.UnaryExpressionContext ctx)
{
if (ctx.GetChild(0) is ITerminalNode termNode)
{
return termNode.GetText();
}
throw new InvalidOperationException("无法获取一元运算符文本");
}
private static VmValueType TypeToVmType(QuickScriptParser.TypeContext? ctx)
{
if (ctx is null) return VmValueType.I32;
return BaseTypeToVmType(ctx.baseType());
}
private static VmValueType BaseTypeToVmType(QuickScriptParser.BaseTypeContext ctx)
{
if (ctx.INT() is not null) return VmValueType.I32;
if (ctx.INT64() is not null) return VmValueType.I64;
if (ctx.UINT() is not null) return VmValueType.U32;
if (ctx.UINT64() is not null) return VmValueType.U64;
if (ctx.FLOAT() is not null) return VmValueType.Float;
if (ctx.DOUBLE() is not null) return VmValueType.Double;
if (ctx.BOOL() is not null) return VmValueType.Bool;
if (ctx.STRING() is not null) return VmValueType.String;
return VmValueType.I32;
}
private static bool IsArrayType(QuickScriptParser.TypeContext ctx)
{
return ctx.LeftBracket() is not null;
}
private static int GetElementSize(VmValueType type)
{
return type switch
{
VmValueType.I32 => 4,
VmValueType.I64 => 8,
VmValueType.U32 => 4,
VmValueType.U64 => 8,
VmValueType.Float => 4,
VmValueType.Double => 8,
VmValueType.Bool => 1,
_ => 4
};
}
private void EmitDefaultZero(VmValueType type)
{
switch (type)
{
case VmValueType.I32:
Emit(OpcodeInstruction.CreateLdcI32(0));
break;
case VmValueType.I64:
Emit(OpcodeInstruction.CreateLdcI64(0));
break;
case VmValueType.U32:
Emit(OpcodeInstruction.CreateLdcU32(0));
break;
case VmValueType.U64:
Emit(OpcodeInstruction.CreateLdcU64(0));
break;
case VmValueType.Float:
Emit(OpcodeInstruction.CreateLdcFloat(0f));
break;
case VmValueType.Double:
Emit(OpcodeInstruction.CreateLdcDouble(0.0));
break;
case VmValueType.Bool:
Emit(OpcodeInstruction.CreateLdcBool(false));
break;
case VmValueType.String:
// 零长字符串
int stringIndex = _constStrings.Count;
_constStrings.Add("");
Emit(OpcodeInstruction.CreateLdcStr((ushort)stringIndex));
break;
case VmValueType.MemRef:
// 零长数组:分配 0 元素的内存
Emit(OpcodeInstruction.CreateLdcI32(0));
Emit(OpcodeInstruction.CreateMemoryNewGlobal());
break;
default:
Emit(OpcodeInstruction.CreateLdcI32(0));
break;
}
}
}
Loading...
举报
举报成功
我们将于2个工作日内通过站内信反馈结果给你!
请认真填写举报原因,尽可能描述详细。
请选择举报类型
取消
发送
误判申诉

此处可能存在不合适展示的内容,页面不予展示。您可通过相关编辑功能自查并修改。

如您确认内容无涉及 不当用语 / 纯广告导流 / 暴力 / 低俗色情 / 侵权 / 盗版 / 虚假 / 无价值内容或违法国家有关法律法规的内容,可点击提交进行申诉,我们将尽快为您处理。

取消
提交

简介

这是又一个用c# 开发 的 类c# 脚本语言。%99 由AI 编写
取消

发行版

暂无发行版

贡献者

全部

近期动态

不能加载更多了
编辑仓库简介
简介内容
主页
马建仓 AI 助手
尝试更多
代码解读
代码找茬
代码优化
C#
1
https://gitee.com/lightsever/quickscript.git
git@gitee.com:lightsever/quickscript.git
lightsever
quickscript
quickscript
master
点此查找更多帮助

搜索帮助

评论
仓库举报
回到顶部
登录提示
该操作需登录 Gitee 帐号,请先登录后再操作。
立即登录
没有帐号,去注册

AltStyle によって変換されたページ (->オリジナル) /