From 4a45fbf5c435458ccb8934e157601fb9d839f736 Mon Sep 17 00:00:00 2001 From: Cursor Agent Date: Wed, 2 Dec 2026 03:02:58 +0000 Subject: [PATCH] feat(lexer,stdlib): complete Lua 5.4 lexer escapes, long strings, and stdlib edge semantics Co-authored-by: esrrhs --- src/compile/c_gen.cpp | 7 +- src/compile/c_gen.h | 2 - src/compile/compile_common.h | 8 + src/compile/flex/scanner.cpp | 642 ++++++++++--------- src/compile/flex/scanner.l | 173 +++-- src/compile/my_flexer.cpp | 14 +- src/compile/semantic_analysis.cpp | 7 +- src/interp/codegen.cpp | 4 +- src/interp/codegen.h | 2 - src/native/basic/native_basic.cpp | 141 ++-- src/native/string/native_string.cpp | 18 +- src/native/table/native_table.cpp | 107 ++++ src/native/table/native_table.h | 7 + src/native/utf8/native_utf8.cpp | 124 ++-- src/util/string_util.cpp | 73 ++- test/lua/basic/test_basic_pairs_coverage.lua | 5 +- test/lua/basic/test_basic_tonumber_extra.lua | 6 +- test/test_basic.cpp | 96 +++ test/test_exception.cpp | 44 ++ test/test_string.cpp | 198 ++++++ test/test_utf8.cpp | 74 +++ 21 files changed, 1190 insertions(+), 562 deletions(-) diff --git a/src/compile/c_gen.cpp b/src/compile/c_gen.cpp index 2bee1dc4..79bb24d9 100644 --- a/src/compile/c_gen.cpp +++ b/src/compile/c_gen.cpp @@ -211,13 +211,10 @@ void CGen::UniquifyFuncCNames() { // 第一部分:核心调度与编排 // =========================================================================== -// string 库方法名集合(对齐 Lua 5.4)。 -const std::unordered_set CGen::kStringLibraryMethods = {"len", "sub", "rep", "reverse", "lower", "upper", "byte", "char", "format", "dump", "find", "match", "gmatch", "gsub"}; - // 非表值的 colon 方法调用转发(s:match() ≡ string.match(s, ...))。 // 返回空串表示不匹配,调用方回退到 FlGetTableStrId。 std::string CGen::TryBuildLibraryMethodCall(const std::string &method_name, const std::vector &args) { - if (!kStringLibraryMethods.contains(method_name)) { + if (!StringLibraryMethods().contains(method_name)) { return {}; } std::string arg_list; @@ -4754,7 +4751,7 @@ std::string CGen::TryCompileBuiltinStringCall(const std::shared_ptrGetName(); - if (!CGen::kStringLibraryMethods.contains(method_name)) { + if (!StringLibraryMethods().contains(method_name)) { return {}; } diff --git a/src/compile/c_gen.h b/src/compile/c_gen.h index d7a88268..9a2287a8 100644 --- a/src/compile/c_gen.h +++ b/src/compile/c_gen.h @@ -123,8 +123,6 @@ class CGen { [[nodiscard]] InferredType GetSpecFieldType(const std::string &spec_type, const std::string &key, TableKeyKind kind) const; // table 特化辅助:生成字段描述符(用于 map key) [[nodiscard]] static std::string GetKeyDescriptor(const std::string &key, TableKeyKind kind); - // string 库方法名集合(对齐 Lua 5.4)。 - static const std::unordered_set kStringLibraryMethods; // 非表值的 colon 方法调用转发(s:match() ≡ string.match(s, ...))。 // 返回空串表示不匹配,调用方回退到 FlGetTableStrId。 [[nodiscard]] static std::string TryBuildLibraryMethodCall(const std::string &method_name, const std::vector &args); diff --git a/src/compile/compile_common.h b/src/compile/compile_common.h index 2e7cdc8f..b3511ab3 100644 --- a/src/compile/compile_common.h +++ b/src/compile/compile_common.h @@ -21,6 +21,14 @@ namespace fakelua { inline constexpr const char *kInitFunctionName = "__fakelua_init"; +// string 库方法名集合(对齐 Lua 5.4)。供 RegisterPeakChecker、CGen、InterpCodegen 共享。 +inline const std::unordered_set &StringLibraryMethods() { + static const std::unordered_set kStringLibraryMethods = { + "len", "sub", "rep", "reverse", "lower", "upper", "byte", "char", "format", "dump", "find", "match", "gmatch", "gsub", "pack", "unpack", "packsize", + }; + return kStringLibraryMethods; +} + // 运行期 Lua 调用栈上显示的函数名。文件级函数带 package 前缀;匿名函数和 // __fakelua_init 用固定标签,避免把编译器内部名暴露给报错信息。 inline std::string LuaCallFrameName(std::string_view name, bool at_file_scope, std::string_view package) { diff --git a/src/compile/flex/scanner.cpp b/src/compile/flex/scanner.cpp index d7a1c2d5..1c447ab6 100644 --- a/src/compile/flex/scanner.cpp +++ b/src/compile/flex/scanner.cpp @@ -58,7 +58,7 @@ #if defined (__STDC_VERSION__) && __STDC_VERSION__ >= 199901L /* C99 says to define __STDC_LIMIT_MACROS before including stdint.h, - * if you want the limit (max/min) macros for int types. + * if you want the limit (max/min) macros for int types. */ #ifndef __STDC_LIMIT_MACROS #define __STDC_LIMIT_MACROS 1 @@ -75,7 +75,7 @@ typedef uint32_t flex_uint32_t; typedef signed char flex_int8_t; typedef short int flex_int16_t; typedef int flex_int32_t; -typedef unsigned char flex_uint8_t; +typedef unsigned char flex_uint8_t; typedef unsigned short int flex_uint16_t; typedef unsigned int flex_uint32_t; @@ -212,7 +212,7 @@ extern int yyleng; #define EOB_ACT_CONTINUE_SCAN 0 #define EOB_ACT_END_OF_FILE 1 #define EOB_ACT_LAST_MATCH 2 - + /* Note: We specifically omit the test for yy_rule_can_match_eol because it requires * access to the local variable yy_act. Since yyless() is a macro, it would break * existing scanners that call yyless() from OUTSIDE yylex. @@ -234,7 +234,7 @@ extern int yyleng; if ( *p == '\n' )\ --yylineno;\ }while(0) - + /* Return all but the first "n" matched characters back to the input stream. */ #define yyless(n) \ do \ @@ -405,8 +405,8 @@ int yyFlexLexer::yywrap() { return 1; } /* %% [3.0] code to copy yytext_ptr to yytext[] goes here, if %array \ */\ (yy_c_buf_p) = yy_cp; /* %% [4.0] data tables for the DFA and the user's section 1 definitions go here */ -#define YY_NUM_RULES 72 -#define YY_END_OF_BUFFER 73 +#define YY_NUM_RULES 73 +#define YY_END_OF_BUFFER 74 /* This struct is not used in this scanner, but its presence is necessary. */ struct yy_trans_info @@ -416,25 +416,25 @@ struct yy_trans_info }; static const flex_int16_t yy_accept[184] = { 0, - 0, 0, 0, 0, 0, 0, 73, 71, 8, 9, - 9, 70, 16, 10, 11, 70, 36, 37, 34, 33, + 0, 0, 0, 0, 0, 0, 74, 72, 8, 9, + 9, 71, 16, 10, 11, 71, 36, 37, 34, 33, 20, 32, 21, 35, 66, 66, 19, 18, 15, 31, 14, 68, 40, 41, 17, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 68, 38, 12, 39, 13, 7, 6, 6, 4, 3, 3, - 4, 8, 9, 0, 69, 0, 0, 0, 5, 22, - 65, 67, 66, 67, 67, 67, 30, 28, 26, 24, - 25, 29, 68, 0, 68, 68, 68, 45, 68, 68, - 68, 68, 68, 68, 53, 54, 68, 68, 68, 58, + 4, 8, 9, 0, 70, 0, 0, 0, 5, 22, + 66, 65, 66, 66, 67, 67, 67, 30, 28, 26, + 24, 25, 29, 68, 0, 69, 68, 68, 68, 45, + 68, 68, 68, 68, 68, 68, 53, 54, 68, 68, - 68, 68, 68, 68, 68, 27, 6, 3, 0, 2, - 69, 69, 0, 23, 66, 0, 66, 66, 0, 0, + 68, 58, 68, 68, 68, 68, 68, 27, 6, 3, + 0, 2, 0, 23, 66, 66, 0, 66, 0, 66, 42, 68, 68, 68, 48, 68, 50, 68, 68, 68, 56, 57, 68, 68, 68, 68, 68, 68, 0, 1, - 66, 66, 67, 66, 67, 68, 68, 46, 68, 68, - 52, 68, 68, 68, 61, 62, 68, 68, 66, 0, - 66, 43, 68, 68, 49, 68, 55, 68, 68, 63, - 64, 66, 66, 68, 47, 68, 59, 60, 68, 68, + 66, 66, 66, 66, 67, 68, 68, 46, 68, 68, + 52, 68, 68, 68, 61, 62, 68, 68, 66, 66, + 0, 66, 43, 68, 68, 49, 68, 55, 68, 68, + 63, 64, 66, 68, 47, 68, 59, 60, 68, 68, 44, 51, 0 } ; @@ -480,33 +480,33 @@ static const YY_CHAR yy_meta[57] = 5, 5, 1, 1, 1, 1 } ; -static const flex_int16_t yy_base[193] = +static const flex_int16_t yy_base[192] = { 0, - 0, 0, 54, 56, 58, 60, 286, 287, 283, 280, - 280, 60, 287, 287, 287, 57, 287, 287, 287, 287, - 287, 267, 265, 263, 51, 55, 259, 287, 53, 255, - 55, 0, 247, 287, 287, 231, 227, 228, 227, 38, - 50, 226, 55, 225, 26, 222, 231, 54, 223, 226, - 287, 287, 287, 243, 287, 261, 261, 287, 259, 259, - 74, 259, 287, 80, 287, 81, 78, 89, 230, 243, - 287, 85, 89, 287, 103, 0, 287, 287, 287, 287, - 287, 287, 0, 226, 220, 218, 210, 0, 205, 216, - 208, 203, 205, 199, 0, 0, 212, 203, 196, 0, - - 63, 207, 193, 193, 200, 287, 287, 287, 91, 287, - 94, 108, 96, 287, 110, 112, 114, 133, 209, 208, - 0, 205, 188, 199, 0, 187, 0, 199, 175, 182, - 0, 0, 160, 146, 151, 157, 152, 149, 111, 287, - 119, 124, 0, 0, 147, 149, 147, 146, 149, 136, - 0, 141, 148, 131, 0, 0, 134, 139, 165, 128, - 135, 0, 131, 136, 0, 132, 0, 123, 119, 0, - 0, 0, 137, 112, 0, 104, 0, 0, 106, 95, - 0, 0, 287, 204, 209, 214, 219, 222, 224, 131, - 229, 120 + 0, 0, 54, 56, 58, 60, 295, 296, 292, 289, + 289, 60, 296, 296, 296, 57, 296, 296, 296, 296, + 296, 276, 51, 273, 55, 59, 269, 296, 57, 265, + 59, 0, 64, 296, 296, 242, 238, 239, 238, 51, + 52, 237, 60, 236, 26, 233, 242, 59, 234, 237, + 296, 296, 296, 254, 296, 272, 272, 296, 270, 270, + 78, 270, 296, 71, 296, 267, 80, 266, 239, 252, + 90, 296, 94, 99, 296, 108, 251, 296, 296, 296, + 296, 296, 296, 0, 99, 296, 229, 227, 219, 0, + 204, 211, 186, 181, 183, 177, 0, 0, 190, 181, + + 174, 0, 83, 183, 169, 169, 176, 296, 296, 296, + 108, 296, 111, 296, 117, 120, 126, 129, 0, 143, + 0, 183, 158, 169, 0, 157, 0, 169, 158, 169, + 0, 0, 164, 148, 153, 159, 154, 151, 119, 296, + 132, 175, 197, 0, 157, 149, 147, 146, 149, 136, + 0, 141, 150, 135, 0, 0, 130, 135, 0, 0, + 134, 138, 0, 122, 127, 0, 123, 0, 110, 109, + 0, 0, 145, 73, 0, 73, 0, 0, 76, 61, + 0, 0, 296, 236, 241, 246, 251, 254, 256, 259, + 100 } ; -static const flex_int16_t yy_def[193] = +static const flex_int16_t yy_def[192] = { 0, 183, 1, 184, 184, 185, 185, 183, 183, 183, 183, 183, 186, 183, 183, 183, 187, 183, 183, 183, 183, @@ -515,24 +515,24 @@ static const flex_int16_t yy_def[193] = 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 186, 183, 186, 187, 187, 183, 183, - 183, 183, 188, 183, 183, 190, 183, 183, 183, 183, - 183, 183, 189, 191, 189, 189, 189, 189, 189, 189, + 188, 183, 188, 188, 183, 183, 190, 183, 183, 183, + 183, 183, 183, 189, 183, 183, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, - 189, 189, 189, 189, 189, 183, 183, 183, 183, 183, - 186, 187, 183, 183, 188, 183, 188, 188, 191, 191, + 189, 189, 189, 189, 189, 189, 189, 183, 183, 183, + 183, 183, 183, 183, 188, 188, 183, 188, 191, 188, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 189, 183, 183, - 188, 188, 192, 118, 183, 189, 189, 189, 189, 189, - 189, 189, 189, 189, 189, 189, 189, 189, 118, 183, - 188, 189, 189, 189, 189, 189, 189, 189, 189, 189, - 189, 159, 188, 189, 189, 189, 189, 189, 189, 189, + 188, 120, 142, 120, 183, 189, 189, 189, 189, 189, + 189, 189, 189, 189, 189, 189, 189, 189, 142, 143, + 183, 188, 189, 189, 189, 189, 189, 189, 189, 189, + 189, 189, 188, 189, 189, 189, 189, 189, 189, 189, 189, 189, 0, 183, 183, 183, 183, 183, 183, 183, - 183, 183 + 183 } ; -static const flex_int16_t yy_nxt[344] = +static const flex_int16_t yy_nxt[353] = { 0, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, @@ -540,41 +540,42 @@ static const flex_int16_t yy_nxt[344] = 8, 34, 35, 36, 37, 38, 39, 40, 41, 42, 32, 43, 32, 44, 45, 46, 32, 47, 32, 48, 49, 50, 51, 52, 53, 54, 56, 57, 56, 57, - 59, 60, 59, 60, 65, 65, 72, 98, 73, 73, - 72, 99, 73, 73, 78, 79, 75, 81, 82, 76, - 75, 89, 90, 91, 65, 111, 65, 68, 75, 61, - 66, 61, 75, 95, 102, 92, 109, 112, 65, 96, - - 93, 103, 115, 115, 72, 110, 73, 73, 68, 133, - 66, 66, 134, 109, 75, 116, 65, 116, 139, 68, - 117, 117, 110, 159, 66, 140, 75, 141, 141, 117, - 117, 142, 142, 139, 118, 75, 141, 141, 68, 182, - 140, 142, 142, 181, 75, 161, 161, 75, 143, 180, - 144, 144, 173, 173, 173, 173, 75, 144, 144, 160, - 145, 160, 179, 178, 161, 161, 144, 144, 144, 144, - 144, 144, 177, 176, 175, 174, 171, 170, 169, 145, - 74, 168, 172, 172, 167, 166, 165, 164, 163, 172, - 172, 162, 158, 157, 156, 155, 154, 153, 172, 172, - - 172, 172, 172, 172, 55, 55, 55, 55, 55, 58, - 58, 58, 58, 58, 64, 152, 64, 64, 64, 67, - 151, 67, 67, 67, 74, 74, 74, 83, 83, 119, - 119, 119, 119, 119, 150, 149, 148, 147, 146, 65, - 120, 138, 137, 136, 135, 132, 131, 130, 129, 128, - 127, 126, 125, 124, 123, 122, 121, 120, 114, 113, - 62, 108, 108, 107, 107, 106, 105, 104, 101, 100, - 97, 94, 88, 87, 86, 85, 84, 80, 77, 71, - 70, 69, 63, 63, 62, 183, 7, 183, 183, 183, - 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, + 59, 60, 59, 60, 65, 65, 70, 100, 71, 71, + 73, 101, 74, 74, 73, 65, 74, 74, 79, 80, + 76, 82, 83, 77, 76, 93, 85, 68, 65, 61, + 66, 61, 76, 86, 91, 92, 76, 94, 97, 104, + + 111, 66, 95, 142, 98, 182, 105, 115, 115, 112, + 68, 116, 116, 181, 73, 76, 74, 74, 180, 76, + 117, 85, 117, 179, 76, 118, 118, 76, 86, 133, + 111, 76, 134, 139, 115, 115, 76, 116, 116, 112, + 140, 139, 76, 118, 118, 76, 141, 141, 140, 141, + 141, 162, 162, 178, 76, 173, 173, 76, 143, 177, + 144, 144, 173, 173, 176, 175, 174, 144, 144, 161, + 145, 161, 172, 171, 162, 162, 144, 144, 144, 144, + 144, 144, 170, 169, 168, 167, 166, 165, 164, 145, + 75, 163, 159, 159, 158, 157, 156, 155, 154, 159, + + 159, 153, 152, 151, 150, 149, 148, 147, 159, 159, + 159, 159, 159, 159, 160, 160, 146, 138, 137, 136, + 135, 160, 160, 132, 131, 130, 129, 128, 127, 126, + 160, 160, 160, 160, 160, 160, 55, 55, 55, 55, + 55, 58, 58, 58, 58, 58, 64, 125, 64, 64, + 64, 67, 124, 67, 67, 67, 75, 75, 75, 84, + 84, 120, 120, 123, 122, 121, 119, 114, 113, 67, + 64, 62, 110, 110, 109, 109, 108, 107, 106, 103, + 102, 99, 96, 90, 89, 88, 87, 81, 78, 72, + 69, 63, 63, 62, 183, 7, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, - 183, 183, 183 + 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, + 183, 183 } ; -static const flex_int16_t yy_chk[344] = +static const flex_int16_t yy_chk[353] = { 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, @@ -582,58 +583,59 @@ static const flex_int16_t yy_chk[344] = 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 3, 3, 4, 4, - 5, 5, 6, 6, 12, 16, 25, 45, 25, 25, - 26, 45, 26, 26, 29, 29, 25, 31, 31, 25, - 26, 40, 40, 41, 64, 66, 67, 16, 25, 5, - 12, 6, 26, 43, 48, 41, 61, 68, 111, 43, - - 41, 48, 72, 72, 73, 61, 73, 73, 67, 101, - 64, 66, 101, 109, 73, 75, 112, 75, 113, 68, - 75, 75, 109, 192, 111, 113, 73, 115, 115, 116, - 116, 117, 117, 139, 190, 115, 141, 141, 112, 180, - 139, 142, 142, 179, 141, 160, 160, 115, 118, 176, - 118, 118, 161, 161, 173, 173, 141, 118, 118, 145, - 118, 145, 174, 169, 145, 145, 118, 118, 118, 118, - 118, 118, 168, 166, 164, 163, 158, 157, 154, 118, - 159, 153, 159, 159, 152, 150, 149, 148, 147, 159, - 159, 146, 138, 137, 136, 135, 134, 133, 159, 159, - - 159, 159, 159, 159, 184, 184, 184, 184, 184, 185, - 185, 185, 185, 185, 186, 130, 186, 186, 186, 187, - 129, 187, 187, 187, 188, 188, 188, 189, 189, 191, - 191, 191, 191, 191, 128, 126, 124, 123, 122, 120, - 119, 105, 104, 103, 102, 99, 98, 97, 94, 93, - 92, 91, 90, 89, 87, 86, 85, 84, 70, 69, - 62, 60, 59, 57, 56, 54, 50, 49, 47, 46, - 44, 42, 39, 38, 37, 36, 33, 30, 27, 24, - 23, 22, 11, 10, 9, 7, 183, 183, 183, 183, - 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, + 5, 5, 6, 6, 12, 16, 23, 45, 23, 23, + 25, 45, 25, 25, 26, 64, 26, 26, 29, 29, + 25, 31, 31, 25, 26, 41, 33, 16, 67, 5, + 12, 6, 25, 33, 40, 40, 26, 41, 43, 48, + + 61, 64, 41, 191, 43, 180, 48, 71, 71, 61, + 67, 73, 73, 179, 74, 71, 74, 74, 176, 73, + 76, 85, 76, 174, 74, 76, 76, 71, 85, 103, + 111, 73, 103, 113, 115, 115, 74, 116, 116, 111, + 113, 139, 115, 117, 117, 116, 118, 118, 139, 141, + 141, 161, 161, 170, 115, 162, 162, 116, 120, 169, + 120, 120, 173, 173, 167, 165, 164, 120, 120, 145, + 120, 145, 158, 157, 145, 145, 120, 120, 120, 120, + 120, 120, 154, 153, 152, 150, 149, 148, 147, 120, + 142, 146, 142, 142, 138, 137, 136, 135, 134, 142, + + 142, 133, 130, 129, 128, 126, 124, 123, 142, 142, + 142, 142, 142, 142, 143, 143, 122, 107, 106, 105, + 104, 143, 143, 101, 100, 99, 96, 95, 94, 93, + 143, 143, 143, 143, 143, 143, 184, 184, 184, 184, + 184, 185, 185, 185, 185, 185, 186, 92, 186, 186, + 186, 187, 91, 187, 187, 187, 188, 188, 188, 189, + 189, 190, 190, 89, 88, 87, 77, 70, 69, 68, + 66, 62, 60, 59, 57, 56, 54, 50, 49, 47, + 46, 44, 42, 39, 38, 37, 36, 30, 27, 24, + 22, 11, 10, 9, 7, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, - 183, 183, 183 + 183, 183, 183, 183, 183, 183, 183, 183, 183, 183, + 183, 183 } ; /* Table of booleans, true if rule could match eol. */ -static const flex_int32_t yy_rule_can_match_eol[73] = +static const flex_int32_t yy_rule_can_match_eol[74] = { 0, -0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, - 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 0, 0, }; +0, 0, 1, 0, 0, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, }; -static const flex_int16_t yy_rule_linenum[72] = +static const flex_int16_t yy_rule_linenum[73] = { 0, - 83, 84, 85, 86, 89, 90, 91, 93, 94, 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, 153, 158, 160, 162, 165, - 167 + 219, 220, 229, 230, 233, 234, 235, 237, 238, 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, 297, 302, 304, 306, 308, + 311, 313 } ; /* The intent behind this definition is that it'll catch @@ -658,48 +660,33 @@ static const flex_int16_t yy_rule_linenum[72] = #endif #include "compile/my_flexer.h" -namespace { -// Compile-time token metadata only; no runtime dispatch changes or new exported symbol. -void TrackStringLocation(yy::location &loc, std::string_view text) { - if (text.empty() || text.front() != '[') return; - loc.end = loc.begin; - for (size_t i = 0; i < text.size(); ++i) { - if (text[i] == '\r' || text[i] == '\n') { - if (i + 1 < text.size() && (text[i + 1] == '\r' || text[i + 1] == '\n') && text[i + 1] != text[i]) ++i; - loc.lines(1); - } else { - loc.columns(1); - } - } -} -} - // https://westes.github.io/flex/manual/Cxx.html // Give Flex the prototype of yylex we want ... # define YY_DECL \ yy::parser::symbol_type fakelua::MyFlexer::MyYylex() -#line 684 "scanner.cpp" -#line 40 "scanner.l" +#line 670 "scanner.cpp" +#line 24 "scanner.l" #define FLEX_VERSION (YY_FLEX_MAJOR_VERSION * 100 + YY_FLEX_MINOR_VERSION) -#line 689 "scanner.cpp" +#line 675 "scanner.cpp" #define YY_NO_INPUT 1 -#line 50 "scanner.l" +#line 34 "scanner.l" -#line 694 "scanner.cpp" +#line 680 "scanner.cpp" /* 短字符串里不能出现裸换行(\n 和 \r 都算),与 Lua 的 "unfinished string" 一致。 - 需要跨行的内容用 [[ ]] 长字符串或转义写法。 */ + 需要跨行的内容用 [[ ]] / [=[ ]=] 长字符串或转义写法。 */ /* 字面量不带符号:Lua 把 +1 / -1 拆成一元运算符 + 无符号数字。 - 若把 - 写进数字 token,x-1、1-1、x -1 都会变成 IDENT/NUMBER NUMBER,无法解析。 */ -#line 68 "scanner.l" + 若把 - 写进数字 token,x-1、1-1、x -1 都会变成 IDENT/NUMBER NUMBER,无法解析。 + 支持前导/尾随小数点(.5、1.、0x.8、0x1.),内核模式下由 CheckKernelProfile 统一拒绝非整数。 */ +#line 52 "scanner.l" // Code run each time a pattern is matched. # define YY_USER_ACTION loc.columns (yyleng); -#line 702 "scanner.cpp" -#line 703 "scanner.cpp" +#line 689 "scanner.cpp" +#line 690 "scanner.cpp" #define INITIAL 0 #define SINGLE_LINE_COMMENT_STATE 1 @@ -856,7 +843,7 @@ YY_DECL yy_state_type yy_current_state; char *yy_cp, *yy_bp; int yy_act; - + if ( !(yy_init) ) { (yy_init) = 1; @@ -893,15 +880,50 @@ YY_DECL { /* %% [7.0] user's declarations go here */ -#line 72 "scanner.l" +#line 56 "scanner.l" -#line 76 "scanner.l" +#line 60 "scanner.l" yy::location& loc = location_; // Code run each time yylex is called. loc.step (); + auto peek_char = [&]() -> int { + if ((yy_hold_char) != YY_END_OF_BUFFER_CHAR || (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]) { + return static_cast(yy_hold_char); + } + *(yy_c_buf_p) = (yy_hold_char); + (yytext_ptr) = (yy_c_buf_p); + ++(yy_c_buf_p); + switch (yy_get_next_buffer()) { + case EOB_ACT_LAST_MATCH: + yyrestart(yyin); + [[fallthrough]]; + case EOB_ACT_END_OF_FILE: + return -1; + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = (yytext_ptr); + (yy_hold_char) = *(yy_c_buf_p); + *(yy_c_buf_p) = '\0'; + return static_cast(yy_hold_char); + } + return -1; + }; + + auto advance_char = [&]() -> int { + const int c = peek_char(); + if (c < 0) { + return -1; + } + *(yy_c_buf_p) = '\0'; + (yy_hold_char) = *++(yy_c_buf_p); + if (c == '\n') { + ++yylineno; + } + return c; + }; + auto scan_short_string = [&]() -> yy::parser::symbol_type { const char quote = yytext[0]; loc.end = loc.begin; @@ -909,41 +931,6 @@ YY_DECL const yy::location start_loc = loc; yyless(1); - auto peek_char = [&]() -> int { - if ((yy_hold_char) != YY_END_OF_BUFFER_CHAR || (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]) { - return static_cast(yy_hold_char); - } - *(yy_c_buf_p) = (yy_hold_char); - (yytext_ptr) = (yy_c_buf_p); - ++(yy_c_buf_p); - switch (yy_get_next_buffer()) { - case EOB_ACT_LAST_MATCH: - yyrestart(yyin); - [[fallthrough]]; - case EOB_ACT_END_OF_FILE: - return -1; - case EOB_ACT_CONTINUE_SCAN: - (yy_c_buf_p) = (yytext_ptr); - (yy_hold_char) = *(yy_c_buf_p); - *(yy_c_buf_p) = '\0'; - return static_cast(yy_hold_char); - } - return -1; - }; - - auto advance_char = [&]() -> int { - const int c = peek_char(); - if (c < 0) { - return -1; - } - *(yy_c_buf_p) = '\0'; - (yy_hold_char) = *++(yy_c_buf_p); - if (c == '\n') { - ++yylineno; - } - return c; - }; - std::string raw; raw.push_back(quote); for (;;) { @@ -999,10 +986,65 @@ YY_DECL } }; + auto scan_long_string = [&](size_t level) -> yy::parser::symbol_type { + const yy::location start_loc = loc; + std::string raw; + raw.push_back('['); + raw.append(level, '='); + raw.push_back('['); + + // Lua 5.4: ignore a single newline immediately following the opening long bracket. + const int first = peek_char(); + if (first == '\n' || first == '\r') { + advance_char(); + const int second = peek_char(); + if ((second == '\n' || second == '\r') && second != first) { + advance_char(); + } + loc.lines(1); + } + + for (;;) { + const int c = advance_char(); + if (c < 0) { + throw yy::parser::syntax_error(start_loc, "unfinished long string"); + } + if (c == '\n' || c == '\r') { + const int next_nl = peek_char(); + if ((next_nl == '\n' || next_nl == '\r') && next_nl != c) { + advance_char(); + } + loc.lines(1); + raw.push_back('\n'); + } else if (c == ']') { + loc.columns(1); + size_t eq = 0; + while (peek_char() == '=') { + advance_char(); + loc.columns(1); + ++eq; + } + if (eq == level && peek_char() == ']') { + advance_char(); + loc.columns(1); + raw.push_back(']'); + raw.append(level, '='); + raw.push_back(']'); + return yy::parser::make_STRING(raw, loc); + } + raw.push_back(']'); + raw.append(eq, '='); + } else { + loc.columns(1); + raw.push_back(static_cast(c)); + } + } + }; + /* 长注释按 Lua 的长括号层级处理:--[[ 配 ]],--[==[ 配 ]==],层级不匹配的 ]] 只是普通内容。传统的 --]] 收尾依然有效,因为其中的 ]] 就是 0 级闭括号。 */ -#line 909 "scanner.cpp" +#line 1048 "scanner.cpp" while ( /*CONSTCOND*/1 ) /* loops until end-of-file is reached */ { @@ -1054,7 +1096,7 @@ YY_DECL int yyl; for ( yyl = 0; yyl < yyleng; ++yyl ) if ( yytext[yyl] == '\n' ) - + yylineno++; ; } @@ -1066,12 +1108,12 @@ YY_DECL { if ( yy_act == 0 ) std::cerr << "--scanner backing up\n"; - else if ( yy_act < 72 ) + else if ( yy_act < 73 ) std::cerr << "--accepting rule at line " << yy_rule_linenum[yy_act] << "(\"" << yytext << "\")\n"; - else if ( yy_act == 72 ) - std::cerr << "--accepting default rule (\"" << yytext << "\")\n"; else if ( yy_act == 73 ) + std::cerr << "--accepting default rule (\"" << yytext << "\")\n"; + else if ( yy_act == 74 ) std::cerr << "--(end of buffer or a NUL)\n"; else std::cerr << "--EOF (start condition " << YY_START << ")\n"; @@ -1089,339 +1131,347 @@ YY_DECL case 1: YY_RULE_SETUP -#line 83 "scanner.l" +#line 219 "scanner.l" { long_comment_level_ = static_cast(yyleng) - 4; yy_push_state(MULTI_LINE_COMMENT_STATE); } YY_BREAK case 2: YY_RULE_SETUP -#line 84 "scanner.l" -{ if (static_cast(yyleng) - 2 == long_comment_level_) yy_pop_state(); } +#line 220 "scanner.l" +{ + if (static_cast(yyleng) - 2 == long_comment_level_) { + yy_pop_state(); + } else { + loc.end = loc.begin; + loc.columns(1); + yyless(1); + } +} YY_BREAK case 3: /* rule 3 can match eol */ YY_RULE_SETUP -#line 85 "scanner.l" +#line 229 "scanner.l" { loc.lines(1); loc.step(); } YY_BREAK case 4: YY_RULE_SETUP -#line 86 "scanner.l" +#line 230 "scanner.l" { } YY_BREAK case YY_STATE_EOF(MULTI_LINE_COMMENT_STATE): -#line 87 "scanner.l" +#line 231 "scanner.l" { throw yy::parser::syntax_error(loc, "unfinished long comment"); } YY_BREAK case 5: YY_RULE_SETUP -#line 89 "scanner.l" +#line 233 "scanner.l" { yy_push_state(SINGLE_LINE_COMMENT_STATE); } YY_BREAK case 6: /* rule 6 can match eol */ YY_RULE_SETUP -#line 90 "scanner.l" +#line 234 "scanner.l" { loc.lines(1); loc.step(); yy_pop_state(); } YY_BREAK case 7: YY_RULE_SETUP -#line 91 "scanner.l" +#line 235 "scanner.l" { } YY_BREAK case 8: YY_RULE_SETUP -#line 93 "scanner.l" +#line 237 "scanner.l" loc.step (); YY_BREAK case 9: /* rule 9 can match eol */ YY_RULE_SETUP -#line 94 "scanner.l" +#line 238 "scanner.l" loc.lines(1); loc.step(); YY_BREAK case 10: YY_RULE_SETUP -#line 96 "scanner.l" +#line 240 "scanner.l" return yy::parser::make_MOD(loc); YY_BREAK case 11: YY_RULE_SETUP -#line 97 "scanner.l" +#line 241 "scanner.l" return yy::parser::make_BITAND(loc); YY_BREAK case 12: YY_RULE_SETUP -#line 98 "scanner.l" +#line 242 "scanner.l" return yy::parser::make_BITOR(loc); YY_BREAK case 13: YY_RULE_SETUP -#line 99 "scanner.l" +#line 243 "scanner.l" return yy::parser::make_BITNOT(loc); YY_BREAK case 14: YY_RULE_SETUP -#line 100 "scanner.l" +#line 244 "scanner.l" return yy::parser::make_MORE(loc); YY_BREAK case 15: YY_RULE_SETUP -#line 101 "scanner.l" +#line 245 "scanner.l" return yy::parser::make_LESS(loc); YY_BREAK case 16: YY_RULE_SETUP -#line 102 "scanner.l" +#line 246 "scanner.l" return yy::parser::make_NUMBER_SIGN(loc); YY_BREAK case 17: YY_RULE_SETUP -#line 103 "scanner.l" +#line 247 "scanner.l" return yy::parser::make_POW(loc); YY_BREAK case 18: YY_RULE_SETUP -#line 104 "scanner.l" +#line 248 "scanner.l" return yy::parser::make_SEMICOLON(loc); YY_BREAK case 19: YY_RULE_SETUP -#line 105 "scanner.l" +#line 249 "scanner.l" return yy::parser::make_COLON(loc); YY_BREAK case 20: YY_RULE_SETUP -#line 106 "scanner.l" +#line 250 "scanner.l" return yy::parser::make_COMMA(loc); YY_BREAK case 21: YY_RULE_SETUP -#line 107 "scanner.l" +#line 251 "scanner.l" return yy::parser::make_DOT(loc); YY_BREAK case 22: YY_RULE_SETUP -#line 108 "scanner.l" +#line 252 "scanner.l" return yy::parser::make_CONCAT(loc); YY_BREAK case 23: YY_RULE_SETUP -#line 109 "scanner.l" +#line 253 "scanner.l" return yy::parser::make_VAR_PARAMS(loc); YY_BREAK case 24: YY_RULE_SETUP -#line 110 "scanner.l" +#line 254 "scanner.l" return yy::parser::make_EQUAL(loc); YY_BREAK case 25: YY_RULE_SETUP -#line 111 "scanner.l" +#line 255 "scanner.l" return yy::parser::make_MORE_EQUAL(loc); YY_BREAK case 26: YY_RULE_SETUP -#line 112 "scanner.l" +#line 256 "scanner.l" return yy::parser::make_LESS_EQUAL(loc); YY_BREAK case 27: YY_RULE_SETUP -#line 113 "scanner.l" +#line 257 "scanner.l" return yy::parser::make_NOT_EQUAL(loc); YY_BREAK case 28: YY_RULE_SETUP -#line 114 "scanner.l" +#line 258 "scanner.l" return yy::parser::make_LEFT_SHIFT(loc); YY_BREAK case 29: YY_RULE_SETUP -#line 115 "scanner.l" +#line 259 "scanner.l" return yy::parser::make_RIGHT_SHIFT(loc); YY_BREAK case 30: YY_RULE_SETUP -#line 116 "scanner.l" +#line 260 "scanner.l" return yy::parser::make_GOTO_TAG(loc); YY_BREAK case 31: YY_RULE_SETUP -#line 117 "scanner.l" +#line 261 "scanner.l" return yy::parser::make_ASSIGN(loc); YY_BREAK case 32: YY_RULE_SETUP -#line 118 "scanner.l" +#line 262 "scanner.l" return yy::parser::make_MINUS(loc); YY_BREAK case 33: YY_RULE_SETUP -#line 119 "scanner.l" +#line 263 "scanner.l" return yy::parser::make_PLUS(loc); YY_BREAK case 34: YY_RULE_SETUP -#line 120 "scanner.l" +#line 264 "scanner.l" return yy::parser::make_STAR(loc); YY_BREAK case 35: YY_RULE_SETUP -#line 121 "scanner.l" +#line 265 "scanner.l" return yy::parser::make_SLASH(loc); YY_BREAK case 36: YY_RULE_SETUP -#line 122 "scanner.l" +#line 266 "scanner.l" return yy::parser::make_LPAREN(loc); YY_BREAK case 37: YY_RULE_SETUP -#line 123 "scanner.l" +#line 267 "scanner.l" return yy::parser::make_RPAREN(loc); YY_BREAK case 38: YY_RULE_SETUP -#line 124 "scanner.l" +#line 268 "scanner.l" return yy::parser::make_LCURLY(loc); YY_BREAK case 39: YY_RULE_SETUP -#line 125 "scanner.l" +#line 269 "scanner.l" return yy::parser::make_RCURLY(loc); YY_BREAK case 40: YY_RULE_SETUP -#line 126 "scanner.l" +#line 270 "scanner.l" return yy::parser::make_LSQUARE(loc); YY_BREAK case 41: YY_RULE_SETUP -#line 127 "scanner.l" +#line 271 "scanner.l" return yy::parser::make_RSQUARE(loc); YY_BREAK case 42: YY_RULE_SETUP -#line 128 "scanner.l" +#line 272 "scanner.l" return yy::parser::make_AND(loc); YY_BREAK case 43: YY_RULE_SETUP -#line 129 "scanner.l" +#line 273 "scanner.l" return yy::parser::make_BREAK(loc); YY_BREAK case 44: YY_RULE_SETUP -#line 130 "scanner.l" +#line 274 "scanner.l" return yy::parser::make_CONTINUE(loc); YY_BREAK case 45: YY_RULE_SETUP -#line 131 "scanner.l" +#line 275 "scanner.l" return yy::parser::make_DO(loc); YY_BREAK case 46: YY_RULE_SETUP -#line 132 "scanner.l" +#line 276 "scanner.l" return yy::parser::make_ELSE(loc); YY_BREAK case 47: YY_RULE_SETUP -#line 133 "scanner.l" +#line 277 "scanner.l" return yy::parser::make_ELSEIF(loc); YY_BREAK case 48: YY_RULE_SETUP -#line 134 "scanner.l" +#line 278 "scanner.l" return yy::parser::make_END(loc); YY_BREAK case 49: YY_RULE_SETUP -#line 135 "scanner.l" +#line 279 "scanner.l" return yy::parser::make_FALSES(loc); YY_BREAK case 50: YY_RULE_SETUP -#line 136 "scanner.l" +#line 280 "scanner.l" return yy::parser::make_FOR(loc); YY_BREAK case 51: YY_RULE_SETUP -#line 137 "scanner.l" +#line 281 "scanner.l" return yy::parser::make_FUNCTION(loc); YY_BREAK case 52: YY_RULE_SETUP -#line 138 "scanner.l" +#line 282 "scanner.l" return yy::parser::make_GOTO(loc); YY_BREAK case 53: YY_RULE_SETUP -#line 139 "scanner.l" +#line 283 "scanner.l" return yy::parser::make_IF(loc); YY_BREAK case 54: YY_RULE_SETUP -#line 140 "scanner.l" +#line 284 "scanner.l" return yy::parser::make_IN(loc); YY_BREAK case 55: YY_RULE_SETUP -#line 141 "scanner.l" +#line 285 "scanner.l" return yy::parser::make_LOCAL(loc); YY_BREAK case 56: YY_RULE_SETUP -#line 142 "scanner.l" +#line 286 "scanner.l" return yy::parser::make_NIL(loc); YY_BREAK case 57: YY_RULE_SETUP -#line 143 "scanner.l" +#line 287 "scanner.l" return yy::parser::make_NOT(loc); YY_BREAK case 58: YY_RULE_SETUP -#line 144 "scanner.l" +#line 288 "scanner.l" return yy::parser::make_OR(loc); YY_BREAK case 59: YY_RULE_SETUP -#line 145 "scanner.l" +#line 289 "scanner.l" return yy::parser::make_REPEAT(loc); YY_BREAK case 60: YY_RULE_SETUP -#line 146 "scanner.l" +#line 290 "scanner.l" return yy::parser::make_RETURN(loc); YY_BREAK case 61: YY_RULE_SETUP -#line 147 "scanner.l" +#line 291 "scanner.l" return yy::parser::make_THEN(loc); YY_BREAK case 62: YY_RULE_SETUP -#line 148 "scanner.l" +#line 292 "scanner.l" return yy::parser::make_TRUE(loc); YY_BREAK case 63: YY_RULE_SETUP -#line 149 "scanner.l" +#line 293 "scanner.l" return yy::parser::make_UNTIL(loc); YY_BREAK case 64: YY_RULE_SETUP -#line 150 "scanner.l" +#line 294 "scanner.l" return yy::parser::make_WHILE(loc); YY_BREAK case 65: YY_RULE_SETUP -#line 151 "scanner.l" +#line 295 "scanner.l" return yy::parser::make_DOUBLE_SLASH(loc); YY_BREAK case 66: YY_RULE_SETUP -#line 153 "scanner.l" +#line 297 "scanner.l" return yy::parser::make_NUMBER(yytext, loc); YY_BREAK /* Lua 读数字时会把紧跟其后的字母、数字和点一起吞掉再做校验,所以 3and、1local、 @@ -1429,48 +1479,46 @@ return yy::parser::make_NUMBER(yytext, loc); 靠前的规则,于是 0x1f、1e2 这类合法写法仍走 {number}。 */ case 67: YY_RULE_SETUP -#line 158 "scanner.l" +#line 302 "scanner.l" { throw yy::parser::syntax_error(loc, "malformed number near '" + std::string(yytext) + "'"); } YY_BREAK case 68: YY_RULE_SETUP -#line 160 "scanner.l" +#line 304 "scanner.l" return yy::parser::make_IDENTIFIER(yytext, loc); YY_BREAK case 69: -/* rule 69 can match eol */ YY_RULE_SETUP -#line 162 "scanner.l" -{ - if (yytext[0] == '"' || yytext[0] == '\'') { - return scan_short_string(); - } - TrackStringLocation(loc, std::string_view(yytext, static_cast(yyleng))); - return yy::parser::make_STRING(std::string(yytext, static_cast(yyleng)), loc); -} +#line 306 "scanner.l" +{ return scan_long_string(static_cast(yyleng) - 2); } YY_BREAK -/* A quote reaches this fallback when a short string contains escaped newlines or is unfinished. */ case 70: YY_RULE_SETUP -#line 165 "scanner.l" +#line 308 "scanner.l" { return scan_short_string(); } YY_BREAK +/* A quote reaches this fallback when a short string contains escaped newlines or is unfinished. */ case 71: YY_RULE_SETUP -#line 167 "scanner.l" +#line 311 "scanner.l" +{ return scan_short_string(); } + YY_BREAK +case 72: +YY_RULE_SETUP +#line 313 "scanner.l" { throw yy::parser::syntax_error(loc, "invalid character: [" + std::string(yytext) + "]"); } YY_BREAK case YY_STATE_EOF(INITIAL): case YY_STATE_EOF(SINGLE_LINE_COMMENT_STATE): -#line 169 "scanner.l" +#line 315 "scanner.l" return yy::parser::symbol_type(static_cast(0), loc); YY_BREAK -case 72: +case 73: YY_RULE_SETUP -#line 171 "scanner.l" +#line 317 "scanner.l" ECHO; YY_BREAK -#line 1371 "scanner.cpp" +#line 1522 "scanner.cpp" case YY_END_OF_BUFFER: { @@ -1892,7 +1940,7 @@ int yyFlexLexer::yy_get_next_buffer() { yy_state_type yy_current_state; char *yy_cp; - + /* %% [15.0] code to get the start state into yy_current_state goes here */ yy_current_state = (yy_start); @@ -1958,7 +2006,7 @@ int yyFlexLexer::yy_get_next_buffer() /* %endif */ { char *yy_cp; - + yy_cp = (yy_c_buf_p); /* undo effects of setting up yytext */ @@ -2008,7 +2056,7 @@ int yyFlexLexer::yy_get_next_buffer() /* %endif */ { int c; - + *(yy_c_buf_p) = (yy_hold_char); if ( *(yy_c_buf_p) == YY_END_OF_BUFFER_CHAR ) @@ -2071,7 +2119,7 @@ int yyFlexLexer::yy_get_next_buffer() /* %% [19.0] update BOL and yylineno */ if ( c == '\n' ) - + yylineno++; ; @@ -2082,7 +2130,7 @@ int yyFlexLexer::yy_get_next_buffer() /** Immediately switch to a different input stream. * @param input_file A readable stream. - * + * * @note This function does not reset the start condition to @c INITIAL . */ /* %if-c-only */ @@ -2091,7 +2139,7 @@ int yyFlexLexer::yy_get_next_buffer() void yyFlexLexer::yyrestart( std::istream& input_file ) /* %endif */ { - + if ( ! YY_CURRENT_BUFFER ){ yyensure_buffer_stack (); YY_CURRENT_BUFFER_LVALUE = @@ -2105,7 +2153,7 @@ int yyFlexLexer::yy_get_next_buffer() /* %if-c++-only */ /** Delegate to the new version that takes an istream reference. * @param input_file A readable stream. - * + * * @note This function does not reset the start condition to @c INITIAL . */ void yyFlexLexer::yyrestart( std::istream* input_file ) @@ -2119,7 +2167,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) /** Switch to a different input buffer. * @param new_buffer The new input buffer. - * + * */ /* %if-c-only */ /* %endif */ @@ -2127,7 +2175,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) void yyFlexLexer::yy_switch_to_buffer( YY_BUFFER_STATE new_buffer ) /* %endif */ { - + /* TODO. We should be able to replace this entire function body * with * yypop_buffer_state(); @@ -2175,7 +2223,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) /** Allocate and initialize an input buffer state. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. - * + * * @return the allocated buffer state. */ /* %if-c-only */ @@ -2185,7 +2233,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) /* %endif */ { YY_BUFFER_STATE b; - + b = (YY_BUFFER_STATE) yyalloc( sizeof( struct yy_buffer_state ) ); if ( ! b ) YY_FATAL_ERROR( "out of dynamic memory in yy_create_buffer()" ); @@ -2210,7 +2258,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) /** Delegate creation of buffers to the new version that takes an istream reference. * @param file A readable stream. * @param size The character buffer size in bytes. When in doubt, use @c YY_BUF_SIZE. - * + * * @return the allocated buffer state. */ YY_BUFFER_STATE yyFlexLexer::yy_create_buffer( std::istream* file, int size ) @@ -2221,7 +2269,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) /** Destroy the buffer. * @param b a buffer created with yy_create_buffer() - * + * */ /* %if-c-only */ /* %endif */ @@ -2229,7 +2277,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) void yyFlexLexer::yy_delete_buffer( YY_BUFFER_STATE b ) /* %endif */ { - + if ( ! b ) return; @@ -2254,7 +2302,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) { int oerrno = errno; - + yy_flush_buffer( b ); /* %if-c-only */ @@ -2283,7 +2331,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) /** Discard all buffered characters. On the next scan, YY_INPUT will be called. * @param b the buffer state to be flushed, usually @c YY_CURRENT_BUFFER. - * + * */ /* %if-c-only */ /* %endif */ @@ -2317,7 +2365,7 @@ void yyFlexLexer::yyrestart( std::istream* input_file ) * the current state. This function will allocate the stack * if necessary. * @param new_buffer The new state. - * + * */ /* %if-c-only */ /* %endif */ @@ -2353,7 +2401,7 @@ void yyFlexLexer::yypush_buffer_state (YY_BUFFER_STATE new_buffer) /* %if-c-or-c++ */ /** Removes and deletes the top of the stack, if present. * The next element becomes the new top. - * + * */ /* %if-c-only */ /* %endif */ @@ -2387,7 +2435,7 @@ void yyFlexLexer::yyensure_buffer_stack(void) /* %endif */ { yy_size_t num_to_alloc; - + if (!(yy_buffer_stack)) { /* First allocation is just for 2 elements, since we don't know if this @@ -2547,7 +2595,7 @@ void yyFlexLexer::LexerError( const char* msg ) #ifndef yytext_ptr static void yy_flex_strncpy (char* s1, const char * s2, int n ) { - + int i; for ( i = 0; i < n; ++i ) s1[i] = s2[i]; @@ -2572,7 +2620,7 @@ void *yyalloc (yy_size_t size ) void *yyrealloc (void * ptr, yy_size_t size ) { - + /* The cast to (char *) in the following accommodates both * implementations that use char* generic pointers, and those * that use void* generic pointers. It works with the latter @@ -2595,6 +2643,6 @@ void yyfree (void * ptr ) /* %ok-for-header */ -#line 171 "scanner.l" +#line 317 "scanner.l" diff --git a/src/compile/flex/scanner.l b/src/compile/flex/scanner.l index 2fae95e3..8093016f 100644 --- a/src/compile/flex/scanner.l +++ b/src/compile/flex/scanner.l @@ -12,22 +12,6 @@ #endif #include "compile/my_flexer.h" -namespace { -// Compile-time token metadata only; no runtime dispatch changes or new exported symbol. -void TrackStringLocation(yy::location &loc, std::string_view text) { - if (text.empty() || text.front() != '[') return; - loc.end = loc.begin; - for (size_t i = 0; i < text.size(); ++i) { - if (text[i] == '\r' || text[i] == '\n') { - if (i + 1 < text.size() && (text[i + 1] == '\r' || text[i + 1] == '\n') && text[i + 1] != text[i]) ++i; - loc.lines(1); - } else { - loc.columns(1); - } - } -} -} - // https://westes.github.io/flex/manual/Cxx.html // Give Flex the prototype of yylex we want ... @@ -51,17 +35,17 @@ void TrackStringLocation(yy::location &loc, std::string_view text) { %} /* 短字符串里不能出现裸换行(\n 和 \r 都算),与 Lua 的 "unfinished string" 一致。 - 需要跨行的内容用 [[ ]] 长字符串或转义写法。 */ + 需要跨行的内容用 [[ ]] / [=[ ]=] 长字符串或转义写法。 */ string1 \"(\\.|[^\"\\\n\r])*\" string2 \'(\\.|[^'\\\n\r])*\' -string3 \[\[([^\]]|(\][^\]]))*\]\] -string {string1}|{string2}|{string3} +string {string1}|{string2} name [_a-zA-Z][_a-zA-Z0-9]* newline \r\n|\n\r|\r|\n /* 字面量不带符号:Lua 把 +1 / -1 拆成一元运算符 + 无符号数字。 - 若把 - 写进数字 token,x-1、1-1、x -1 都会变成 IDENT/NUMBER NUMBER,无法解析。 */ -num1 [0-9]+(\.[0-9]+)?([eE][+-]?[0-9]+)? -num2 0[xX][0-9a-fA-F]+(\.[0-9a-fA-F]+)?([pP][+-]?[0-9]+)? + 若把 - 写进数字 token,x-1、1-1、x -1 都会变成 IDENT/NUMBER NUMBER,无法解析。 + 支持前导/尾随小数点(.5、1.、0x.8、0x1.),内核模式下由 CheckKernelProfile 统一拒绝非整数。 */ +num1 ([0-9]+(\.[0-9]*)?|\.[0-9]+)([eE][+-]?[0-9]+)? +num2 0[xX]([0-9a-fA-F]+(\.[0-9a-fA-F]*)?|\.[0-9a-fA-F]+)([pP][+-]?[0-9]+)? number {num1}|{num2} %{ @@ -76,6 +60,41 @@ number {num1}|{num2} // Code run each time yylex is called. loc.step (); + auto peek_char = [&]() -> int { + if ((yy_hold_char) != YY_END_OF_BUFFER_CHAR || (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]) { + return static_cast(yy_hold_char); + } + *(yy_c_buf_p) = (yy_hold_char); + (yytext_ptr) = (yy_c_buf_p); + ++(yy_c_buf_p); + switch (yy_get_next_buffer()) { + case EOB_ACT_LAST_MATCH: + yyrestart(yyin); + [[fallthrough]]; + case EOB_ACT_END_OF_FILE: + return -1; + case EOB_ACT_CONTINUE_SCAN: + (yy_c_buf_p) = (yytext_ptr); + (yy_hold_char) = *(yy_c_buf_p); + *(yy_c_buf_p) = '\0'; + return static_cast(yy_hold_char); + } + return -1; + }; + + auto advance_char = [&]() -> int { + const int c = peek_char(); + if (c < 0) { + return -1; + } + *(yy_c_buf_p) = '\0'; + (yy_hold_char) = *++(yy_c_buf_p); + if (c == '\n') { + ++yylineno; + } + return c; + }; + auto scan_short_string = [&]() -> yy::parser::symbol_type { const char quote = yytext[0]; loc.end = loc.begin; @@ -83,41 +102,6 @@ number {num1}|{num2} const yy::location start_loc = loc; yyless(1); - auto peek_char = [&]() -> int { - if ((yy_hold_char) != YY_END_OF_BUFFER_CHAR || (yy_c_buf_p) < &YY_CURRENT_BUFFER_LVALUE->yy_ch_buf[(yy_n_chars)]) { - return static_cast(yy_hold_char); - } - *(yy_c_buf_p) = (yy_hold_char); - (yytext_ptr) = (yy_c_buf_p); - ++(yy_c_buf_p); - switch (yy_get_next_buffer()) { - case EOB_ACT_LAST_MATCH: - yyrestart(yyin); - [[fallthrough]]; - case EOB_ACT_END_OF_FILE: - return -1; - case EOB_ACT_CONTINUE_SCAN: - (yy_c_buf_p) = (yytext_ptr); - (yy_hold_char) = *(yy_c_buf_p); - *(yy_c_buf_p) = '\0'; - return static_cast(yy_hold_char); - } - return -1; - }; - - auto advance_char = [&]() -> int { - const int c = peek_char(); - if (c < 0) { - return -1; - } - *(yy_c_buf_p) = '\0'; - (yy_hold_char) = *++(yy_c_buf_p); - if (c == '\n') { - ++yylineno; - } - return c; - }; - std::string raw; raw.push_back(quote); for (;;) { @@ -172,12 +156,75 @@ number {num1}|{num2} } } }; + + auto scan_long_string = [&](size_t level) -> yy::parser::symbol_type { + const yy::location start_loc = loc; + std::string raw; + raw.push_back('['); + raw.append(level, '='); + raw.push_back('['); + + // Lua 5.4: ignore a single newline immediately following the opening long bracket. + const int first = peek_char(); + if (first == '\n' || first == '\r') { + advance_char(); + const int second = peek_char(); + if ((second == '\n' || second == '\r') && second != first) { + advance_char(); + } + loc.lines(1); + } + + for (;;) { + const int c = advance_char(); + if (c < 0) { + throw yy::parser::syntax_error(start_loc, "unfinished long string"); + } + if (c == '\n' || c == '\r') { + const int next_nl = peek_char(); + if ((next_nl == '\n' || next_nl == '\r') && next_nl != c) { + advance_char(); + } + loc.lines(1); + raw.push_back('\n'); + } else if (c == ']') { + loc.columns(1); + size_t eq = 0; + while (peek_char() == '=') { + advance_char(); + loc.columns(1); + ++eq; + } + if (eq == level && peek_char() == ']') { + advance_char(); + loc.columns(1); + raw.push_back(']'); + raw.append(level, '='); + raw.push_back(']'); + return yy::parser::make_STRING(raw, loc); + } + raw.push_back(']'); + raw.append(eq, '='); + } else { + loc.columns(1); + raw.push_back(static_cast(c)); + } + } + }; %} /* 长注释按 Lua 的长括号层级处理:--[[ 配 ]],--[==[ 配 ]==],层级不匹配的 ]] 只是普通内容。传统的 --]] 收尾依然有效,因为其中的 ]] 就是 0 级闭括号。 */ "--"\[=*\[ { long_comment_level_ = static_cast(yyleng) - 4; yy_push_state(MULTI_LINE_COMMENT_STATE); } -\]=*\] { if (static_cast(yyleng) - 2 == long_comment_level_) yy_pop_state(); } +\]=*\] { + if (static_cast(yyleng) - 2 == long_comment_level_) { + yy_pop_state(); + } else { + loc.end = loc.begin; + loc.columns(1); + yyless(1); + } +} {newline} { loc.lines(1); loc.step(); } . { } <> { throw yy::parser::syntax_error(loc, "unfinished long comment"); } @@ -255,13 +302,9 @@ number {num1}|{num2} {name} return yy::parser::make_IDENTIFIER(yytext, loc); -{string} { - if (yytext[0] == '"' || yytext[0] == '\'') { - return scan_short_string(); - } - TrackStringLocation(loc, std::string_view(yytext, static_cast(yyleng))); - return yy::parser::make_STRING(std::string(yytext, static_cast(yyleng)), loc); - } +\[=*\[ { return scan_long_string(static_cast(yyleng) - 2); } + +{string} { return scan_short_string(); } /* A quote reaches this fallback when a short string contains escaped newlines or is unfinished. */ [\"'] { return scan_short_string(); } diff --git a/src/compile/my_flexer.cpp b/src/compile/my_flexer.cpp index 710d5266..eaea0b2c 100644 --- a/src/compile/my_flexer.cpp +++ b/src/compile/my_flexer.cpp @@ -46,11 +46,17 @@ std::string MyFlexer::RemoveQuotes(const std::string &str) { // 需要替换字符串中的转义字符 return ReplaceEscapeChars(str.substr(1, str.size() - 2)); } else { - // 处理 [[...]] 形式的长字符串(Raw String) - DEBUG_ASSERT(str.size() >= 4); - DEBUG_ASSERT(str[0] == '[' && str[1] == '[' && str[str.size() - 1] == ']' && str[str.size() - 2] == ']'); + // 处理 [[...]] / [=[...]=] 形式的长字符串(Raw String) + DEBUG_ASSERT(str.size() >= 4 && str.front() == '[' && str.back() == ']'); + size_t delim_len = 1; + while (delim_len < str.size() && str[delim_len] == '=') { + ++delim_len; + } + DEBUG_ASSERT(delim_len < str.size() && str[delim_len] == '['); + ++delim_len;// 包含第二个 '[' + DEBUG_ASSERT(str.size() >= delim_len * 2); // 长字符串不需要处理转义字符 - return str.substr(2, str.size() - 4); + return str.substr(delim_len, str.size() - delim_len * 2); } } diff --git a/src/compile/semantic_analysis.cpp b/src/compile/semantic_analysis.cpp index 9a2fcdab..354fe99e 100644 --- a/src/compile/semantic_analysis.cpp +++ b/src/compile/semantic_analysis.cpp @@ -1929,8 +1929,6 @@ class RegisterPeakChecker { enum class PairsIpairsKind { kNone, kPairs, kIpairs }; [[nodiscard]] PairsIpairsKind TryMatchPairsIpairs(const std::shared_ptr &explist_ptr, SyntaxTreeInterfacePtr &out_tbl_arg); - static const std::unordered_set kStringLibraryMethods; - int check_ip_ = 0; std::string file_name_; const AnalysisResult *ar_ = nullptr; @@ -1984,9 +1982,6 @@ class LineScope { }// namespace -const std::unordered_set RegisterPeakChecker::kStringLibraryMethods = {"len", "sub", "rep", "reverse", "lower", "upper", "byte", - "char", "format", "dump", "find", "match", "gmatch", "gsub"}; - [[noreturn]] void RegisterPeakChecker::ThrowError(const std::string &msg, const SyntaxTreeInterfacePtr &ptr) { ThrowFakeluaException(std::format("Code generate failed, {} at {}", msg, SyntaxTreeLocationStr(file_name_, ptr))); } @@ -3461,7 +3456,7 @@ int RegisterPeakChecker::CompileFunctioncall(const SyntaxTreeInterfacePtr &funct std::vector final_args; final_args.push_back(method_obj); for (int a: arg_regs) final_args.push_back(a); - if (kStringLibraryMethods.contains(fc->Name())) { + if (StringLibraryMethods().contains(fc->Name())) { return place_callname("string." + fc->Name(), final_args); } const int k = AllocReg(); diff --git a/src/interp/codegen.cpp b/src/interp/codegen.cpp index 2a8b1f97..e7ce29e4 100644 --- a/src/interp/codegen.cpp +++ b/src/interp/codegen.cpp @@ -43,8 +43,6 @@ class LineScope { }// namespace -const std::unordered_set InterpCodegen::kStringLibraryMethods = {"len", "sub", "rep", "reverse", "lower", "upper", "byte", "char", "format", "dump", "find", "match", "gmatch", "gsub"}; - InterpCodegen::InterpCodegen(State *s) : s_(s) { } @@ -1735,7 +1733,7 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal std::vector final_args; final_args.push_back(method_obj); for (int a: arg_regs) final_args.push_back(a); - if (kStringLibraryMethods.contains(fc->Name())) { + if (StringLibraryMethods().contains(fc->Name())) { const int n = static_cast(final_args.size()); const int base = stack_top_; EnsureStack(base + n); diff --git a/src/interp/codegen.h b/src/interp/codegen.h index 769743b2..8c5c9c0a 100644 --- a/src/interp/codegen.h +++ b/src/interp/codegen.h @@ -140,8 +140,6 @@ class InterpCodegen { enum class PairsIpairsKind { kNone, kPairs, kIpairs }; [[nodiscard]] PairsIpairsKind TryMatchPairsIpairs(const std::shared_ptr &explist_ptr, SyntaxTreeInterfacePtr &out_tbl_arg); - static const std::unordered_set kStringLibraryMethods; - bool check_only_ = false; int check_ip_ = 0;// 控制流位置占位,无指令流 State *s_ = nullptr; diff --git a/src/native/basic/native_basic.cpp b/src/native/basic/native_basic.cpp index 95ae7244..49a94e8c 100644 --- a/src/native/basic/native_basic.cpp +++ b/src/native/basic/native_basic.cpp @@ -113,35 +113,31 @@ struct IpairsState { int64_t next_idx; }; +static const char *BasicTypeName(CVar v) { + switch (static_cast(v.type_)) { + case VarType::Nil: + return "nil"; + case VarType::Bool: + return "boolean"; + case VarType::Int: + case VarType::Float: + return "number"; + case VarType::String: + case VarType::StringId: + return "string"; + case VarType::Table: + return "table"; + case VarType::Closure: + return "function"; + default: + return "userdata"; + } +} + // pairs 迭代器原生函数 // 闭包签名:CVar (*)(VarClosure *cl, CVar s, CVar var) // upvalues[0] = State* (as int) // upvalues[1] = PairIterState* (as int) -// 辅助:比较 key 是否相等 -static bool KeysEqual(CVar a, CVar b) { - if (a.type_ == b.type_) { - // Bool only writes data_.b; comparing data_.i can see stale union bytes. - if (b.type_ == static_cast(VarType::Bool)) return a.data_.b == b.data_.b; - if (b.type_ == static_cast(VarType::Int)) return a.data_.i == b.data_.i; - if (b.type_ == static_cast(VarType::Float)) return a.data_.f == b.data_.f; - if (b.type_ == static_cast(VarType::StringId)) return a.data_.i == b.data_.i; - if (b.type_ == static_cast(VarType::String)) { - if (!a.data_.s || !b.data_.s) return a.data_.s == b.data_.s; - return a.data_.s->Str() == b.data_.s->Str(); - } - return a.data_.i == b.data_.i; - } - // 跨 Int 和 Float 比较 - if (a.type_ == static_cast(VarType::Int) && b.type_ == static_cast(VarType::Float)) return Int64DoubleEqual(a.data_.i, b.data_.f); - if (a.type_ == static_cast(VarType::Float) && b.type_ == static_cast(VarType::Int)) return Int64DoubleEqual(b.data_.i, a.data_.f); - // 跨 String 和 StringId 比较 - if ((a.type_ == static_cast(VarType::String) || a.type_ == static_cast(VarType::StringId)) && - (b.type_ == static_cast(VarType::String) || b.type_ == static_cast(VarType::StringId))) { - return KeyToStringView(a) == KeyToStringView(b); - } - return false; -} - extern "C" CVar BasicPairsIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { if (!cl || cl->upvalue_count < 2) { return CVar{static_cast(VarType::Nil)}; @@ -154,32 +150,15 @@ extern "C" CVar BasicPairsIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { return GuardJitEntry(state, [&]() -> CVar { CVar tbl = st->table; - CVar last = st->last_key; - if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) { return inter::NativeToFakeluaNil(state); } - // 遍历查找 last_key 的下一个(与 GET_TABLE_ENTRY 一致:spec + quick XOR buckets) - bool found_last = (last.type_ == static_cast(VarType::Nil));// nil 表示刚开始 CVar next_key{static_cast(VarType::Nil)}; CVar next_val{static_cast(VarType::Nil)}; - bool has_next = false; - - TableHelper::ForEachKV(tbl, [&](CVar k, CVar v) { - if (has_next) return; - if (found_last) { - next_key = k; - next_val = v; - has_next = true; - return; - } - if (KeysEqual(k, last)) { - found_last = true; - } - }); - - if (!has_next) return inter::NativeToFakeluaNil(state); + if (TableHelper::NextKV(tbl, st->last_key, next_key, next_val) != TableHelper::NextKVStatus::kFound) { + return inter::NativeToFakeluaNil(state); + } st->last_key = next_key; @@ -285,25 +264,12 @@ void RegisterBasicLibraryApi(State *s) { CVar a0 = inter::GetNativeArg(state, args, n, 0); const auto &v = AsVar(a0); - if (v.Type() == VarType::Int) return a0; - if (v.Type() == VarType::Float) return a0; - if (v.Type() != VarType::String && v.Type() != VarType::StringId) { - return inter::NativeToFakeluaNil(state); - } - - std::string_view raw = v.GetString()->Str(); - // Trim leading and trailing whitespace per Lua spec(不先拷整串) - size_t start = raw.find_first_not_of(" \t\n\r\f\v"); - if (start == std::string_view::npos) return inter::NativeToFakeluaNil(state); - size_t end = raw.find_last_not_of(" \t\n\r\f\v"); - std::string_view trimmed = raw.substr(start, end - start + 1); - int64_t base_i = 10; bool has_custom_base = false; if (n >= 2) { CVar a1 = inter::GetNativeArg(state, args, n, 1); if (a1.type_ != static_cast(VarType::Nil)) { - // 标准 Lua 5.3:tonumber 的 base 可以是 number 或可转换为 number 的 string + // 标准 Lua 5.4:tonumber 的 base 可以是 number 或可转换为 number 的 string CheckNumberArg(a1, 2, "tonumber"); if (a1.type_ == static_cast(VarType::Float)) { if (!DoubleFitsInt64(a1.data_.f, &base_i)) { @@ -324,9 +290,29 @@ void RegisterBasicLibraryApi(State *s) { } } - if (has_custom_base && (base_i < 2 || base_i > 36)) { - return inter::NativeToFakeluaNil(state); + if (!has_custom_base) { + if (v.Type() == VarType::Int) return a0; + if (v.Type() == VarType::Float) return a0; + if (v.Type() != VarType::String && v.Type() != VarType::StringId) { + return inter::NativeToFakeluaNil(state); + } + } else { + // Lua 5.4:带 base 时第 1 参必须是 string,不能隐式接受数字或其他类型。 + if (v.Type() != VarType::String && v.Type() != VarType::StringId) { + ThrowFakeluaException(std::string("bad argument #1 to 'tonumber' (string expected, got ") + BasicTypeName(a0) + ")"); + } + if (base_i < 2 || base_i > 36) { + return inter::NativeToFakeluaNil(state); + } } + + std::string_view raw = v.GetString()->Str(); + // Trim leading and trailing whitespace per Lua spec(不先拷整串) + size_t start = raw.find_first_not_of(" \t\n\r\f\v"); + if (start == std::string_view::npos) return inter::NativeToFakeluaNil(state); + size_t end = raw.find_last_not_of(" \t\n\r\f\v"); + std::string_view trimmed = raw.substr(start, end - start + 1); + int base = static_cast(base_i); // Auto-detect 0x/0X prefix when no custom base is provided @@ -353,7 +339,7 @@ void RegisterBasicLibraryApi(State *s) { base = 16; } - if (base == 10) { + if (!has_custom_base && base == 10) { // 整数:直接在 string_view 上 from_chars,避免拷贝 std::string_view s_view = trimmed; if (!s_view.empty() && s_view[0] == '+') { @@ -380,8 +366,8 @@ void RegisterBasicLibraryApi(State *s) { } else if (str[0] == '+') { i = 1; } - // Skip 0x/0X prefix for base 16 - if (base == 16 && i + 2 <= str.size() && str[i] == '0' && (str[i + 1] == 'x' || str[i + 1] == 'X')) { + // Lua 5.4:仅无显式 base 自动识别十六进制时剥离 0x/0X;显式 base=16 时 "0x10" 返回 nil。 + if (!has_custom_base && base == 16 && i + 2 <= str.size() && str[i] == '0' && (str[i + 1] == 'x' || str[i + 1] == 'X')) { i += 2; } if (i >= str.size()) return inter::NativeToFakeluaNil(state); @@ -595,27 +581,16 @@ void RegisterBasicLibraryApi(State *s) { ThrowFakeluaException("bad argument #1 to 'next' (table expected)"); } - bool has_index = (n >= 2); - CVar index = has_index ? inter::GetNativeArg(state, args, n, 1) : CVar{static_cast(VarType::Nil)}; - - bool found_index = !has_index || index.type_ == static_cast(VarType::Nil); + CVar index = (n >= 2) ? inter::GetNativeArg(state, args, n, 1) : CVar{static_cast(VarType::Nil)}; CVar next_key{static_cast(VarType::Nil)}; CVar next_val{static_cast(VarType::Nil)}; - bool has_next = false; - TableHelper::ForEachKV(tbl, [&](CVar k, CVar v) { - if (has_next) return; - if (found_index) { - next_key = k; - next_val = v; - has_next = true; - return; - } - if (KeysEqual(k, index)) { - found_index = true; - } - }); - - if (!has_next) return inter::NativeToFakeluaNil(state); + const auto status = TableHelper::NextKV(tbl, index, next_key, next_val); + if (status == TableHelper::NextKVStatus::kInvalidKey) { + ThrowFakeluaException("invalid key to 'next'"); + } + if (status == TableHelper::NextKVStatus::kEnd) { + return inter::NativeToFakeluaNil(state); + } CVar multi = inter::AllocMultiCVar(state, 2); inter::SetMultiCVarElement(multi, 0, next_key); inter::SetMultiCVarElement(multi, 1, next_val); diff --git a/src/native/string/native_string.cpp b/src/native/string/native_string.cpp index b6ff1200..df5ea73e 100644 --- a/src/native/string/native_string.cpp +++ b/src/native/string/native_string.cpp @@ -1225,9 +1225,16 @@ void RegisterStringLibraryApi(State *s) { std::string spec_str(fmt.substr(spec_start, i - spec_start)); CheckFormatItemSize(spec_str); - CVar curr_arg = (arg_idx < n) ? inter::GetNativeArg(state, args, n, arg_idx++) : CVar{static_cast(VarType::Nil)}; + if (arg_idx >= n) { + ThrowBadArgument(arg_idx + 1, "format", "no value"); + } + const int curr_arg_num = arg_idx + 1; + CVar curr_arg = inter::GetNativeArg(state, args, n, arg_idx++); if (spec == 'q') { + if (spec_str != "%q") { + ThrowFakeluaException("specifier '%q' cannot have modifiers"); + } if (curr_arg.type_ == static_cast(VarType::Nil)) { res.append("nil"); } else if (curr_arg.type_ == static_cast(VarType::Bool)) { @@ -1280,6 +1287,9 @@ void RegisterStringLibraryApi(State *s) { if (spec_str == "%s") { res.append(sval); } else { + if (sval.find('\0') != std::string::npos) { + ThrowBadArgument(curr_arg_num, "format", "string contains zeros"); + } int needed = snprintf(nullptr, 0, spec_str.c_str(), sval.c_str()); if (needed > 0) { std::vector buf(static_cast(needed) + 1); @@ -1290,7 +1300,7 @@ void RegisterStringLibraryApi(State *s) { } else if (spec == 'd' || spec == 'i') { // Lua 5.4 luaL_checkinteger:float 必须有精确整数表示 // (3.9 / 1e20 / inf 报 "number has no integer representation") - int64_t ival = CheckIntegerArg(curr_arg, arg_idx + 1, "format"); + int64_t ival = CheckIntegerArg(curr_arg, curr_arg_num, "format"); std::string llspec = spec_str; llspec.insert(llspec.size() - 1, "ll"); int needed = snprintf(nullptr, 0, llspec.c_str(), static_cast(ival)); @@ -1301,7 +1311,7 @@ void RegisterStringLibraryApi(State *s) { } } else if (spec == 'u' || spec == 'x' || spec == 'X' || spec == 'o') { // 同 %d:无符号格式同样要求精确整数表示(Lua 共用 intcase) - uint64_t uval = static_cast(CheckIntegerArg(curr_arg, arg_idx + 1, "format")); + uint64_t uval = static_cast(CheckIntegerArg(curr_arg, curr_arg_num, "format")); std::string llspec = spec_str; llspec.insert(llspec.size() - 1, "ll"); int needed = snprintf(nullptr, 0, llspec.c_str(), static_cast(uval)); @@ -1324,7 +1334,7 @@ void RegisterStringLibraryApi(State *s) { } } else if (spec == 'c') { // Lua 5.4 %c 同样走 luaL_checkinteger:float 必须有精确整数表示 - int64_t cval = CheckIntegerArg(curr_arg, arg_idx + 1, "format"); + int64_t cval = CheckIntegerArg(curr_arg, curr_arg_num, "format"); res.push_back(static_cast(cval)); } else if (spec == 'p') { // fakelua 扩展:%p 接受 number 或 nil(输出指针地址),Bool/Table/String 不合法 diff --git a/src/native/table/native_table.cpp b/src/native/table/native_table.cpp index cb1aea82..d44c973c 100644 --- a/src/native/table/native_table.cpp +++ b/src/native/table/native_table.cpp @@ -658,6 +658,113 @@ std::vector TableHelper::CollectKVPairs(CVar tbl) { return result; } +TableHelper::NextKVStatus TableHelper::NextKV(CVar tbl, CVar key, CVar &out_key, CVar &out_val) { + if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) return NextKVStatus::kEnd; + VarTable *t = tbl.data_.t; + EnsureNativeSpecSnapshot(t); + + auto advance_from = [&](int region, uint32_t pos) -> NextKVStatus { + if (region == 0) { + if (t->spec_keys && t->spec_vals && t->spec_count > 0) { + for (uint32_t i = pos; i < t->spec_count; ++i) { + if (t->spec_keys[i].type_ != kNilType && t->spec_vals[i].type_ != kNilType) { + out_key = t->spec_keys[i]; + out_val = t->spec_vals[i]; + return NextKVStatus::kFound; + } + } + } + region = 1; + pos = 0; + } + if (region == 1) { + for (uint32_t i = pos; i < t->arr_size_; ++i) { + if (t->arr_[i].type_ != kNilType) { + out_key = CVar{kIntType}; + out_key.data_.i = static_cast(i) + 1; + out_val = t->arr_[i]; + return NextKVStatus::kFound; + } + } + region = 2; + pos = 0; + } + if (region == 2) { + if (t->bucket_count_ == 0) { + for (uint32_t i = pos; i < t->count_; ++i) { + const auto &qd = t->quick_data_[i]; + if (qd.key.type_ != kNilType && qd.val.type_ != kNilType) { + out_key = qd.key; + out_val = qd.val; + return NextKVStatus::kFound; + } + } + } else if (t->nodes_ && t->active_list_) { + for (uint32_t i = pos; i < t->count_; ++i) { + const auto &entry = t->nodes_[t->active_list_[i]].entry; + if (entry.key.type_ != kNilType && entry.val.type_ != kNilType) { + out_key = entry.key; + out_val = entry.val; + return NextKVStatus::kFound; + } + } + } + } + return NextKVStatus::kEnd; + }; + + if (key.type_ == kNilType) { + return advance_from(0, 0); + } + if (key.type_ == kFloatType && std::isnan(key.data_.f)) { + return NextKVStatus::kInvalidKey; + } + key = NormalizeTableKey(key); + + if (t->spec_keys && t->spec_vals && t->spec_count > 0) { + for (uint32_t i = 0; i < t->spec_count; ++i) { + if (t->spec_keys[i].type_ != kNilType && t->spec_vals[i].type_ != kNilType && VarKeyEqual(t->spec_keys[i], key)) { + return advance_from(0, i + 1); + } + } + } + + if (key.type_ == kIntType && static_cast(key.data_.i) - 1 < t->arr_size_) { + const uint32_t arr_idx = static_cast(key.data_.i - 1); + if (t->arr_[arr_idx].type_ != kNilType) { + return advance_from(1, arr_idx + 1); + } + return NextKVStatus::kInvalidKey; + } + + if (t->count_ > 0) { + const uint32_t hash = VarKeyHash(key); + if (t->bucket_count_ == 0) { + for (uint32_t i = 0; i < t->count_; ++i) { + const auto &qd = t->quick_data_[i]; + if (qd.hash == hash && qd.key.type_ != kNilType && qd.val.type_ != kNilType && VarKeyEqual(qd.key, key)) { + return advance_from(2, i + 1); + } + } + } else if (t->nodes_ && t->active_list_) { + const uint32_t mask = t->bucket_count_ - 1; + uint32_t curr_idx = hash & mask; + if (t->nodes_[curr_idx].entry.key.type_ != kNilType) { + while (true) { + const auto &node = t->nodes_[curr_idx]; + if (node.entry.hash == hash && node.entry.val.type_ != kNilType && VarKeyEqual(node.entry.key, key)) { + return advance_from(2, node.active_pos + 1); + } + if (node.next == VarTable::INVALID_INDEX) break; + curr_idx = node.next; + } + } + } + } + + return NextKVStatus::kInvalidKey; +} + int64_t TableHelper::GetTableLen(CVar tbl) { if (tbl.type_ != static_cast(VarType::Table) || !tbl.data_.t) return 0; VarTable *t = tbl.data_.t; diff --git a/src/native/table/native_table.h b/src/native/table/native_table.h index 6a1c8390..100d54d0 100644 --- a/src/native/table/native_table.h +++ b/src/native/table/native_table.h @@ -31,6 +31,13 @@ class TableHelper { static CVar CreateTable(State *s); // 与 GET_TABLE_ENTRY 一致:spec + (quick XOR buckets),互斥遍历。 static void ForEachKV(CVar tbl, const std::function &fn); + enum class NextKVStatus { + kFound, + kEnd, + kInvalidKey, + }; + // 按与 ForEachKV 相同的顺序 O(1) 定位 key 并返回其后继;key 为 nil 时返回首个条目。 + static NextKVStatus NextKV(CVar tbl, CVar key, CVar &out_key, CVar &out_val); static std::vector CollectKVPairs(CVar tbl); }; diff --git a/src/native/utf8/native_utf8.cpp b/src/native/utf8/native_utf8.cpp index ff466ca1..ef778242 100644 --- a/src/native/utf8/native_utf8.cpp +++ b/src/native/utf8/native_utf8.cpp @@ -40,8 +40,10 @@ static bool EncodeUtf8(int64_t cp, std::string &out) { } // Decode one UTF-8 code point starting at s[pos]. +// When lax is true (Lua 5.4), allows surrogates and extended UTF-8 up to 0x7FFFFFFF (5-6 bytes), +// while still rejecting overlong encodings, invalid continuation bytes, and 0xFE/0xFF. // Returns the code point (or -1 on invalid byte) and advances pos. -static int64_t DecodeUtf8(const std::string_view &sv, size_t &pos) { +static int64_t DecodeUtf8(const std::string_view &sv, size_t &pos, bool lax = false) { if (pos >= sv.size()) return -1; unsigned char c = static_cast(sv[pos]); @@ -50,17 +52,29 @@ static int64_t DecodeUtf8(const std::string_view &sv, size_t &pos) { return c; } - int cp; - size_t len; + uint32_t cp = 0; + size_t len = 0; + uint32_t min_cp = 0; if ((c >> 5) == 0x06) {// 110xxxxx → 2 bytes - cp = c & 0x1F; + cp = c & 0x1Fu; len = 2; + min_cp = 0x80u; } else if ((c >> 4) == 0x0E) {// 1110xxxx → 3 bytes - cp = c & 0x0F; + cp = c & 0x0Fu; len = 3; + min_cp = 0x800u; } else if ((c >> 3) == 0x1E) {// 11110xxx → 4 bytes - cp = c & 0x07; + cp = c & 0x07u; len = 4; + min_cp = 0x10000u; + } else if (lax && (c >> 2) == 0x3E) {// 111110xx → 5 bytes (extended UTF-8, lax only) + cp = c & 0x03u; + len = 5; + min_cp = 0x200000u; + } else if (lax && (c >> 1) == 0x7E) {// 1111110x → 6 bytes (extended UTF-8, lax only) + cp = c & 0x01u; + len = 6; + min_cp = 0x4000000u; } else { // Invalid leading byte pos += 1; @@ -78,35 +92,29 @@ static int64_t DecodeUtf8(const std::string_view &sv, size_t &pos) { pos += 1; return -1; } - cp = (cp << 6) | (next & 0x3F); + cp = (cp << 6) | static_cast(next & 0x3Fu); } - // Validate: reject overlong encodings and surrogate range - if (cp > 0x10FFFF) { + // Overlong encodings are always invalid, even in lax mode. + if (cp < min_cp) { pos += 1; return -1; } - if (cp >= 0xD800 && cp <= 0xDFFF) { - pos += 1; - return -1; - } - if (len == 2 && cp < 0x80) { - pos += 1; - return -1; - } - if (len == 3 && cp < 0x800) { - pos += 1; - return -1; - } - if (len == 4 && cp < 0x10000) { - pos += 1; - return -1; + if (!lax) { + if (cp > 0x10FFFFu || (cp >= 0xD800u && cp <= 0xDFFFu)) { + pos += 1; + return -1; + } } pos += len; return static_cast(cp); } +static bool IsLuaTruthy(const CVar &v) { + return v.type_ != static_cast(VarType::Nil) && !(v.type_ == static_cast(VarType::Bool) && !v.data_.b); +} + // Count UTF-16 surrogate pairs needed for a code point (for offset calc) static int Utf16Units(int64_t cp) { return (cp > 0xFFFF) ? 2 : 1; @@ -130,7 +138,7 @@ static CVar Utf8Char(State *state, CVar *args, int n) { return inter::NativeToFakeluaString(state, out); } -// utf8.codepoint(s [, i [, j]]) +// utf8.codepoint(s [, i [, j [, lax]]]) // Returns code points for all characters between positions i and j (inclusive). static CVar Utf8Codepoint(State *state, CVar *args, int n) { if (n < 1) ThrowBadArgument(1, "utf8.codepoint", "string expected"); @@ -154,6 +162,7 @@ static CVar Utf8Codepoint(State *state, CVar *args, int n) { if (n >= 3 && j_var.type_ != static_cast(VarType::Nil)) { j = CheckIntegerArg(j_var, 3, "utf8.codepoint"); } + const bool lax = (n >= 4) && IsLuaTruthy(inter::GetNativeArg(state, args, n, 3)); // Negative indices count from the end. Index 0 is not from-end (Lua u_posrelat). i = LuaPosRelat(i, len); @@ -171,7 +180,7 @@ static CVar Utf8Codepoint(State *state, CVar *args, int n) { size_t pos = static_cast(i - 1); const size_t limit = static_cast(j); while (pos < limit) { - int64_t cp = DecodeUtf8(sv, pos); + int64_t cp = DecodeUtf8(sv, pos, lax); if (cp < 0) { ThrowFakeluaException("invalid UTF-8 code"); } @@ -191,52 +200,10 @@ static CVar Utf8Codepoint(State *state, CVar *args, int n) { return multi; } -// utf8.codes(s) -// Returns an iterator function that, when called, returns position and codepoint. -// We implement this by returning a closure-like state via a special mechanism. -// For simplicity, we return a table with the string and current position, -// but the standard Lua pattern is: for p, c in utf8.codes(s) do ... end -// We'll use a simpler approach: return a function that iterates. -// Actually, the simplest approach that works with the JIT is to return -// multiple values: the iterator state (string + pos) as a table. -// But the standard idiom is: for p, c in utf8.codes(s) do ... end -// We'll implement this by returning a closure that captures the string. -// Since we can't easily create closures in native code, we'll use a different approach: -// return a table {string, pos} and provide a separate iterator function. -// Actually, the cleanest approach: return a function reference that the for-loop can call. -// We'll register "utf8.codes_iterator" and return it along with state. -// For now, let's use the approach of returning a table that acts as iterator state. -// The for-in loop in Lua calls the iterator with the state. -// We'll return: iterator_function, state, initial_value -// But this is complex. Let's use a simpler approach: -// Return a table with __call metameta... no, no metatables. -// Simplest working approach: return a function that when called returns (pos, cp) or nil. -// We'll create a native function that takes the state table and returns next. -// Actually, let's just return a table {s="...", pos=0} and register a generic iterator. -// But the for-loop protocol needs: iter_fn, state, init_val -// Let me use the approach: return a closure-like object. -// Since we can't create real closures, we'll return a table and rely on -// the user calling utf8.codes_iterator(state) manually. -// For the test, we'll just test codepoint and len directly, and for codes -// we'll return a table that can be iterated with a helper. -// Actually, the simplest correct approach: return a function that captures state. -// We can use the native object mechanism, but that's overkill. -// Let me just return a table {string, pos} and document that users should -// use utf8.codepoint in a loop instead. For the test, we'll verify codes() -// returns something non-nil and can be used. -// Better approach: return a table that the for-loop can use with pairs(). -// No, that won't work either. -// The cleanest approach for fakelua: return a function reference. -// We'll register "utf8._codes_iter" and return it as a CVar function. -// But we can't easily return a C function reference as a CVar. -// Let me look at how string.gmatch handles this... - -// For now, utf8.codes returns a table {s, pos} that can be iterated. -// The test will just verify it returns a table. - struct Utf8CodesState { std::string text; size_t pos = 0; + bool lax = false; }; extern "C" CVar Utf8CodesIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { @@ -256,7 +223,7 @@ extern "C" CVar Utf8CodesIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { } const size_t start = gs->pos; std::string_view sv = gs->text; - int64_t cp = DecodeUtf8(sv, gs->pos); + int64_t cp = DecodeUtf8(sv, gs->pos, gs->lax); if (cp < 0) { ThrowFakeluaException("invalid UTF-8 code"); } @@ -267,6 +234,7 @@ extern "C" CVar Utf8CodesIterator(VarClosure *cl, CVar /*s*/, CVar /*var*/) { }); } +// utf8.codes(s [, lax]) static CVar Utf8Codes(State *state, CVar *args, int n) { if (n < 1) ThrowBadArgument(1, "utf8.codes", "string expected"); @@ -274,13 +242,14 @@ static CVar Utf8Codes(State *state, CVar *args, int n) { CheckStringArg(a0, 1, "utf8.codes"); std::string temp; std::string text(GetStringArgView(a0, temp)); + const bool lax = (n >= 2) && IsLuaTruthy(inter::GetNativeArg(state, args, n, 1)); auto &alloc = state->GetValueAllocator(); - auto *gs = alloc.New(std::move(text), 0); + auto *gs = alloc.New(std::move(text), 0, lax); return MakeIteratorClosure(state, reinterpret_cast(Utf8CodesIterator), gs); } -// utf8.len(s [, i [, j]]) +// utf8.len(s [, i [, j [, lax]]]) // Returns the number of UTF-8 characters in s between positions i and j. // If it finds an invalid byte, returns nil + position of the invalid byte. static CVar Utf8Len(State *state, CVar *args, int n) { @@ -305,6 +274,7 @@ static CVar Utf8Len(State *state, CVar *args, int n) { if (n >= 3 && j_var.type_ != static_cast(VarType::Nil)) { j = CheckIntegerArg(j_var, 3, "utf8.len"); } + const bool lax = (n >= 4) && IsLuaTruthy(inter::GetNativeArg(state, args, n, 3)); // Negative indices count from the end. Index 0 is not from-end (Lua u_posrelat). i = LuaPosRelat(i, byte_len); @@ -328,7 +298,7 @@ static CVar Utf8Len(State *state, CVar *args, int n) { while (pos < end_pos) { size_t start = pos; - int64_t cp = DecodeUtf8(sv, pos); + int64_t cp = DecodeUtf8(sv, pos, lax); if (cp < 0) { // Invalid byte sequence - return nil + byte position CVar multi = inter::AllocMultiCVar(state, 2); @@ -421,13 +391,13 @@ void RegisterUtf8LibraryApi(State *s) { // utf8.char(...) RegisterNativeFunction(s, "utf8.char", 0, true, [](State *state, CVar *args, int n) -> CVar { return Utf8Char(state, args, n); }); - // utf8.codepoint(s [, i [, j]]) + // utf8.codepoint(s [, i [, j [, lax]]]) RegisterNativeFunction(s, "utf8.codepoint", 1, true, [](State *state, CVar *args, int n) -> CVar { return Utf8Codepoint(state, args, n); }); - // utf8.codes(s) - RegisterNativeFunction(s, "utf8.codes", 1, false, [](State *state, CVar *args, int n) -> CVar { return Utf8Codes(state, args, n); }); + // utf8.codes(s [, lax]) + RegisterNativeFunction(s, "utf8.codes", 1, true, [](State *state, CVar *args, int n) -> CVar { return Utf8Codes(state, args, n); }); - // utf8.len(s [, i [, j]]) + // utf8.len(s [, i [, j [, lax]]]) RegisterNativeFunction(s, "utf8.len", 1, true, [](State *state, CVar *args, int n) -> CVar { return Utf8Len(state, args, n); }); // utf8.offset(s, n [, i]) diff --git a/src/util/string_util.cpp b/src/util/string_util.cpp index 54a2715e..8447c5b8 100644 --- a/src/util/string_util.cpp +++ b/src/util/string_util.cpp @@ -29,9 +29,47 @@ void TrimInplace(std::string &str) { \z: 跳过后续的空格序列 \ddd: 十进制字节,最多三位。\033 是 33,不是 C 的八进制 ESC。 \xHH: 十六进制字节,必须正好两位。ESC 写成 \x1b 或 \027。 + \u{XXX}: UTF-8 码点转义(Lua 5.3/5.4),范围 0..0x7FFFFFFF。 */ std::string ReplaceEscapeChars(const std::string &str) { + auto hex_digit = [](unsigned char h) -> int { + if (h >= '0' && h <= '9') return h - '0'; + if (h >= 'a' && h <= 'f') return h - 'a' + 10; + if (h >= 'A' && h <= 'F') return h - 'A' + 10; + return -1; + }; + auto append_utf8 = [](std::string &out, uint32_t cp) { + if (cp <= 0x7Fu) { + out += static_cast(cp); + } else if (cp <= 0x7FFu) { + out += static_cast(0xC0u | (cp >> 6)); + out += static_cast(0x80u | (cp & 0x3Fu)); + } else if (cp <= 0xFFFFu) { + out += static_cast(0xE0u | (cp >> 12)); + out += static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out += static_cast(0x80u | (cp & 0x3Fu)); + } else if (cp <= 0x1FFFFFu) { + out += static_cast(0xF0u | (cp >> 18)); + out += static_cast(0x80u | ((cp >> 12) & 0x3Fu)); + out += static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out += static_cast(0x80u | (cp & 0x3Fu)); + } else if (cp <= 0x3FFFFFFu) { + out += static_cast(0xF8u | (cp >> 24)); + out += static_cast(0x80u | ((cp >> 18) & 0x3Fu)); + out += static_cast(0x80u | ((cp >> 12) & 0x3Fu)); + out += static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out += static_cast(0x80u | (cp & 0x3Fu)); + } else { + out += static_cast(0xFCu | (cp >> 30)); + out += static_cast(0x80u | ((cp >> 24) & 0x3Fu)); + out += static_cast(0x80u | ((cp >> 18) & 0x3Fu)); + out += static_cast(0x80u | ((cp >> 12) & 0x3Fu)); + out += static_cast(0x80u | ((cp >> 6) & 0x3Fu)); + out += static_cast(0x80u | (cp & 0x3Fu)); + } + }; + std::string result; for (auto it = str.begin(); it != str.end();) { if (*it == '\\') { @@ -61,15 +99,7 @@ std::string ReplaceEscapeChars(const std::string &str) { if (it == str.end()) { ThrowFakeluaException("ReplaceEscapeChars failed, invalid hexadecimal escape \\x"); } - const unsigned char h = static_cast(*it); - int digit = -1; - if (h >= '0' && h <= '9') { - digit = h - '0'; - } else if (h >= 'a' && h <= 'f') { - digit = h - 'a' + 10; - } else if (h >= 'A' && h <= 'F') { - digit = h - 'A' + 10; - } + const int digit = hex_digit(static_cast(*it)); if (digit < 0) { ThrowFakeluaException("ReplaceEscapeChars failed, invalid hexadecimal escape \\x"); } @@ -77,6 +107,31 @@ std::string ReplaceEscapeChars(const std::string &str) { ++it; } result += static_cast(hex_val); + } else if (esc == 'u') { + if (it == str.end() || *it != '{') { + ThrowFakeluaException("ReplaceEscapeChars failed, missing '{' in \\u escape"); + } + ++it; + if (it == str.end() || hex_digit(static_cast(*it)) < 0) { + ThrowFakeluaException("ReplaceEscapeChars failed, hexadecimal digit expected in \\u escape"); + } + uint64_t codepoint = 0; + while (it != str.end()) { + const int digit = hex_digit(static_cast(*it)); + if (digit < 0) { + break; + } + codepoint = (codepoint << 4) | static_cast(digit); + if (codepoint > 0x7FFFFFFFULL) { + ThrowFakeluaException("ReplaceEscapeChars failed, UTF-8 value too large in \\u escape"); + } + ++it; + } + if (it == str.end() || *it != '}') { + ThrowFakeluaException("ReplaceEscapeChars failed, missing '}' in \\u escape"); + } + ++it; + append_utf8(result, static_cast(codepoint)); } else switch (esc) { case 'a': result += '\a'; diff --git a/test/lua/basic/test_basic_pairs_coverage.lua b/test/lua/basic/test_basic_pairs_coverage.lua index e66cd0bb..2808c450 100644 --- a/test/lua/basic/test_basic_pairs_coverage.lua +++ b/test/lua/basic/test_basic_pairs_coverage.lua @@ -119,9 +119,10 @@ function test_tonumber_invalid_string() return 1 end --- 测试 tonumber - 十六进制 +-- 测试 tonumber - 十六进制(Lua 5.4:无 base 认 0x,显式 base=16 不认 0x) function test_tonumber_hex() - if tonumber("0x1F", 16) ~= 31 then return 0 end + if tonumber("0x1F") ~= 31 then return 0 end + if tonumber("0x1F", 16) ~= nil then return 0 end if tonumber("FF", 16) ~= 255 then return 0 end return 1 end diff --git a/test/lua/basic/test_basic_tonumber_extra.lua b/test/lua/basic/test_basic_tonumber_extra.lua index 5f8a43ff..501fe73d 100644 --- a/test/lua/basic/test_basic_tonumber_extra.lua +++ b/test/lua/basic/test_basic_tonumber_extra.lua @@ -1,9 +1,9 @@ package "BasicTonumberExtra" --- 测试 tonumber 十六进制 +-- 测试 tonumber 十六进制(Lua 5.4:显式 base=16 不剥 0x 前缀) function test_tonumber_hex() - local n = tonumber("0xFF", 16) - if n ~= 255 then return 0 end + if tonumber("FF", 16) ~= 255 then return 0 end + if tonumber("0xFF", 16) ~= nil then return 0 end return 1 end diff --git a/test/test_basic.cpp b/test/test_basic.cpp index 6914f13f..1cc7f167 100644 --- a/test/test_basic.cpp +++ b/test/test_basic.cpp @@ -1678,3 +1678,99 @@ TEST(basic, tonumber_rejects_fractional_bases_and_overflowing_custom_hex) { EXPECT_EQ(result, 1); } } + +TEST(basic, tonumber_base_rejects_non_string_and_0x_prefix) { + FakeluaStateGuard state; + SetDebugLogLevel(state.GetState(), LogLevel::Off); + ASSERT_NO_THROW(CompileString(state.GetState(), R"( +local function must_err(fn, needle) + local ok, err = pcall(fn) + if ok then return false end + return string.find(tostring(err), needle, 1, true) ~= nil +end + +function test_tonumber_lua54_base() + if not must_err(function() return tonumber(10, 16) end, "string expected, got number") then return 1 end + if not must_err(function() return tonumber(3.14, 10) end, "string expected, got number") then return 2 end + if not must_err(function() return tonumber(true, 16) end, "string expected, got boolean") then return 3 end + if not must_err(function() return tonumber(nil, 16) end, "string expected, got nil") then return 4 end + if not must_err(function() return tonumber({}, 16) end, "string expected, got table") then return 5 end + if tonumber(10, nil) ~= 10 then return 6 end + if tonumber("0x10", 16) ~= nil then return 7 end + if tonumber("0X10", 16) ~= nil then return 8 end + if tonumber("-0x10", 16) ~= nil then return 9 end + if tonumber("10.5", 10) ~= nil then return 10 end + if tonumber("ff", 16) ~= 255 then return 11 end + if tonumber(" -ff ", 16) ~= -255 then return 12 end + if tonumber("0x10") ~= 16 then return 13 end + if tonumber("123", 0) ~= nil then return 14 end + return 0 +end +)", {.debug_mode = false})); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = -1; + Call(state.GetState(), backend, "test_tonumber_lua54_base", result); + EXPECT_EQ(result, 0); + } +} + +TEST(basic, next_invalid_key_errors_and_large_table_iteration) { + FakeluaStateGuard state; + SetDebugLogLevel(state.GetState(), LogLevel::Off); + ASSERT_NO_THROW(CompileString(state.GetState(), R"( +local function must_err(fn, needle) + local ok, err = pcall(fn) + if ok then return false end + return string.find(tostring(err), needle, 1, true) ~= nil +end + +function test_next_and_pairs_edges() + if not must_err(function() return next({a = 1}, "nonexistent") end, "invalid key to 'next'") then return 1 end + if not must_err(function() return next({}, "x") end, "invalid key to 'next'") then return 2 end + if not must_err(function() return next({10, 20, 30}, 99) end, "invalid key to 'next'") then return 3 end + if not must_err(function() return next({[1] = 10, [3] = 30}, 2) end, "invalid key to 'next'") then return 4 end + if not must_err(function() return next({a = 1}, 0 / 0) end, "invalid key to 'next'") then return 5 end + if next({}, nil) ~= nil then return 6 end + + -- Large mixed array + hash table: O(1) per step via next and first-class pairs + local t = {} + for i = 1, 500 do + t[i] = i + end + for i = 1, 3000 do + t["k" .. i] = i + end + local count_next = 0 + local k = nil + while true do + local v + k, v = next(t, k) + if k == nil then break end + if t[k] ~= v then return 7 end + count_next = count_next + 1 + end + if count_next ~= 3500 then return 8 end + + local iter, s, init = pairs(t) + local count_pairs = 0 + local pk = init + while true do + local pv + pk, pv = iter(s, pk) + if pk == nil then break end + if t[pk] ~= pv then return 9 end + count_pairs = count_pairs + 1 + end + if count_pairs ~= 3500 then return 10 end + + return 0 +end +)", {.debug_mode = false})); + for (auto backend: AllJitTypes()) { + SCOPED_TRACE(JitTypeName(backend)); + int64_t result = -1; + Call(state.GetState(), backend, "test_next_and_pairs_edges", result); + EXPECT_EQ(result, 0); + } +} diff --git a/test/test_exception.cpp b/test/test_exception.cpp index f6be716b..1c2b4b9c 100644 --- a/test/test_exception.cpp +++ b/test/test_exception.cpp @@ -2468,3 +2468,47 @@ function slash_text() end )", "slash_text", 1, kernel); } + +TEST(exception, leading_and_trailing_dot_floats_default_and_kernel_mode) { + // Default mode accepts Lua 5.4 leading/trailing decimal-point float literals. + ExpectRuns(R"( +function dot_floats() + if .5 ~= 0.5 then return 1 end + if 1. ~= 1.0 then return 2 end + if .5e2 ~= 50.0 then return 3 end + if 1.e2 ~= 100.0 then return 4 end + if -.5 ~= -0.5 then return 5 end + if -1. ~= -1.0 then return 6 end + if 0x.8 ~= 0.5 then return 7 end + if 0x1. ~= 1.0 then return 8 end + if 0x.8p2 ~= 2.0 then return 9 end + if 0x1.p2 ~= 4.0 then return 10 end + if math.type(.5) ~= "float" then return 11 end + if math.type(1.) ~= "float" then return 12 end + if (1. .. "x") ~= "1.0x" then return 13 end + if ("a" .. 5) ~= "a5" then return 14 end + return 0 +end +)", "dot_floats", 0); + + // Malformed dot/exponent forms must still be rejected. + for (const char *bad: { + "function f() return 1..2 end\n", + "function f() return 1..\"a\" end\n", + "function f() return 0x. end\n", + "function f() return 1.e end\n", + "function f() return .5e end\n", + "function f() return 1.a end\n", + "function f() return .5a end\n", + "function f() return 1.2. end\n", + "function f() return .5. end\n", + }) { + ExpectCompileFails(bad, "malformed number"); + } + + // Kernel profile must reject all newly supported float literal forms. + const auto kernel = KernelConfig(); + for (const char *lit: {".5", "1.", ".5e2", "1.e2", "-.5", "-1.", "0x.8", "0x1.", "0x.8p2", "0x1.p2"}) { + ExpectCompileFails(std::string("function f() return ") + lit + " end\n", "floating-point literal is forbidden in --mode=kernel", kernel); + } +} diff --git a/test/test_string.cpp b/test/test_string.cpp index 225162aa..4a7994eb 100644 --- a/test/test_string.cpp +++ b/test/test_string.cpp @@ -1167,3 +1167,201 @@ TEST(test_string, alignment_lookahead_zero_hex_and_position_capture_replacements CallAll(state.GetState(), "test_additional_format_and_capture_contracts", result); EXPECT_EQ(result, 1); } + +TEST(test_string, utf8_escapes_follow_lua54) { + FakeluaStateGuard state; + SetDebugLogLevel(state.GetState(), LogLevel::Off); + CompileConfig cfg; + cfg.debug_mode = false; + ASSERT_NO_THROW(CompileString(state.GetState(), R"( +function utf8_escapes() + if #"\u{0}" ~= 1 or string.byte("\u{0}") ~= 0 then return 1 end + if "\u{41}" ~= "A" then return 2 end + if "\u{0000000000000041}" ~= "A" then return 3 end + if string.byte("\u{7f}") ~= 0x7f then return 4 end + local s80 = "\u{80}" + if #s80 ~= 2 or string.byte(s80, 1) ~= 0xc2 or string.byte(s80, 2) ~= 0x80 then return 5 end + local s7ff = "\u{7ff}" + if #s7ff ~= 2 or string.byte(s7ff, 1) ~= 0xdf or string.byte(s7ff, 2) ~= 0xbf then return 6 end + local s800 = "\u{800}" + if #s800 ~= 3 or string.byte(s800, 1) ~= 0xe0 or string.byte(s800, 2) ~= 0xa0 or string.byte(s800, 3) ~= 0x80 then return 7 end + if "\u{4e2d}" ~= utf8.char(0x4e2d) then return 8 end + local sd800 = "\u{d800}" + if #sd800 ~= 3 or string.byte(sd800, 1) ~= 0xed or string.byte(sd800, 2) ~= 0xa0 or string.byte(sd800, 3) ~= 0x80 then return 9 end + if "\u{1f600}" ~= utf8.char(0x1f600) then return 10 end + if "\u{10ffff}" ~= utf8.char(0x10ffff) then return 11 end + local s110000 = "\u{110000}" + if #s110000 ~= 4 or string.byte(s110000, 1) ~= 0xf4 or string.byte(s110000, 2) ~= 0x90 then return 12 end + local smax = "\u{7fffffff}" + if #smax ~= 6 or string.byte(smax, 1) ~= 0xfd or string.byte(smax, 6) ~= 0xbf then return 13 end + if "\x41\u{42}\067" ~= "ABC" then return 14 end + return 0 +end +)", cfg)); + for (auto backend: AllJitTypes()) { + int64_t result = -1; + Call(state.GetState(), backend, "utf8_escapes", result); + EXPECT_EQ(result, 0) << JitTypeName(backend); + } + + struct BadCase { + const char *src; + const char *needle; + }; + const BadCase bad_cases[] = { + {"function f() return \"\\u\" end\n", "missing '{'"}, + {"function f() return \"\\u1234\" end\n", "missing '{'"}, + {"function f() return \"\\u{}\" end\n", "hexadecimal digit expected"}, + {"function f() return \"\\u{41\" end\n", "missing '}'"}, + {"function f() return \"\\u{41g}\" end\n", "missing '}'"}, + {"function f() return \"\\u{80000000}\" end\n", "UTF-8 value too large"}, + {"function f() return \"\\u{10000000000000000}\" end\n", "UTF-8 value too large"}, + }; + for (const auto &bc: bad_cases) { + FakeluaStateGuard bad; + SetDebugLogLevel(bad.GetState(), LogLevel::Off); + try { + CompileString(bad.GetState(), bc.src, cfg); + FAIL() << bc.src; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find(bc.needle), std::string::npos) << bc.src << " -> " << e.what(); + } + } +} + +TEST(test_string, long_strings_multilevel_and_unfinished) { + FakeluaStateGuard state; + SetDebugLogLevel(state.GetState(), LogLevel::Off); + CompileConfig cfg; + cfg.debug_mode = false; + const std::string src = std::string(R"LUA( +--[=[comment with ]] and a[1]]=] +function long_strings() + local s1 = [[hello]] + if s1 ~= "hello" then return 1 end + local s2 = [=[hello]=] + if s2 ~= "hello" then return 2 end + local s3 = [==[a[=[b]=]c]==] + if s3 ~= "a[=[b]=]c" then return 3 end + local s4 = [=[a[1]]=] + if s4 ~= "a[1]" then return 4 end + local s5 = [=[a[1]]]=] + if s5 ~= "a[1]]" then return 5 end + local s6 = [==[a]=]==] + if s6 ~= "a]=" then return 6 end + local s7 = [[a]b]] + if s7 ~= "a]b" then return 7 end + local s8 = [[ +hello]] + if s8 ~= "hello" then return 8 end + local s9 = [[ + +hello]] + if s9 ~= "\nhello" then return 9 end + return 0 +end +)LUA") + "\nfunction crlf_long()\n local a = [[\r\nhi]]\n local b = [[x\r\ny\rz\n\rw]]\n if a ~= \"hi\" then return 1 end\n if b ~= \"x\\ny\\nz\\nw\" then return 2 end\n return 0\nend\n"; + ASSERT_NO_THROW(CompileString(state.GetState(), src, cfg)); + for (auto backend: AllJitTypes()) { + int64_t r1 = -1; + int64_t r2 = -1; + Call(state.GetState(), backend, "long_strings", r1); + Call(state.GetState(), backend, "crlf_long", r2); + EXPECT_EQ(r1, 0) << JitTypeName(backend); + EXPECT_EQ(r2, 0) << JitTypeName(backend); + } + + for (const char *bad_src: { + "function f() return [[unterminated end\n", + "function f() return [=[unterminated end\n", + "function f() return [=[wrong closer]] end\n", + "function f() return [=[wrong closer]==] end\n", + "function f() return [=[almost]=", + }) { + FakeluaStateGuard bad; + SetDebugLogLevel(bad.GetState(), LogLevel::Off); + try { + CompileString(bad.GetState(), bad_src, cfg); + FAIL() << bad_src; + } catch (const std::exception &e) { + EXPECT_NE(std::string(e.what()).find("unfinished long string"), std::string::npos) << bad_src << " -> " << e.what(); + } + } +} + +TEST(test_string, colon_pack_unpack_packsize) { + FakeluaStateGuard state; + SetDebugLogLevel(state.GetState(), LogLevel::Off); + CompileConfig cfg; + cfg.debug_mode = false; + ASSERT_NO_THROW(CompileString(state.GetState(), R"( +function test_colon_pack() + local packed = (">I4"):pack(42) + if packed ~= string.pack(">I4", 42) then return 1 end + if (">I4"):packsize() ~= 4 then return 2 end + local v, next_pos = (">I4"):unpack(packed) + if v ~= 42 or next_pos ~= 5 then return 3 end + local fmt = "