Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 2 additions & 5 deletions src/compile/c_gen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -211,13 +211,10 @@ void CGen::UniquifyFuncCNames() {
// 第一部分:核心调度与编排
// ===========================================================================

// string 库方法名集合(对齐 Lua 5.4)。
const std::unordered_set<std::string> 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<std::string> &args) {
if (!kStringLibraryMethods.contains(method_name)) {
if (!StringLibraryMethods().contains(method_name)) {
return {};
}
std::string arg_list;
Expand Down Expand Up @@ -4754,7 +4751,7 @@ std::string CGen::TryCompileBuiltinStringCall(const std::shared_ptr<SyntaxTreeFu
}

const std::string method_name = callee_var->GetName();
if (!CGen::kStringLibraryMethods.contains(method_name)) {
if (!StringLibraryMethods().contains(method_name)) {
return {};
}

Expand Down
2 changes: 0 additions & 2 deletions src/compile/c_gen.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> kStringLibraryMethods;
// 非表值的 colon 方法调用转发(s:match() ≡ string.match(s, ...))。
// 返回空串表示不匹配,调用方回退到 FlGetTableStrId。
[[nodiscard]] static std::string TryBuildLibraryMethodCall(const std::string &method_name, const std::vector<std::string> &args);
Expand Down
8 changes: 8 additions & 0 deletions src/compile/compile_common.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<std::string> &StringLibraryMethods() {
static const std::unordered_set<std::string> 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) {
Expand Down
642 changes: 345 additions & 297 deletions src/compile/flex/scanner.cpp

Large diffs are not rendered by default.

173 changes: 108 additions & 65 deletions src/compile/flex/scanner.l
Original file line number Diff line number Diff line change
Expand Up @@ -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 ...
Expand All @@ -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}

%{
Expand All @@ -76,48 +60,48 @@ 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<unsigned char>(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<unsigned char>(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;
loc.columns(1);
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<unsigned char>(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<unsigned char>(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 (;;) {
Expand Down Expand Up @@ -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<char>(c));
}
}
};
%}

/* 长注释按 Lua 的长括号层级处理:--[[ 配 ]],--[==[ 配 ]==],层级不匹配的
]] 只是普通内容。传统的 --]] 收尾依然有效,因为其中的 ]] 就是 0 级闭括号。 */
"--"\[=*\[ { long_comment_level_ = static_cast<int>(yyleng) - 4; yy_push_state(MULTI_LINE_COMMENT_STATE); }
<MULTI_LINE_COMMENT_STATE>\]=*\] { if (static_cast<int>(yyleng) - 2 == long_comment_level_) yy_pop_state(); }
<MULTI_LINE_COMMENT_STATE>\]=*\] {
if (static_cast<int>(yyleng) - 2 == long_comment_level_) {
yy_pop_state();
} else {
loc.end = loc.begin;
loc.columns(1);
yyless(1);
}
}
<MULTI_LINE_COMMENT_STATE>{newline} { loc.lines(1); loc.step(); }
<MULTI_LINE_COMMENT_STATE>. { }
<MULTI_LINE_COMMENT_STATE><<EOF>> { throw yy::parser::syntax_error(loc, "unfinished long comment"); }
Expand Down Expand Up @@ -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<size_t>(yyleng)));
return yy::parser::make_STRING(std::string(yytext, static_cast<size_t>(yyleng)), loc);
}
\[=*\[ { return scan_long_string(static_cast<size_t>(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(); }
Expand Down
14 changes: 10 additions & 4 deletions src/compile/my_flexer.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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);
}
}

Expand Down
7 changes: 1 addition & 6 deletions src/compile/semantic_analysis.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1929,8 +1929,6 @@ class RegisterPeakChecker {
enum class PairsIpairsKind { kNone, kPairs, kIpairs };
[[nodiscard]] PairsIpairsKind TryMatchPairsIpairs(const std::shared_ptr<class SyntaxTreeExplist> &explist_ptr, SyntaxTreeInterfacePtr &out_tbl_arg);

static const std::unordered_set<std::string> kStringLibraryMethods;

int check_ip_ = 0;
std::string file_name_;
const AnalysisResult *ar_ = nullptr;
Expand Down Expand Up @@ -1984,9 +1982,6 @@ class LineScope {

}// namespace

const std::unordered_set<std::string> 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)));
}
Expand Down Expand Up @@ -3461,7 +3456,7 @@ int RegisterPeakChecker::CompileFunctioncall(const SyntaxTreeInterfacePtr &funct
std::vector<int> 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();
Expand Down
4 changes: 1 addition & 3 deletions src/interp/codegen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -43,8 +43,6 @@ class LineScope {

}// namespace

const std::unordered_set<std::string> InterpCodegen::kStringLibraryMethods = {"len", "sub", "rep", "reverse", "lower", "upper", "byte", "char", "format", "dump", "find", "match", "gmatch", "gsub"};

InterpCodegen::InterpCodegen(State *s) : s_(s) {
}

Expand Down Expand Up @@ -1735,7 +1733,7 @@ int InterpCodegen::CompileFunctioncall(const SyntaxTreeInterfacePtr &functioncal
std::vector<int> 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<int>(final_args.size());
const int base = stack_top_;
EnsureStack(base + n);
Expand Down
2 changes: 0 additions & 2 deletions src/interp/codegen.h
Original file line number Diff line number Diff line change
Expand Up @@ -140,8 +140,6 @@ class InterpCodegen {
enum class PairsIpairsKind { kNone, kPairs, kIpairs };
[[nodiscard]] PairsIpairsKind TryMatchPairsIpairs(const std::shared_ptr<class SyntaxTreeExplist> &explist_ptr, SyntaxTreeInterfacePtr &out_tbl_arg);

static const std::unordered_set<std::string> kStringLibraryMethods;

bool check_only_ = false;
int check_ip_ = 0;// 控制流位置占位,无指令流
State *s_ = nullptr;
Expand Down
Loading
Loading