Compare commits

...
88 Commits
Author SHA1 Message Date
zzy b5a7a811b3 stage2 迁移ast解析器 stage1 防止错误死循环 2026-09-18 22:32:57 +08:00
zzy bb9d0a9f18 stage2 提供词法分析器通过与stage1的差异测试 stage1提供数组到切片的隐式转换 2026-09-18 19:40:10 +08:00
zzy c30143609a stage2 更多的工具库 2026-09-18 11:17:33 +08:00
zzy b3e38ba7e4 stage2 更多的工具库 stage1 修复问题 2026-09-18 10:10:53 +08:00
zzy 16a1f030d4 stage2 更多的工具库 2026-09-17 22:32:36 +08:00
zzy 4141e7d574 stage2 更多底层函数 stage1 layout正确使用 内置函数重新编写 2026-09-17 22:03:23 +08:00
zzy fb0ff9b663 stage1 解决重构哈希 nob优化支持头文件缓存以及win下exe缓存 2026-09-17 20:55:21 +08:00
zzy 70ac7380e9 stage1 支持函数指针 2026-09-17 20:13:24 +08:00
zzy 73c9a40abd stage1 实现短路逻辑 2026-09-17 19:37:33 +08:00
zzy b8e2bba140 stage2 更多的工具函数 stage1支持更多的内置函数 2026-09-17 18:47:56 +08:00
zzy 1a6df012cd stage2 提供sys包装 解决stage1的bug 2026-09-17 17:25:55 +08:00
zzy 5de4937637 stage1 解决defer实现的缺陷 2026-09-17 16:44:50 +08:00
zzy 2594a81034 stage1 解决@self无法在文件内直接使用的问题 2026-09-17 16:30:38 +08:00
zzy acfbbeee8b stage1 支持更多语法 修复更多问题 暂时stage1功能结束 2026-09-17 13:37:59 +08:00
zzy 54425a50c7 stage1 重构代码 语法上重新实现解包语法 2026-09-17 00:33:03 +08:00
zzy 2a84b61e3d stage1 大量重构 2026-09-16 20:09:24 +08:00
zzy e4347cc3ea stage1 重写进行代码设计并重构 提供diag替换老旧错误处理 2026-09-16 15:21:59 +08:00
zzy 7cbe2d2b9a stage1 重制类型转换系统 修复问题 提供更多表达式 2026-09-16 11:36:29 +08:00
zzy f6a0bce9f0 stage1 vm abi更新 修复更多问题 2026-09-16 10:35:36 +08:00
zzy 09d05e3a34 stage1 指针计算类型的错误修复 as运算符优先级的修改 ir2vm的bug修复 2026-09-15 21:24:58 +08:00
zzy 06f3884c30 stage1 支持指针运算 提供新的类型检查计算 2026-09-15 19:11:01 +08:00
zzy be41a82d55 stage1 支持defer 支持null 支持指针运算 支持*any指针 2026-09-15 11:08:44 +08:00
zzy 983746c797 stage1 支持label break, continue 2026-09-14 19:35:58 +08:00
zzy 3175e04e6e stage1 支持tuple 修复悬垂指针问题 2026-09-14 19:01:33 +08:00
zzy a621e34d51 stage1 支持任意顺序声明 使用eval求值的机制 2026-09-14 18:11:58 +08:00
zzy a1e684f6d4 stage0 修复部分问题 2026-09-14 16:01:33 +08:00
zzy 5073c2b3ea stage1 支持聚合类型方法 2026-09-14 15:36:43 +08:00
zzy 9bdb7f892e stage1 支持结构体初始化 2026-09-14 10:09:32 +08:00
zzy 72ae6d6994 stage1 使用切片表达字符串而非C字符串 提供属性系统 2026-09-13 22:26:41 +08:00
zzy a64a96f9a4 stage1 实现ir2vm 修复nob test命令的构建问题 2026-09-12 18:51:10 +08:00
zzy 87d9b7ea34 stage1 实现并修复ast2ir的核心功能的正确性 2026-09-12 09:46:56 +08:00
zzy 49ccdec3dd stage1 实现更多ast2ir 修复bug 提供内置操作 2026-09-11 19:26:48 +08:00
zzy ab6e99c958 stage1 重新实现ast2ir 2026-09-10 23:20:09 +08:00
zzy bcd26d3021 stage1 实现部分sema 解析数组 2026-09-09 20:21:49 +08:00
zzy 8aa7a89c7e stage1 基于新的ast实现部分sema 2026-09-09 10:47:29 +08:00
zzy 98b35a98e3 stage1 新的ast结构 使用pest描述语法 2026-09-08 13:14:29 +08:00
zzy 34df303b56 stage1 实现部分ast2ir内容并重构stage0 引入并重构ir2vm 构建系统修改部分 2026-08-28 13:01:19 +08:00
zzy 3d57260f3f stage1 实现部分ast2ir内容 2026-08-26 14:55:47 +08:00
zzy f1d86b6e34 stage1 更多的语义以及类型构造器 2026-08-22 19:35:01 +08:00
zzy 0f40de43a1 stage1 更多的语义及其附属基础设施 2026-08-20 19:51:08 +08:00
zzy d6113a5417 stage0 printf的格式化统一 展开strdup 2026-08-19 21:42:06 +08:00
zzy c81a57dacb builder 更改构建方式从python换成nob.h 2026-08-19 21:38:41 +08:00
zzy b2e6ade484 stage1 继续重构sema 提供更多dbg宏用于日志记录 2026-08-19 21:37:40 +08:00
zzy 994a35a942 stage1 重构语义分析 ast2ir ir部分 2026-08-18 11:22:15 +08:00
zzy 4d9509c167 stage1 重构词法分析 2026-08-16 23:23:56 +08:00
zzy d3c63dab5c stage0 重命名 stage1 ast重新整理 2026-08-16 10:51:45 +08:00
zzy 78d767bf21 stage0 修复windows函数没有进入宏包装 2026-08-14 20:42:11 +08:00
zzy 2a7db9e48c stage0 重命名字段 修复windows函数没有进入宏包装 2026-08-14 20:41:09 +08:00
zzy c06d7247bb stage1 人工重构ast以及type部分 修复vm的UB行为 2026-08-14 18:10:58 +08:00
zzy b0e6b406ac stage1 人工重构ast.c 2026-08-12 10:29:38 +08:00
zzy 314100afbc stage1 初步实现 2026-08-06 19:26:30 +08:00
zzy a56b4cbb70 stage0 支持类gdb的调试vm手段 2026-08-06 09:11:15 +08:00
zzy ca7cf221c8 stage1 修复设计问题 实现ir2vm 2026-08-05 19:13:48 +08:00
zzy 2ccee5f1cf stage1 修复设计问题 实现ast2ir 2026-08-05 08:14:23 +08:00
zzy 8ac59dfaa1 stage1 完成sema词法 2026-08-04 10:20:57 +08:00
zzy 74d7376039 stage1 完成ast 定义sema 2026-08-03 12:39:28 +08:00
zzy a4ec5656d2 stage1 完整ast 部分ir 定义 2026-08-01 22:48:42 +08:00
zzy b43042c88d stage1 重构代码 2026-08-01 21:15:47 +08:00
zzy a77eade06f stage0 更改名称spl_ir -> spl_mcode spl_cli提供debug模式 提供临时语言规范 2026-07-29 12:05:18 +08:00
zzy 89d4bae8db stage1 修复错误 提供类型检查 2026-07-25 22:48:35 +08:00
zzy 02095524b1 stage1 修复错误 提供类型检查 2026-07-25 10:28:24 +08:00
zzy da9dae734c stage1 修复错误 提供类型检查 2026-07-22 18:04:35 +08:00
zzy a2d5dd9ce8 stage1 整理代码 修复错误 2026-07-21 20:00:19 +08:00
zzy 7c5bb41e09 stage1 整理代码 提供更多错误信息 2026-07-21 09:56:19 +08:00
zzy 459b6188a9 stage1 - 全面重构 stage1 编译器架构:类型系统(arena + items)、IR 发射层(spl_emit.h/c)、统一所有 emit 调用点。
- 实现 as 类型转换运算符、修复 &&/|| 短路求值 bug。
- 在 splc1.spl 中实现 Vec/Map/Emit 基础库(~50 个方法)。
- 修复实例方法调用中 self 参数被错误丢弃的 bug。
2026-07-20 20:53:41 +08:00
zzy 21f35b30fa stage1 重构代码 2026-07-20 12:10:55 +08:00
zzy ab63c8ed90 stage1 修复vm 提供简单参数检查 修复聚合类型bug 2026-07-14 22:30:19 +08:00
zzy f7f71c5f52 stage1 修复bug 2026-07-13 21:50:28 +08:00
zzy b67edc5cee stage1 修复类型体内部函数前向引用时 CALL 地址错误 2026-07-12 22:16:17 +08:00
zzy 1ceda90207 stage1 修复类型重复解析 修复嵌套结构体字面量无限循环 2026-07-12 14:20:41 +08:00
zzy 9b9b25ce0f stage1 禁止隐式调用 修复bug 2026-07-12 11:43:27 +08:00
zzy 118c153280 stage1 优化重构代码 2026-07-12 10:01:57 +08:00
zzy f1b4225c92 stage1 优化重构代码 2026-07-11 23:18:06 +08:00
zzy 53ae30f1ca stage1 重制18测试用例替换成match 完成现有全部测试 2026-07-11 21:24:52 +08:00
zzy 147f26e063 stage1 修复bug 删除递归测试 2026-07-08 11:45:45 +08:00
zzy 463177d3be stage1 修改部分测试 完成17-19测试 2026-07-07 12:11:49 +08:00
zzy 1df3e3bcb4 stage1 将数组和聚合类型使用byte offset而不是slot idx 2026-07-07 11:38:31 +08:00
zzy 3cf11f922e stage1 优化代码 完成16测试 2026-07-07 10:40:30 +08:00
zzy 69cea030dc stage1 完成15测试 2026-07-06 21:26:27 +08:00
zzy 0892c084ee stage1 完成14测试 2026-07-06 15:18:17 +08:00
zzy ad473f245c stage1 完成11-13测试 2026-07-06 13:00:55 +08:00
zzy 0182b8ed5c stage1 完成09,10测试 2026-07-06 10:52:31 +08:00
zzy 777b6b42d1 stage1 完成07,08测试 2026-07-06 10:44:01 +08:00
zzy 5dadf6d6ee stage1 重构到 USIZE, 使得 vm 支持 usize, isize 2026-07-06 00:07:39 +08:00
zzy 67c8a137dd stage1 实现06测试 2026-07-05 22:47:00 +08:00
zzy e2e0ebc21f stage1 重构测试且成功00-05 2026-07-05 21:45:43 +08:00
zzy 51d8510b79 stage1 部分功能测试00,01,02,06成功 2026-07-05 18:23:33 +08:00
zzy 50b07074fb stage0 2026-07-03 22:27:50 +08:00
90 changed files with 40955 additions and 0 deletions

No files matched your search

+9
View File
@@ -2,3 +2,12 @@
!.gitignore
build/
*.sir
*.o
*.obj
*.old
*.exe
*.out
+1216
View File
File diff suppressed because it is too large. Load diff
+429
View File
@@ -0,0 +1,429 @@
Root = { SOI ~ ContainerMembers ~ EOI }
ContainerMembers = { ExternalHeaderList ~ (ContainerDeclaration ~ (COMMA | SEMICOLON)*)* }
HeaderItem = { (AT | SHARP) ~ IDENTIFIER ~ (LPAREN ~ ExprList? ~ RPAREN)? }
HeaderList = { HeaderItem* }
DeclHeader = { HeaderList? ~ KEYWORD_pub? }
ExternalHeaderItem = { (AT | SHARP) ~ BANG ~ IDENTIFIER ~ (LPAREN ~ ExprList? ~ RPAREN)? }
ExternalHeaderList = { ExternalHeaderItem* }
BindingIdent = { IDENTIFIER | UNDERSCORE }
ContainerDeclaration = {
FnDecl
| VarDecl
| ConstDecl
| TypeDecl
| MemberDecl
| ComptimeDecl
| HeaderList ~ Block
}
ComptimeDecl = { KEYWORD_comptime ~ (Block | Expr) }
FnDecl = {
DeclHeader ~ KEYWORD_comptime? ~ KEYWORD_fn ~ IDENTIFIER ~ LPAREN ~ ParamDeclList ~ RPAREN ~ (COLON ~ TypeExpr)? ~ (SEMICOLON | Block)
}
ParamDeclList = { (ParamDecl ~ COMMA)* ~ (ParamDecl | DOT3)? }
ParamDecl = { HeaderList? ~ BindingIdent ~ COLON ~ TypeExpr }
VarDecl = { DeclHeader ~ KEYWORD_var ~ VarBody }
ConstDecl = { DeclHeader ~ KEYWORD_const ~ VarBody }
VarBody = { Pattern ~ (COLON ~ TypeExpr)? ~ (EQUAL ~ Expr)? }
TypeDecl = { DeclHeader ~ KEYWORD_type ~ Pattern ~ EQUAL ~ TypeExpr }
MemberDecl = { DeclHeader ~ IDENTIFIER ~ (COLON ~ TypeExpr)? ~ (EQUAL ~ Expr)? }
Pattern = { PatternAtom ~ (COMMA ~ PatternAtom)* }
PatternAtom = {
UNDERSCORE
| AnonymousAggregatePattern
| DOT ~ IDENTIFIER ~ (LPAREN ~ Pattern? ~ RPAREN)?
| LPAREN ~ Pattern? ~ RPAREN
| PatternLiteral
| IDENTIFIER
}
AnonymousAggregatePattern = { DOT ~ LBRACE ~ PatternFieldList? ~ RBRACE }
PatternFieldList = { PatternField ~ ((COMMA | SEMICOLON) ~ PatternField)* ~ (COMMA | SEMICOLON)? }
PatternField = { DOT ~ IDENTIFIER ~ (EQUAL ~ PatternAtom)? }
PatternLiteral = {
FLOAT_LITERAL
| INTEGER_LITERAL
| CHAR_LITERAL
| STRING_LITERAL
| KEYWORD_true
| KEYWORD_false
| KEYWORD_null
}
Block = { LBRACE ~ Statement* ~ Expr? ~ RBRACE }
Statement = {
RetStatement
| BreakStatement
| ContinueStatement
| DeferStatement
| DeclStatement
| ExprStatement
| ComptimeStatement
}
DeclStatement = { (VarDecl | ConstDecl | TypeDecl) ~ (COMMA | SEMICOLON)? }
ExprStatement = { Expr ~ (COMMA | SEMICOLON)? }
ComptimeStatement = { ComptimeDecl ~ (COMMA | SEMICOLON)? }
RetStatement = { KEYWORD_ret ~ Expr? ~ (COMMA | SEMICOLON)? }
BreakStatement = { KEYWORD_break ~ Label? ~ Expr? ~ (COMMA | SEMICOLON)? }
ContinueStatement = { KEYWORD_continue ~ Label? ~ (COMMA | SEMICOLON)? }
DeferStatement = { KEYWORD_defer ~ (Block | Statement) ~ (COMMA | SEMICOLON)? }
Label = { DOLLAR ~ IDENTIFIER }
Expr = { AssignExpr }
AssignExpr = { BoolOrExpr ~ (AssignOp ~ AssignExpr)? }
BoolOrExpr = { BoolAndExpr ~ (BOOL_OR ~ BoolAndExpr)* }
BoolAndExpr = { BitOrExpr ~ (BOOL_AND ~ BitOrExpr)* }
BitOrExpr = { BitXorExpr ~ (PIPE ~ BitXorExpr)* }
BitXorExpr = { BitAndExpr ~ (CARET ~ BitAndExpr)* }
BitAndExpr = { CmpEqExpr ~ (AMPERSAND ~ CmpEqExpr)* }
CmpEqExpr = { CmpExpr ~ ((EQ_EQ | BANG_EQUAL) ~ CmpExpr)* }
CmpExpr = { ArrowExpr ~ ((L_ARROW_EQ | L_ARROW | R_ARROW_EQ | R_ARROW) ~ ArrowExpr)* }
ArrowExpr = { RangeExpr ~ ((THIN_R_ARROW | THIN_L_ARROW | FAT_D_ARROW | THIN_D_ARROW) ~ RangeExpr)* }
RangeExpr = { ShiftExpr ~ (DOT2 ~ ShiftExpr?)? }
ShiftExpr = { AddExpr ~ ((L_ARROW2_EQ | L_ARROW2 | R_ARROW2_EQ | R_ARROW2) ~ AddExpr)* }
AddExpr = { MulExpr ~ ((PLUS | MINUS) ~ MulExpr)* }
MulExpr = { CastExpr ~ ((ASTERISK | SLASH | PERCENT) ~ CastExpr)* }
CastExpr = { PrefixExpr ~ (KEYWORD_as ~ TypeExpr)* }
PrefixExpr = { PrefixOp* ~ PostfixExpr }
PrefixOp = { MINUS | BANG | TILDE | AMPERSAND }
PostfixExpr = {
PrimaryExpr ~ (LPAREN ~ ExprList ~ RPAREN | DOT ~ IDENTIFIER | DOT ~ ASTERISK | LBRACKET ~ Expr ~ RBRACKET | LBRACKET ~ Expr ~ DOT2 ~ Expr? ~ RBRACKET)*
}
ExprList = { (Expr ~ COMMA)* ~ Expr? }
PrimaryExpr = {
FLOAT_LITERAL
| INTEGER_LITERAL
| CHAR_LITERAL
| STRING_LITERAL
| KEYWORD_true
| KEYWORD_false
| KEYWORD_null
| TupleLiteral
| AggregateLiteral
| AnonymousAggregateLiteral
| ArrayLiteral
| AnonymousArrayLiteral
| VariantConstruct
| ComptimeCallExpr
| IDENTIFIER
| Block
| IfExpr
| IfVarExpr
| WhileExpr
| LoopExpr
| ForExpr
| MatchExpr
| FnTypeExpr
}
TupleLiteral = { ParenExpr }
AggregateLiteral = { IDENTIFIER ~ LBRACE ~ StructInitList? ~ RBRACE }
AnonymousAggregateLiteral = { DOT ~ LBRACE ~ StructInitList? ~ RBRACE }
StructInitList = { StructInit ~ ((COMMA | SEMICOLON) ~ StructInit)* ~ (COMMA | SEMICOLON)? }
StructInit = { DOT ~ IDENTIFIER ~ (EQUAL ~ Expr)? }
VariantConstruct = { DOT ~ IDENTIFIER ~ (LPAREN ~ ExprList? ~ RPAREN)? }
ArrayLiteral = {
LBRACKET ~ RBRACKET ~ TypeExpr ~ LBRACKET ~ ExprList? ~ RBRACKET
| LBRACKET ~ (INTEGER_LITERAL | UNDERSCORE) ~ RBRACKET ~ TypeExpr ~ LBRACKET ~ ExprList? ~ RBRACKET
}
AnonymousArrayLiteral = {
DOT ~ LBRACKET ~ ExprList? ~ RBRACKET
}
ExprNoStruct = { AssignExprNoStruct }
AssignExprNoStruct = { BoolOrExprNoStruct ~ (AssignOp ~ AssignExprNoStruct)? }
BoolOrExprNoStruct = { BoolAndExprNoStruct ~ (BOOL_OR ~ BoolAndExprNoStruct)* }
BoolAndExprNoStruct = { BitOrExprNoStruct ~ (BOOL_AND ~ BitOrExprNoStruct)* }
BitOrExprNoStruct = { BitXorExprNoStruct ~ (PIPE ~ BitXorExprNoStruct)* }
BitXorExprNoStruct = { BitAndExprNoStruct ~ (CARET ~ BitAndExprNoStruct)* }
BitAndExprNoStruct = { CmpEqExprNoStruct ~ (AMPERSAND ~ CmpEqExprNoStruct)* }
CmpEqExprNoStruct = { CmpExprNoStruct ~ ((EQ_EQ | BANG_EQUAL) ~ CmpExprNoStruct)* }
CmpExprNoStruct = { ArrowExprNoStruct ~ ((L_ARROW_EQ | L_ARROW | R_ARROW_EQ | R_ARROW) ~ ArrowExprNoStruct)* }
ArrowExprNoStruct = { RangeExprNoStruct ~ ((THIN_R_ARROW | THIN_L_ARROW | FAT_D_ARROW | THIN_D_ARROW) ~ RangeExprNoStruct)* }
RangeExprNoStruct = { ShiftExprNoStruct ~ (DOT2 ~ ShiftExprNoStruct?)? }
ShiftExprNoStruct = { AddExprNoStruct ~ ((L_ARROW2_EQ | L_ARROW2 | R_ARROW2_EQ | R_ARROW2) ~ AddExprNoStruct)* }
AddExprNoStruct = { MulExprNoStruct ~ ((PLUS | MINUS) ~ MulExprNoStruct)* }
MulExprNoStruct = { CastExprNoStruct ~ ((ASTERISK | SLASH | PERCENT) ~ CastExprNoStruct)* }
CastExprNoStruct = { PrefixExprNoStruct ~ (KEYWORD_as ~ TypeExpr)* }
PrefixExprNoStruct = { PrefixOp* ~ PostfixExprNoStruct }
PostfixExprNoStruct = {
PrimaryExprNoStruct ~ (LPAREN ~ ExprList ~ RPAREN | DOT ~ IDENTIFIER | DOT ~ ASTERISK | LBRACKET ~ Expr ~ RBRACKET | LBRACKET ~ Expr ~ DOT2 ~ Expr? ~ RBRACKET)*
}
PrimaryExprNoStruct = {
FLOAT_LITERAL
| INTEGER_LITERAL
| CHAR_LITERAL
| STRING_LITERAL
| KEYWORD_true
| KEYWORD_false
| KEYWORD_null
| TupleLiteral
| AnonymousAggregateLiteral
| ArrayLiteral
| AnonymousArrayLiteral
| VariantConstruct
| ComptimeCallExpr
| IDENTIFIER
| Block
| IfExpr
| IfVarExpr
| WhileExpr
| LoopExpr
| ForExpr
| MatchExpr
| FnTypeExpr
}
VarBodyNoStruct = { Pattern ~ (COLON ~ TypeExpr)? ~ (EQUAL ~ ExprNoStruct)? }
TypeExpr = { HeaderList? ~ TypePrefixExpr }
TypePrefixExpr = { ASTERISK* ~ TypePostfixExpr }
TypePostfixExpr = {
TypePrimary ~ (LPAREN ~ TypeExprList ~ RPAREN | DOT ~ IDENTIFIER | LBRACKET ~ TypeExpr ~ RBRACKET | KEYWORD_as ~ TypeExpr)*
}
TypePrimary = {
AT ~ IDENTIFIER // @self 等自引用/内置类型
| ComptimeCallExpr // @import("...") 等导入即类型
| IDENTIFIER
| KEYWORD_i8
| KEYWORD_u8
| KEYWORD_i16
| KEYWORD_u16
| KEYWORD_i32
| KEYWORD_u32
| KEYWORD_i64
| KEYWORD_u64
| KEYWORD_f32
| KEYWORD_f64
| KEYWORD_isize
| KEYWORD_usize
| KEYWORD_bool
| KEYWORD_void
| KEYWORD_ptr
| FnTypeExpr
| AggregateTypeExpr
| TypeParenExpr
| ArrayTypeExpr
}
ArrayTypeExpr = {
LBRACKET ~ RBRACKET ~ TypeExpr
| LBRACKET ~ (INTEGER_LITERAL | UNDERSCORE) ~ RBRACKET ~ TypeExpr
}
TypeParenExpr = {
LPAREN ~ RPAREN
| LPAREN ~ TypeExpr ~ COMMA ~ (TypeExpr ~ COMMA)* ~ TypeExpr? ~ RPAREN
| LPAREN ~ TypeExpr ~ RPAREN
}
TypeExprList = { (TypeExpr ~ COMMA)* ~ TypeExpr? }
FnTypeExpr = { KEYWORD_comptime? ~ KEYWORD_fn ~ LPAREN ~ TypeExprList? ~ RPAREN ~ (COLON ~ TypeExpr)? }
AggregateTypeExpr = { (KEYWORD_struct | KEYWORD_union | KEYWORD_enum | KEYWORD_shape) ~ LBRACE ~ ContainerMembers ~ RBRACE }
IfExpr = { KEYWORD_if ~ ExprNoStruct ~ Block ~ (KEYWORD_else ~ (Block | IfExpr | IfVarExpr))? }
IfVarExpr = { KEYWORD_if ~ KEYWORD_var ~ VarBodyNoStruct ~ Block ~ (KEYWORD_else ~ (Block | IfExpr | IfVarExpr))? }
WhileExpr = { Label? ~ KEYWORD_while ~ ExprNoStruct ~ Block ~ (KEYWORD_else ~ (Block | Expr))? }
LoopExpr = { Label? ~ KEYWORD_loop ~ Block }
ForExpr = { Label? ~ KEYWORD_for ~ Pattern ~ COLON ~ ExprNoStruct ~ (COMMA ~ ExprNoStruct)* ~ Block ~ (KEYWORD_else ~ (Block | Expr))? }
MatchExpr = { KEYWORD_match ~ ExprNoStruct ~ LBRACE ~ MatchArm* ~ RBRACE }
MatchArm = { Pattern ~ FAT_R_ARROW ~ Block ~ COMMA? }
ComptimeCallExpr = { AT ~ IDENTIFIER ~ LPAREN ~ ExprList? ~ RPAREN }
ParenExpr = {
LPAREN ~ RPAREN
| LPAREN ~ Expr ~ COMMA ~ (Expr ~ COMMA)* ~ Expr? ~ RPAREN
| LPAREN ~ Expr ~ RPAREN
}
AssignOp = { EQUAL | PLUS_EQ | MINUS_EQ | ASTERISK_EQ | SLASH_EQ | PERCENT_EQ | AMPERSAND_EQ | PIPE_EQ | CARET_EQ | L_ARROW2_EQ | R_ARROW2_EQ }
BOOL_OR = { PIPE ~ PIPE }
BOOL_AND = { AMPERSAND ~ AMPERSAND }
EQ_EQ = { EQUAL ~ EQUAL }
BANG_EQUAL = { BANG ~ EQUAL }
keyword_suffix = _{ !(ASCII_ALPHANUMERIC | "_") }
KEYWORD_fn = @{ "fn" ~ keyword_suffix }
KEYWORD_type = @{ "type" ~ keyword_suffix }
KEYWORD_pub = @{ "pub" ~ keyword_suffix }
KEYWORD_var = @{ "var" ~ keyword_suffix }
KEYWORD_const = @{ "const" ~ keyword_suffix }
KEYWORD_if = @{ "if" ~ keyword_suffix }
KEYWORD_else = @{ "else" ~ keyword_suffix }
KEYWORD_while = @{ "while" ~ keyword_suffix }
KEYWORD_loop = @{ "loop" ~ keyword_suffix }
KEYWORD_for = @{ "for" ~ keyword_suffix }
KEYWORD_as = @{ "as" ~ keyword_suffix }
KEYWORD_match = @{ "match" ~ keyword_suffix }
KEYWORD_ret = @{ "ret" ~ keyword_suffix }
KEYWORD_break = @{ "break" ~ keyword_suffix }
KEYWORD_continue = @{ "continue" ~ keyword_suffix }
KEYWORD_defer = @{ "defer" ~ keyword_suffix }
KEYWORD_shape = @{ "shape" ~ keyword_suffix }
KEYWORD_struct = @{ "struct" ~ keyword_suffix }
KEYWORD_union = @{ "union" ~ keyword_suffix }
KEYWORD_enum = @{ "enum" ~ keyword_suffix }
KEYWORD_comptime = @{ "comptime" ~ keyword_suffix }
KEYWORD_void = @{ "void" ~ keyword_suffix }
KEYWORD_bool = @{ "bool" ~ keyword_suffix }
KEYWORD_isize = @{ "isize" ~ keyword_suffix }
KEYWORD_usize = @{ "usize" ~ keyword_suffix }
KEYWORD_ptr = @{ "ptr" ~ keyword_suffix }
KEYWORD_true = @{ "true" ~ keyword_suffix }
KEYWORD_false = @{ "false" ~ keyword_suffix }
KEYWORD_null = @{ "null" ~ keyword_suffix }
KEYWORD_undefined = @{ "undefined" ~ keyword_suffix }
KEYWORD_i8 = @{ "i8" ~ keyword_suffix }
KEYWORD_u8 = @{ "u8" ~ keyword_suffix }
KEYWORD_i16 = @{ "i16" ~ keyword_suffix }
KEYWORD_u16 = @{ "u16" ~ keyword_suffix }
KEYWORD_i32 = @{ "i32" ~ keyword_suffix }
KEYWORD_u32 = @{ "u32" ~ keyword_suffix }
KEYWORD_i64 = @{ "i64" ~ keyword_suffix }
KEYWORD_u64 = @{ "u64" ~ keyword_suffix }
KEYWORD_f32 = @{ "f32" ~ keyword_suffix }
KEYWORD_f64 = @{ "f64" ~ keyword_suffix }
FAT_D_ARROW = { "<=>" }
THIN_D_ARROW = { "<->" }
L_ARROW2_EQ = { "<<=" }
R_ARROW2_EQ = { ">>=" }
DOT3 = { "..." }
THIN_R_ARROW = { "<-" }
THIN_L_ARROW = { "->" }
L_ARROW_EQ = { "<=" }
R_ARROW_EQ = { ">=" }
L_ARROW2 = { "<<" }
R_ARROW2 = { ">>" }
FAT_R_ARROW = { "=>" }
PLUS_EQ = { "+=" }
MINUS_EQ = { "-=" }
ASTERISK_EQ = { "*=" }
SLASH_EQ = { "/=" }
PERCENT_EQ = { "%=" }
AMPERSAND_EQ = { "&=" }
PIPE_EQ = { "|=" }
CARET_EQ = { "^=" }
DOT2 = { ".." }
LPAREN = { "(" }
RPAREN = { ")" }
LBRACKET = { "[" }
RBRACKET = { "]" }
LBRACE = { "{" }
RBRACE = { "}" }
COMMA = { "," }
SEMICOLON = { ";" }
COLON = { ":" }
DOT = { "." }
AT = { "@" }
SHARP = { "#" }
DOLLAR = { "$" }
EQUAL = { "=" }
PLUS = { "+" }
MINUS = { "-" }
ASTERISK = { "*" }
SLASH = { "/" }
PERCENT = { "%" }
AMPERSAND = { "&" }
PIPE = { "|" }
CARET = { "^" }
TILDE = { "~" }
BANG = { "!" }
L_ARROW = { "<" }
R_ARROW = { ">" }
UNDERSCORE = { "_" }
keyword = _{
KEYWORD_fn
| KEYWORD_type
| KEYWORD_var
| KEYWORD_const
| KEYWORD_if
| KEYWORD_else
| KEYWORD_while
| KEYWORD_loop
| KEYWORD_for
| KEYWORD_as
| KEYWORD_match
| KEYWORD_ret
| KEYWORD_break
| KEYWORD_continue
| KEYWORD_defer
| KEYWORD_shape
| KEYWORD_struct
| KEYWORD_union
| KEYWORD_enum
| KEYWORD_comptime
| KEYWORD_void
| KEYWORD_bool
| KEYWORD_true
| KEYWORD_false
| KEYWORD_null
| KEYWORD_undefined
| KEYWORD_i8
| KEYWORD_u8
| KEYWORD_i16
| KEYWORD_u16
| KEYWORD_i32
| KEYWORD_u32
| KEYWORD_i64
| KEYWORD_u64
| KEYWORD_f32
| KEYWORD_f64
| KEYWORD_isize
| KEYWORD_usize
| KEYWORD_ptr
}
IDENTIFIER = @{
!(keyword ~ !(ASCII_ALPHANUMERIC | "_")) ~ (ASCII_ALPHA | "_" ~ (ASCII_ALPHANUMERIC | "_")) ~ (ASCII_ALPHANUMERIC | "_")*
}
INTEGER_LITERAL = { DECIMAL | HEX | BINARY | OCTAL | "0" }
DECIMAL = { ASCII_NONZERO_DIGIT ~ (ASCII_DIGIT | "_")* }
HEX = { "0" ~ ("x" | "X") ~ ASCII_HEX_DIGIT ~ (ASCII_HEX_DIGIT | "_")* }
BINARY = { "0" ~ ("b" | "B") ~ ASCII_BIN_DIGIT ~ (ASCII_BIN_DIGIT | "_")* }
OCTAL = { "0" ~ ("o" | "O") ~ ASCII_OCT_DIGIT ~ (ASCII_OCT_DIGIT | "_")* }
FLOAT_LITERAL = { ASCII_DIGIT ~ "." ~ ASCII_DIGIT ~ (ASCII_DIGIT | "_")* }
CHAR_LITERAL = { "'" ~ (!"'" ~ ANY) ~ "'" }
STRING_LITERAL = { "\"" ~ ANY* ~ "\"" }
COMMENT = _{ LINE_COMMENT | BLOCK_COMMENT }
LINE_COMMENT = { "//" ~ (!"\n" ~ ANY)* }
BLOCK_COMMENT = { "/*" ~ ANY* ~ "*/" }
WHITESPACE = _{ " " | "\t" | "\r" | "\n" }
+650
View File
@@ -0,0 +1,650 @@
#define SPL_CFLAGS "-Wall", "-Wextra", "-O0", "-g", "-D_CRT_SECURE_NO_WARNINGS"
#define nob_cc_flags(cmd) nob_cmd_append(cmd, SPL_CFLAGS)
#undef UNICODE
#define NOB_IMPLEMENTATION
#include "nob.h"
#undef NOB_IMPLEMENTATION
#include "nob_popen.h"
#ifdef _WIN32
#include <consoleapi2.h>
#endif
#define BUILD_FOLDER "build/"
// Content of the .cflags stamp file; must match SPL_CFLAGS above.
#define CFLAGS_STR "-Wall -Wextra -O0 -g"
// Stamp file whose mtime is refreshed whenever the flags change so that all
// object files get rebuilt.
static const char *CFLAGS_STAMP = BUILD_FOLDER ".cflags";
/* clang-format off */
#define VM_SRCS "stage0/spl_mcode.c", "stage0/spl_syscall.c", "stage0/spl_vm.c",
static const char *spl_cli_srcs[] = {"stage0/spl_cli.c", VM_SRCS};
static const char *test_srcs[] = {"stage0/test_spl_vm.c", VM_SRCS};
static const char *splc0_srcs[] = {
"stage1/splc0.c",
"stage1/spl_diag.c",
"stage1/spl_tok.c",
"stage1/spl_lexer.c",
"stage1/spl_ast.c",
"stage1/spl_parser.c",
"stage1/spl_dumptree.c",
"stage1/spl_type.c",
"stage1/spl_fold.c",
"stage1/spl_lang_type.c",
"stage1/spl_attr.c",
"stage1/spl_scope.c",
"stage1/spl_sema.c",
"stage1/spl_intrin.c",
"stage1/spl_ir.c",
"stage1/spl_ast2ir.c",
"stage1/spl_layout.c",
"stage1/spl_ir2vm.c",
"stage0/spl_mcode.c",
};
/* clang-format on */
typedef struct {
const char *name;
const char **srcs;
size_t srcs_count;
} target_t;
static target_t exe_targets[] = {
{"spl_cli", spl_cli_srcs, NOB_ARRAY_LEN(spl_cli_srcs)},
{"test", test_srcs, NOB_ARRAY_LEN(test_srcs)},
{"splc0", splc0_srcs, NOB_ARRAY_LEN(splc0_srcs)},
};
static const target_t *find_exe_target(const char *name) {
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
if (strcmp(exe_targets[i].name, name) == 0) {
return &exe_targets[i];
}
}
return NULL;
}
static const char *obj_path(const char *src) {
// "stage0/spl_vm.c" -> "build/stage0_spl_vm.o"
size_t prefix_len = strlen(BUILD_FOLDER);
char *out = (char *)nob_temp_alloc(prefix_len + strlen(src) + 2 + 1);
char *w = out;
memcpy(w, BUILD_FOLDER, prefix_len);
w += prefix_len;
for (const char *p = src; *p && *p != '.'; ++p) {
*w++ = (*p == '/' || *p == '\\') ? '_' : *p;
}
memcpy(w, ".o", 3);
return out;
}
// Windows 上 clang/gcc 会输出 build/foo.exe;这里统一带上后缀,
// 否则 nob_needs_rebuild 找不到输出会每次重新链接。
static const char *exe_path(const char *name) {
#ifdef _WIN32
return nob_temp_sprintf(BUILD_FOLDER "%s.exe", name);
#else
return nob_temp_sprintf(BUILD_FOLDER "%s", name);
#endif
}
static bool sync_cflags_stamp(void) {
Nob_String_View cflags = nob_sv_from_cstr(CFLAGS_STR);
Nob_String_Builder old = {0};
bool changed = true;
if (nob_file_exists(CFLAGS_STAMP) && nob_read_entire_file(CFLAGS_STAMP, &old)) {
changed = !nob_sv_eq(nob_sb_to_sv(old), cflags);
}
nob_sb_free(old);
if (changed) {
if (!nob_write_entire_file(CFLAGS_STAMP, cflags.data, cflags.count)) {
return false;
}
}
return true;
}
// 头文件依赖:收集 stage0/stage1 下的所有 .h,作为每个 object 的输入。
// nob 不解析 #include,这里用“任一头文件变化则重建全部 object”的保守策略,
// 避免头文件改动后各 .o 结构体布局/常量不一致导致的隐蔽错误。
static Nob_Files g_headers = {0};
static bool collect_header_entry(Nob_Walk_Entry entry) {
if (entry.type != NOB_FILE_REGULAR)
return true;
const char *dot = strrchr(entry.path, '.');
if (!dot || strcmp(dot, ".h") != 0)
return true;
if (strstr(entry.path, ".old") != NULL)
return true;
da_append(&g_headers, nob_temp_strdup(entry.path));
return true;
}
static bool collect_headers(void) {
if (g_headers.count > 0)
return true;
if (!nob_walk_dir("stage0", collect_header_entry))
return false;
if (!nob_walk_dir("stage1", collect_header_entry))
return false;
return true;
}
// stage2 的所有 .spl:作为 splc1.sir 的依赖(不解析 @import,保守全量重建)。
static Nob_Files g_spl2 = {0};
static bool collect_spl2_entry(Nob_Walk_Entry entry) {
if (entry.type != NOB_FILE_REGULAR)
return true;
const char *dot = strrchr(entry.path, '.');
if (!dot || strcmp(dot, ".spl") != 0)
return true;
da_append(&g_spl2, nob_temp_strdup(entry.path));
return true;
}
static bool collect_spl2(void) {
if (g_spl2.count > 0)
return true;
return nob_walk_dir("stage2", collect_spl2_entry);
}
static bool prepare_build(void) {
if (!nob_mkdir_if_not_exists(BUILD_FOLDER))
return false;
if (!sync_cflags_stamp())
return false;
if (!collect_headers())
return false;
return collect_spl2();
}
static bool build_object(const char *src) {
const char *obj = obj_path(src);
if (!nob_file_exists(src)) {
nob_log(NOB_ERROR, "source file `%s` does not exist", src);
return false;
}
// 依赖:源文件 + 所有头文件 + cflags 戳。
size_t ninputs = g_headers.count + 2;
const char **inputs = (const char **)nob_temp_alloc(sizeof(const char *) * ninputs);
inputs[0] = src;
for (size_t i = 0; i < g_headers.count; ++i) {
inputs[i + 1] = g_headers.items[i];
}
inputs[ninputs - 1] = CFLAGS_STAMP;
int needs = nob_needs_rebuild(obj, inputs, ninputs);
if (needs < 0)
return false;
if (needs == 0)
return true;
Nob_Cmd cmd = {0};
nob_cc(&cmd);
nob_cc_flags(&cmd);
nob_cmd_append(&cmd, "-c");
nob_cc_inputs(&cmd, src);
nob_cc_output(&cmd, obj);
return nob_cmd_run(&cmd);
}
static bool link_exe(const target_t *target) {
const char *exe = exe_path(target->name);
const char **objs = (const char **)nob_temp_alloc(sizeof(const char *) * target->srcs_count);
for (size_t i = 0; i < target->srcs_count; ++i) {
objs[i] = obj_path(target->srcs[i]);
}
int needs = nob_needs_rebuild(exe, objs, target->srcs_count);
if (needs < 0)
return false;
if (needs == 0)
return true;
Nob_Cmd cmd = {0};
nob_cc(&cmd);
nob_cc_flags(&cmd);
for (size_t i = 0; i < target->srcs_count; ++i) {
nob_cc_inputs(&cmd, objs[i]);
}
nob_cc_output(&cmd, exe);
return nob_cmd_run(&cmd);
}
static bool build_target(const char *name) {
const target_t *target = find_exe_target(name);
if (target == NULL) {
nob_log(NOB_ERROR, "unknown target `%s`", name);
return false;
}
for (size_t i = 0; i < target->srcs_count; ++i) {
if (!build_object(target->srcs[i])) {
return false;
}
}
return link_exe(target);
}
static bool build_all(void) {
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
if (!build_target(exe_targets[i].name)) {
return false;
}
}
return true;
}
static void parse_expect(const char *name, Nob_Cmd_Result *expect) {
Nob_String_Builder sb = {0};
nob_read_entire_file(name, &sb);
Nob_String_View sv = nob_sb_to_sv(sb);
while (sv.count > 0) {
Nob_String_View line = nob_sv_chop_by_delim(&sv, '\n');
line = nob_sv_trim_left(line); // 去掉前导空格
if (!nob_sv_starts_with(line, nob_sv_from_cstr("//"))) {
break;
}
Nob_String_View rest = nob_sv_from_parts(line.data + 2, line.count - 2);
rest = nob_sv_trim_left(rest);
if (rest.count == 0)
continue;
if (!nob_sv_starts_with(rest, nob_sv_from_cstr("Expect"))) {
break;
}
rest = nob_sv_from_parts(rest.data + 6, rest.count - 6);
rest = nob_sv_trim_left(rest);
// 按 '=' 分割
Nob_String_View key = nob_sv_chop_by_delim(&rest, '=');
key = nob_sv_trim(key);
Nob_String_View value = nob_sv_trim(rest);
if (nob_sv_eq(key, nob_sv_from_cstr("retcode"))) {
int val = 0;
for (size_t i = 0; i < value.count && isdigit(value.data[i]); ++i) {
val = val * 10 + (value.data[i] - '0');
}
// printf("expected code %d\n", val);
expect->exit_code = val;
} else if (nob_sv_eq(key, nob_sv_from_cstr("stdout"))) {
}
}
}
static bool test_once(const char *fname, void *user_data) {
(void)user_data;
const char *compiler_path = "splc0";
const char *cli_path = "spl_cli";
const char *target_sir = BUILD_FOLDER "test.sir";
Nob_Cmd cmd = {0};
if (!build_target(compiler_path)) {
return 1;
}
cmd.count = 0;
nob_cmd_append(&cmd, exe_path(compiler_path));
nob_cmd_append(&cmd, fname, target_sir);
if (!nob_cmd_run(&cmd)) {
return false;
}
if (!build_target(cli_path)) {
return 1;
}
cmd.count = 0;
nob_cmd_append(&cmd, exe_path(cli_path));
nob_cmd_append(&cmd, target_sir);
// nob_cmd_run(&cmd);
Nob_Cmd_Result result = {0};
Nob_String_Builder cmd_str = {0};
nob_cmd_render(cmd, &cmd_str);
Nob_String_View sv = nob_sb_to_sv(cmd_str);
nob_cmd_capture_popen(nob_temp_sv_to_cstr(sv), &result);
// Expect retcode = number
Nob_Cmd_Result expect = {0};
parse_expect(fname, &expect);
if (expect.exit_code != result.exit_code) {
nob_log(NOB_ERROR, "Expect code `%d`, Result code `%d`", expect.exit_code,
result.exit_code);
return false;
}
nob_cmd_result_free(result);
return true;
}
static bool test_once_with_dump(const char *fname, void *user_data) {
const char *target_name = "splc0";
if (!prepare_build())
return 1;
if (!build_target(target_name))
return 1;
Nob_Cmd cmd = {0};
nob_cmd_append(&cmd, exe_path(target_name));
nob_cmd_append(&cmd, "--dump", (char *)user_data, fname, BUILD_FOLDER "t.sir");
return nob_cmd_run(&cmd);
}
// 用 splc0 编译 stage2/splc1.spl -> build/splc1.sir(依赖 stage2 全部 .spl)。
static bool build_splc1(void) {
if (!build_target("splc0"))
return false;
const char *src = "stage2/splc1.spl";
const char *sir = BUILD_FOLDER "splc1.sir";
size_t ninputs = g_spl2.count + 2;
const char **inputs = (const char **)nob_temp_alloc(sizeof(const char *) * ninputs);
inputs[0] = src;
for (size_t i = 0; i < g_spl2.count; ++i)
inputs[i + 1] = g_spl2.items[i];
inputs[ninputs - 1] = CFLAGS_STAMP;
int needs = nob_needs_rebuild(sir, inputs, ninputs);
if (needs < 0)
return false;
if (needs == 0)
return true;
Nob_Cmd cmd = {0};
nob_cmd_append(&cmd, exe_path("splc0"), src, sir);
return nob_cmd_run(&cmd);
}
static bool run_capture(Nob_Cmd *cmd, Nob_Cmd_Result *result) {
Nob_String_Builder rendered = {0};
nob_cmd_render(*cmd, &rendered);
Nob_String_View sv = nob_sb_to_sv(rendered);
bool ok = nob_cmd_capture_popen(nob_temp_sv_to_cstr(sv), result);
nob_sb_free(rendered);
return ok;
}
// diff 测试:对同一文件跑 `splc0 --dump <mode>` 与 `spl_cli splc1.sir --dump <mode>`,
// 逐字节比较 stdout。
static bool test_once_diff(const char *fname, void *user_data) {
const char *mode = (const char *)user_data;
if (!mode) {
nob_log(NOB_ERROR, "diff test requires a mode: lex|ast|sema|ir|vm");
return false;
}
if (!build_target("splc0"))
return false;
if (!build_target("spl_cli"))
return false;
if (!build_splc1())
return false;
Nob_Cmd c_cmd = {0};
nob_cmd_append(&c_cmd, exe_path("splc0"), "--dump", (char *)mode, (char *)fname,
BUILD_FOLDER "diff_c.sir");
Nob_Cmd_Result c_res = {0};
if (!run_capture(&c_cmd, &c_res)) {
nob_cmd_result_free(c_res);
return false;
}
Nob_Cmd s_cmd = {0};
nob_cmd_append(&s_cmd, exe_path("spl_cli"), BUILD_FOLDER "splc1.sir", "--dump", (char *)mode,
(char *)fname);
Nob_Cmd_Result s_res = {0};
if (!run_capture(&s_cmd, &s_res)) {
nob_cmd_result_free(c_res);
nob_cmd_result_free(s_res);
return false;
}
Nob_String_View c_out = nob_sb_to_sv(c_res.out);
Nob_String_View s_out = nob_sb_to_sv(s_res.out);
bool same = nob_sv_eq(c_out, s_out);
if (!same) {
nob_log(NOB_ERROR, "diff mismatch: %s (c=%zu bytes, spl=%zu bytes)", fname, c_out.count,
s_out.count);
// 打印首个不相同行(按行比较)。
Nob_String_View ca = c_out;
Nob_String_View sa = s_out;
size_t lineno = 1;
while (ca.count > 0 || sa.count > 0) {
Nob_String_View cl = nob_sv_chop_by_delim(&ca, '\n');
Nob_String_View sl = nob_sv_chop_by_delim(&sa, '\n');
if (!nob_sv_eq(cl, sl)) {
nob_log(NOB_ERROR, " line %zu:", lineno);
nob_log(NOB_ERROR, " c : %.*s", (int)cl.count, cl.data);
nob_log(NOB_ERROR, " spl: %.*s", (int)sl.count, sl.data);
break;
}
lineno++;
}
nob_log(NOB_ERROR, "--- c stderr/stdout merged above; exit=%d vs spl exit=%d ---",
c_res.exit_code, s_res.exit_code);
}
nob_cmd_result_free(c_res);
nob_cmd_result_free(s_res);
return same;
}
static bool is_stage_name(const char *s) {
return strcmp(s, "stage1") == 0 || strcmp(s, "stage2") == 0 || strcmp(s, "diff") == 0;
}
static bool is_dump_mode(const char *s) {
return strcmp(s, "lex") == 0 || strcmp(s, "ast") == 0 || strcmp(s, "sema") == 0 ||
strcmp(s, "ir") == 0 || strcmp(s, "vm") == 0;
}
static const char *stage_dir_of(const char *stage) {
if (strcmp(stage, "stage2") == 0)
return "./stage2/";
return "./tests/stage1/";
}
typedef bool (*test_fn_t)(const char *fname, void *user_data);
typedef struct {
Nob_Files *files;
test_fn_t test_once;
void *user_data;
} test_walk_ctx_t;
static bool test_walk_entry(Nob_Walk_Entry entry) {
if (entry.type != NOB_FILE_REGULAR)
return true;
const char *dot = strrchr(entry.path, '.');
if (!dot || strcmp(dot, ".spl") != 0)
return true;
test_walk_ctx_t *ctx = (test_walk_ctx_t *)entry.data;
bool run_all = (ctx->files->count == 0);
bool matched = run_all;
for (int i = 0; !matched && i < ctx->files->count; i += 1) {
if (strstr(entry.path, ctx->files->items[i]))
matched = true;
}
if (!matched)
return true;
printf("--- test %s ---\n", entry.path);
if (ctx->test_once(entry.path, ctx->user_data) == false)
return false;
return true;
}
static bool run_test(const char *stage, Nob_Files *files, test_fn_t test_once, void *user_data) {
const char *test_folder = stage_dir_of(stage);
if (!prepare_build())
return false;
if (!nob_file_exists(test_folder)) {
nob_log(NOB_INFO, "%s does not exist, skip", test_folder);
return true;
}
test_walk_ctx_t ctx = {
.files = files,
.test_once = test_once,
.user_data = user_data,
};
return nob_walk_dir(test_folder, test_walk_entry, .data = &ctx);
}
static bool delete_walk_entry(Nob_Walk_Entry entry) { return nob_delete_file(entry.path); }
static bool delete_directory_recursively(const char *dir_path) {
return nob_walk_dir(dir_path, delete_walk_entry, .post_order = true);
}
static void print_help(const char *program_name) {
nob_log(NOB_INFO, "SPL C-side bootstrap build system (nob)");
nob_log(NOB_INFO, "%s", " ");
nob_log(NOB_INFO, "Usage: %s <command> [args...]", program_name);
nob_log(NOB_INFO, "%s", " ");
nob_log(NOB_INFO, "Commands:");
nob_log(NOB_INFO, " build [targets...] build all targets or the given ones");
nob_log(NOB_INFO, " run <target> [args] build and run a target");
nob_log(NOB_INFO, " test build and run VM unit tests");
nob_log(NOB_INFO, " clean remove build artifacts");
nob_log(NOB_INFO, " list list all targets");
nob_log(NOB_INFO, " help/-h/--help print this help message");
nob_log(NOB_INFO, "%s", " ");
nob_log(NOB_INFO, "Targets:");
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
nob_log(NOB_INFO, " %s", exe_targets[i].name);
}
}
int main(int argc, char **argv) {
#ifdef _WIN32
SetConsoleOutputCP(CP_UTF8);
#endif
NOB_GO_REBUILD_URSELF_PLUS(argc, argv, "nob.h", "nob_popen.h");
set_log_handler(nob_cancer_log_handler);
const char *program_name = nob_shift(argv, argc);
const char *command_name = "build";
if (argc > 0) {
command_name = nob_shift(argv, argc);
}
if (strcmp(command_name, "build") == 0) {
if (!prepare_build())
return 1;
if (argc > 0) {
while (argc > 0) {
const char *target_name = nob_shift(argv, argc);
if (!build_target(target_name))
return 1;
}
} else {
if (!build_all())
return 1;
}
return 0;
}
if (strcmp(command_name, "run") == 0) {
if (argc <= 0) {
nob_log(NOB_ERROR, "usage: %s run <target> [args...]", program_name);
return 1;
}
const char *target_name = nob_shift(argv, argc);
if (!prepare_build())
return 1;
if (!build_target(target_name))
return 1;
Nob_Cmd cmd = {0};
nob_cmd_append(&cmd, exe_path(target_name));
while (argc > 0) {
nob_cmd_append(&cmd, nob_shift(argv, argc));
}
return nob_cmd_run(&cmd) ? 0 : 1;
}
if (strcmp(command_name, "test") == 0) {
// 1. stage(可选,默认 stage1)
const char *stage = "stage1";
if (argc > 0 && is_stage_name(argv[0])) {
stage = nob_shift(argv, argc);
}
// 2. mode(可选)
test_fn_t tfn = test_once;
const char *mode_name = NULL;
if (argc > 0) {
if (is_dump_mode(argv[0])) {
tfn = test_once_with_dump;
mode_name = nob_shift(argv, argc);
} else if (strcmp(argv[0], "run") == 0) {
nob_shift(argv, argc);
// HACK:只对 stage1 有意义,跑上次生成的 build/test.sir
Nob_Cmd cmd = {0};
nob_cmd_append(&cmd, BUILD_FOLDER "spl_cli", "-d");
nob_cmd_append(&cmd, BUILD_FOLDER "test.sir");
return nob_cmd_run(&cmd) ? 0 : 1;
}
}
// diff 需要显式 mode,且使用专门的双编译器比较函数。
if (strcmp(stage, "diff") == 0) {
if (!mode_name) {
nob_log(NOB_ERROR, "diff requires a mode: lex|ast|sema|ir|vm");
return 1;
}
tfn = test_once_diff;
}
// 3. 剩下的都当 pattern
Nob_Files files = {0};
while (argc > 0) {
da_append(&files, nob_shift(argv, argc));
}
return run_test(stage, &files, tfn, (void *)mode_name) ? 0 : 1;
}
if (strcmp(command_name, "clean") == 0) {
if (nob_file_exists(BUILD_FOLDER)) {
if (!delete_directory_recursively(BUILD_FOLDER))
return 1;
}
nob_log(NOB_INFO, "cleaned %s", BUILD_FOLDER);
return 0;
}
if (strcmp(command_name, "list") == 0) {
for (size_t i = 0; i < NOB_ARRAY_LEN(exe_targets); ++i) {
nob_log(NOB_INFO, "%s:", exe_targets[i].name);
for (size_t j = 0; j < exe_targets[i].srcs_count; ++j) {
nob_log(NOB_INFO, " %s", exe_targets[i].srcs[j]);
}
}
return 0;
}
if (strcmp(command_name, "help") == 0 || strcmp(command_name, "-h") == 0 ||
strcmp(command_name, "--help") == 0) {
print_help(program_name);
return 0;
}
nob_log(NOB_ERROR, "unknown command `%s`", command_name);
print_help(program_name);
return 1;
}
+3391
View File
File diff suppressed because it is too large. Load diff
+145
View File
@@ -0,0 +1,145 @@
#ifndef __NOB_POPEN_H__
#define __NOB_POPEN_H__
#include "nob.h"
typedef struct {
Nob_String_Builder out; // stdout 内容
int exit_code; // 实际退出码
bool ok; // 是否成功启动
} Nob_Cmd_Result;
typedef struct {
const char **items;
int capacity;
int count;
} Nob_Files;
// 运行命令,捕获 stdout(Windows 下会合并 stderr)和真实退出码。
// 返回 true 仅表示命令成功启动并完成,不代表 exit_code == 0。
bool nob_cmd_capture_popen(const char *tname, Nob_Cmd_Result *res) {
memset(res, 0, sizeof(*res));
#ifdef _WIN32
// ---------- Windows: CreateProcessA + 匿名管道 ----------
SECURITY_ATTRIBUTES sa = {0};
sa.nLength = sizeof(sa);
sa.bInheritHandle = TRUE;
sa.lpSecurityDescriptor = NULL;
HANDLE hRead = NULL;
HANDLE hWrite = NULL;
if (!CreatePipe(&hRead, &hWrite, &sa, 0)) {
nob_log(NOB_ERROR, "CreatePipe failed: %s", nob_win32_error_message(GetLastError()));
return false;
}
// 读端不能被继承,否则父进程 ReadFile 永远等不到 EOF
if (!SetHandleInformation(hRead, HANDLE_FLAG_INHERIT, 0)) {
nob_log(NOB_ERROR, "SetHandleInformation failed: %s",
nob_win32_error_message(GetLastError()));
CloseHandle(hRead);
CloseHandle(hWrite);
return false;
}
STARTUPINFOA si = {0};
si.cb = sizeof(si);
si.dwFlags = STARTF_USESTDHANDLES;
si.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
si.hStdOutput = hWrite;
si.hStdError = hWrite; // 把 stderr 也并入 out,需要分离的话另开一条管道
PROCESS_INFORMATION pi = {0};
// CreateProcessA 会就地修改 lpCommandLine,必须传可写缓冲
char *cmdline = NULL;
{
size_t n = strlen(tname) + 1;
cmdline = (char *)malloc(n);
if (!cmdline) {
CloseHandle(hRead);
CloseHandle(hWrite);
nob_log(NOB_ERROR, "malloc failed");
return false;
}
memcpy(cmdline, tname, n);
}
BOOL ok = CreateProcessA(NULL, // lpApplicationName: 让系统从 lpCommandLine 里解析
cmdline, // lpCommandLine
NULL, // lpProcessAttributes
NULL, // lpThreadAttributes
TRUE, // bInheritHandles: 必须为 TRUE,才能继承管道写端
CREATE_NO_WINDOW, // 不弹黑窗;想弹就传 0
NULL, // lpEnvironment
NULL, // lpCurrentDirectory
&si, &pi);
free(cmdline);
// 无论成功与否,父进程都不再需要写端(子进程已持有自己的副本)
CloseHandle(hWrite);
if (!ok) {
nob_log(NOB_ERROR, "CreateProcessA failed for \"%s\": %s", tname,
nob_win32_error_message(GetLastError()));
CloseHandle(hRead);
return false;
}
// ---------- 读取 stdout ----------
{
char buffer[4096];
DWORD n = 0;
while (ReadFile(hRead, buffer, sizeof(buffer), &n, NULL) && n > 0) {
nob_sb_append_buf(&res->out, buffer, (size_t)n);
}
}
CloseHandle(hRead);
// ---------- 等待并取真实退出码 ----------
WaitForSingleObject(pi.hProcess, INFINITE);
DWORD code = 0;
if (!GetExitCodeProcess(pi.hProcess, &code)) {
nob_log(NOB_ERROR, "GetExitCodeProcess failed: %s",
nob_win32_error_message(GetLastError()));
code = (DWORD)-1;
}
res->exit_code = (int)code;
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
#else
// ---------- POSIX: popen ----------
FILE *fp = popen(tname, "r");
if (!fp) {
nob_log(NOB_ERROR, "popen failed: %s", strerror(errno));
return false;
}
char buffer[4096];
while (fgets(buffer, sizeof(buffer), fp)) {
nob_sb_append_cstr(&res->out, buffer);
}
int status = pclose(fp);
if (status == -1) {
nob_log(NOB_ERROR, "pclose failed: %s", strerror(errno));
return false;
}
if (WIFEXITED(status))
status = WEXITSTATUS(status);
else if (WIFSIGNALED(status))
status = 128 + WTERMSIG(status);
res->exit_code = status;
#endif
res->ok = true;
return true;
}
#define nob_cmd_result_free(res) nob_sb_free((res).out)
#endif /* __NOB_POPEN_H__ */
File diff suppressed because it is too large. Load diff
+61
View File
@@ -0,0 +1,61 @@
/**
* @file color.h
* @brief ANSI终端颜色控制码定义
*
* 提供跨平台的终端文本颜色和样式控制支持
*/
#ifndef __SCC_TERMINAL_COLOR_H__
#define __SCC_TERMINAL_COLOR_H__
/* clang-format off */
/// @name 前景色控制码
/// @{
#define ANSI_FG_BLACK "\33[30m" ///< 黑色前景
#define ANSI_FG_RED "\33[31m" ///< 红色前景
#define ANSI_FG_GREEN "\33[32m" ///< 绿色前景
#define ANSI_FG_YELLOW "\33[33m" ///< 黄色前景
#define ANSI_FG_BLUE "\33[34m" ///< 蓝色前景
#define ANSI_FG_MAGENTA "\33[35m" ///< 品红色前景
#define ANSI_FG_CYAN "\33[36m" ///< 青色前景
#define ANSI_FG_WHITE "\33[37m" ///< 白色前景
/// @}
/// @name 背景色控制码
/// @{
#define ANSI_BG_BLACK "\33[40m" ///< 黑色背景
#define ANSI_BG_RED "\33[41m" ///< 红色背景
#define ANSI_BG_GREEN "\33[42m" ///< 绿色背景
#define ANSI_BG_YELLOW "\33[43m" ///< 黄色背景
#define ANSI_BG_BLUE "\33[44m" ///< 蓝色背景
#define ANSI_BG_MAGENTA "\33[45m" ///< 品红色背景(注:原始代码此处应为45m)
#define ANSI_BG_CYAN "\33[46m" ///< 青色背景
#define ANSI_BG_WHITE "\33[47m" ///< 白色背景
/// @}
/// @name 文字样式控制码
/// @{
#define ANSI_UNDERLINED "\33[4m" ///< 下划线样式
#define ANSI_BOLD "\33[1m" ///< 粗体样式
#define ANSI_NONE "\33[0m" ///< 重置所有样式
/// @}
/* clang-format on */
/**
* @def ANSI_FMT
* @brief 安全文本格式化宏
* @param str 目标字符串
* @param fmt ANSI格式序列(可组合多个样式)
*
* @note 当定义ANSI_FMT_DISABLE时自动禁用颜色输出
* @code
* printf(ANSI_FMT("Warning!", ANSI_FG_YELLOW ANSI_BOLD));
* @endcode
*/
#ifndef ANSI_FMT_DISABLE
#define ANSI_FMT(str, fmt) fmt str ANSI_NONE ///< 启用样式包裹
#else
#define ANSI_FMT(str, fmt) str ///< 禁用样式输出
#endif
#endif /* __SCC_TERMINAL_COLOR_H__ */
+225
View File
@@ -0,0 +1,225 @@
#ifndef __CORE_MAP_H__
#define __CORE_MAP_H__
#include <stddef.h>
#include <stdint.h>
#include <stdlib.h>
#include <string.h>
#ifndef nullptr
#define nullptr NULL
#endif
typedef uintptr_t usize;
typedef intptr_t isize;
#define MAP_TYPEOF __typeof__
/* 状态常量 */
#define __MAP_SLOT_EMPTY 0
#define __MAP_SLOT_OCCUPIED 1
#define __MAP_SLOT_DELETED 2
/* 默认负载因子 factor/128 */
#define MAP_DEFAULT_LOAD_FACTOR 70
/* ---------- 默认哈希/比较函数 ---------- */
#define MAP_HASH_INT(k) ((usize)((k) * 2654435761U))
#define MAP_CMP_INT(a, b) ((a) != (b))
static inline usize map_hash_str(const char *s) {
usize h = 5381;
while (*s)
h = ((h << 5) + h) + (unsigned char)*s++;
return h;
}
#define MAP_HASH_STR map_hash_str
#define MAP_CMP_STR strcmp
/* ---------- 数据结构宏 ---------- */
#define MAP_SLOT(key_t, val_t) \
struct { \
key_t key; \
val_t val; \
char state; \
}
#define MAP(key_t, val_t) \
struct { \
usize size; \
usize cap; \
MAP_SLOT(key_t, val_t) * data; \
usize (*hash)(key_t); \
int (*cmp)(key_t, key_t); \
}
/* ---------- 操作宏 ---------- */
/** 初始化,必须提供哈希和比较函数 */
#define map_init(map, hash_fn, cmp_fn) \
do { \
(map).size = 0; \
(map).cap = 0; \
(map).data = nullptr; \
(map).hash = (hash_fn); \
(map).cmp = (cmp_fn); \
} while (0)
/** 释放内部数组 */
#define map_free(map) \
do { \
free((map).data); \
(map).data = nullptr; \
(map).size = (map).cap = 0; \
} while (0)
/** 遍历所有有效元素 */
#define map_for(map, idx) \
for (usize(idx) = 0; (idx) < (map).cap; ++(idx)) \
if ((map).data[(idx)].state == __MAP_SLOT_OCCUPIED)
#define unsafe_map_at(map, idx) ((map).data[(idx)])
/**
* 插入(若键已存在则更新值)
* 注意:扩容使用 realloc,失败会 abort(可自行修改错误处理)
*/
#define map_put(map, _key, _val) \
do { \
/* 扩容 */ \
if ((map).cap == 0 || (map).size * 128 / (map).cap >= MAP_DEFAULT_LOAD_FACTOR) { \
usize new_cap = (map).cap == 0 ? 8 : (map).cap * 2; \
MAP_SLOT(MAP_TYPEOF((map).data->key), MAP_TYPEOF((map).data->val)) *new_data = \
calloc(new_cap, sizeof(*new_data)); \
if (!new_data) \
abort(); \
/* 重新插入旧元素 */ \
for (usize _i = 0; _i < (map).cap; ++_i) { \
if ((map).data[_i].state == __MAP_SLOT_OCCUPIED) { \
usize _h = (map).hash((map).data[_i].key) & (new_cap - 1); \
while (new_data[_h].state == __MAP_SLOT_OCCUPIED) \
_h = (_h + 1) & (new_cap - 1); \
new_data[_h].key = (map).data[_i].key; \
new_data[_h].val = (map).data[_i].val; \
new_data[_h].state = __MAP_SLOT_OCCUPIED; \
} \
} \
free((map).data); \
(map).data = (void *)new_data; \
(map).cap = new_cap; \
} \
/* 查找或插入 */ \
usize _mask = (map).cap - 1; \
usize _idx = (map).hash(_key) & _mask; \
usize _first_del = (usize) - 1; \
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
(map).cmp((map).data[_idx].key, _key) == 0) { \
(map).data[_idx].val = _val; \
break; \
} \
if ((map).data[_idx].state == __MAP_SLOT_DELETED && _first_del == (usize) - 1) \
_first_del = _idx; \
_idx = (_idx + 1) & _mask; \
} \
if ((map).data[_idx].state == __MAP_SLOT_EMPTY) { \
usize _target = (_first_del != (usize) - 1) ? _first_del : _idx; \
(map).data[_target].key = _key; \
(map).data[_target].val = _val; \
(map).data[_target].state = __MAP_SLOT_OCCUPIED; \
++(map).size; \
} \
} while (0)
/**
* 插入(仅当键不存在时),若键已存在则静默跳过,不更新值
* 与 map_put 的差异仅在"键已存在时":map_put 更新值,map_put_new 放弃
*/
#define map_put_new(map, _key, _val) \
do { \
/* 扩容 */ \
if ((map).cap == 0 || (map).size * 128 / (map).cap >= MAP_DEFAULT_LOAD_FACTOR) { \
usize new_cap = (map).cap == 0 ? 8 : (map).cap * 2; \
MAP_SLOT(MAP_TYPEOF((map).data->key), MAP_TYPEOF((map).data->val)) *new_data = \
calloc(new_cap, sizeof(*new_data)); \
if (!new_data) \
abort(); \
/* 重新插入旧元素 */ \
for (usize _i = 0; _i < (map).cap; ++_i) { \
if ((map).data[_i].state == __MAP_SLOT_OCCUPIED) { \
usize _h = (map).hash((map).data[_i].key) & (new_cap - 1); \
while (new_data[_h].state == __MAP_SLOT_OCCUPIED) \
_h = (_h + 1) & (new_cap - 1); \
new_data[_h].key = (map).data[_i].key; \
new_data[_h].val = (map).data[_i].val; \
new_data[_h].state = __MAP_SLOT_OCCUPIED; \
} \
} \
free((map).data); \
(map).data = (void *)new_data; \
(map).cap = new_cap; \
} \
/* 查找 */ \
usize _mask = (map).cap - 1; \
usize _idx = (map).hash(_key) & _mask; \
usize _first_del = (usize) - 1; \
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
(map).cmp((map).data[_idx].key, _key) == 0) { \
break; /* 已存在,不更新 */ \
} \
if ((map).data[_idx].state == __MAP_SLOT_DELETED && _first_del == (usize) - 1) \
_first_del = _idx; \
_idx = (_idx + 1) & _mask; \
} \
if ((map).data[_idx].state == __MAP_SLOT_EMPTY) { \
usize _target = (_first_del != (usize) - 1) ? _first_del : _idx; \
(map).data[_target].key = _key; \
(map).data[_target].val = _val; \
(map).data[_target].state = __MAP_SLOT_OCCUPIED; \
++(map).size; \
} \
} while (0)
/**
* 查询:若找到,*out_val 被赋值为对应值并返回 1;否则返回 0
*/
#define map_get(map, _key, out_val) \
(({ \
int _found = 0; \
if ((map).cap > 0) { \
usize _mask = (map).cap - 1; \
usize _idx = (map).hash(_key) & _mask; \
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
(map).cmp((map).data[_idx].key, _key) == 0) { \
*out_val = (map).data[_idx].val; \
_found = 1; \
break; \
} \
_idx = (_idx + 1) & _mask; \
} \
} \
_found; \
}))
/**
* 删除指定键
*/
#define map_del(map, _key) \
do { \
if ((map).cap == 0) \
break; \
usize _mask = (map).cap - 1; \
usize _idx = (map).hash(_key) & _mask; \
while ((map).data[_idx].state != __MAP_SLOT_EMPTY) { \
if ((map).data[_idx].state == __MAP_SLOT_OCCUPIED && \
(map).cmp((map).data[_idx].key, _key) == 0) { \
(map).data[_idx].state = __MAP_SLOT_DELETED; \
--(map).size; \
break; \
} \
_idx = (_idx + 1) & _mask; \
} \
} while (0)
#endif /* __CORE_MAP_H__ */
+258
View File
@@ -0,0 +1,258 @@
/**
* @file vec.h
* @brief 动态数组(Dynamic Array)实现
*
* 提供类型安全的动态数组容器实现,支持自动扩容和基本操作
*/
#ifndef __CORE_VEC_H__
#define __CORE_VEC_H__
#define __CORE_VEC_USE_STD__
#ifndef __CORE_VEC_USE_STD__
#include "core_log.h"
#include "core_impl.h"
#include "core_type.h"
#define __vec_realloc realloc
#define __vec_free free
#define __vec_memcpy memcpy
#else
#include <stdbool.h>
#include <stddef.h>
#include <stdlib.h>
#include <string.h>
#ifndef nullptr
#define nullptr NULL
#endif
typedef size_t usize;
#define __vec_realloc realloc
#define __vec_free free
#define __vec_memcpy memcpy
#ifndef LOG_FATAL
#include <stdio.h>
#define LOG_FATAL(...) \
do { \
printf(__VA_ARGS__); \
abort(); \
} while (0)
#endif
#ifndef Assert
#include <assert.h>
#define Assert(cond) assert(cond)
#endif
#endif
/** @defgroup vec_struct 数据结构定义 */
/**
* @def VEC(type)
* @brief 声明向量结构体
* @param type 存储的数据类型
*
* 生成包含size/cap/data三个字段的结构体定义:
* - size: 当前元素数量
* - cap: 数组容量
* - data: 存储数组指针
* @example
* VEC(char) string; <=> char[dynamic_array] string;
* struct people { VEC(char) name; int age; VEC(struct people) children;
* };
*/
#define VEC(type) \
struct { \
usize size; \
usize cap; \
type *data; \
}
/** @defgroup vec_operations 动态数组操作宏 */
/**
* @def vec_init(vec)
* @brief 初始化向量结构体
* @param vec 要初始化的向量结构体变量
*
* @note 此宏不会分配内存,仅做零初始化
*/
#define vec_init(vec) \
do { \
(vec).size = 0, (vec).cap = 0, (vec).data = 0; \
} while (0)
#define vec_realloc(vec, new_cap) \
do { \
void *data = __vec_realloc((vec).data, new_cap * sizeof(*(vec).data)); \
if (!data) { \
LOG_FATAL("vector_push: realloc failed\n"); \
} \
(vec).cap = new_cap; \
(vec).data = data; \
} while (0)
#define vec_size(vec) ((vec).size)
#define vec_cap(vec) ((vec).cap)
#define vec_for(vec, idx) for (usize idx = 0; idx < vec_size(vec); idx += 1)
/**
* @def vec_push(vec, value)
* @brief 添加元素到向量末尾
* @param vec 目标向量结构体
* @param value 要添加的值(需匹配存储类型)
*
* @note 当容量不足时自动扩容为2倍(初始容量为4)
* @warning 内存分配失败时会触发LOG_FATAL
*/
#define vec_push(vec, value) \
do { \
if ((vec).size >= (vec).cap) { \
usize cap = (vec).cap ? (vec).cap * 2 : 4; \
vec_realloc(vec, cap); \
} \
Assert((vec).data != nullptr); \
(vec).data[(vec).size++] = value; \
} while (0)
/**
* @def vec_pop(vec)
* @brief 弹出最后一个元素
* @param vec 目标向量结构体
* @return 最后元素的引用
* @warning 需确保size > 0时使用
*/
#define vec_pop(vec) ((vec).data[--(vec).size])
/**
* @def vec_at(vec, idx)
* @brief 获取指定索引元素
* @param vec 目标向量结构体
* @param idx 元素索引(0 <= idx < size)
* @return 对应元素的引用
*/
#define vec_at(vec, idx) (((vec).data)[idx])
/**
* @def vec_idx(vec, ptr)
* @brief 获取元素指针对应的索引
* @param vec 目标向量结构体
* @param ptr 元素指针(需在data数组范围内)
* @return 元素索引值
*/
#define vec_idx(vec, ptr) ((ptr) - (vec).data)
/**
* @def vec_free(vec)
* @brief 释放向量内存
* @param vec 目标向量结构体
*
* @note 释放后需重新初始化才能再次使用
*/
#define vec_free(vec) \
do { \
if ((vec).data == nullptr) \
break; \
__vec_free((vec).data); \
(vec).data = nullptr; \
(vec).size = (vec).cap = 0; \
} while (0)
#define vec_unsafe_get_data(vec) ((vec).data)
#define vec_unsafe_from_buffer(vec, buffer, buffer_size) \
do { \
(vec).size = buffer_size; \
(vec).cap = (vec).size; \
(vec).data = buffer; \
} while (0)
#define vec_unsafe_from_static_array(vec, array) \
do { \
(vec).size = sizeof(array) / sizeof((array)[0]); \
(vec).cap = (vec).size; \
(vec).data = array; \
} while (0)
/**
* @def vec_sized_realloc(vec, elem_size, new_cap)
* @brief 内部宏:按 elem_size 重新分配内存
*/
#define vec_sized_realloc(vec, elem_size, new_cap) \
do { \
void *new_data = __vec_realloc((vec).data, (new_cap) * (elem_size)); \
if (!new_data) \
LOG_FATAL("vec_sized_realloc: failed\n"); \
(vec).data = new_data; \
(vec).cap = new_cap; \
} while (0)
/**
* @def vec_sized_push(vec, elem_size, src_ptr)
* @brief 添加一个元素(从 src_ptr 拷贝 elem_size 字节)
* @param vec VEC(type) 定义的向量变量(type 可为 char 或 void)
* @param elem_size 每个元素占用的字节数
* @param src_ptr 源数据的指针
* @param copy_size 要拷贝的字节数
*
* @note 使用前需确保 vec.data 类型与 src_ptr 无关,内部会按字节拷贝。
* 推荐声明时为 `VEC(char)` 或 `VEC(unsigned char)`。
*/
#define vec_sized_push(vec, elem_size, src_ptr, copy_size) \
do { \
if ((vec).size >= (vec).cap) { \
usize new_cap = (vec).cap ? (vec).cap * 2 : 4; \
vec_sized_realloc(vec, elem_size, new_cap); \
} \
char *slot = (char *)(vec).data + (vec).size * (elem_size); \
__vec_memcpy(slot, (src_ptr), (copy_size)); \
(vec).size++; \
} while (0)
/**
* @def vec_sized_at_ptr(vec, elem_size, idx)
* @brief 获取第 idx 个元素的指针(void*)
* @return 指向元素的指针,需转换为具体类型使用
*/
#define vec_sized_at_ptr(vec, elem_size, idx) ((void *)((char *)(vec).data + (idx) * (elem_size)))
/**
* @def vec_sized_foreach(vec, elem_size, elem_ptr_var, block)
* @brief 遍历所有元素
* @param elem_ptr_var 循环内的变量名(void* 类型)
* @param block 循环体语句块
*/
#define vec_sized_foreach(vec, elem_size, elem_ptr_var, block) \
do { \
for (usize __i = 0; __i < (vec).size; ++__i) { \
void *elem_ptr_var = vec_sized_at_ptr(vec, elem_size, __i); \
block; \
} \
} while (0)
/**
* @def vec_sized_pop(vec, elem_size)
* @brief 弹出最后一个元素(仅减小 size,不返回数据)
*/
#define vec_sized_pop(vec, elem_size) \
do { \
if ((vec).size == 0) \
LOG_FATAL("vec_sized_pop: empty\n"); \
(vec).size--; \
} while (0)
/**
* @def vec_sized_clear(vec)
* @brief 清空向量(重置 size = 0,不释放内存)
*/
#define vec_sized_clear(vec) ((vec).size = 0)
/**
* @def vec_sized_free(vec)
* @brief 释放向量内存(与原始 vec_free 相同,可复用)
* @note 注意:如果元素内部有堆资源,需在释放前自行遍历调用析构函数。
*/
#define vec_sized_free(vec) vec_free(vec)
#endif /* __CORE_VEC_H__ */
+88
View File
@@ -0,0 +1,88 @@
#include "log.h"
static inline int log_snprintf(char *s, size_t n, const char *format, ...) {
int ret;
va_list args;
va_start(args, format);
ret = log_vsnprintf(s, n, format, args);
va_end(args);
return ret;
}
int log_default_handler(logger_t *module, log_level_t level, const char *file, int line,
const char *func, const char *fmt, ...) {
const char *level_str;
int offset = 0;
va_list args;
va_start(args, fmt);
/* clang-format off */
switch (level) {
case LOG_LEVEL_DEBUG: level_str = "DEBUG"; break;
case LOG_LEVEL_INFO: level_str = "INFO "; break;
case LOG_LEVEL_WARN: level_str = "WARN "; break;
case LOG_LEVEL_ERROR: level_str = "ERROR"; break;
case LOG_LEVEL_FATAL: level_str = "FATAL"; break;
case LOG_LEVEL_TRACE: level_str = "TRACE"; break;
default: level_str = "NOTSET"; break;
}
/// @note: 定义 __LOG_NO_COLOR__ 会取消颜色输出
#ifndef __LOG_NO_COLOR__
const char *color_code;
switch (level) {
case LOG_LEVEL_DEBUG: color_code = ANSI_FG_CYAN; break;
case LOG_LEVEL_INFO: color_code = ANSI_FG_GREEN; break;
case LOG_LEVEL_TRACE: color_code = ANSI_FG_BLUE; break;
case LOG_LEVEL_WARN: color_code = ANSI_FG_YELLOW; break;
case LOG_LEVEL_ERROR: color_code = ANSI_FG_RED; break;
case LOG_LEVEL_FATAL: color_code = ANSI_FG_RED ANSI_UNDERLINED; break;
default: color_code = ANSI_NONE;
}
/* clang-format on */
offset = log_snprintf(module->buf, sizeof(module->buf),
ANSI_BOLD "%s[%s] %s - %s:%d in %s()" ANSI_NONE " ", color_code,
level_str, module->name, file, line, func);
#else
offset = log_snprintf(module->buf, sizeof(module->buf), "[%s] %s - %s:%d in %s() ", level_str,
module->name, file, line, func);
#endif
/* 然后写入用户消息(如果有) */
if (fmt && fmt[0]) {
log_vsnprintf(module->buf + offset, sizeof(module->buf) - offset, fmt, args);
}
va_end(args);
log_puts(module->buf);
// for clangd warning
// clang-analyzer-deadcode.DeadStores
(void)color_code;
(void)level_str;
if (level & LOG_LEVEL_FATAL) {
log_abort();
}
return 0;
}
logger_t __default_logger_root = {
.name = "root",
.level = LOG_LEVEL_ALL,
.handler = log_default_handler,
};
void init_logger(logger_t *logger, const char *name) {
logger->name = name;
logger->handler = log_default_handler;
log_set_level(logger, LOG_LEVEL_ALL);
}
void log_set_level(logger_t *logger, int level) {
if (logger)
logger->level = level;
else
__default_logger_root.level = level;
}
void log_set_handler(logger_t *logger, log_handler handler) {
if (logger)
logger->handler = handler;
else
__default_logger_root.handler = handler;
}
+193
View File
@@ -0,0 +1,193 @@
/**
* @file log.h
* @brief 日志系统核心模块(支持多级日志、断言和异常处理)
*/
#ifndef __SCC_LOG_IMPL_H__
#define __SCC_LOG_IMPL_H__
#include "color.h"
#include <stdarg.h>
#ifdef __SCC_LOG_IMPL_USE_STD_IMPL__
#include <stdio.h>
#include <stdlib.h>
#define log_vsnprintf vsnprintf
#define log_puts puts
#define log_abort() exit(1)
#endif
#ifdef __GNUC__ // GCC, Clang
#define __scc_log_unreachable() (__builtin_unreachable())
#elif defined _MSC_VER // MSVC
#define __scc_log_unreachable() (__assume(false))
#elif defined __SCC_BUILTIN_UNREACHEABLE__ // The SCC Compiler (my compiler)
#define __scc_log_unreachable() (__scc_builtin_unreachable())
#else
#define __scc_log_unreachable() ((void)0)
#endif
#ifndef log_vsnprintf
#define log_vsnprintf(...)
#warning "log_vsnprintf not defined"
#endif
#ifndef log_puts
#define log_puts(...)
#warning "log_puts not defined"
#endif
#ifndef log_abort
#define log_abort(...)
#warning "log_abort not defined"
#endif
/**
* @brief 日志级别枚举
*
* 定义日志系统的输出级别和组合标志位
*/
typedef enum log_level {
LOG_LEVEL_NOTSET = 0, ///< 未设置级别(继承默认配置)
LOG_LEVEL_DEBUG = 1 << 0, ///< 调试信息(开发阶段详细信息)
LOG_LEVEL_INFO = 1 << 1, ///< 常规信息(系统运行状态)
LOG_LEVEL_WARN = 1 << 2, ///< 警告信息(潜在问题提示)
LOG_LEVEL_ERROR = 1 << 3, ///< 错误信息(可恢复的错误)
LOG_LEVEL_FATAL = 1 << 4, ///< 致命错误(导致程序终止的严重错误)
LOG_LEVEL_TRACE = 1 << 5, ///< 追踪(性能追踪或者栈帧追踪)
LOG_LEVEL_ALL = 0xFF, ///< 全级别标志(组合所有日志级别)
} log_level_t;
#ifndef LOGGER_MAX_BUF_SIZE
#define LOGGER_MAX_BUF_SIZE 512 ///< 单条日志最大缓冲区尺寸
#endif
typedef struct logger logger_t;
typedef int (*log_handler)(logger_t *module, log_level_t level, const char *file, int line,
const char *func, const char *fmt, ...);
/**
* @brief 日志器实例结构体
*
* 每个日志器实例维护独立的配置和缓冲区
*/
struct logger {
const char *name; ///< 日志器名称(用于模块区分)
log_level_t level; ///< 当前设置的日志级别
union {
log_handler handler;
void *user_handler;
}; ///< 日志处理回调函数
void *user_data; ///< 用户自定义数据
char buf[LOGGER_MAX_BUF_SIZE]; ///< 格式化缓冲区
};
int log_default_handler(logger_t *module, log_level_t level, const char *file, int line,
const char *func, const char *fmt, ...);
extern logger_t __default_logger_root;
#ifndef LOG_DEFAULT_HANDLER
#define LOG_DEFAULT_HANDLER &__default_logger_root
#endif
/**
* @brief 初始化日志实例 其余参数设置为默认值
* @param[in] logger 日志器实例指针
* @param[in] name 日志器名称(nullptr表示获取默认日志器名称)
*/
void init_logger(logger_t *logger, const char *name);
/**
* @brief 设置日志级别
* @param[in] logger 目标日志器实例
* @param[in] level 要设置的日志级别(可组合多个级别)
*/
void log_set_level(logger_t *logger, int level);
/**
* @brief 设置自定义日志处理器
* @param[in] logger 目标日志器实例
* @param[in] handler 自定义处理函数(nullptr恢复默认处理)
*/
void log_set_handler(logger_t *logger, log_handler handler);
#ifndef LOG_MAX_MAROC_BUF_SIZE
#define LOG_MAX_MAROC_BUF_SIZE LOGGER_MAX_BUF_SIZE ///< 宏展开缓冲区尺寸
#endif
#define SCC_LOG_HANDLE_ARGS(_module_, _level_, ...) \
(_module_), (_level_), __FILE__, __LINE__, __func__, ##__VA_ARGS__
#define SCC_LOG_IMPL(_module_, _level_, _fmt_, ...) \
do { \
/* TODO check _module_ is nullptr */ \
if ((_module_)->handler && ((_module_)->level & (_level_))) \
(_module_)->handler(SCC_LOG_HANDLE_ARGS(_module_, _level_, _fmt_, ##__VA_ARGS__)); \
} while (0)
/* clang-format off */
/// @name 模块日志宏
/// @{
#define MLOG_NOTSET(module, ...)SCC_LOG_IMPL(module, LOG_LEVEL_NOTSET, __VA_ARGS__) ///< 未分类日志
#define MLOG_DEBUG(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_DEBUG, __VA_ARGS__) ///< 调试日志(需启用DEBUG级别)
#define MLOG_INFO(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_INFO, __VA_ARGS__) ///< 信息日志(常规运行日志)
#define MLOG_WARN(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_WARN, __VA_ARGS__) ///< 警告日志(潜在问题)
#define MLOG_ERROR(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_ERROR, __VA_ARGS__) ///< 错误日志(可恢复错误)
#define MLOG_FATAL(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_FATAL, __VA_ARGS__) ///< 致命错误日志(程序终止前)
#define MLOG_TRACE(module, ...) SCC_LOG_IMPL(module, LOG_LEVEL_TRACE, __VA_ARGS__) ///< 追踪日志(调用栈跟踪)
/// @}
/// @name 快捷日志宏
/// @{
#define LOG_NOTSET(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_NOTSET, __VA_ARGS__) ///< 未分类日志
#define LOG_DEBUG(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_DEBUG, __VA_ARGS__) ///< 调试日志(需启用DEBUG级别)
#define LOG_INFO(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_INFO, __VA_ARGS__) ///< 信息日志(常规运行日志)
#define LOG_WARN(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_WARN, __VA_ARGS__) ///< 警告日志(潜在问题)
#define LOG_ERROR(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_ERROR, __VA_ARGS__) ///< 错误日志(可恢复错误)
#define LOG_FATAL(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_FATAL, __VA_ARGS__) ///< 致命错误日志(程序终止前)
#define LOG_TRACE(...) SCC_LOG_IMPL(LOG_DEFAULT_HANDLER, LOG_LEVEL_TRACE, __VA_ARGS__) ///< 追踪日志(调用栈跟踪)
/// @}
/* clang-format on */
/**
* @def _Assert
* @brief 断言检查内部宏
* @param cond 检查条件表达式
* @param ... 错误信息参数(格式字符串+参数)
*/
#define _Assert(cond, ...) \
((void)((cond) || (__default_logger_root.handler(SCC_LOG_HANDLE_ARGS( \
&__default_logger_root, LOG_LEVEL_FATAL, __VA_ARGS__)), \
log_abort(), __scc_log_unreachable(), 0)))
/// @name 断言工具宏
/// @{
#define __INNERSCC_LOG_IMPL_STR(str) #str
#define _SCC_LOG_IMPL_STR(str) __INNERSCC_LOG_IMPL_STR(str)
#define AssertFmt(cond, format, ...) \
_Assert(cond, "Assertion Failure: " format, ##__VA_ARGS__) ///< 带格式的断言检查
#define PanicFmt(format, ...) _Assert(0, "Panic: " format, ##__VA_ARGS__) ///< 立即触发致命错误
#define Assert(cond) AssertFmt(cond, "cond is `" _SCC_LOG_IMPL_STR(cond) "`") ///< 基础断言检查
#define Panic(...) PanicFmt(__VA_ARGS__) ///< 触发致命错误(带自定义消息)
#define TODO() PanicFmt("TODO please implement me") ///< 标记未实现代码(触发致命错误)
#define UNREACHABLE() PanicFmt("UNREACHABLE") ///< 触发致命错误(代码不可达)
#define FIXME(str) PanicFmt("FIXME " _SCC_LOG_IMPL_STR(str)) ///< 提醒开发者修改代码(触发致命错误)
/// @}
/**
* @brief 静态断言(编译时)
*
* 利用数组大小不能为负的特性
* 或使用 _Static_assert (C11)
*/
#if __STDC_VERSION__ >= 201112L
#define StaticAssert _Static_assert
#else
#define StaticAssert(cond, msg) extern char __static_assertion[(cond) ? 1 : -1]
#endif
#ifdef __SCC_LOG_IMPL_IMPORT_SRC__
#include "log.c"
#endif
#endif /* __SCC_LOG_IMPL_H__ */
+10
View File
@@ -0,0 +1,10 @@
#ifndef __UTILS_H__
#define __UTILS_H__
#define __SCC_LOG_IMPL_USE_STD_IMPL__
#include "log.h"
#include "core_map.h"
#include "core_vec.h"
#endif /* __UTILS_H__ */
+699
View File
@@ -0,0 +1,699 @@
/* spl_cli.c SIR VM launcher + gdb-style interactive debugger
*
* Usage: spl_cli [options] <file.sir> [args...]
* -d, --debug stack-canary checks
* -g, --debug-cli interactive debugger (REPL)
* --entry <name> entry function (default: main)
* --trace print every instruction
* -h, --help show help
*
* spl 程序 argv:argv[0]=file.sir,argv[1..]=args。
* REPL 配合 splc0 -g(.sir 尾部内嵌 debug 段:IR 行 + VAR 行)可显示
* 当前 IR 节点/源行/局部变量。
*/
#include "spl_mcode.h"
#include "spl_syscall.h"
#include "spl_vm.h"
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ================================================================
* 命令行解析
* ================================================================ */
typedef struct {
int debug;
int debug_cli;
int trace;
int disasm;
const char *entry;
const char *path; /* file.sir */
const char **args; /* spl 程序参数(file.sir 之后) */
int nargs;
} cli_opts_t;
static void usage(void) {
fprintf(stderr, "Usage: spl_cli [options] <file.sir> [args...]\n"
" -d, --debug stack-canary checks\n"
" -g, --debug-cli interactive debugger (REPL)\n"
" --disasm disasm dump sir\n"
" --entry <name> entry function (default: main)\n"
" --trace print every instruction\n"
" -h, --help show help\n");
}
/* options 可穿插;`--` 终止 option 解析(本身不作为 file/args)。
* 第一个非 option 为 file.sir,其后为 spl args。 */
static int parse_args(int argc, const char **argv, cli_opts_t *o) {
memset(o, 0, sizeof *o);
o->entry = "main";
int i = 1;
for (; i < argc; i++) {
const char *a = argv[i];
if (a[0] == '-' && a[1]) {
if (strcmp(a, "--") == 0) {
i++;
break;
}
if (strcmp(a, "-d") == 0 || strcmp(a, "--debug") == 0) {
o->debug = 1;
} else if (strcmp(a, "-g") == 0 || strcmp(a, "--debug-cli") == 0) {
o->debug_cli = 1;
} else if (strcmp(a, "--trace") == 0) {
o->trace = 1;
} else if (strcmp(a, "--disasm") == 0) {
o->disasm = 1;
} else if (strcmp(a, "--entry") == 0) {
if (i + 1 >= argc) {
fprintf(stderr, "spl_cli: --entry needs a name\n");
return -1;
}
o->entry = argv[++i];
} else if (strcmp(a, "-h") == 0 || strcmp(a, "--help") == 0) {
usage();
return -1;
} else {
fprintf(stderr, "spl_cli: unknown option '%s'\n", a);
usage();
return -1;
}
} else {
break;
}
}
/* 跳过前导 `--`(pipeline 调用会带 `--` 分隔 file 与 args) */
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
if (i >= argc) {
fprintf(stderr, "spl_cli: missing <file.sir>\n");
usage();
return -1;
}
o->path = argv[i++];
while (i < argc && strcmp(argv[i], "--") == 0)
i++;
o->args = argv + i;
o->nargs = argc - i;
return 0;
}
/* ================================================================
* Debug map(splc0 -g 追加在 .sir 尾部的文本段)
* IR <ip> <node_ref> <line> <kind>
* VAR <func> <name> <fp_offset> <tid> <is_param>
* ================================================================ */
typedef struct {
usize ip;
usize ref;
int line;
char kind[64];
} dbg_irline_t;
typedef VEC(dbg_irline_t) dbg_irline_vec_t;
typedef struct {
char func[128];
char name[128];
usize offset;
usize tid;
int is_param;
} dbg_var_t;
typedef VEC(dbg_var_t) dbg_var_vec_t;
typedef struct {
dbg_irline_vec_t irlines;
dbg_var_vec_t vars;
int loaded;
} dbg_map_t;
static void dbg_map_load(dbg_map_t *m, const char *text) {
memset(m, 0, sizeof *m);
vec_init(m->irlines);
vec_init(m->vars);
m->loaded = 0;
if (!text)
return;
const char *p = strstr(text, "SPLDBG");
if (!p)
return;
p += 6;
while (p && *p) {
const char *nl = strchr(p, '\n');
size_t len = nl ? (size_t)(nl - p) : strlen(p);
char line[512];
if (len >= sizeof line)
len = sizeof line - 1;
memcpy(line, p, len);
line[len] = 0;
if (strncmp(line, "IR ", 3) == 0) {
dbg_irline_t ir;
memset(&ir, 0, sizeof ir);
sscanf(line + 3, "%zu %zu %d %63s", &ir.ip, &ir.ref, &ir.line, ir.kind);
vec_push(m->irlines, ir);
} else if (strncmp(line, "VAR ", 4) == 0) {
dbg_var_t v;
memset(&v, 0, sizeof v);
sscanf(line + 4, "%127s %127s %zu %zu %d", v.func, v.name, &v.offset, &v.tid,
&v.is_param);
vec_push(m->vars, v);
}
if (!nl)
break;
p = nl + 1;
}
m->loaded = 1;
}
/* 当前 ip 所属 IR 节点行(ip 恰好是某节点首指令) */
static const dbg_irline_t *irline_at_exact(dbg_map_t *m, usize ip) {
for (usize i = 0; i < m->irlines.size; i++)
if (m->irlines.data[i].ip == ip)
return &m->irlines.data[i];
return NULL;
}
/* ================================================================
* 调试器核心
* ================================================================ */
typedef struct {
spl_vm_t *vm;
spl_prog_t *prog;
const char *entry;
dbg_map_t map;
usize last_ptr; /* p 最近读到的值(x 无参重读) */
int quit;
} dbg_t;
/* ---- 位置/指令显示辅助 ---- */
static const char *fn_name_at(spl_prog_t *prog, usize ip) {
for (usize i = 0; i < vec_size(prog->funcs); i++) {
spl_vm_func_t *f = &vec_at(prog->funcs, i);
if (ip >= f->address && ip < f->address + f->ninsns)
return f->name ? f->name : "?";
}
return "?";
}
/* ip 所在函数的指令范围 [*start, *end) */
static void cur_func_bounds(spl_prog_t *prog, usize ip, usize *start, usize *end) {
*start = 0;
*end = vec_size(prog->insns);
for (usize i = 0; i < vec_size(prog->funcs); i++) {
spl_vm_func_t *f = &vec_at(prog->funcs, i);
if (ip >= f->address && ip < f->address + f->ninsns) {
*start = f->address;
*end = f->address + f->ninsns;
return;
}
}
}
/* 格式化一条指令(不含行号前缀) */
static void fmt_insn(const spl_vm_ins_t *ins, char *buf, size_t n) {
snprintf(buf, n, "%-11s %-5s %zu", spl_vm_opcode_name(ins->opcode),
spl_vm_type_kind_name(ins->type), ins->imm);
}
static void dbg_show_location(dbg_t *d) {
spl_vm_t *vm = d->vm;
if (vm->ip >= vec_size(vm->prog->insns)) {
printf(" (end of program)\n");
return;
}
char ib[80];
fmt_insn(&vec_at(vm->prog->insns, vm->ip), ib, sizeof ib);
printf(" %s @ ip=%zu %s [sp=%zu fp=%zu cp=%zu]\n", fn_name_at(vm->prog, vm->ip), vm->ip,
ib, vm->sp, vm->fp, vm->cp);
const dbg_irline_t *ir = irline_at_exact(&d->map, vm->ip);
if (ir)
printf(" -> ir node#%zu line %d %s\n", ir->ref, ir->line, ir->kind);
}
static void dbg_handle_status(dbg_t *d, int r) {
if (r == 1) {
printf(" program halted, exit_code=%d\n", d->vm->exit_code);
d->quit = 1;
} else if (r == 2) {
printf(" breakpoint hit\n");
} else if (r == -1) {
printf(" VM error: %s\n", d->vm->error_msg[0] ? d->vm->error_msg : "(no detail)");
d->quit = 1;
}
}
/* ---- 变量查找(p / x 复用) ---- */
static dbg_var_t *dbg_find_var(dbg_t *d, const char *fn, const char *name) {
for (usize i = 0; i < d->map.vars.size; i++) {
dbg_var_t *v = &d->map.vars.data[i];
if (strcmp(v->func, fn) == 0 && strcmp(v->name, name) == 0)
return v;
}
return NULL;
}
/* ================================================================
* 命令
* ================================================================ */
static int cmd_help(dbg_t *d, const char *args);
static int cmd_run(dbg_t *d, const char *args);
static int cmd_step(dbg_t *d, const char *args);
static int cmd_next(dbg_t *d, const char *args);
static int cmd_finish(dbg_t *d, const char *args);
static int cmd_break(dbg_t *d, const char *args);
static int cmd_delete(dbg_t *d, const char *args);
static int cmd_info(dbg_t *d, const char *args);
static int cmd_list(dbg_t *d, const char *args);
static int cmd_backtrace(dbg_t *d, const char *args);
static int cmd_stack(dbg_t *d, const char *args);
static int cmd_x(dbg_t *d, const char *args);
static int cmd_p(dbg_t *d, const char *args);
static int cmd_quit(dbg_t *d, const char *args);
typedef struct {
const char *name;
const char *alias;
const char *usage;
const char *help;
int (*fn)(dbg_t *, const char *);
} dbg_cmd_t;
static const dbg_cmd_t cmds[] = {
/* 会话 */
{"help", "h", "[cmd]", "list commands / help", cmd_help},
{"quit", "q", "", "quit debugger", cmd_quit},
/* 执行 */
{"run", "r", "", "run to next breakpoint or exit", cmd_run},
{"continue", "c", "", "alias of run", cmd_run},
{"step", "s", "", "step one instruction (into calls)", cmd_step},
{"next", "n", "", "step over a call", cmd_next},
{"finish", "f", "", "run until current function returns", cmd_finish},
/* 断点 */
{"break", "b", "<fn|ip>", "set breakpoint (no arg: list)", cmd_break},
{"delete", "d", "", "clear all breakpoints", cmd_delete},
/* 信息 */
{"info", "i", "b|stack|locals|args|var", "breakpoints/stack/locals", cmd_info},
{"list", "l", "[N]", "disassemble ip±N of current function", cmd_list},
{"backtrace", "bt", "", "print call stack backtrace", cmd_backtrace},
{"stack", "st", "", "dump stack words", cmd_stack},
/* 内存/变量 */
{"x", "x", "<var|addr|fp+N>", "read memory (no arg: last pointer)", cmd_x},
{"print", "p", "<var>", "print local variable (needs splc0 -g)", cmd_p},
{NULL, NULL, NULL, NULL, NULL},
};
static const dbg_cmd_t *find_cmd(const char *name) {
for (const dbg_cmd_t *c = cmds; c->name; c++)
if (!strcmp(c->name, name) || (c->alias && !strcmp(c->alias, name)))
return c;
return NULL;
}
static int cmd_help(dbg_t *d, const char *args) {
(void)d;
if (*args) {
const dbg_cmd_t *c = find_cmd(args);
if (c) {
printf(" %-10s %-22s %s", c->name, c->usage, c->help);
if (c->alias)
printf(" (alias: %s)", c->alias);
printf("\n");
} else {
printf(" unknown command '%s'\n", args);
}
return 0;
}
printf("commands:\n");
for (const dbg_cmd_t *c = cmds; c->name; c++) {
printf(" %-10s %-22s %s", c->name, c->usage, c->help);
if (c->alias)
printf(" (alias: %s)", c->alias);
printf("\n");
}
return 0;
}
/* ---- 执行 ---- */
static int ip_is_breakpoint(dbg_t *d) {
for (usize i = 0; i < vec_size(d->vm->breakpoints); i++)
if (d->vm->breakpoints.data[i] == (usize)d->vm->ip)
return 1;
return 0;
}
static int cmd_run(dbg_t *d, const char *args) {
(void)args;
if (ip_is_breakpoint(d)) /* 越过当前断点指令,避免原地重停 */
spl_vm_skip_breakpoint(d->vm);
dbg_handle_status(d, spl_vm_run_until(d->vm, 0));
return 0;
}
static int cmd_step(dbg_t *d, const char *args) {
(void)args;
dbg_handle_status(d, spl_vm_run_once(d->vm));
return 0;
}
static int cmd_next(dbg_t *d, const char *args) {
(void)args;
/* 执行 1 条;若进入被调(cp 增),继续执行到返回原深度 */
usize base_cp = d->vm->cp;
int r = spl_vm_run_once(d->vm);
if (r)
return dbg_handle_status(d, r), 0;
while (d->vm->cp > base_cp) {
r = spl_vm_run_once(d->vm);
if (r)
return dbg_handle_status(d, r), 0;
}
return 0;
}
static int cmd_finish(dbg_t *d, const char *args) {
(void)args;
usize base_cp = d->vm->cp;
while (d->vm->cp >= base_cp) {
int r = spl_vm_run_once(d->vm);
if (r)
return dbg_handle_status(d, r), 0;
}
return 0;
}
/* ---- 断点 ---- */
static int is_all_digits(const char *s) {
if (!*s)
return 0;
for (; *s; s++)
if (!isdigit((unsigned char)*s))
return 0;
return 1;
}
static int cmd_break(dbg_t *d, const char *args) {
if (!*args) {
printf(" ip breakpoints:\n");
for (usize i = 0; i < vec_size(d->vm->breakpoints); i++)
printf(" %zu\n", d->vm->breakpoints.data[i]);
printf(" fn breakpoints:\n");
for (usize i = 0; i < vec_size(d->vm->fn_breakpoints); i++)
printf(" %s\n", d->vm->fn_breakpoints.data[i]);
return 0;
}
while (*args && isspace((unsigned char)*args))
args++;
if (is_all_digits(args)) {
usize ip = (usize)strtoul(args, NULL, 10);
spl_vm_add_breakpoint(d->vm, ip);
printf(" breakpoint at ip=%zu\n", ip);
} else {
spl_vm_add_breakpoint_fn(d->vm, args);
printf(" breakpoint at function '%s'\n", args);
}
return 0;
}
static int cmd_delete(dbg_t *d, const char *args) {
(void)args;
spl_vm_clear_breakpoints(d->vm);
printf(" breakpoints cleared\n");
return 0;
}
/* ---- 信息 ---- */
/* 列出当前函数变量:args_flag=1 列参数,local_flag=1 列局部 */
static void list_vars(dbg_t *d, int args_flag, int local_flag) {
if (!d->map.loaded) {
printf(" no debug info (compile with splc0 -g)\n");
return;
}
const char *fn = fn_name_at(d->prog, d->vm->ip);
int any = 0;
for (usize i = 0; i < d->map.vars.size; i++) {
dbg_var_t *v = &d->map.vars.data[i];
if (strcmp(v->func, fn) != 0)
continue;
if ((v->is_param && !args_flag) || (!v->is_param && !local_flag))
continue;
printf(" %-20s @ fp+%-5zu %s\n", v->name, v->offset, v->is_param ? "[param]" : "[local]");
any = 1;
}
if (!any)
printf(" (no matching variables in %s)\n", fn);
}
static int cmd_info(dbg_t *d, const char *args) {
while (*args && isspace((unsigned char)*args))
args++;
if (!strncmp(args, "b", 1) || !strncmp(args, "break", 5))
return cmd_break(d, "");
if (!strncmp(args, "st", 2) || !strncmp(args, "stack", 5))
spl_vm_stackdump(d->vm, d->vm->sp);
else if (!strncmp(args, "l", 1) || !strncmp(args, "local", 5))
list_vars(d, 0, 1);
else if (!strncmp(args, "a", 1) || !strncmp(args, "arg", 3))
list_vars(d, 1, 0);
else if (!strncmp(args, "v", 1) || !strncmp(args, "var", 3))
list_vars(d, 1, 1);
else
printf(" usage: info b|stack|locals|args|var\n");
return 0;
}
/* l [N]:当前函数内 ip±N 反汇编 */
static int cmd_list(dbg_t *d, const char *args) {
usize ip = d->vm->ip;
long half = 5;
if (*args)
half = strtol(args, NULL, 10);
if (half < 0)
half = 0;
usize fstart, fend;
cur_func_bounds(d->prog, ip, &fstart, &fend);
usize lo = (ip > (usize)half) ? ip - (usize)half : fstart;
usize hi = ip + (usize)half;
if (hi >= fend)
hi = fend - 1;
if (lo < fstart)
lo = fstart;
for (usize i = lo; i <= hi; i++) {
char ib[80];
fmt_insn(&vec_at(d->prog->insns, i), ib, sizeof ib);
printf("%s%6zu: %s", i == ip ? "=>" : " ", i, ib);
const dbg_irline_t *ir = irline_at_exact(&d->map, i);
if (ir)
printf(" || node#%zu line %d %s", ir->ref, ir->line, ir->kind);
printf("\n");
}
return 0;
}
static int cmd_backtrace(dbg_t *d, const char *args) {
(void)args;
spl_vm_backtrace(d->vm, d->vm->fp);
return 0;
}
static int cmd_stack(dbg_t *d, const char *args) {
(void)args;
spl_vm_stackdump(d->vm, d->vm->sp);
return 0;
}
/* ---- 内存 / 变量 ---- */
static int cmd_x(dbg_t *d, const char *args) {
while (*args && isspace((unsigned char)*args))
args++;
unsigned long long addr = 0;
if (*args) {
if (strncmp(args, "fp+", 3) == 0 || strncmp(args, "sp+", 3) == 0) {
int is_fp = args[0] == 'f';
unsigned long long off = strtoull(args + 3, NULL, 0);
addr = (uintptr_t)((char *)&d->vm->stacks.data[is_fp ? d->vm->fp : d->vm->sp] + off);
printf(" (%s+%llu)\n", is_fp ? "fp" : "sp", off);
} else if (d->map.loaded && !isdigit((unsigned char)*args)) {
const char *fn = fn_name_at(d->prog, d->vm->ip);
dbg_var_t *v = dbg_find_var(d, fn, args);
if (v) {
addr = (uintptr_t)((char *)&d->vm->stacks.data[d->vm->fp] + v->offset);
printf(" (%s @ fp+%zu)\n", v->name, v->offset);
} else {
printf(" no variable '%s' in %s\n", args, fn);
}
} else {
addr = strtoull(args, NULL, 0);
}
} else {
addr = (unsigned long long)d->last_ptr;
}
if (!addr) {
printf(" usage: x <var|addr|fp+N> (no arg: re-read last printed pointer)\n");
return 0;
}
unsigned char *sbase = (unsigned char *)d->vm->stacks.data;
usize slen = d->vm->config.max_stack_depth * sizeof(spl_vm_val_t);
printf(" addr=%#llx stack=[%p,+%zu) in=%d\n", addr, sbase, slen,
addr >= (uintptr_t)sbase && addr < (uintptr_t)(sbase + slen));
unsigned char *p = (unsigned char *)(uintptr_t)addr;
printf(" ");
for (int i = 0; i < 32; i++)
printf("%02x ", p[i]);
printf("\n");
return 0;
}
static int cmd_p(dbg_t *d, const char *args) {
while (*args && isspace((unsigned char)*args))
args++;
if (!*args) {
printf(" usage: p <varname>\n");
return 0;
}
if (!d->map.loaded) {
printf(" no debug info (compile with splc0 -g)\n");
return 0;
}
const char *fn = fn_name_at(d->prog, d->vm->ip);
dbg_var_t *v = dbg_find_var(d, fn, args);
if (!v) {
printf(" no variable '%s' in %s\n", args, fn);
return 0;
}
spl_vm_val_t *addr = (spl_vm_val_t *)((char *)&d->vm->stacks.data[d->vm->fp] + v->offset);
printf(" %s = %zu (0x%zx) @ fp+%zu\n", v->name, *addr, *addr, v->offset);
d->last_ptr = (usize)*addr; /* 供 x 无参重读 */
return 0;
}
static int cmd_quit(dbg_t *d, const char *args) {
(void)args;
d->quit = 1;
return 0;
}
static void repl_loop(dbg_t *d) {
char line[1024];
while (!d->quit) {
dbg_show_location(d);
printf("spl-dbg> ");
fflush(stdout);
if (!fgets(line, sizeof line, stdin))
break;
char *nl = strchr(line, '\n');
if (nl)
*nl = 0;
char *p = line;
while (*p && isspace((unsigned char)*p))
p++;
if (!*p)
continue;
/* 拆命令名 + 参数 */
char *sp = p;
while (*sp && !isspace((unsigned char)*sp))
sp++;
char saved = *sp;
*sp = 0;
const dbg_cmd_t *c = find_cmd(p);
*sp = saved;
char *args = sp;
while (*args && isspace((unsigned char)*args))
args++;
if (c) {
c->fn(d, args);
} else {
printf(" unknown command '%s' (h for help)\n", p);
}
}
}
int main(int argc, const char **argv) {
cli_opts_t o;
if (parse_args(argc, argv, &o) != 0)
return 1;
spl_prog_t prog;
if (spl_prog_load_from_file(o.path, &prog) != 0) {
fprintf(stderr, "spl_cli: cannot load '%s'\n", o.path);
return 1;
}
if (o.disasm) {
spl_prog_dump(&prog);
return 0;
}
spl_syscall_register(&prog);
spl_vm_t vm;
spl_vm_init(&vm);
if (o.debug) {
fprintf(stderr, "spl_cli: debug mode on\n");
spl_vm_set_debug(&vm, 1);
}
if (o.trace) {
fprintf(stderr, "spl_cli: trace mode on\n");
spl_vm_set_trace(&vm, 1);
}
if (spl_vm_load_prog(&vm, &prog) != 0) {
fprintf(stderr, "spl_cli: failed to load prog\n");
spl_vm_drop(&vm);
spl_prog_drop(&prog);
return 1;
}
/* spl 程序 argv:argv[0]=file.sir(程序名),argv[1..]=args */
const char **spl_argv = (const char **)malloc(sizeof(char *) * (size_t)(o.nargs + 1));
if (!spl_argv) {
spl_vm_drop(&vm);
spl_prog_drop(&prog);
return 1;
}
spl_argv[0] = o.path;
for (int i = 0; i < o.nargs; i++)
spl_argv[i + 1] = o.args[i];
if (spl_vm_prepare(&vm, o.entry, o.nargs + 1, spl_argv, NULL) != 0) {
fprintf(stderr, "spl_cli: entry point '%s' not found\n", o.entry);
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
return 1;
}
int ret = 0;
if (o.debug_cli) {
dbg_t d;
d.vm = &vm;
d.prog = &prog;
d.entry = o.entry;
d.quit = 0;
d.last_ptr = 0;
dbg_map_load(&d.map, prog.debug);
repl_loop(&d);
vec_free(d.map.irlines);
vec_free(d.map.vars);
} else {
ret = spl_vm_run_until(&vm, 0);
if (ret == 2)
fprintf(stderr, "spl_cli: hit breakpoint (run with -g to debug)\n");
}
free(spl_argv);
spl_vm_drop(&vm);
spl_prog_drop(&prog);
if (ret < 0)
return 1;
return (int)vm.exit_code;
}
+532
View File
@@ -0,0 +1,532 @@
/* spl_mcode.c - SPL VM machine code binary serialization, deserialization, and utilities
*
* Binary format (all metadata fields are spl_val_t = uint64_t LE):
* [HEADER] magic(8) nfuncs(8) ninsns(8) nnatives(8) nstrs(8) ndata(8)
* [FUNCS] each: name_len(8) name(padded to 8) idx_of_strtab(8)
* nargs(8) ninsns(8) address(8)
* [INSTRS] each: opcode(2) type(2) imm(8) = 12 bytes
* [NATIVES] each: name_len(8) name(padded to 8) idx_of_strtab(8)
* [STRTAB] each: slen(8) str(slen bytes, padded to 8)
*/
#include "spl_mcode.h"
void spl_prog_init(spl_prog_t *prog) {
if (!prog)
return;
vec_init(prog->insns);
vec_init(prog->funcs);
vec_init(prog->natives);
vec_init(prog->strtab);
vec_init(prog->gdata);
vec_push(prog->gdata, (spl_vm_gdata_t){0});
map_init(prog->symtab, MAP_HASH_STR, MAP_CMP_STR);
prog->debug = NULL;
}
void spl_prog_drop(spl_prog_t *prog) {
if (!prog)
return;
vec_free(prog->insns);
/* free each func name */
vec_for(prog->funcs, i) { free(vec_at(prog->funcs, i).name); }
vec_free(prog->funcs);
/* free each native name */
vec_for(prog->natives, i) { free(vec_at(prog->natives, i).name); }
vec_free(prog->natives);
/* free each gdata entry */
vec_for(prog->gdata, i) { free(vec_at(prog->gdata, i).data); }
vec_free(prog->gdata);
/* free each strtab entry */
vec_for(prog->strtab, i) { free((void *)vec_at(prog->strtab, i)); }
vec_free(prog->strtab);
map_free(prog->symtab);
if (prog->debug) {
free(prog->debug);
}
prog->debug = NULL;
}
void spl_prog_dump(spl_prog_t *prog) {
printf(";; SPL bytecode dump: \n");
printf(";; ninsns=%zu nfuncs=%zu nnatives=%zu nstrs=%zu\n\n", vec_size(prog->insns),
vec_size(prog->funcs), vec_size(prog->natives), vec_size(prog->strtab));
if (vec_size(prog->funcs) > 0) {
printf(";; --- functions ---\n");
for (usize i = 0; i < vec_size(prog->funcs); i++) {
spl_vm_func_t *f = &vec_at(prog->funcs, i);
printf(" %s nargs=%zu ninsns=%zu addr=%zu\n", f->name ? f->name : "(anon)", f->nargs,
f->ninsns, f->address);
}
printf("\n");
}
if (vec_size(prog->natives) > 0) {
printf(";; --- natives ---\n");
for (int i = 0; i < (int)vec_size(prog->natives); i++) {
spl_vm_native_t *n = &vec_at(prog->natives, i);
printf(" %s\n", n->name ? n->name : "(anon)");
}
printf("\n");
}
if (vec_size(prog->strtab) > 0) {
printf(";; --- string table ---\n");
for (int i = 0; i < (int)vec_size(prog->strtab); i++) {
printf(" %d: \"%s\"\n", i, vec_at(prog->strtab, i));
}
printf("\n");
}
printf(";; --- instructions ---\n");
for (usize i = 0; i < vec_size(prog->insns); i++) {
spl_vm_ins_t *ins = &vec_at(prog->insns, i);
printf("%4zd: %s", i, spl_vm_opcode_name((spl_vm_opcode_t)ins->opcode));
if (ins->type != SPL_VOID)
printf(" %s", spl_vm_type_kind_name((spl_vm_kind_t)ins->type));
printf(" %zd", ins->imm);
/* annotate jumps / calls */
if (ins->opcode == SPL_JMP || ins->opcode == SPL_BZ || ins->opcode == SPL_BNZ) {
spl_vm_val_t target = i + 1 + ins->imm;
printf(" ; -> %zu", target);
} else if (ins->opcode == SPL_CALL) {
printf(" ; nargs=%zu, from stack", ins->imm);
} else if (ins->opcode == SPL_CALLI) {
printf(" ; indirect call");
} else if (ins->opcode == SPL_GADDR) {
printf(" ; gdata[%zu]", ins->imm);
}
printf("\n");
}
}
/* ---- LE read/write helpers ---- */
static inline spl_vm_val_t rd64(const unsigned char **p) {
spl_vm_val_t v = (spl_vm_val_t)(*p)[0] | ((spl_vm_val_t)(*p)[1] << 8) |
((spl_vm_val_t)(*p)[2] << 16) | ((spl_vm_val_t)(*p)[3] << 24) |
((spl_vm_val_t)(*p)[4] << 32) | ((spl_vm_val_t)(*p)[5] << 40) |
((spl_vm_val_t)(*p)[6] << 48) | ((spl_vm_val_t)(*p)[7] << 56);
*p += 8;
return v;
}
static inline void wr64(unsigned char **p, spl_vm_val_t v) {
*(*p)++ = (unsigned char)(v);
*(*p)++ = (unsigned char)(v >> 8);
*(*p)++ = (unsigned char)(v >> 16);
*(*p)++ = (unsigned char)(v >> 24);
*(*p)++ = (unsigned char)(v >> 32);
*(*p)++ = (unsigned char)(v >> 40);
*(*p)++ = (unsigned char)(v >> 48);
*(*p)++ = (unsigned char)(v >> 56);
}
/* Round n up to next multiple of 8 */
#define ALIGN8(n) (((n) + 7) & ~7)
int spl_prog_load_from_file(const char *fname, spl_prog_t *prog) {
FILE *f;
unsigned char *data;
long len;
const unsigned char *p;
spl_vm_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
if (!fname || !prog)
return -1;
f = fopen(fname, "rb");
if (!f)
return -1;
fseek(f, 0, SEEK_END);
len = ftell(f);
fseek(f, 0, SEEK_SET);
if (len < 48) {
fclose(f);
return -1;
}
data = (unsigned char *)malloc((size_t)len);
if (!data) {
fclose(f);
return -1;
}
if (fread(data, 1, (size_t)len, f) != (size_t)len) {
free(data);
fclose(f);
return -1;
}
fclose(f);
p = data;
/* magic */
if (p[0] != 'S' || p[1] != 'P' || p[2] != 'L' || p[3] != 'B' || p[4] != 'I' || p[5] != 'N' ||
p[6] != '\0' || p[7] != '\0') {
free(data);
return -1;
}
p += 8;
spl_prog_init(prog);
/* header counts */
nfuncs = rd64(&p);
ninsns = rd64(&p);
nnatives = rd64(&p);
nstrs = rd64(&p);
ndata = rd64(&p);
/* ---- function table ---- */
for (spl_vm_val_t i = 0; i < nfuncs; i++) {
spl_vm_func_t func = {0};
spl_vm_val_t nlen = rd64(&p);
usize pad = ALIGN8((usize)nlen) - (usize)nlen;
func.name = (char *)malloc((usize)nlen);
if (!func.name) {
free(data);
return -1;
}
memcpy(func.name, p, (usize)nlen);
p += (usize)nlen + pad;
func.idx_of_strtab = rd64(&p);
func.nargs = rd64(&p);
func.ninsns = rd64(&p);
func.address = rd64(&p);
vec_push(prog->funcs, func);
}
/* ---- instructions ---- */
for (spl_vm_val_t i = 0; i < ninsns; i++) {
if ((size_t)(p - data) + 12 > (size_t)len) {
free(data);
return -1;
}
spl_vm_ins_t ins;
ins.opcode = (uint16_t)p[0] | ((uint16_t)p[1] << 8);
ins.type = (uint16_t)p[2] | ((uint16_t)p[3] << 8);
p += 4;
ins.imm = rd64(&p);
vec_push(prog->insns, ins);
}
/* ---- native table ---- */
for (spl_vm_val_t i = 0; i < nnatives; i++) {
spl_vm_native_t nat = {0};
spl_vm_val_t nlen = rd64(&p);
usize pad = ALIGN8((usize)nlen) - (usize)nlen;
nat.name = (char *)malloc((usize)nlen);
if (!nat.name) {
free(data);
return -1;
}
memcpy(nat.name, p, (usize)nlen);
p += (usize)nlen + pad;
nat.idx_of_strtab = rd64(&p);
nat.impl_fn = NULL; /* function pointer can't be serialised */
vec_push(prog->natives, nat);
}
/* ---- string table ---- */
for (spl_vm_val_t i = 0; i < nstrs; i++) {
spl_vm_val_t slen = rd64(&p);
usize pad = ALIGN8((usize)slen) - (usize)slen;
char *s = (char *)malloc((usize)slen + 1);
if (!s) {
free(data);
return -1;
}
memcpy(s, p, (usize)slen);
s[(usize)slen] = '\0';
p += (usize)slen + pad;
vec_push(prog->strtab, s);
}
/* ---- global data ---- */
for (spl_vm_val_t i = 0; i < ndata; i++) {
spl_vm_gdata_t entry;
entry.size = rd64(&p);
usize pad = ALIGN8(entry.size) - entry.size;
entry.data = (unsigned char *)malloc(entry.size);
if (!entry.data) {
free(data);
return -1;
}
memcpy(entry.data, p, entry.size);
p += entry.size + pad;
vec_push(prog->gdata, entry);
}
/* ---- debug 段(splc0 -g 追加在文件尾部) ---- */
prog->debug = NULL;
prog->debug_size = 0;
{
ptrdiff_t used = p - data;
if (used >= 0 && (usize)used < (usize)len) {
size_t dlen = (size_t)len - (size_t)used;
char *dbg = (char *)malloc(dlen + 1);
if (dbg) {
memcpy(dbg, data + used, dlen);
dbg[dlen] = 0;
prog->debug = dbg;
prog->debug_size = dlen;
}
}
}
free(data);
return 0;
}
int spl_prog_store_to_file(const char *fname, spl_prog_t *prog) {
unsigned char *buf, *p;
spl_vm_val_t i;
size_t total;
spl_vm_val_t nfuncs, ninsns, nnatives, nstrs, ndata;
usize nlen, pad;
if (!fname || !prog)
return -1;
nfuncs = vec_size(prog->funcs);
ninsns = vec_size(prog->insns);
nnatives = vec_size(prog->natives);
nstrs = vec_size(prog->strtab);
ndata = vec_size(prog->gdata) - 1; /* jump 0 node */
/* Calculate total size */
total = 8 /* magic */
+ 8 + 8 + 8 + 8 + 8; /* 5 counts (nfuncs+ninsns+nnatives+nstrs+ndata) */
/* funcs */
for (i = 0; i < nfuncs; i++) {
nlen = strlen(vec_at(prog->funcs, i).name) + 1; /* include null */
total +=
8 + ALIGN8(nlen) + 8 + 8 + 8 + 8; /* nlen + name(pad) + idx + nargs + ninsns + addr */
}
/* insns */
total += ninsns * 12; /* opcode(2) + type(2) + imm(8) */
/* natives */
for (i = 0; i < nnatives; i++) {
nlen = strlen(vec_at(prog->natives, i).name) + 1;
total += 8 + ALIGN8(nlen) + 8; /* nlen + name(pad) + idx_of_strtab */
}
/* strtab */
for (i = 0; i < nstrs; i++) {
nlen = strlen(vec_at(prog->strtab, i));
total += 8 + ALIGN8(nlen); /* slen + str(pad) */
}
/* gdata */
for (i = 1; i < vec_size(prog->gdata); i++) {
usize dsize = vec_at(prog->gdata, i).size;
total += 8 + ALIGN8(dsize); /* dsize + data(pad) */
}
buf = (unsigned char *)malloc(total);
if (!buf)
return -1;
p = buf;
/* magic */
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
/* counts */
wr64(&p, nfuncs);
wr64(&p, ninsns);
wr64(&p, nnatives);
wr64(&p, nstrs);
wr64(&p, ndata);
/* ---- function table ---- */
for (i = 0; i < nfuncs; i++) {
const char *name = vec_at(prog->funcs, i).name;
nlen = strlen(name) + 1;
pad = ALIGN8(nlen) - nlen;
wr64(&p, nlen);
memcpy(p, name, nlen);
p += nlen;
memset(p, 0, pad);
p += pad;
wr64(&p, vec_at(prog->funcs, i).idx_of_strtab);
wr64(&p, vec_at(prog->funcs, i).nargs);
wr64(&p, vec_at(prog->funcs, i).ninsns);
wr64(&p, vec_at(prog->funcs, i).address);
}
/* ---- instructions ---- */
for (i = 0; i < ninsns; i++) {
spl_vm_ins_t *ins = &vec_at(prog->insns, i);
*p++ = (unsigned char)(ins->opcode);
*p++ = (unsigned char)(ins->opcode >> 8);
*p++ = (unsigned char)(ins->type);
*p++ = (unsigned char)(ins->type >> 8);
wr64(&p, ins->imm);
}
/* ---- native table ---- */
for (i = 0; i < nnatives; i++) {
const char *name = vec_at(prog->natives, i).name;
nlen = strlen(name) + 1;
pad = ALIGN8(nlen) - nlen;
wr64(&p, nlen);
memcpy(p, name, nlen);
p += nlen;
memset(p, 0, pad);
p += pad;
wr64(&p, vec_at(prog->natives, i).idx_of_strtab);
}
/* ---- string table ---- */
for (i = 0; i < nstrs; i++) {
const char *s = vec_at(prog->strtab, i);
nlen = strlen(s);
pad = ALIGN8(nlen) - nlen;
wr64(&p, nlen);
memcpy(p, s, nlen);
p += nlen;
memset(p, 0, pad);
p += pad;
}
/* ---- global data ---- */
for (i = 1; i <= ndata; i++) {
spl_vm_gdata_t *entry = &vec_at(prog->gdata, i);
pad = ALIGN8(entry->size) - entry->size;
wr64(&p, entry->size);
memcpy(p, entry->data, entry->size);
p += entry->size;
memset(p, 0, pad);
p += pad;
}
/* Write file */
FILE *f = fopen(fname, "wb");
if (!f) {
free(buf);
return -1;
}
fwrite(buf, 1, total, f);
fclose(f);
free(buf);
return 0;
}
int spl_prog_add_instr(spl_prog_t *prog, uint8_t opcode, uint8_t type, spl_vm_val_t imm) {
if (!prog)
return 0;
spl_vm_ins_t ins = (spl_vm_ins_t){.opcode = opcode, .type = type, .imm = imm};
vec_push(prog->insns, ins);
return vec_size(prog->insns);
}
int spl_prog_add_func(spl_prog_t *prog, spl_vm_func_t *func) {
if (!prog || !func)
return 0;
vec_push(prog->funcs, *func);
return vec_size(prog->funcs);
}
int spl_prog_add_native(spl_prog_t *prog, spl_vm_native_t *native) {
if (!prog || !native)
return 0;
vec_push(prog->natives, *native);
return vec_size(prog->natives);
}
int spl_prog_add_data(spl_prog_t *prog, void *ptr, usize size) {
spl_vm_gdata_t entry;
if (!prog)
return 0;
entry.data = (unsigned char *)malloc(size);
if (!entry.data)
return 0;
memcpy(entry.data, ptr, size);
entry.size = size;
vec_push(prog->gdata, entry);
return (int)(vec_size(prog->gdata) - 1);
}
spl_vm_func_t *spl_prog_get_func(spl_prog_t *prog, const char *name) {
if (!prog || !name)
return NULL;
vec_for(prog->funcs, i) {
const char *match_name = vec_at(prog->funcs, i).name;
if (match_name && strcmp(match_name, name) == 0) {
return &vec_at(prog->funcs, i);
}
}
return NULL;
}
spl_vm_native_t *spl_prog_get_native(spl_prog_t *prog, const char *name) {
if (!prog || !name)
return NULL;
vec_for(prog->natives, i) {
const char *match_name = vec_at(prog->natives, i).name;
if (match_name && strcmp(match_name, name) == 0) {
return &vec_at(prog->natives, i);
}
}
return NULL;
}
const char *opcode_name[] = {
#define X(opcode, name, argc, pop, push, desc) [opcode] = name,
SPL_OPCODES(X)
#undef X
};
const char *spl_vm_opcode_name(spl_vm_opcode_t opcode) { return opcode_name[opcode]; }
const char *spl_vm_type_kind_name(spl_vm_kind_t type) {
switch (type) {
case SPL_VOID:
return "void";
case SPL_BOOL:
return "bool";
case SPL_I8:
return "i8";
case SPL_U8:
return "u8";
case SPL_I16:
return "i16";
case SPL_U16:
return "u16";
case SPL_I32:
return "i32";
case SPL_U32:
return "u32";
case SPL_I64:
return "i64";
case SPL_U64:
return "u64";
case SPL_F32:
return "f32";
case SPL_F64:
return "f64";
case SPL_USIZE:
return "usize";
case SPL_ISIZE:
return "isize";
case SPL_PTR:
return "ptr";
default:
return "???";
}
}
void spl_vm_ins_dump(spl_vm_ins_t *ins, spl_vm_val_t addr) {
printf("%4zu: %s", addr, spl_vm_opcode_name((spl_vm_opcode_t)ins->opcode));
if (ins->type != SPL_VOID)
printf(" %s", spl_vm_type_kind_name((spl_vm_kind_t)ins->type));
printf(" %zd:%zx", ins->imm, ins->imm);
printf("\n");
}
+211
View File
@@ -0,0 +1,211 @@
/* spl_mcode.h - SPL VM Machine Code: instruction set and binary format
*/
#ifndef __SPL_MCODE_H__
#define __SPL_MCODE_H__
#include "include/core_map.h"
#include "include/core_vec.h"
#include <stddef.h>
#include <stdint.h>
typedef uintptr_t usize;
typedef intptr_t isize;
typedef enum {
SPL_VOID,
SPL_BOOL,
SPL_I8,
SPL_U8,
SPL_I16,
SPL_U16,
SPL_I32,
SPL_U32,
SPL_I64,
SPL_U64,
SPL_ISIZE,
SPL_USIZE,
SPL_F32,
SPL_F64,
SPL_PTR,
SPL_TYPE_COUNT,
} spl_vm_kind_t;
/* clang-format off */
#define SPL_OPCODES(X) \
/* opcode, name, argc, pop, push, desc */ \
X(SPL_ERROR, "error", 0, 0, 0, "invalid opcode / internal error") \
/* 栈操作 */ \
X(SPL_PUSH, "push", 1, 0, 1, "push immediate") \
X(SPL_DUP, "dup", 0, 0, 1, "duplicate top of stack") \
X(SPL_DROP, "drop", 0, 1, 0, "discard top of stack") \
X(SPL_SWAP, "swap", 0, 2, 2, "swap top two elements") \
X(SPL_PICK, "pick", 1, 0, 1, "push copy of stack[imm] (0=TOS)") \
X(SPL_ROT, "rot", 0, 3, 3, "rotate top three (a b c -- b c a)") \
/* 算术 */ \
X(SPL_ADD, "add", 0, 2, 1, "integer addition") \
X(SPL_SUB, "sub", 0, 2, 1, "integer subtraction") \
X(SPL_MUL, "mul", 0, 2, 1, "integer multiplication") \
X(SPL_DIV_S, "div_s", 0, 2, 1, "signed division") \
X(SPL_DIV_U, "div_u", 0, 2, 1, "unsigned division") \
X(SPL_REM_S, "rem_s", 0, 2, 1, "signed remainder") \
X(SPL_REM_U, "rem_u", 0, 2, 1, "unsigned remainder") \
X(SPL_NEG, "neg", 0, 1, 1, "two's complement negation") \
/* 位运算 */ \
X(SPL_AND, "and", 0, 2, 1, "bitwise AND") \
X(SPL_OR, "or", 0, 2, 1, "bitwise OR") \
X(SPL_XOR, "xor", 0, 2, 1, "bitwise XOR") \
X(SPL_NOT, "not", 0, 1, 1, "bitwise NOT") \
X(SPL_SHL, "shl", 0, 2, 1, "left shift") \
X(SPL_SHR_U, "shr_u", 0, 2, 1, "logical right shift (zero-fill)") \
X(SPL_SHR_S, "shr_s", 0, 2, 1, "arithmetic right shift (sign-fill)") \
/* 比较 */ \
X(SPL_EQ, "eq", 0, 2, 1, "equal") \
X(SPL_NE, "ne", 0, 2, 1, "not equal") \
X(SPL_SLT, "slt", 0, 2, 1, "signed less than") \
X(SPL_SLE, "sle", 0, 2, 1, "signed less or equal") \
X(SPL_ULT, "ult", 0, 2, 1, "unsigned less than") \
X(SPL_ULE, "ule", 0, 2, 1, "unsigned less or equal") \
X(SPL_SGT, "sgt", 0, 2, 1, "signed greater than") \
X(SPL_SGE, "sge", 0, 2, 1, "signed greater or equal") \
X(SPL_UGT, "ugt", 0, 2, 1, "unsigned greater than") \
X(SPL_UGE, "uge", 0, 2, 1, "unsigned greater or equal") \
/* 类型转换 */ \
X(SPL_TRUNC, "trunc", 1, 1, 1, "truncate to low imm bits") \
X(SPL_SEXT, "sext", 1, 1, 1, "sign-extend from bit imm") \
X(SPL_ZEXT, "zext", 1, 1, 1, "zero-extend from bit imm") \
/* 控制流 */ \
X(SPL_JMP, "jmp", 1, 0, 0, "unconditional jump (offset isize)") \
X(SPL_BZ, "bz", 1, 1, 0, "pop; jump if zero (offset isize)") \
X(SPL_BNZ, "bnz", 1, 1, 0, "pop; jump if non-zero (offset isize)") \
X(SPL_HALT, "halt", 0, 0, 0, "stop execution") \
/* 函数调用 */ \
X(SPL_CALL, "call", 1, 0, 0, "call function pop function offset, call it") \
X(SPL_CALLI, "calli", 0, 1, 0, "indirect call: pop function address, call it") \
X(SPL_RET, "ret", 0, 0, 0, "return from function") \
/* 栈帧局部变量 */ \
X(SPL_ALLOC, "alloc", 1, 0, 0, "allocate imm zero-slots on stack") \
X(SPL_LADDR, "laddr", 1, 0, 1, "push address of local at fp + imm bytes") \
X(SPL_GADDR, "gaddr", 1, 0, 1, "push address of global at gp + imm") \
/* 间接内存访问 */ \
X(SPL_LOAD, "load", 0, 1, 1, "load sizeof(type)-bits zero-extended") \
X(SPL_STORE, "store", 0, 2, 0, "store low sizeof(type)-bits") \
/* 原生接口 */ \
X(SPL_NCALL, "ncall", 1, 0, 1, "call native function by index") \
X(SPL_NLIB, "nlib", 1, 0, 0, "dlopen library (name idx)") \
/* 调试 */ \
X(SPL_BK, "breakpoint", 0, 0, 0, "break point when exec will stop run") \
X(SPL_DBG, "dbg", 0, 0, 0, "print VM debug info (stack, backtrace, locals)")
/* clang-format on */
typedef enum {
#define X(opcode, name, argc, pop, push, desc) opcode,
SPL_OPCODES(X)
#undef X
} spl_vm_opcode_t;
/*
* Binary format (all metadata fields spl_val_t LE):
* magic[8] = "SPLBIN\0\0"
* nfuncs, ninsns, nnatives, nstrs, ndata
* [func table] each: name_len, name(pad8), idx_of_strtab, nargs, ninsns, address
* [insns] each: opcode(2) type(2) imm(8) = 12 bytes
* [natives] each: name_len, name(pad8), idx_of_strtab
* [strtab] each: slen, str(pad8)
* [gdata] each: dsize(8), data(dsize bytes, padded to 8)
*
* === Aggregate Return ABI (sret) ===
*
* 凡返回值类型为聚合(struct / union / enum / array / shape),
* 采用调用者分配 / 被调用者填充的间接返回约定:
*
* Before CALL:
* - caller 在自己的帧里 alloca 一块 RetTy 大小的空间
* - 该空间的地址作为第 0 个实参先压栈
* - 其余实参照常从左到右压栈
* - target 地址最后压栈
* - CALL imm = 普通实参个数 + 1
*
* Callee 进入后:
* - fp+0 存放 sret 指针
* - 形参 i 位于 fp + 8*(i+1)
* - 返回值直接写入 *(fp+0),然后执行 RET void
*
* Caller 侧:
* - 调用完成后,CALL 结果槽保存 sret 指针;
* 后续对聚合值的所有读取都通过该指针进行
*/
#define SPL_BINFMT_MAGIC "SPLBIN\0\0"
// All SIR stack values are ptr-bit unsigned integers
typedef usize spl_vm_val_t;
typedef struct spl_vm_ins {
uint8_t opcode;
uint8_t type;
spl_vm_val_t imm;
} spl_vm_ins_t;
typedef VEC(spl_vm_ins_t) spl_vm_ins_vec_t;
typedef struct spl_vm_func {
char *name;
spl_vm_val_t idx_of_strtab;
spl_vm_val_t nargs;
spl_vm_val_t ninsns;
spl_vm_val_t address;
} spl_vm_func_t;
typedef VEC(spl_vm_func_t) spl_vm_func_vec_t;
/* Native function pointer type */
struct spl_vm;
typedef struct spl_vm spl_vm_t;
typedef spl_vm_val_t (*spl_vm_fn_t)(spl_vm_t *vm, int nargs, spl_vm_val_t *args);
typedef struct spl_vm_native {
char *name;
spl_vm_val_t idx_of_strtab;
spl_vm_fn_t impl_fn;
} spl_vm_native_t;
typedef VEC(spl_vm_native_t) spl_vm_native_vec_t;
typedef struct {
unsigned char *data;
usize size;
} spl_vm_gdata_t;
typedef VEC(spl_vm_gdata_t) spl_vm_data_t;
typedef VEC(const char *) spl_vm_strtab_t;
typedef MAP(const char *, const char *) spl_vm_symtab_t;
/* Opaque handle for loaded program */
typedef struct spl_prog {
spl_vm_ins_vec_t insns;
spl_vm_func_vec_t funcs;
spl_vm_native_vec_t natives;
spl_vm_data_t gdata;
spl_vm_strtab_t strtab;
spl_vm_symtab_t symtab;
char *debug; /* 文件尾部 debug 段(splc0 -g 追加的文本),无则 NULL */
usize debug_size;
} spl_prog_t;
void spl_prog_init(spl_prog_t *prog);
void spl_prog_drop(spl_prog_t *prog);
void spl_prog_dump(spl_prog_t *prog);
int spl_prog_load_from_file(const char *fname, spl_prog_t *prog);
int spl_prog_store_to_file(const char *fname, spl_prog_t *prog);
int spl_prog_add_instr(spl_prog_t *prog, uint8_t opcode, uint8_t type, spl_vm_val_t imm);
int spl_prog_add_data(spl_prog_t *prog, void *ptr, usize size);
int spl_prog_add_func(spl_prog_t *prog, spl_vm_func_t *func);
int spl_prog_add_native(spl_prog_t *prog, spl_vm_native_t *native);
spl_vm_func_t *spl_prog_get_func(spl_prog_t *prog, const char *name);
spl_vm_native_t *spl_prog_get_native(spl_prog_t *prog, const char *name);
/* Opcode name lookup for debugging/dumping */
const char *spl_vm_opcode_name(spl_vm_opcode_t opcode);
const char *spl_vm_type_kind_name(spl_vm_kind_t type);
void spl_vm_ins_dump(spl_vm_ins_t *ins, spl_vm_val_t addr);
#endif /* __SPL_MCODE_H__ */
+505
View File
@@ -0,0 +1,505 @@
/* spl_syscall.c - built-in syscall implementations + registration
*
* All syscalls validate nargs, cast spl_val_t args to the expected C types,
* execute, and return the result as spl_val_t.
*
* Simple syscalls use the SYSCALL_N macros; complex ones are written
* manually but follow the same template.
*/
#include "spl_syscall.h"
#include "include/core_map.h"
#include "include/core_vec.h"
#include "spl_mcode.h"
#include "spl_vm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* =================================================================
* Macro templates
*
* Each SYSCALL_N macro:
* 1. Validates nargs (prints error and returns -1 on mismatch)
* 2. Casts args[n] from spl_val_t to the specified C type via
* (type)(uintptr_t) - this handles both integer and pointer types
* 3. Evaluates the expression and returns the result as spl_val_t
* ================================================================= */
#define CHECK_NARGS(fname, expected) \
do { \
if (nargs != (expected)) { \
fprintf(stderr, fname ": expected " #expected " args, got %d\n", nargs); \
return -1; \
} \
} while (0)
#define SYSCALL_0(name, ret_expr) \
static spl_vm_val_t name(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) { \
(void)_vm; \
CHECK_NARGS(#name, 0); \
(void)args; \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_1(name, t1, ret_expr) \
static spl_vm_val_t name(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) { \
(void)_vm; \
CHECK_NARGS(#name, 1); \
t1 a1 = (t1)(uintptr_t)args[0]; \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_2(name, t1, t2, ret_expr) \
static spl_vm_val_t name(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) { \
(void)_vm; \
CHECK_NARGS(#name, 2); \
t1 a1 = (t1)(uintptr_t)args[0]; \
t2 a2 = (t2)(uintptr_t)args[1]; \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_3(name, t1, t2, t3, ret_expr) \
static spl_vm_val_t name(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) { \
(void)_vm; \
CHECK_NARGS(#name, 3); \
t1 a1 = (t1)(uintptr_t)args[0]; \
t2 a2 = (t2)(uintptr_t)args[1]; \
t3 a3 = (t3)(uintptr_t)args[2]; \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
#define SYSCALL_4(name, t1, t2, t3, t4, ret_expr) \
static spl_vm_val_t name(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) { \
(void)_vm; \
CHECK_NARGS(#name, 4); \
t1 a1 = (t1)(uintptr_t)args[0]; \
t2 a2 = (t2)(uintptr_t)args[1]; \
t3 a3 = (t3)(uintptr_t)args[2]; \
t4 a4 = (t4)(uintptr_t)args[3]; \
return (spl_vm_val_t)(uintptr_t)(ret_expr); \
}
/* syscall / VM 内部统一地址检查宏。
* 失败时打印 ctx + 地址 + size + ip,置 native_error,return 0。
* 要求所在函数有可用的 _vm 变量。 */
#define ADDRCHECK(vm, ptr, size, ctx) \
do { \
uintptr_t _acp = (uintptr_t)(ptr); \
usize _acs = (usize)(size); \
if (!spl_vm_addr_valid(_acp, _acs)) { \
fprintf(stderr, "%s: invalid address %p size=%zu (ip=%zu fp=%zu sp=%zu)\n", (ctx), \
(void *)_acp, _acs, (vm)->ip, (vm)->fp, (vm)->sp); \
spl_vm_backtrace((vm), (vm)->fp); \
(vm)->exit_code = 2; \
return 0; \
} \
} while (0)
/* syscall 内部:把当前栈和调用栈打印出来,供出错时定位 */
#define SYSCALL_DUMP(vm) \
do { \
fprintf(stderr, " --- syscall dump (sp=%zu fp=%zu cp=%zu ip=%zu) ---\n", (vm)->sp, \
(vm)->fp, (vm)->cp, (vm)->ip); \
spl_vm_backtrace((vm), (vm)->fp); \
spl_vm_stackdump((vm), (vm)->sp); \
} while (0)
/* syscall 内部:报告致命错误,dump 后让 VM 停在当前 ip */
#define SYSCALL_FAIL(vm, ...) \
do { \
fprintf(stderr, "syscall error: "); \
fprintf(stderr, __VA_ARGS__); \
fprintf(stderr, "\n"); \
SYSCALL_DUMP(vm); \
(vm)->exit_code = 1; \
return 0; \
} while (0)
/* =================================================================
* OS syscalls
* ================================================================= */
/* vm_exit - terminate process with the given exit code */
SYSCALL_1(vm_exit, int, (exit(a1), (spl_vm_val_t)0))
/* vm_putchar - write a single character to stdout */
SYSCALL_1(vm_putchar, int, putchar(a1))
/* vm_getchar - read a single character from stdin */
SYSCALL_0(vm_getchar, getchar())
/* vm_putint - print an integer to stdout */
SYSCALL_1(vm_putint, int, (fprintf(stdout, "%d", a1), (spl_vm_val_t)0))
/* vm_putstr - print a string to stdout (no trailing newline) */
SYSCALL_1(vm_putstr, const char *, (fputs(a1, stdout), (spl_vm_val_t)0))
/* vm_fopen - open a file, returns FILE* as spl_val_t */
SYSCALL_2(vm_fopen, const char *, const char *, (uintptr_t)fopen(a1, a2))
/* vm_fclose - close a file, returns 0 on success */
SYSCALL_1(vm_fclose, FILE *, fclose(a1))
/* vm_fread - read from file, returns number of items read */
SYSCALL_4(vm_fread, void *, size_t, size_t, FILE *, fread(a1, a2, a3, a4))
/* vm_fwrite - write to file, returns number of items written */
SYSCALL_4(vm_fwrite, const void *, size_t, size_t, FILE *, fwrite(a1, a2, a3, a4))
/* vm_fsize - get file size in bytes */
static spl_vm_val_t vm_fsize(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_fsize", 1);
FILE *f = (FILE *)(uintptr_t)args[0];
long cur = ftell(f);
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, cur, SEEK_SET);
return (spl_vm_val_t)(uintptr_t)sz;
}
SYSCALL_0(vm_stdin, stdin)
SYSCALL_0(vm_stdout, stdout)
SYSCALL_0(vm_stderr, stderr)
/* vm_read_file - read entire file into a malloc'd, null-terminated buffer */
static spl_vm_val_t vm_read_file(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_read_file", 1);
const char *path = (const char *)(uintptr_t)args[0];
if (path == nullptr) {
fprintf(stderr, "filepath can't be null");
return 0;
}
FILE *f = fopen(path, "rb");
if (!f) {
fprintf(stderr, "filepath %s can't be open", path);
return 1;
}
fseek(f, 0, SEEK_END);
long sz = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = (char *)malloc((size_t)sz + 1);
if (!buf) {
fclose(f);
return 0;
}
size_t nread = fread(buf, 1, (size_t)sz, f);
fclose(f);
buf[nread] = '\0';
return (spl_vm_val_t)(uintptr_t)buf;
}
static spl_vm_val_t vm_alloc(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_alloc", 1);
size_t sz = (size_t)args[0];
if (sz == 0)
SYSCALL_FAIL(_vm, "vm_alloc: zero size");
if (sz > (size_t)1 << 32)
SYSCALL_FAIL(_vm, "vm_alloc: size too large (%zu)", sz);
void *p = malloc(sz);
if (!p)
SYSCALL_FAIL(_vm, "vm_alloc: malloc(%zu) failed", sz);
return (spl_vm_val_t)(uintptr_t)p;
}
static spl_vm_val_t vm_free(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_free", 1);
void *p = (void *)(uintptr_t)args[0];
if (p)
free(p);
return 0;
}
static spl_vm_val_t vm_realloc(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_realloc", 2);
void *p = (void *)(uintptr_t)args[0];
size_t sz = (size_t)args[1];
if (!p)
SYSCALL_FAIL(_vm, "vm_realloc: NULL ptr");
if (sz == 0)
SYSCALL_FAIL(_vm, "vm_realloc: zero size");
ADDRCHECK(_vm, p, 1, "vm_realloc");
void *np = realloc(p, sz);
if (!np)
SYSCALL_FAIL(_vm, "vm_realloc: realloc(%p, %zu) failed", p, sz);
return (spl_vm_val_t)(uintptr_t)np;
}
static spl_vm_val_t vm_memcpy(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_memcpy", 3);
void *dst = (void *)(uintptr_t)args[0];
const void *src = (const void *)(uintptr_t)args[1];
size_t size = (size_t)args[2];
if (size == 0)
return (spl_vm_val_t)(uintptr_t)dst;
ADDRCHECK(_vm, dst, size, "vm_memcpy(dst)");
ADDRCHECK(_vm, src, size, "vm_memcpy(src)");
memcpy(dst, src, size);
return (spl_vm_val_t)(uintptr_t)dst;
}
static spl_vm_val_t vm_memcmp(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
CHECK_NARGS("vm_memcmp", 3);
const void *a = (const void *)(uintptr_t)args[0];
const void *b = (const void *)(uintptr_t)args[1];
size_t size = (size_t)args[2];
if (size == 0)
return 0;
ADDRCHECK(_vm, a, size, "vm_memcmp(a)");
ADDRCHECK(_vm, b, size, "vm_memcmp(b)");
return (spl_vm_val_t)memcmp(a, b, size);
}
static spl_vm_val_t vm_printf(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
if (nargs <= 0)
return 0;
/* args[0] 是 SPL 的 []u8 format 参数。VM 里 slice 作为参数传递时,
栈上压的是"指向 slice 结构体的指针",结构为 {ptr:*u8, len:u64} */
const spl_vm_val_t *fmt_slice = (const spl_vm_val_t *)args[0];
const char *fmt = (const char *)fmt_slice[0];
usize fmt_len = (usize)fmt_slice[1];
if (nargs <= 1) {
fwrite(fmt, 1, fmt_len, stdout);
return (spl_vm_val_t)nargs;
}
typedef VEC(char) string_builder_t;
string_builder_t buffer;
vec_init(buffer);
int arg_idx = 1; /* 0 是 format */
char tmp_buf[32];
for (usize i = 0; i < fmt_len; ++i) {
if (fmt[i] != '%') {
vec_push(buffer, fmt[i]);
continue;
}
if (++i >= fmt_len)
break;
if (arg_idx >= nargs)
break;
switch (fmt[i]) {
case 'd': {
memset(tmp_buf, 0, sizeof(tmp_buf));
snprintf(tmp_buf, sizeof(tmp_buf), "%zd", (isize)args[arg_idx]);
for (usize j = 0; tmp_buf[j] != '\0'; ++j)
vec_push(buffer, tmp_buf[j]);
arg_idx++;
break;
}
case 'c':
vec_push(buffer, (char)args[arg_idx]);
arg_idx++;
break;
case 's': {
const spl_vm_val_t *s = (const spl_vm_val_t *)args[arg_idx];
const char *p = (const char *)s[0];
usize l = (usize)s[1];
for (usize j = 0; j < l; ++j)
vec_push(buffer, p[j]);
arg_idx++;
break;
}
default:
vec_push(buffer, '%');
vec_push(buffer, fmt[i]);
break;
}
}
if (vec_size(buffer) > 0)
fwrite(buffer.data, 1, vec_size(buffer), stdout);
vec_free(buffer);
return (spl_vm_val_t)nargs;
}
/* =================================================================
* VM syscalls (for comptime - compile-time code execution)
*
* These let SPL code create isolated sub-VMs, load compiled .sir
* programs into them, push arguments, call functions, and run.
* ================================================================= */
/* vm_new - create a new sub-VM instance, returns spl_vm_t* */
static spl_vm_val_t vm_new(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_new", 0);
(void)args;
spl_vm_t *vm = (spl_vm_t *)malloc(sizeof(spl_vm_t));
if (!vm)
return 0;
spl_vm_init(vm);
return (spl_vm_val_t)(uintptr_t)vm;
}
/* vm_drop - destroy a sub-VM and its loaded program */
static spl_vm_val_t vm_drop(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_drop", 1);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
if (!vm)
return 0;
if (vm->prog) {
spl_prog_drop(vm->prog);
free(vm->prog);
vm->prog = NULL;
}
spl_vm_drop(vm);
free(vm);
return 0;
}
/* vm_load - load a .sir file, register syscalls, return spl_prog_t* */
static spl_vm_val_t vm_load(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_load", 2);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
const char *path = (const char *)(uintptr_t)args[1];
if (!vm || !path)
return -1;
spl_prog_t *prog = (spl_prog_t *)malloc(sizeof(spl_prog_t));
if (!prog)
return -1;
if (spl_prog_load_from_file(path, prog) != 0) {
free(prog);
return -1;
}
spl_syscall_register(prog);
if (spl_vm_load_prog(vm, prog) != 0) {
spl_prog_drop(prog);
free(prog);
return -1;
}
return (spl_vm_val_t)(uintptr_t)prog;
}
/* vm_push - push a value onto the sub-VM's stack (for passing arguments) */
static spl_vm_val_t vm_push(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_push", 2);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
spl_vm_val_t val = args[1];
if (!vm)
return -1;
if (vm->sp >= vm->config.max_stack_depth) {
fprintf(stderr, "vm_push: stack overflow\n");
return -1;
}
vm->stacks.data[vm->sp++] = val;
return 0;
}
/* vm_call - call a function by name with pre-pushed arguments
*
* Args (3): vm, function_name, nargs
* The arguments should already be on the sub-VM's stack via vm_push.
*
* Mirrors the CALL instruction's frame setup:
* - Pushes a sentinel frame (saved_ip=-1) if cp==0 so RET halts properly
* - Pushes the actual call frame
* - Sets fp = sp - nargs (so arg0 = data[fp], arg1 = data[fp+1], ...)
* - Sets ip to the function address
*/
static spl_vm_val_t vm_call(spl_vm_t *_vm, int nargs, spl_vm_val_t *args) {
(void)_vm;
CHECK_NARGS("vm_call", 3);
spl_vm_t *vm = (spl_vm_t *)(uintptr_t)args[0];
const char *name = (const char *)(uintptr_t)args[1];
spl_vm_val_t call_nargs = args[2];
if (!vm || !name)
return -1;
spl_vm_func_t *func = spl_prog_get_func(vm->prog, name);
if (!func) {
fprintf(stderr, "vm_call: function '%s' not found\n", name);
return -1;
}
if (vm->cp >= vm->config.max_call_depth - 1) {
fprintf(stderr, "vm_call: call stack overflow\n");
return -1;
}
/* Sentinel frame so the entry function's RET halts cleanly */
if (vm->cp == 0) {
vm->frames.data[vm->cp].saved_fp = 0;
vm->frames.data[vm->cp].saved_ip = (uintptr_t)-1;
vm->frames.data[vm->cp].nargs = 0;
vm->cp++;
}
/* Actual call frame (same logic as the CALL instruction) */
vm->frames.data[vm->cp].saved_fp = vm->fp;
vm->frames.data[vm->cp].saved_ip = vm->ip;
vm->frames.data[vm->cp].nargs = call_nargs;
vm->cp++;
vm->fp = vm->sp - call_nargs;
vm->ip = (uintptr_t)func->address;
return 0;
}
/* vm_run - run a sub-VM to completion, returns exit_code */
SYSCALL_1(vm_run, spl_vm_t *, spl_vm_run_until(a1, 0))
/* =================================================================
* Registration
*
* Called after loading a .sir file. Matches native declarations in
* prog->natives against known syscall names and hooks up impl_fn.
* ================================================================= */
void spl_syscall_register(spl_prog_t *prog) {
static spl_vm_native_t table[] = {
/* OS operations */
{"vm_exit", 0, vm_exit},
{"vm_putchar", 0, vm_putchar},
{"vm_getchar", 0, vm_getchar},
{"vm_putint", 0, vm_putint},
{"vm_putstr", 0, vm_putstr},
{"vm_fopen", 0, vm_fopen},
{"vm_fclose", 0, vm_fclose},
{"vm_fread", 0, vm_fread},
{"vm_fwrite", 0, vm_fwrite},
{"vm_fsize", 0, vm_fsize},
{"vm_stdin", 0, vm_stdin},
{"vm_stdout", 0, vm_stdout},
{"vm_stderr", 0, vm_stderr},
{"vm_read_file", 0, vm_read_file},
{"vm_alloc", 0, vm_alloc},
{"vm_free", 0, vm_free},
{"vm_realloc", 0, vm_realloc},
{"vm_memcpy", 0, vm_memcpy},
{"vm_memcmp", 0, vm_memcmp},
{"vm_printf", 0, vm_printf},
/* VM operations (comptime) */
{"vm_new", 0, vm_new},
{"vm_drop", 0, vm_drop},
{"vm_load", 0, vm_load},
{"vm_push", 0, vm_push},
{"vm_call", 0, vm_call},
{"vm_run", 0, vm_run},
};
int n = (int)(sizeof(table) / sizeof(table[0]));
if (!prog)
return;
vec_for(prog->natives, i) {
spl_vm_native_t *nat = &vec_at(prog->natives, i);
if (!nat->name || nat->impl_fn)
continue;
for (int j = 0; j < n; j++) {
if (strcmp(nat->name, table[j].name) == 0) {
nat->impl_fn = table[j].impl_fn;
break;
}
}
}
}
+22
View File
@@ -0,0 +1,22 @@
/* spl_syscall.h - built-in syscall layer for SIR VM
*
* Provides I/O native functions (putchar, getchar, file ops, etc.)
* that compiled SPL programs can call via NCALL.
*
* spl_syscall_register() must be called AFTER spl_prog_load_from_file()
* and BEFORE spl_vm_run_until(). It matches native declarations in the
* loaded program against known syscall names and hooks up the C
* implementations.
*/
#ifndef __SPL_SYSCALL_H__
#define __SPL_SYSCALL_H__
#include "spl_mcode.h"
/* Register all known built-in syscalls into prog->natives[].
* Entries whose name matches a known syscall get their impl_fn set;
* unmatched entries remain NULL (will error at runtime if called). */
void spl_syscall_register(spl_prog_t *prog);
#endif /* __SPL_SYSCALL_H__ */
+1267
View File
File diff suppressed because it is too large. Load diff
+80
View File
@@ -0,0 +1,80 @@
/* spl_vm.h - SIR interpreter */
#ifndef __SPL_VM_H__
#define __SPL_VM_H__
#include "include/core_vec.h"
#include "spl_mcode.h"
#include <stdint.h>
#define SPL_STACK_CANARY ((spl_vm_val_t)0xDEADBEEFCAFEBABEull)
typedef struct {
uintptr_t saved_sp;
uintptr_t saved_fp;
uintptr_t saved_ip;
spl_vm_val_t nargs;
} spl_callframe_t;
typedef VEC(spl_vm_val_t) spl_stack_vec_t;
typedef VEC(spl_callframe_t) spl_frame_vec_t;
typedef struct spl_vm {
spl_stack_vec_t stacks;
spl_frame_vec_t frames;
uintptr_t gp; // global pointer
uintptr_t sp; // stack pointer
uintptr_t fp; // frame pointer
uintptr_t cp; // call pointer
uintptr_t ip; // instr pointer
int exit_code;
int trace; /* non-zero to print each instruction */
int debug; /* non-zero to enable canary checks */
int debug_addr; /* non-zero to check for low-address memory access */
int skip_bp; /* non-zero: run_once 忽略下一次断点(continue 越过当前断点指令) */
VEC(usize) breakpoints; /* ip 断点(执行到该指令前暂停,run_once 返回 2) */
VEC(char *) fn_breakpoints; /* 函数名断点(CALL/CALLI 目标函数入口暂停) */
spl_prog_t *prog;
char error_msg[1024];
struct {
uintptr_t max_stack_depth;
uintptr_t max_call_depth;
} config;
} spl_vm_t;
/* Initialize VM with default sizes (SPL_DEFAULT_STACK_SIZE /
* SPL_DEFAULT_CALL_DEPTH) */
void spl_vm_init(spl_vm_t *vm);
/* Initialize VM with custom sizes (pass 0 to use defaults) */
void spl_vm_init_ex(spl_vm_t *vm, int stack_size, int call_depth);
/* Free dynamically allocated memory in VM */
void spl_vm_drop(spl_vm_t *vm);
int spl_vm_addr_valid(uintptr_t p, usize size);
int spl_vm_load_prog(spl_vm_t *vm, spl_prog_t *prog);
int spl_vm_prepare(spl_vm_t *vm, const char *entry, int argc, const char **argv, const char **envp);
/* Enable/disable instruction-level tracing */
void spl_vm_set_trace(spl_vm_t *vm, int enabled);
/* Enable/disable debug mode (stack canary protection) */
void spl_vm_set_debug(spl_vm_t *vm, int enabled);
int spl_vm_run_once(spl_vm_t *vm);
int spl_vm_run_until(spl_vm_t *vm, size_t step);
/* 断点:ip 断点 / 函数名断点(CALL/CALLI 目标函数入口)。命中时 run_once 返回 2。 */
void spl_vm_add_breakpoint(spl_vm_t *vm, usize ip);
void spl_vm_add_breakpoint_fn(spl_vm_t *vm, const char *name);
void spl_vm_clear_breakpoints(spl_vm_t *vm);
/* 让 run_once 执行当前指令(忽略一次断点命中);continue 越过当前断点用 */
void spl_vm_skip_breakpoint(spl_vm_t *vm);
void spl_vm_dump_instr(spl_vm_t *vm, spl_vm_val_t ip);
void spl_vm_stackdump(spl_vm_t *vm, spl_vm_val_t sp);
int spl_vm_backtrace(spl_vm_t *vm, spl_vm_val_t fp);
#endif /* __SPL_VM_H__ */
+878
View File
@@ -0,0 +1,878 @@
/* test_spl_vm.c – unit tests for SPL VM using acutest.h
*
* Constructs SIR binaries, writes to temp files, loads via
* spl_prog_load_from_file, and runs via the spl_vm_t API.
*/
#include "include/acutest.h"
#include "spl_mcode.h"
#include "spl_vm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
/* ================================================================
* Binary-writing helpers (mirrors spl_mcode.c internal format)
* ================================================================ */
/* Write spl_val_t (8 LE bytes), advance pointer */
#define LE64(p, v) \
do { \
unsigned char *_p = (p); \
spl_vm_val_t _v = (spl_vm_val_t)(v); \
*_p++ = (unsigned char)(_v); \
*_p++ = (unsigned char)(_v >> 8); \
*_p++ = (unsigned char)(_v >> 16); \
*_p++ = (unsigned char)(_v >> 24); \
*_p++ = (unsigned char)(_v >> 32); \
*_p++ = (unsigned char)(_v >> 40); \
*_p++ = (unsigned char)(_v >> 48); \
*_p++ = (unsigned char)(_v >> 56); \
(p) = _p; \
} while (0)
/* Convenience: build spl_ins_t from raw fields */
static spl_vm_ins_t ins(uint16_t op, uint16_t type, spl_vm_val_t imm) {
spl_vm_ins_t x;
x.opcode = op;
x.type = type;
x.imm = imm;
return x;
}
/* Build a single-function SIR binary in malloc'd memory.
* Returns buffer that must be freed by caller. */
static unsigned char *build_binary(const char *fname, spl_vm_val_t nargs,
const spl_vm_ins_t *instns, int ninsns, size_t *out_len) {
size_t nlen = strlen(fname) + 1;
size_t npad = ((nlen + 7) / 8) * 8 - nlen;
size_t sz = 8 + 8 + 8 + 8 + 8 + 8 /* magic + 5 counts */
+ 8 + nlen + npad + 8 + 8 + 8 + 8 /* func entry */
+ (size_t)ninsns * 12; /* instructions */
unsigned char *buf = (unsigned char *)malloc(sz);
unsigned char *p = buf;
memcpy(p, "SPLBIN\0\0", 8);
p += 8; /* magic */
LE64(p, 1); /* nfuncs */
LE64(p, (spl_vm_val_t)ninsns); /* ninsns */
LE64(p, 0); /* nnatives */
LE64(p, 0); /* nstrs */
LE64(p, 0); /* ndata */
/* func entry */
LE64(p, (spl_vm_val_t)nlen); /* name_len */
memcpy(p, fname, nlen);
p += nlen;
memset(p, 0, npad);
p += npad;
LE64(p, 0); /* idx_of_strtab */
LE64(p, nargs);
LE64(p, (spl_vm_val_t)ninsns);
LE64(p, 0); /* address = 0 */
for (int i = 0; i < ninsns; i++) {
*p++ = (unsigned char)(instns[i].opcode);
*p++ = (unsigned char)(instns[i].opcode >> 8);
*p++ = (unsigned char)(instns[i].type);
*p++ = (unsigned char)(instns[i].type >> 8);
LE64(p, instns[i].imm);
}
*out_len = sz;
return buf;
}
/* ================================================================
* VM test helpers (file-based prog load)
* ================================================================ */
static const char *TMPFILE = "test_spl_vm_tmp.bin";
/* Write binary buffer to temp file */
static int write_temp(const unsigned char *bin, size_t len) {
FILE *f = fopen(TMPFILE, "wb");
if (!f)
return -1;
fwrite(bin, 1, len, f);
fclose(f);
return 0;
}
/* Run a single-function program, return exit code (or -1 on failure). */
static int run(const spl_vm_ins_t *instns, int ninsns) {
size_t len;
unsigned char *bin = build_binary("main", 0, instns, ninsns, &len);
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
if (spl_vm_load_prog(&vm, &prog) == 0) {
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1) /* halted normally */
rc = (int)vm.exit_code;
else if (ret == 0) /* still running (shouldn't happen with halt) */
rc = -2;
}
}
}
spl_vm_drop(&vm);
remove(TMPFILE);
free(bin);
return rc;
}
/* Run with native functions registered. */
static int run_with_natives(const spl_vm_ins_t *instns, int ninsns, spl_vm_native_t *natives,
int nnatives) {
size_t len;
unsigned char *bin = build_binary("main", 0, instns, ninsns, &len);
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
for (int i = 0; i < nnatives; i++)
spl_prog_add_native(&prog, &natives[i]);
if (spl_vm_load_prog(&vm, &prog) == 0) {
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
else if (ret == 0)
rc = -2;
}
}
}
spl_vm_drop(&vm);
remove(TMPFILE);
free(bin);
return rc;
}
/* ================================================================
* Native function for NCALL tests
* ================================================================ */
static spl_vm_val_t native_add_impl(int nargs, spl_vm_val_t *args) {
return (nargs >= 2) ? args[0] + args[1] : 0;
}
/* ================================================================
* Stack tests
* ================================================================ */
void test_push_imm(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 2) == 42);
}
void test_dup(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 99), ins(SPL_DUP, SPL_VOID, 0),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 198);
}
void test_drop(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
ins(SPL_DROP, SPL_VOID, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_swap(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
ins(SPL_SWAP, SPL_VOID, 0), ins(SPL_DROP, SPL_VOID, 0),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 5) == 2);
}
void test_pick(void) {
/* push 10, 20, 30, pick 1 -> copy 20, add -> 50 */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_PUSH, SPL_I32, 30), ins(SPL_PICK, SPL_VOID, 1),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 6) == 50);
}
/* ================================================================
* Arithmetic tests
* ================================================================ */
void test_add(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 2), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 5);
}
void test_sub(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_SUB, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 7);
}
void test_mul(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 6), ins(SPL_PUSH, SPL_I32, 7),
ins(SPL_MUL, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 42);
}
void test_div(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 100), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_DIV_S, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 33);
}
void test_rem(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 100), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_REM_S, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_neg(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_NEG, SPL_I32, 0),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 3) == -42);
}
void test_i64_arith(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I64, 42), ins(SPL_RET, SPL_I64, 0)};
TEST_CHECK(run(p, 2) == 42);
}
/* ================================================================
* Bitwise tests
* ================================================================ */
void test_and(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFF00), ins(SPL_PUSH, SPL_U32, 0x0FF0),
ins(SPL_AND, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0x0F00);
}
void test_or(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFF00), ins(SPL_PUSH, SPL_U32, 0x00FF),
ins(SPL_OR, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0xFFFF);
}
void test_xor(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF), ins(SPL_PUSH, SPL_U32, 0x0FF0),
ins(SPL_XOR, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0xF00F);
}
void test_not(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF0000), ins(SPL_NOT, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 3) == (unsigned int)0x0000FFFF);
}
void test_shl(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 1), ins(SPL_PUSH, SPL_U32, 10),
ins(SPL_SHL, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1024);
}
void test_shr(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 1024), ins(SPL_PUSH, SPL_U32, 10),
ins(SPL_SHR_U, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_shr_s(void) {
/* arithmetic right shift: -1024 >> 5 sign-extends */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, (spl_vm_val_t)(int32_t)-1024),
ins(SPL_PUSH, SPL_U32, 5), ins(SPL_SHR_S, SPL_I32, 0),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == -32);
}
/* ================================================================
* Comparison tests
* ================================================================ */
void test_eq(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_PUSH, SPL_I32, 42),
ins(SPL_EQ, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_neq(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 42), ins(SPL_PUSH, SPL_I32, 99),
ins(SPL_NE, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_lt(void) {
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_SLT, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_gt_signed(void) {
/* -1 > 1 should be 0 (false) for signed compare */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
ins(SPL_SGT, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 0);
}
void test_sle(void) {
/* -1 <= 1 -> true (1) for signed */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
ins(SPL_SLE, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_sge(void) {
/* -1 >= 1 -> false (0) for signed */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_I32, 1),
ins(SPL_SGE, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 4) == 0);
}
void test_ult(void) {
/* 0xFFFFFFFF < 1 -> false (0) for unsigned */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
ins(SPL_ULT, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 0);
}
void test_ule(void) {
/* 0xFFFFFFFF <= 0xFFFFFFFF -> true (1) */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF),
ins(SPL_ULE, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_ugt(void) {
/* 0xFFFFFFFF > 1 -> true (1) for unsigned */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
ins(SPL_UGT, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
void test_uge(void) {
/* 0xFFFFFFFF >= 1 -> true (1) */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFFFFFF), ins(SPL_PUSH, SPL_U32, 1),
ins(SPL_UGE, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
/* ================================================================
* Control flow tests (relative offset)
* ================================================================ */
void test_jmp(void) {
/* push 1, jmp +3 (skip next 2 insns), push 2 (skipped), push 3, add, ret -> 4 */
/* jmp at ip=1, after fetch ip=2, target ip=3 (push 3) => offset = 1 */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_JMP, SPL_VOID, 1),
ins(SPL_PUSH, SPL_I32, 2), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 6) == 4);
}
void test_bz_bnz(void) {
/* push 0, bz +2 (skip to ret with 1) -> return 1 */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0), ins(SPL_BZ, SPL_VOID, 2),
ins(SPL_PUSH, SPL_I32, 99), ins(SPL_RET, SPL_I32, 0),
ins(SPL_PUSH, SPL_I32, 1), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 6) == 1);
/* push 1, bnz +2 (skip to ret with 42) -> return 42 */
spl_vm_ins_t q[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_BNZ, SPL_VOID, 2),
ins(SPL_PUSH, SPL_I32, 99), ins(SPL_RET, SPL_I32, 0),
ins(SPL_PUSH, SPL_I32, 42), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(q, 6) == 42);
}
/* ================================================================
* Memory tests (ALLOC, LADDR, LD, ST)
* ================================================================ */
void test_alloc_laddr_st64_ld64(void) {
/* alloc 1 local, laddr + st64 42, laddr + ld64 back -> 42 */
spl_vm_ins_t p[] = {
ins(SPL_ALLOC, SPL_VOID, 1), /* 0: alloc 1 local */
ins(SPL_LADDR, SPL_VOID, 0), /* 1: addr of local[0] */
ins(SPL_PUSH, SPL_I64, 42), /* 2: value */
ins(SPL_STORE, SPL_I64, 0), /* 3: store */
ins(SPL_LADDR, SPL_VOID, 0), /* 4: addr of local[0] */
ins(SPL_LOAD, SPL_I64, 0), /* 5: load */
ins(SPL_RET, SPL_I64, 0) /* 6: ret */
};
TEST_CHECK(run(p, 7) == 42);
}
void test_alloc_zeroed(void) {
/* alloc 1 local, laddr + ld64 -> should be 0 (zero-initialized) */
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 1), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_LOAD, SPL_I64, 0), ins(SPL_RET, SPL_I64, 0)};
TEST_CHECK(run(p, 4) == 0);
}
/* ================================================================
* Indirect memory load/store tests (stack-based, no heap)
* ================================================================ */
void test_ld_st64(void) {
/* alloc 8 slots, st64 42, ld64 back -> 42 */
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 42),
ins(SPL_STORE, SPL_I64, 0), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_RET, SPL_I64, 0)};
TEST_CHECK(run(p, 7) == 42);
}
void test_ld_st32(void) {
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 0xAABBCCDD),
ins(SPL_STORE, SPL_U32, 0), ins(SPL_LOAD, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 7) == (int)0xAABBCCDD);
}
void test_ld_st16(void) {
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 0xBEEF),
ins(SPL_STORE, SPL_U16, 0), ins(SPL_LOAD, SPL_U16, 0),
ins(SPL_RET, SPL_U16, 0)};
TEST_CHECK(run(p, 7) == 0xBEEF);
}
void test_ld_st8(void) {
spl_vm_ins_t p[] = {ins(SPL_ALLOC, SPL_VOID, 8), ins(SPL_LADDR, SPL_VOID, 0),
ins(SPL_DUP, SPL_VOID, 0), ins(SPL_PUSH, SPL_I64, 0xAB),
ins(SPL_STORE, SPL_U8, 0), ins(SPL_LOAD, SPL_U8, 0),
ins(SPL_RET, SPL_U8, 0)};
TEST_CHECK(run(p, 7) == 0xAB);
}
/* ================================================================
* Function call tests (relative offset CALL)
* ================================================================ */
void test_call_add(void) {
/*
* add(a, b) address 0, 6 insns, 2 args
* main() address 6, 5 insns, 0 args
*
* add (ip=0):
* laddr 0 ip=0 arg0 addr
* ld64 ip=1 load arg0
* laddr 1 ip=2 arg1 addr
* ld64 ip=3 load arg1
* add i64 ip=4
* ret i64 ip=5
*
* main (ip=6):
* push 10 ip=6
* push 20 ip=7
* push 0 ip=8 target address = add at 0
* call 2 ip=9 nargs=2
* ret i64 ip=10
*/
spl_vm_ins_t add_insns[] = {ins(SPL_LADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_LADDR, SPL_VOID, 8), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_ADD, SPL_I64, 0), ins(SPL_RET, SPL_I64, 0)};
spl_vm_ins_t main_insns[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_PUSH, SPL_VOID, 0), ins(SPL_CALL, SPL_VOID, 2),
ins(SPL_RET, SPL_I64, 0)};
int nadd = (int)(sizeof(add_insns) / sizeof(add_insns[0]));
int nmain = (int)(sizeof(main_insns) / sizeof(main_insns[0]));
int ninsns_t = nadd + nmain;
size_t nlen0 = strlen("add") + 1;
size_t npad0 = ((nlen0 + 7) / 8) * 8 - nlen0;
size_t nlen1 = strlen("main") + 1;
size_t npad1 = ((nlen1 + 7) / 8) * 8 - nlen1;
size_t sz = 8 + 8 + 8 + 8 + 8 + 8 /* magic + 5 counts */
+ 8 + nlen0 + npad0 + 8 + 8 + 8 + 8 /* func 0 */
+ 8 + nlen1 + npad1 + 8 + 8 + 8 + 8 /* func 1 */
+ (size_t)ninsns_t * 12;
unsigned char *bin = (unsigned char *)malloc(sz);
unsigned char *p = bin;
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
LE64(p, 2);
LE64(p, (spl_vm_val_t)ninsns_t);
LE64(p, 0);
LE64(p, 0);
LE64(p, 0);
/* func[0]: "add" */
LE64(p, (spl_vm_val_t)nlen0);
memcpy(p, "add", nlen0);
p += nlen0;
memset(p, 0, npad0);
p += npad0;
LE64(p, 0);
LE64(p, 2);
LE64(p, (spl_vm_val_t)nadd);
LE64(p, 0);
/* func[1]: "main" */
LE64(p, (spl_vm_val_t)nlen1);
memcpy(p, "main", nlen1);
p += nlen1;
memset(p, 0, npad1);
p += npad1;
LE64(p, 0);
LE64(p, 0);
LE64(p, (spl_vm_val_t)nmain);
LE64(p, (spl_vm_val_t)nadd); /* address */
for (int i = 0; i < nadd; i++) {
*p++ = (unsigned char)(add_insns[i].opcode);
*p++ = (unsigned char)(add_insns[i].opcode >> 8);
*p++ = (unsigned char)(add_insns[i].type);
*p++ = (unsigned char)(add_insns[i].type >> 8);
LE64(p, add_insns[i].imm);
}
for (int i = 0; i < nmain; i++) {
*p++ = (unsigned char)(main_insns[i].opcode);
*p++ = (unsigned char)(main_insns[i].opcode >> 8);
*p++ = (unsigned char)(main_insns[i].type);
*p++ = (unsigned char)(main_insns[i].type >> 8);
LE64(p, main_insns[i].imm);
}
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, sz) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == 30);
}
/* ================================================================
* CALLI test
* ================================================================ */
void test_calli(void) {
/*
* add (ip=0, 2 args):
* laddr 0 ip=0
* ld64 ip=1
* laddr 1 ip=2
* ld64 ip=3
* add i64 ip=4
* ret i64 ip=5
*
* main (ip=6, 0 args):
* push 10 ip=6
* push 20 ip=7
* push 2 ip=8 (nargs)
* push 0 ip=9 (address of add)
* calli ip=10
* ret i64 ip=11
*/
spl_vm_ins_t add_insns[] = {ins(SPL_LADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_LADDR, SPL_VOID, 8), ins(SPL_LOAD, SPL_I64, 0),
ins(SPL_ADD, SPL_I64, 0), ins(SPL_RET, SPL_I64, 0)};
spl_vm_ins_t main_insns[] = {ins(SPL_PUSH, SPL_I32, 10), ins(SPL_PUSH, SPL_I32, 20),
ins(SPL_PUSH, SPL_VOID, 2), ins(SPL_PUSH, SPL_VOID, 0),
ins(SPL_CALLI, SPL_VOID, 0), ins(SPL_RET, SPL_I64, 0)};
int ninsns_t = 6 + 6;
size_t nlen0 = strlen("add") + 1;
size_t npad0 = ((nlen0 + 7) / 8) * 8 - nlen0;
size_t nlen1 = strlen("main") + 1;
size_t npad1 = ((nlen1 + 7) / 8) * 8 - nlen1;
size_t sz = 8 + 8 + 8 + 8 + 8 + 8 + 8 + nlen0 + npad0 + 8 + 8 + 8 + 8 + 8 + nlen1 + npad1 + 8 +
8 + 8 + 8 + (size_t)ninsns_t * 12;
unsigned char *bin = (unsigned char *)malloc(sz);
unsigned char *p = bin;
memcpy(p, "SPLBIN\0\0", 8);
p += 8;
LE64(p, 2);
LE64(p, (spl_vm_val_t)ninsns_t);
LE64(p, 0);
LE64(p, 0);
LE64(p, 0);
/* func[0]: add */
LE64(p, (spl_vm_val_t)nlen0);
memcpy(p, "add", nlen0);
p += nlen0;
memset(p, 0, npad0);
p += npad0;
LE64(p, 0);
LE64(p, 2);
LE64(p, 6);
LE64(p, 0);
/* func[1]: main */
LE64(p, (spl_vm_val_t)nlen1);
memcpy(p, "main", nlen1);
p += nlen1;
memset(p, 0, npad1);
p += npad1;
LE64(p, 0);
LE64(p, 0);
LE64(p, 6);
LE64(p, 6);
for (int i = 0; i < 6; i++) {
*p++ = (unsigned char)(add_insns[i].opcode);
*p++ = (unsigned char)(add_insns[i].opcode >> 8);
*p++ = (unsigned char)(add_insns[i].type);
*p++ = (unsigned char)(add_insns[i].type >> 8);
LE64(p, add_insns[i].imm);
}
for (int i = 0; i < 6; i++) {
*p++ = (unsigned char)(main_insns[i].opcode);
*p++ = (unsigned char)(main_insns[i].opcode >> 8);
*p++ = (unsigned char)(main_insns[i].type);
*p++ = (unsigned char)(main_insns[i].type >> 8);
LE64(p, main_insns[i].imm);
}
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, sz) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == 30);
}
/* ================================================================
* Global data (GADDR) test
* ================================================================ */
void test_gaddr_ld32(void) {
/* Load program, add global data, GADDR + LD32 to read it back */
spl_vm_ins_t p[] = {ins(SPL_GADDR, SPL_VOID, 0), ins(SPL_LOAD, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
size_t len;
unsigned char *bin = build_binary("main", 0, p, 3, &len);
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
uint32_t val = 0xDEADBEEF;
spl_prog_add_data(&prog, &val, sizeof(val));
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == (int)0xDEADBEEF);
}
void test_gaddr_multi(void) {
/* Two global data entries: read second one via GADDR 1 */
spl_vm_ins_t p[] = {ins(SPL_GADDR, SPL_VOID, 1), ins(SPL_LOAD, SPL_U32, 0),
ins(SPL_RET, SPL_U32, 0)};
size_t len;
unsigned char *bin = build_binary("main", 0, p, 3, &len);
spl_prog_t prog;
spl_vm_t vm;
int rc = -1;
spl_vm_init(&vm);
if (write_temp(bin, len) == 0 && spl_prog_load_from_file(TMPFILE, &prog) == 0) {
uint32_t a = 0xAAAAAAAA, b = 0xBBBBBBBB;
spl_prog_add_data(&prog, &a, sizeof(a));
spl_prog_add_data(&prog, &b, sizeof(b));
spl_vm_load_prog(&vm, &prog);
if (spl_vm_prepare(&vm, "main", 0, NULL, NULL) == 0) {
int ret = spl_vm_run_until(&vm, 0);
if (ret == 1)
rc = (int)vm.exit_code;
}
spl_vm_drop(&vm);
}
remove(TMPFILE);
free(bin);
TEST_CHECK(rc == (int)0xBBBBBBBB);
}
/* ================================================================
* Native call test
* ================================================================ */
void test_ncall(void) {
/* main() -> i32 { return native_add(30, 12); } */
/* NCALL imm = nargs, native index is pushed separately */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 30), ins(SPL_PUSH, SPL_I32, 12),
ins(SPL_PUSH, SPL_VOID, 0), ins(SPL_NCALL, SPL_I32, 2),
ins(SPL_RET, SPL_I32, 0)};
spl_vm_native_t nat[] = {{"native_add", 0, native_add_impl}};
TEST_CHECK(run_with_natives(p, 5, nat, 1) == 42);
}
/* ================================================================
* Type conversion tests
* ================================================================ */
void test_trunc(void) {
/* push 0xABCD, trunc to 8 bits -> 0xCD */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xABCD), ins(SPL_TRUNC, SPL_U8, 8),
ins(SPL_RET, SPL_U8, 0)};
TEST_CHECK(run(p, 3) == 0xCD);
}
void test_sext(void) {
/* push 0x80, sext from 8 bits -> 0xFFFFFF80 */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 0x80), ins(SPL_SEXT, SPL_I32, 8),
ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 3) == (int)(int8_t)(0x80));
}
void test_zext(void) {
/* push 0xFFFF, zext from 8 bits -> 0xFF */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 0xFFFF), ins(SPL_ZEXT, SPL_U32, 8),
ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 3) == 0xFF);
}
/* ================================================================
* Extended arithmetic tests (unsigned div/rem)
* ================================================================ */
void test_div_u(void) {
/* unsigned: 100 / 3 = 33 */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 100), ins(SPL_PUSH, SPL_U32, 3),
ins(SPL_DIV_U, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 33);
}
void test_rem_u(void) {
/* unsigned: 100 % 3 = 1 */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_U32, 100), ins(SPL_PUSH, SPL_U32, 3),
ins(SPL_REM_U, SPL_U32, 0), ins(SPL_RET, SPL_U32, 0)};
TEST_CHECK(run(p, 4) == 1);
}
/* ================================================================
* Edge case tests
* ================================================================ */
void test_many_ops(void) {
/* (1+2) * (3+4) = 21 */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 1), ins(SPL_PUSH, SPL_I32, 2),
ins(SPL_ADD, SPL_I32, 0), ins(SPL_PUSH, SPL_I32, 3),
ins(SPL_PUSH, SPL_I32, 4), ins(SPL_ADD, SPL_I32, 0),
ins(SPL_MUL, SPL_I32, 0), ins(SPL_RET, SPL_I32, 0)};
TEST_CHECK(run(p, 8) == 21);
}
void test_halt(void) {
/* push 77, halt -> exit code 0 (HALT doesn't pop) */
spl_vm_ins_t p[] = {ins(SPL_PUSH, SPL_I32, 77), ins(SPL_HALT, SPL_VOID, 0)};
TEST_CHECK(run(p, 2) == 0);
}
/* ================================================================
* Bad program tests
* ================================================================ */
void test_bad_magic(void) {
unsigned char bad[8] = {0, 0, 0, 0, 0, 0, 0, 0};
spl_prog_t prog;
if (write_temp(bad, 8) == 0) {
TEST_CHECK(spl_prog_load_from_file(TMPFILE, &prog) != 0);
remove(TMPFILE);
}
}
void test_empty(void) {
TEST_CHECK(spl_prog_load_from_file("nonexistent_file_xyz.bin", NULL) != 0);
}
/* ================================================================
* Test list
* ================================================================ */
TEST_LIST = {
{"push", test_push_imm},
{"dup", test_dup},
{"drop", test_drop},
{"swap", test_swap},
{"pick", test_pick},
{"add", test_add},
{"sub", test_sub},
{"mul", test_mul},
{"div", test_div},
{"rem", test_rem},
{"neg", test_neg},
{"i64_arith", test_i64_arith},
{"and", test_and},
{"or", test_or},
{"xor", test_xor},
{"not", test_not},
{"shl", test_shl},
{"shr", test_shr},
{"shr_s", test_shr_s},
{"eq", test_eq},
{"neq", test_neq},
{"lt", test_lt},
{"gt_signed", test_gt_signed},
{"sle", test_sle},
{"sge", test_sge},
{"ult", test_ult},
{"ule", test_ule},
{"ugt", test_ugt},
{"uge", test_uge},
{"jmp", test_jmp},
{"bz_bnz", test_bz_bnz},
{"alloc_laddr_ld_st", test_alloc_laddr_st64_ld64},
{"alloc_zeroed", test_alloc_zeroed},
{"call_add", test_call_add},
{"calli", test_calli},
{"gaddr_ld32", test_gaddr_ld32},
{"gaddr_multi", test_gaddr_multi},
{"ncall", test_ncall},
{"div_u", test_div_u},
{"rem_u", test_rem_u},
{"trunc", test_trunc},
{"sext", test_sext},
{"zext", test_zext},
{"ld_st8", test_ld_st8},
{"ld_st16", test_ld_st16},
{"ld_st32", test_ld_st32},
{"ld_st64", test_ld_st64},
{"many_ops", test_many_ops},
{"halt", test_halt},
{"bad_magic", test_bad_magic},
{"empty", test_empty},
{NULL, NULL},
};
+432
View File
@@ -0,0 +1,432 @@
#include "spl_ast.h"
const char *spl_ast_kind_name(spl_ast_node_kind_t kind) {
static const char *const names[] = {
#define X(a, b, c) #c,
SPL_AST_KIND_TABLE
#undef X
};
if ((usize)kind < sizeof(names) / sizeof(names[0]))
return names[kind];
return "?";
}
const char *spl_binary_op_name(spl_binary_op_t op) {
static const char *const names[] = {
#define X(a, b, c, name) #name,
SPL_BINARY_OP_TABLE
#undef X
};
if ((usize)op < sizeof(names) / sizeof(names[0]))
return names[op];
return "?";
}
const char *spl_unary_op_name(spl_unary_op_t op) {
switch (op) {
case SPL_UNARY_OP_MINUS:
return "neg";
case SPL_UNARY_OP_NOT:
return "not";
case SPL_UNARY_OP_BIT_NOT:
return "bitnot";
case SPL_UNARY_OP_ADDRESS:
return "addr";
case SPL_UNARY_OP_DEREF:
return "deref";
default:
return "?";
}
}
void spl_ast_init(spl_ast_t *ast, const spl_tok_vec_t *tok_vec) {
ast->input = *tok_vec;
vec_init(ast->node_buckets);
vec_init(ast->str_buckets);
ast->root = 0;
spl_ast_node_t n = {0};
vec_push(ast->node_buckets, n);
}
void spl_ast_drop(spl_ast_t *ast) {
if (!ast)
return;
vec_for(ast->str_buckets, idx) { free(vec_at(ast->str_buckets, idx)); }
vec_free(ast->str_buckets);
vec_for(ast->node_buckets, idx) { vec_free(vec_at(ast->node_buckets, idx).attrs); }
vec_free(ast->node_buckets);
vec_free(ast->input);
ast->root = 0;
}
spl_ast_node_t *spl_ast_node(spl_ast_t *ast, spl_ast_node_ref_t node) {
if (!ast || node == 0 || node >= ast->node_buckets.size)
return NULL;
return &ast->node_buckets.data[node];
}
typedef VEC(char) dump_stack_t;
static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t *stack, bool last);
void spl_ast_dump(spl_ast_t *ast, spl_ast_node_ref_t node) {
if (!ast || !node || node >= ast->node_buckets.size)
return;
dump_stack_t stack;
vec_init(stack);
printf("AST:\n");
dump_node(ast, node, &stack, true);
vec_free(stack);
}
#define dump_vec(_ast, _vec, _stack) \
do { \
vec_for(_vec, _i) { dump_node(_ast, vec_at(_vec, _i), _stack, _i + 1 == vec_size(_vec)); } \
} while (0)
static void dump_node(spl_ast_t *ast, spl_ast_node_ref_t node_ref, dump_stack_t *stack, bool last) {
spl_ast_node_t *node = &ast->node_buckets.data[node_ref];
for (usize i = 0; i < vec_size(*stack); i++)
printf("%s", vec_at(*stack, i) ? " " : "| ");
printf("%s%s #%zu", last ? "`-" : "|-", spl_ast_kind_name(node->kind), node_ref);
if (node->dbg.fname)
printf(" [%d:%d]", node->dbg.line, node->dbg.col);
printf("\n");
vec_push(*stack, last);
switch (node->kind) {
case SPL_AST_ROOT:
if (node->root.members)
dump_node(ast, node->root.members, stack, true);
break;
case SPL_AST_CONTAINER_MEMBERS:
dump_vec(ast, node->container_members.external_tags, stack);
dump_vec(ast, node->container_members.declarations, stack);
break;
case SPL_AST_TAG_ITEM:
case SPL_AST_EXTERNAL_TAG_ITEM:
dump_vec(ast, node->tag_item.args, stack);
break;
case SPL_AST_FN_DECL:
dump_vec(ast, node->fn_decl.tag_list, stack);
dump_vec(ast, node->fn_decl.params, stack);
if (node->fn_decl.ret_type)
dump_node(ast, node->fn_decl.ret_type, stack, false);
if (node->fn_decl.body)
dump_node(ast, node->fn_decl.body, stack, true);
break;
case SPL_AST_VAR_DECL:
case SPL_AST_CONST_DECL:
dump_vec(ast, node->var_const_decl.attr_list, stack);
if (node->var_const_decl.pattern)
dump_node(ast, node->var_const_decl.pattern, stack, false);
if (node->var_const_decl.type)
dump_node(ast, node->var_const_decl.type, stack, false);
if (node->var_const_decl.init_expr)
dump_node(ast, node->var_const_decl.init_expr, stack, true);
break;
case SPL_AST_TYPE_DECL:
dump_vec(ast, node->type_decl.attr_list, stack);
if (node->type_decl.pattern)
dump_node(ast, node->type_decl.pattern, stack, false);
if (node->type_decl.type_expr)
dump_node(ast, node->type_decl.type_expr, stack, true);
break;
case SPL_AST_MEMBER_DECL:
dump_vec(ast, node->member_decl.attr_list, stack);
if (node->member_decl.type_expr)
dump_node(ast, node->member_decl.type_expr, stack, false);
if (node->member_decl.init_expr)
dump_node(ast, node->member_decl.init_expr, stack, true);
break;
case SPL_AST_PARAM_DECL:
dump_vec(ast, node->param_decl.attr_list, stack);
if (node->param_decl.type_expr)
dump_node(ast, node->param_decl.type_expr, stack, true);
break;
case SPL_AST_COMPTIME_DECL:
if (node->comptime_decl.body)
dump_node(ast, node->comptime_decl.body, stack, true);
break;
case SPL_AST_TOP_LEVEL_BLOCK:
dump_vec(ast, node->top_level_block.tag_list, stack);
if (node->top_level_block.block)
dump_node(ast, node->top_level_block.block, stack, true);
break;
case SPL_AST_STATEMENT_RET:
if (node->statement_ret.expr)
dump_node(ast, node->statement_ret.expr, stack, true);
break;
case SPL_AST_STATEMENT_BREAK:
if (node->statement_break.label)
dump_node(ast, node->statement_break.label, stack, false);
if (node->statement_break.expr)
dump_node(ast, node->statement_break.expr, stack, true);
break;
case SPL_AST_STATEMENT_CONTINUE:
if (node->statement_continue.label)
dump_node(ast, node->statement_continue.label, stack, true);
break;
case SPL_AST_STATEMENT_DEFER:
case SPL_AST_STATEMENT_COMPTIME:
if (node->statement_defer.body)
dump_node(ast, node->statement_defer.body, stack, true);
break;
case SPL_AST_STATEMENT_DECL:
if (node->statement_decl.decl)
dump_node(ast, node->statement_decl.decl, stack, true);
break;
case SPL_AST_STATEMENT_EXPR:
if (node->statement_expr.expr)
dump_node(ast, node->statement_expr.expr, stack, true);
break;
case SPL_AST_AGGREGATE_MEMBER:
dump_vec(ast, node->aggregate_member.attr_list, stack);
if (node->aggregate_member.type_expr)
dump_node(ast, node->aggregate_member.type_expr, stack, false);
if (node->aggregate_member.init_expr)
dump_node(ast, node->aggregate_member.init_expr, stack, true);
break;
case SPL_AST_STRUCT_INIT_ITEM:
if (node->struct_init_item.expr)
dump_node(ast, node->struct_init_item.expr, stack, true);
break;
case SPL_AST_MATCH_ARM:
if (node->match_arm.pattern)
dump_node(ast, node->match_arm.pattern, stack, false);
if (node->match_arm.body)
dump_node(ast, node->match_arm.body, stack, true);
break;
case SPL_AST_LABEL:
break;
case SPL_AST_EXPR_INT_LIT:
case SPL_AST_EXPR_FLOAT_LIT:
case SPL_AST_EXPR_CHAR_LIT:
case SPL_AST_EXPR_STRING_LIT:
case SPL_AST_EXPR_BOOL_LIT:
case SPL_AST_EXPR_NULL_LIT:
case SPL_AST_EXPR_UNDEFINED_LIT:
case SPL_AST_EXPR_IDENT:
break;
case SPL_AST_EXPR_UNARY:
if (node->unary.operand)
dump_node(ast, node->unary.operand, stack, true);
break;
case SPL_AST_EXPR_BINARY:
if (node->binary.left)
dump_node(ast, node->binary.left, stack, false);
if (node->binary.right)
dump_node(ast, node->binary.right, stack, true);
break;
case SPL_AST_EXPR_CALL:
if (node->call.callee)
dump_node(ast, node->call.callee, stack, false);
dump_vec(ast, node->call.args, stack);
break;
case SPL_AST_EXPR_FIELD:
if (node->field.obj)
dump_node(ast, node->field.obj, stack, true);
break;
case SPL_AST_EXPR_INDEX:
if (node->index.obj)
dump_node(ast, node->index.obj, stack, false);
if (node->index.index)
dump_node(ast, node->index.index, stack, true);
break;
case SPL_AST_EXPR_SLICE:
if (node->slice.obj)
dump_node(ast, node->slice.obj, stack, false);
if (node->slice.begin)
dump_node(ast, node->slice.begin, stack, false);
if (node->slice.end)
dump_node(ast, node->slice.end, stack, true);
break;
case SPL_AST_EXPR_CAST:
if (node->cast.expr)
dump_node(ast, node->cast.expr, stack, false);
if (node->cast.type)
dump_node(ast, node->cast.type, stack, true);
break;
case SPL_AST_EXPR_TUPLE:
dump_vec(ast, node->tuple.elems, stack);
break;
case SPL_AST_EXPR_ARRAY_LIT:
if (node->array_literal.elem_type)
dump_node(ast, node->array_literal.elem_type, stack, false);
dump_vec(ast, node->array_literal.elems, stack);
break;
case SPL_AST_EXPR_AGGREGATE_LIT:
dump_vec(ast, node->aggregate_literal.fields, stack);
break;
case SPL_AST_EXPR_COMPTIME_CALL:
dump_vec(ast, node->comptime_call.args, stack);
break;
case SPL_AST_EXPR_BLOCK:
dump_vec(ast, node->block.stmts, stack);
if (node->block.tail_expr)
dump_node(ast, node->block.tail_expr, stack, true);
break;
case SPL_AST_EXPR_IF:
if (node->if_expr.cond)
dump_node(ast, node->if_expr.cond, stack, false);
if (node->if_expr.then_block)
dump_node(ast, node->if_expr.then_block, stack, false);
if (node->if_expr.else_branch)
dump_node(ast, node->if_expr.else_branch, stack, true);
break;
case SPL_AST_EXPR_IFVAR:
if (node->ifvar_expr.var_decl)
dump_node(ast, node->ifvar_expr.var_decl, stack, false);
if (node->ifvar_expr.then_block)
dump_node(ast, node->ifvar_expr.then_block, stack, false);
if (node->ifvar_expr.else_branch)
dump_node(ast, node->ifvar_expr.else_branch, stack, true);
break;
case SPL_AST_EXPR_WHILE:
if (node->while_expr.label)
dump_node(ast, node->while_expr.label, stack, false);
if (node->while_expr.cond)
dump_node(ast, node->while_expr.cond, stack, false);
if (node->while_expr.body)
dump_node(ast, node->while_expr.body, stack, false);
if (node->while_expr.else_branch)
dump_node(ast, node->while_expr.else_branch, stack, true);
break;
case SPL_AST_EXPR_LOOP:
if (node->loop_expr.label)
dump_node(ast, node->loop_expr.label, stack, false);
if (node->loop_expr.body)
dump_node(ast, node->loop_expr.body, stack, true);
break;
case SPL_AST_EXPR_FOR:
if (node->for_expr.label)
dump_node(ast, node->for_expr.label, stack, false);
dump_vec(ast, node->for_expr.iter_exprs, stack);
if (node->for_expr.pattern)
dump_node(ast, node->for_expr.pattern, stack, false);
if (node->for_expr.body)
dump_node(ast, node->for_expr.body, stack, false);
if (node->for_expr.else_branch)
dump_node(ast, node->for_expr.else_branch, stack, true);
break;
case SPL_AST_EXPR_MATCH:
if (node->match_expr.matched_expr)
dump_node(ast, node->match_expr.matched_expr, stack, false);
dump_vec(ast, node->match_expr.arms, stack);
break;
case SPL_AST_EXPR_FN_TYPE:
dump_vec(ast, node->fn_type.params, stack);
if (node->fn_type.ret_type)
dump_node(ast, node->fn_type.ret_type, stack, true);
break;
case SPL_AST_TYPE_PATH:
break;
case SPL_AST_TYPE_POINTER:
if (node->type_pointer.pointee)
dump_node(ast, node->type_pointer.pointee, stack, true);
break;
case SPL_AST_TYPE_ARRAY:
if (node->type_array.elem_type)
dump_node(ast, node->type_array.elem_type, stack, true);
break;
case SPL_AST_TYPE_SLICE:
if (node->type_slice.elem_type)
dump_node(ast, node->type_slice.elem_type, stack, true);
break;
case SPL_AST_TYPE_FN:
dump_vec(ast, node->type_fn.params, stack);
if (node->type_fn.ret_type)
dump_node(ast, node->type_fn.ret_type, stack, true);
break;
case SPL_AST_TYPE_PAREN:
dump_vec(ast, node->type_paren.types, stack);
break;
case SPL_AST_TYPE_AGGREGATE:
dump_vec(ast, node->type_aggregate.members, stack);
break;
case SPL_AST_TYPE_COMPTIME_CALL:
dump_vec(ast, node->type_comptime_call.args, stack);
break;
case SPL_AST_PATTERN_IDENT:
case SPL_AST_PATTERN_UNDERSCORE:
break;
case SPL_AST_PATTERN_DOT:
if (node->pattern_dot.sub_pattern)
dump_node(ast, node->pattern_dot.sub_pattern, stack, true);
break;
case SPL_AST_PATTERN_TUPLE:
dump_vec(ast, node->pattern_tuple.patterns, stack);
break;
case SPL_AST_PATTERN_LIST:
dump_vec(ast, node->pattern_list.patterns, stack);
break;
case SPL_AST_PATTERN_AGGREGATE:
dump_vec(ast, node->pattern_aggregate.fields, stack);
break;
case SPL_AST_PATTERN_FIELD:
if (node->pattern_field.pattern)
dump_node(ast, node->pattern_field.pattern, stack, true);
break;
default:
break;
}
(void)vec_pop(*stack);
}
+478
View File
@@ -0,0 +1,478 @@
#ifndef __SPL_AST_H__
#define __SPL_AST_H__
#include "../stage0/include/utils.h"
#include "spl_attr.h"
#include "spl_dbg.h"
#include "spl_tok.h"
/* clang-format off */
#define SPL_AST_KIND_TABLE \
X(SPL_AST_NONE, V0, none) \
X(SPL_AST_ROOT, V0, root) \
X(SPL_AST_CONTAINER_MEMBERS, V0, container_members) \
X(SPL_AST_EXTERNAL_TAG_ITEM, V0, external_tag_item) \
X(SPL_AST_TAG_ITEM, V0, tag_item) \
X(SPL_AST_COMPTIME_DECL, V0, comptime_decl) \
X(SPL_AST_TOP_LEVEL_BLOCK, V0, top_level_block) \
X(SPL_AST_FN_DECL, V0, fn_decl) \
X(SPL_AST_VAR_DECL, V0, var_decl) \
X(SPL_AST_CONST_DECL, V0, const_decl) \
X(SPL_AST_TYPE_DECL, V0, type_decl) \
X(SPL_AST_MEMBER_DECL, V0, member_decl) \
X(SPL_AST_PARAM_DECL, V0, param_decl) \
X(SPL_AST_STATEMENT_RET, V0, statement_ret) \
X(SPL_AST_STATEMENT_BREAK, V0, statement_break) \
X(SPL_AST_STATEMENT_CONTINUE, V0, statement_continue) \
X(SPL_AST_STATEMENT_DEFER, V0, statement_defer) \
X(SPL_AST_STATEMENT_COMPTIME, V0, statement_comptime) \
X(SPL_AST_STATEMENT_DECL, V0, statement_decl) \
X(SPL_AST_STATEMENT_EXPR, V0, statement_expr) \
X(SPL_AST_AGGREGATE_MEMBER, V0, aggregate_member) \
X(SPL_AST_STRUCT_INIT_ITEM, V0, struct_init_item) \
X(SPL_AST_MATCH_ARM, V0, match_arm) \
X(SPL_AST_LABEL, V0, label) \
X(SPL_AST_EXPR_INT_LIT, V0, int_lit) \
X(SPL_AST_EXPR_FLOAT_LIT, V0, float_lit) \
X(SPL_AST_EXPR_CHAR_LIT, V0, char_lit) \
X(SPL_AST_EXPR_STRING_LIT, V0, string_lit) \
X(SPL_AST_EXPR_BOOL_LIT, V0, bool_lit) \
X(SPL_AST_EXPR_NULL_LIT, V0, null_lit) \
X(SPL_AST_EXPR_UNDEFINED_LIT, V0, undefined_lit) \
X(SPL_AST_EXPR_IDENT, V0, ident) \
X(SPL_AST_EXPR_UNARY, V0, unary) \
X(SPL_AST_EXPR_BINARY, V0, binary) \
X(SPL_AST_EXPR_CALL, V0, call) \
X(SPL_AST_EXPR_FIELD, V0, field) \
X(SPL_AST_EXPR_INDEX, V0, index) \
X(SPL_AST_EXPR_SLICE, V0, slice) \
X(SPL_AST_EXPR_CAST, V0, cast) \
X(SPL_AST_EXPR_TUPLE, V0, tuple) \
X(SPL_AST_EXPR_ARRAY_LIT, V0, array_literal) \
X(SPL_AST_EXPR_AGGREGATE_LIT, V0, aggregate_literal) \
X(SPL_AST_EXPR_COMPTIME_CALL, V0, comptime_call) \
X(SPL_AST_EXPR_BLOCK, V0, block) \
X(SPL_AST_EXPR_IF, V0, if_expr) \
X(SPL_AST_EXPR_IFVAR, V0, ifvar_expr) \
X(SPL_AST_EXPR_WHILE, V0, while_expr) \
X(SPL_AST_EXPR_LOOP, V0, loop_expr) \
X(SPL_AST_EXPR_FOR, V0, for_expr) \
X(SPL_AST_EXPR_MATCH, V0, match_expr) \
X(SPL_AST_EXPR_FN_TYPE, V0, fn_type) \
X(SPL_AST_TYPE_PATH, V0, type_path) \
X(SPL_AST_TYPE_POINTER, V0, type_pointer) \
X(SPL_AST_TYPE_ARRAY, V0, type_array) \
X(SPL_AST_TYPE_SLICE, V0, type_slice) \
X(SPL_AST_TYPE_FN, V0, type_fn) \
X(SPL_AST_TYPE_PAREN, V0, type_paren) \
X(SPL_AST_TYPE_AGGREGATE, V0, type_aggregate) \
X(SPL_AST_TYPE_COMPTIME_CALL, V0, type_comptime_call) \
X(SPL_AST_PATTERN_IDENT, V0, pattern_ident) \
X(SPL_AST_PATTERN_UNDERSCORE, V0, pattern_underscore) \
X(SPL_AST_PATTERN_DOT, V0, pattern_dot) \
X(SPL_AST_PATTERN_TUPLE, V0, pattern_tuple) \
X(SPL_AST_PATTERN_LIST, V0, pattern_list) \
X(SPL_AST_PATTERN_AGGREGATE, V0, pattern_aggregate) \
X(SPL_AST_PATTERN_FIELD, V0, pattern_field)
/* clang-format on */
typedef enum {
#ifdef X
#undef X
#endif
#define X(name, ...) name,
SPL_AST_KIND_TABLE
#undef X
SPL_AST_COUNT,
} spl_ast_node_kind_t;
/* clang-format off */
#define SPL_BINARY_OP_TABLE \
X(SPL_OP_ASSIGN, 1, 'R', =) \
X(SPL_OP_ASSIGN_ADD, 1, 'R', +=) \
X(SPL_OP_ASSIGN_SUB, 1, 'R', -=) \
X(SPL_OP_ASSIGN_MUL, 1, 'R', *=) \
X(SPL_OP_ASSIGN_DIV, 1, 'R', /=) \
X(SPL_OP_ASSIGN_MOD, 1, 'R', %=) \
X(SPL_OP_ASSIGN_AND, 1, 'R', &=) \
X(SPL_OP_ASSIGN_OR, 1, 'R', |=) \
X(SPL_OP_ASSIGN_XOR, 1, 'R', ^=) \
X(SPL_OP_ASSIGN_LSHIFT, 1, 'R', <<=) \
X(SPL_OP_ASSIGN_RSHIFT, 1, 'R', >>=) \
X(SPL_OP_BOOL_OR, 2, 'L', ||) \
X(SPL_OP_BOOL_AND, 3, 'L', &&) \
X(SPL_OP_BIT_OR, 4, 'L', |) \
X(SPL_OP_BIT_XOR, 5, 'L', ^) \
X(SPL_OP_BIT_AND, 6, 'L', &) \
X(SPL_OP_CMP_EQ, 7, 'L', ==) \
X(SPL_OP_CMP_NE, 7, 'L', !=) \
X(SPL_OP_CMP_LE, 8, 'L', <=) \
X(SPL_OP_CMP_GE, 8, 'L', >=) \
X(SPL_OP_CMP_LT, 8, 'L', <) \
X(SPL_OP_CMP_GT, 8, 'L', >) \
X(SPL_OP_ARROW_LEFT, 9, 'L', <-) \
X(SPL_OP_ARROW_RIGHT, 9, 'L', ->) \
X(SPL_OP_ARROW_FAT_BOTH, 9, 'L', <=>) \
X(SPL_OP_ARROW_THIN_BOTH, 9, 'L', <->) \
X(SPL_OP_ARROW_FAT_RIGHT, 9, 'L', =>) \
X(SPL_OP_RANGE, 10, 'L', ..) \
X(SPL_OP_LSHIFT, 11, 'L', <<) \
X(SPL_OP_RSHIFT, 11, 'L', >>) \
X(SPL_OP_ADD, 12, 'L', +) \
X(SPL_OP_SUB, 12, 'L', -) \
X(SPL_OP_MUL, 13, 'L', *) \
X(SPL_OP_DIV, 13, 'L', /) \
X(SPL_OP_MOD, 13, 'L', %)
/* clang-format on */
typedef enum {
#ifdef X
#undef X
#endif
#define X(name, ...) name,
SPL_BINARY_OP_TABLE
#undef X
} spl_binary_op_t;
typedef enum {
SPL_UNARY_OP_MINUS,
SPL_UNARY_OP_NOT,
SPL_UNARY_OP_BIT_NOT,
SPL_UNARY_OP_ADDRESS,
SPL_UNARY_OP_DEREF,
} spl_unary_op_t;
struct spl_ast_node;
typedef struct spl_ast_node spl_ast_node_t;
typedef usize spl_ast_node_ref_t;
typedef VEC(spl_ast_node_ref_t) spl_ast_node_ref_vec_t;
struct spl_ast_node {
spl_ast_node_kind_t kind;
spl_dbg_node_t dbg;
usize resolved_def_id;
usize resolved_lang_tid;
usize expected_lang_tid;
spl_attr_id_vec_t attrs;
union {
struct {
spl_ast_node_ref_t members;
} root;
struct {
spl_ast_node_ref_vec_t external_tags;
spl_ast_node_ref_vec_t declarations;
} container_members;
struct {
spl_ast_node_ref_vec_t tag_list;
bool is_comptime;
const char *name;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
spl_ast_node_ref_t body;
} fn_decl;
struct {
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t type;
spl_ast_node_ref_t init_expr;
} var_const_decl;
struct {
spl_ast_node_ref_vec_t attr_list;
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t type_expr;
} type_decl;
struct {
spl_ast_node_ref_vec_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t init_expr;
} member_decl;
struct {
spl_ast_node_ref_vec_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
} param_decl;
struct {
bool is_at;
bool is_external;
const char *name;
spl_ast_node_ref_vec_t args;
} tag_item;
struct {
spl_ast_node_ref_t body;
} comptime_decl;
struct {
spl_ast_node_ref_vec_t tag_list;
spl_ast_node_ref_t block;
} top_level_block;
struct {
spl_ast_node_ref_t expr;
} statement_ret;
struct {
spl_ast_node_ref_t label;
spl_ast_node_ref_t expr;
} statement_break;
struct {
spl_ast_node_ref_t label;
} statement_continue;
struct {
spl_ast_node_ref_t body;
} statement_defer;
struct {
spl_ast_node_ref_t body;
} statement_comptime;
struct {
spl_ast_node_ref_t decl;
} statement_decl;
struct {
spl_ast_node_ref_t expr;
} statement_expr;
struct {
spl_ast_node_ref_vec_t attr_list;
const char *name;
spl_ast_node_ref_t type_expr;
spl_ast_node_ref_t init_expr;
} aggregate_member;
struct {
const char *name;
spl_ast_node_ref_t expr;
} struct_init_item;
struct {
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t body;
} match_arm;
struct {
const char *name;
} label;
spl_mpa_int_t int_lit;
spl_mpa_float_t float_lit;
struct {
char val;
} char_lit;
struct {
const char *data;
usize len;
} string_lit;
struct {
bool val;
} bool_lit;
struct {
const char *name;
} ident;
struct {
spl_unary_op_t op;
spl_ast_node_ref_t operand;
} unary;
struct {
spl_binary_op_t op;
spl_ast_node_ref_t left;
spl_ast_node_ref_t right;
} binary;
struct {
spl_ast_node_ref_t callee;
spl_ast_node_ref_vec_t args;
} call;
struct {
spl_ast_node_ref_t obj;
const char *field;
} field;
struct {
spl_ast_node_ref_t obj;
spl_ast_node_ref_t index;
} index;
struct {
spl_ast_node_ref_t obj;
spl_ast_node_ref_t begin;
spl_ast_node_ref_t end;
} slice;
struct {
spl_ast_node_ref_t expr;
spl_ast_node_ref_t type;
} cast;
struct {
spl_ast_node_ref_vec_t elems;
} tuple;
struct {
bool has_len;
usize len;
bool is_underscore_len;
spl_ast_node_ref_t elem_type;
spl_ast_node_ref_vec_t elems;
} array_literal;
struct {
const char *name;
spl_ast_node_ref_vec_t fields;
} aggregate_literal;
struct {
const char *name;
spl_ast_node_ref_vec_t args;
} comptime_call;
struct {
spl_ast_node_ref_vec_t stmts;
spl_ast_node_ref_t tail_expr;
} block;
struct {
spl_ast_node_ref_t cond;
spl_ast_node_ref_t then_block;
spl_ast_node_ref_t else_branch;
} if_expr;
struct {
spl_ast_node_ref_t var_decl;
spl_ast_node_ref_t then_block;
spl_ast_node_ref_t else_branch;
} ifvar_expr;
struct {
spl_ast_node_ref_t label;
spl_ast_node_ref_t cond;
spl_ast_node_ref_t body;
spl_ast_node_ref_t else_branch;
} while_expr;
struct {
spl_ast_node_ref_t label;
spl_ast_node_ref_t body;
} loop_expr;
struct {
spl_ast_node_ref_t label;
spl_ast_node_ref_vec_t iter_exprs;
spl_ast_node_ref_t pattern;
spl_ast_node_ref_t body;
spl_ast_node_ref_t else_branch;
} for_expr;
struct {
spl_ast_node_ref_t matched_expr;
spl_ast_node_ref_vec_t arms;
} match_expr;
struct {
bool is_comptime;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
} fn_type;
struct {
const char *name;
spl_ast_node_ref_vec_t generic_args;
} type_path;
struct {
spl_ast_node_ref_t pointee;
} type_pointer;
struct {
bool has_len;
isize len;
bool is_underscore_len;
spl_ast_node_ref_t elem_type;
} type_array;
struct {
spl_ast_node_ref_t elem_type;
} type_slice;
struct {
bool is_comptime;
spl_ast_node_ref_vec_t params;
spl_ast_node_ref_t ret_type;
} type_fn;
struct {
spl_ast_node_ref_vec_t types;
} type_paren;
struct {
const char *kind_name;
spl_ast_node_ref_vec_t members;
} type_aggregate;
struct {
const char *name;
spl_ast_node_ref_vec_t args;
} type_comptime_call;
struct {
const char *name;
} pattern_ident;
struct {
const char *name;
spl_ast_node_ref_t sub_pattern;
} pattern_dot;
struct {
spl_ast_node_ref_vec_t patterns;
} pattern_tuple;
struct {
spl_ast_node_ref_vec_t patterns;
} pattern_list;
struct {
spl_ast_node_ref_vec_t fields;
} pattern_aggregate;
struct {
const char *name;
spl_ast_node_ref_t pattern;
} pattern_field;
};
};
typedef VEC(spl_ast_node_t) spl_ast_node_vec_t;
typedef VEC(char *) spl_ast_cstr_ref_vec_t;
typedef struct spl_ast {
spl_tok_vec_t input;
spl_ast_node_vec_t node_buckets;
spl_ast_cstr_ref_vec_t str_buckets;
spl_ast_node_ref_t root;
} spl_ast_t;
typedef VEC(spl_ast_t *) spl_ast_ptr_vec_t;
void spl_ast_init(spl_ast_t *ast, const spl_tok_vec_t *tok_vec /*move*/);
void spl_ast_drop(spl_ast_t *ast);
spl_ast_node_t *spl_ast_node(spl_ast_t *ast, spl_ast_node_ref_t node);
void spl_ast_dump(spl_ast_t *ast, spl_ast_node_ref_t node);
const char *spl_ast_kind_name(spl_ast_node_kind_t kind);
const char *spl_binary_op_name(spl_binary_op_t op);
const char *spl_unary_op_name(spl_unary_op_t op);
#endif /* __SPL_AST_H__ */
+2134
View File
File diff suppressed because it is too large. Load diff
+42
View File
@@ -0,0 +1,42 @@
#ifndef __SPL_AST2IR_H__
#define __SPL_AST2IR_H__
#include "spl_diag.h"
#include "spl_ir.h"
#include "spl_sema.h"
typedef MAP(spl_def_id_t, spl_ir_node_ref_t) spl_def2ir_map_t;
typedef struct {
usize cont_blk;
usize defer_base;
const char *label;
spl_ir_node_ref_vec_t breaks;
spl_ir_node_ref_t result_slot;
spl_type_id_t result_tid;
} spl_loop_ctx_t;
typedef VEC(spl_loop_ctx_t) spl_loop_ctx_vec_t;
typedef VEC(spl_ast_node_ref_t) spl_defer_stack_t;
typedef struct {
const spl_sema_t *sema;
spl_ir_builder_t *ir;
spl_ast_t *ast;
spl_layout_t *layout; /* 借用 splc0 的 layout */
spl_def2ir_map_t def2ir_map;
spl_loop_ctx_vec_t loop_stack;
spl_defer_stack_t defer_stack;
spl_lang_type_id_t cur_ret_lang;
usize cur_defer_base;
spl_diag_t *diag;
} spl_ast2ir_t;
void spl_ast2ir_init(spl_ast2ir_t *ast2ir, spl_ir_builder_t *ir, spl_layout_t *layout,
const spl_sema_t *sema);
void spl_ast2ir_drop(spl_ast2ir_t *ast2ir);
void spl_ast2ir_run(spl_ast2ir_t *ast2ir, spl_ast_ptr_vec_t ast_vec);
#endif /* __SPL_AST2IR_H__ */
+152
View File
@@ -0,0 +1,152 @@
#include "spl_attr.h"
static spl_attr_info_t spl_builtin_attrs[] = {
{NULL, "extern", SPL_ATTR_STAGE_IR, SPL_ATTR_TARGET_DECL, SPL_ATTR_REQUIRED, 1, 1},
{NULL, "inline", SPL_ATTR_STAGE_OPT, SPL_ATTR_TARGET_DECL, SPL_ATTR_OPTIONAL, 0, 0},
{NULL, "noinline", SPL_ATTR_STAGE_OPT, SPL_ATTR_TARGET_DECL, SPL_ATTR_OPTIONAL, 0, 0},
{NULL, "align", SPL_ATTR_STAGE_LAYOUT, SPL_ATTR_TARGET_TYPE, SPL_ATTR_REQUIRED, 1, 1},
{NULL, "volatile", SPL_ATTR_STAGE_IR, SPL_ATTR_TARGET_EXPR, SPL_ATTR_REQUIRED, 0, 0},
{NULL, "atomic", SPL_ATTR_STAGE_IR, SPL_ATTR_TARGET_EXPR, SPL_ATTR_REQUIRED, 0, 1},
};
void spl_attr_init(spl_attr_t *ctx) {
vec_init(ctx->table);
vec_push(ctx->table, (spl_attr_node_t){0});
vec_init(ctx->registry);
spl_attr_register_builtins(ctx);
}
void spl_attr_drop(spl_attr_t *ctx) {
for (usize i = 1; i < vec_size(ctx->table); ++i)
vec_free(vec_at(ctx->table, i).args);
vec_free(ctx->table);
vec_free(ctx->registry);
}
spl_attr_id_t spl_attr_alloc(spl_attr_t *ctx, spl_attr_info_t *info, spl_attr_arg_vec_t args) {
spl_attr_node_t a = {0};
a.info = info;
a.args = args;
vec_push(ctx->table, a);
return vec_size(ctx->table) - 1;
}
spl_attr_node_t *spl_attr_node(const spl_attr_t *ctx, spl_attr_id_t id) {
if (!id || id >= vec_size(ctx->table))
return NULL;
return &vec_at(ctx->table, id);
}
void spl_attr_registry_add(spl_attr_t *ctx, spl_attr_info_t *info) {
vec_push(ctx->registry, info);
}
static int name_eq(const char *a, const char *b) {
if (a == NULL && b == NULL)
return 1;
if (a == NULL || b == NULL)
return 0;
return strcmp(a, b) == 0;
}
spl_attr_info_t *spl_attr_lookup(spl_attr_t *ctx, const char *ns, const char *name) {
for (usize i = 0; i < vec_size(ctx->registry); ++i) {
spl_attr_info_t *info = vec_at(ctx->registry, i);
if (name_eq(info->ns, ns) && strcmp(info->name, name) == 0)
return info;
}
return NULL;
}
void spl_attr_register_builtins(spl_attr_t *ctx) {
usize n = sizeof(spl_builtin_attrs) / sizeof(spl_builtin_attrs[0]);
for (usize i = 0; i < n; ++i)
spl_attr_registry_add(ctx, &spl_builtin_attrs[i]);
}
static const char *attr_stage_name(spl_attr_stage_t s) {
switch (s) {
case SPL_ATTR_STAGE_SEMA:
return "SEMA";
case SPL_ATTR_STAGE_LAYOUT:
return "LAYOUT";
case SPL_ATTR_STAGE_IR:
return "IR";
case SPL_ATTR_STAGE_OPT:
return "OPT";
case SPL_ATTR_STAGE_BACKEND:
return "BACKEND";
}
return "?";
}
static const char *attr_target_name(spl_attr_target_t t) {
switch (t) {
case SPL_ATTR_TARGET_DECL:
return "DECL";
case SPL_ATTR_TARGET_TYPE:
return "TYPE";
case SPL_ATTR_TARGET_EXPR:
return "EXPR";
case SPL_ATTR_TARGET_STMT:
return "STMT";
}
return "?";
}
static const char *attr_demand_name(spl_attr_demand_t d) {
return d == SPL_ATTR_REQUIRED ? "REQUIRED" : "OPTIONAL";
}
void spl_attr_dump_id(const spl_attr_t *ctx, spl_attr_id_t id) {
if (!ctx || !id) {
printf("?");
return;
}
spl_attr_node_t *a = spl_attr_node(ctx, id);
if (!a || !a->info) {
printf("?");
return;
}
printf("%s", a->info->name);
if (vec_size(a->args) > 0) {
printf("(");
for (usize i = 0; i < vec_size(a->args); ++i) {
if (i > 0)
printf(", ");
spl_attr_arg_t *arg = &vec_at(a->args, i);
switch (arg->kind) {
case SPL_ATTR_ARG_INT:
printf("%zd", arg->value.i);
break;
case SPL_ATTR_ARG_STR:
printf("\"%s\"", arg->value.s ? arg->value.s : "");
break;
case SPL_ATTR_ARG_DEF:
printf("def#%zu", arg->value.d);
break;
case SPL_ATTR_ARG_TYPE:
printf("type#%zu", arg->value.t);
break;
}
}
printf(")");
}
}
void spl_attr_dump(const spl_attr_t *ctx) {
if (!ctx)
return;
printf("AttrTable:\n");
for (usize i = 1; i < vec_size(ctx->table); ++i) {
spl_attr_node_t *a = &vec_at(ctx->table, i);
printf(" #%zu ", i);
spl_attr_dump_id(ctx, i);
if (a->info) {
printf(" [stage=%s target=%s demand=%s consumed=0x%x]", attr_stage_name(a->info->stage),
attr_target_name(a->info->target), attr_demand_name(a->info->demand),
a->consumed_mask);
}
printf("\n");
}
}
+85
View File
@@ -0,0 +1,85 @@
#ifndef __SPL_ATTR_H__
#define __SPL_ATTR_H__
#include "../stage0/include/utils.h"
#include "spl_mpa.h"
typedef enum {
SPL_ATTR_STAGE_SEMA,
SPL_ATTR_STAGE_LAYOUT,
SPL_ATTR_STAGE_IR,
SPL_ATTR_STAGE_OPT,
SPL_ATTR_STAGE_BACKEND,
} spl_attr_stage_t;
typedef enum {
SPL_ATTR_TARGET_DECL,
SPL_ATTR_TARGET_TYPE,
SPL_ATTR_TARGET_EXPR,
SPL_ATTR_TARGET_STMT,
} spl_attr_target_t;
typedef enum {
SPL_ATTR_OPTIONAL,
SPL_ATTR_REQUIRED,
} spl_attr_demand_t;
typedef struct {
const char *ns;
const char *name;
spl_attr_stage_t stage;
spl_attr_target_t target;
spl_attr_demand_t demand;
int min_args;
int max_args;
} spl_attr_info_t;
typedef enum {
SPL_ATTR_ARG_INT,
SPL_ATTR_ARG_STR,
SPL_ATTR_ARG_DEF,
SPL_ATTR_ARG_TYPE,
} spl_attr_arg_kind_t;
typedef struct {
spl_attr_arg_kind_t kind;
union {
isize i;
const char *s;
usize d;
usize t;
} value;
} spl_attr_arg_t;
typedef VEC(spl_attr_arg_t) spl_attr_arg_vec_t;
typedef usize spl_attr_id_t;
typedef struct {
spl_attr_info_t *info;
spl_attr_arg_vec_t args;
uint32_t consumed_mask;
} spl_attr_node_t;
typedef VEC(spl_attr_node_t) spl_attr_node_vec_t;
typedef VEC(spl_attr_id_t) spl_attr_id_vec_t;
typedef VEC(spl_attr_info_t *) spl_attr_registry_t;
typedef struct {
spl_attr_node_vec_t table;
spl_attr_registry_t registry;
} spl_attr_t;
void spl_attr_init(spl_attr_t *ctx);
void spl_attr_drop(spl_attr_t *ctx);
spl_attr_id_t spl_attr_alloc(spl_attr_t *ctx, spl_attr_info_t *info, spl_attr_arg_vec_t args);
spl_attr_node_t *spl_attr_node(const spl_attr_t *ctx, spl_attr_id_t id);
void spl_attr_registry_add(spl_attr_t *ctx, spl_attr_info_t *info);
spl_attr_info_t *spl_attr_lookup(spl_attr_t *ctx, const char *ns, const char *name);
void spl_attr_register_builtins(spl_attr_t *ctx);
void spl_attr_dump(const spl_attr_t *ctx);
void spl_attr_dump_id(const spl_attr_t *ctx, spl_attr_id_t id);
#endif /* __SPL_ATTR_H__ */
+25
View File
@@ -0,0 +1,25 @@
#ifndef __SPL_DBG_H__
#define __SPL_DBG_H__
typedef struct {
const char *fname;
int line;
int col;
const char *dbg_name;
// TODO
} spl_dbg_node_t;
#define SPL_FATAL(dbg, fmt, ...) \
LOG_FATAL("fatal at %s:%d:%d " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#define SPL_ERROR(dbg, fmt, ...) \
LOG_ERROR("error at %s:%d:%d " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#define SPL_WARN(dbg, fmt, ...) \
LOG_ERROR("warn at %s:%d:%d " fmt, ((dbg) && (dbg)->fname ? (dbg)->fname : "<null>"), \
((dbg) ? (dbg)->line : 0), ((dbg) ? (dbg)->col : 0), ##__VA_ARGS__)
#endif /* __SPL_DBG_H__ */
+368
View File
@@ -0,0 +1,368 @@
#include "spl_diag.h"
#include "../stage0/include/color.h"
#include <stdarg.h>
static const char *const g_kind_names[] = {
[SPL_DIAG_KIND_NONE] = "none",
[SPL_DIAG_KIND_LEX_UNEXPECTED] = "lex_unexpected",
[SPL_DIAG_KIND_PARSE_EXPECTED] = "parse_expected",
[SPL_DIAG_KIND_PARSE_UNRECOGNIZED] = "parse_unrecognized",
[SPL_DIAG_KIND_UNDEFINED_SYMBOL] = "undefined_symbol",
[SPL_DIAG_KIND_DUPLICATE_SYMBOL] = "duplicate_symbol",
[SPL_DIAG_KIND_TYPE_MISMATCH] = "type_mismatch",
[SPL_DIAG_KIND_ARG_COUNT_MISMATCH] = "arg_count_mismatch",
[SPL_DIAG_KIND_NOT_A_FUNCTION] = "not_a_function",
[SPL_DIAG_KIND_NO_FIELD] = "no_field",
[SPL_DIAG_KIND_NO_METHOD] = "no_method",
[SPL_DIAG_KIND_INDEX_BASE_INVALID] = "index_base_invalid",
[SPL_DIAG_KIND_TUPLE_INDEX_OOB] = "tuple_index_oob",
[SPL_DIAG_KIND_FITS_OVERFLOW] = "fits_overflow",
[SPL_DIAG_KIND_CIRCULAR_DEP] = "circular_dep",
[SPL_DIAG_KIND_BREAK_OUTSIDE_LOOP] = "break_outside_loop",
[SPL_DIAG_KIND_CONTINUE_OUTSIDE_LOOP] = "continue_outside_loop",
[SPL_DIAG_KIND_UNDEFINED_LABEL] = "undefined_label",
[SPL_DIAG_KIND_CAST_INVALID] = "cast_invalid",
[SPL_DIAG_KIND_UNKNOWN_ATTR] = "unknown_attr",
[SPL_DIAG_KIND_UNKNOWN_INTRIN] = "unknown_intrin",
[SPL_DIAG_KIND_INTRIN_ARG_COUNT] = "intrin_arg_count",
[SPL_DIAG_KIND_VAR_UNINITIALIZED] = "var_uninitialized",
[SPL_DIAG_KIND_CANNOT_INFER] = "cannot_infer",
[SPL_DIAG_KIND_MUST_RETURN_VALUE] = "must_return_value",
[SPL_DIAG_KIND_UNHANDLED_NODE] = "unhandled_node",
[SPL_DIAG_KIND_IMPLICIT_CAST_FAIL] = "implicit_cast_fail",
[SPL_DIAG_KIND_NO_LVALUE] = "no_lvalue",
[SPL_DIAG_KIND_BAD_FIELD_INDEX] = "bad_field_index",
[SPL_DIAG_KIND_BAD_BLOCK] = "bad_block",
[SPL_DIAG_KIND_IR_UNKNOWN_KIND] = "ir_unknown_kind",
[SPL_DIAG_KIND_FRAME_OVERFLOW] = "frame_overflow",
[SPL_DIAG_KIND_INTERNAL] = "internal",
};
const char *spl_diag_kind_name(spl_diag_kind_t k) {
if ((usize)k < sizeof(g_kind_names) / sizeof(g_kind_names[0]) && g_kind_names[k])
return g_kind_names[k];
return "unknown";
}
static const char *const g_stage_names[] = {
[SPL_STAGE_NONE] = "none", [SPL_STAGE_LEX] = "lex", [SPL_STAGE_PARSE] = "parse",
[SPL_STAGE_SEMA] = "sema", [SPL_STAGE_AST2IR] = "ast2ir", [SPL_STAGE_IR2VM] = "ir2vm",
[SPL_STAGE_DRIVER] = "driver",
};
const char *spl_diag_stage_name(spl_diag_stage_t s) {
if ((usize)s < sizeof(g_stage_names) / sizeof(g_stage_names[0]) && g_stage_names[s])
return g_stage_names[s];
return "?";
}
const char *spl_diag_level_name(spl_diag_level_t l) {
switch (l) {
case SPL_DIAG_LEVEL_NOTE:
return "note";
case SPL_DIAG_LEVEL_WARN:
return "warn";
case SPL_DIAG_LEVEL_ERROR:
return "error";
case SPL_DIAG_LEVEL_FATAL:
return "fatal";
}
return "?";
}
static const char *level_color(spl_diag_level_t l) {
switch (l) {
case SPL_DIAG_LEVEL_NOTE:
return ANSI_FG_CYAN;
case SPL_DIAG_LEVEL_WARN:
return ANSI_FG_YELLOW;
case SPL_DIAG_LEVEL_ERROR:
return ANSI_FG_RED;
case SPL_DIAG_LEVEL_FATAL:
return ANSI_FG_RED ANSI_UNDERLINED;
}
return ANSI_NONE;
}
static char *diag_strdup(const char *s) {
if (!s)
return NULL;
usize n = strlen(s);
char *r = malloc(n + 1);
if (!r)
return NULL;
memcpy(r, s, n);
r[n] = '\0';
return r;
}
void spl_diag_init(spl_diag_t *d, void *fout) {
memset(d, 0, sizeof *d);
vec_init(d->ctx);
vec_init(d->records);
d->collect = true;
d->fout = fout;
d->color = true;
d->stage = SPL_STAGE_NONE;
}
static void frame_free(spl_diag_frame_t *f) {
free(f->fn_name);
free(f->label);
f->fn_name = NULL;
f->label = NULL;
}
static void record_free(spl_diag_record_t *r) {
free(r->message);
r->message = NULL;
for (usize i = 0; i < vec_size(r->ctx); ++i)
frame_free(&vec_at(r->ctx, i));
vec_free(r->ctx);
for (usize i = 0; i < vec_size(r->notes); ++i)
free(vec_at(r->notes, i).message);
vec_free(r->notes);
}
void spl_diag_reset(spl_diag_t *d) {
for (usize i = 0; i < vec_size(d->ctx); ++i)
frame_free(&vec_at(d->ctx, i));
d->ctx.size = 0;
for (usize i = 0; i < vec_size(d->records); ++i)
record_free(&vec_at(d->records, i));
d->records.size = 0;
d->num_printed = 0;
d->n_errors = 0;
d->n_warns = 0;
d->n_fatals = 0;
}
void spl_diag_drop(spl_diag_t *d) {
spl_diag_reset(d);
vec_free(d->ctx);
vec_free(d->records);
}
void spl_diag_set_stage(spl_diag_t *d, spl_diag_stage_t stage) { d->stage = stage; }
void spl_diag_set_output(spl_diag_t *d, FILE *out) { d->fout = out; }
void spl_diag_set_color(spl_diag_t *d, bool enabled) { d->color = enabled; }
void spl_diag_set_collect(spl_diag_t *d, bool enabled) { d->collect = enabled; }
void spl_diag_push(spl_diag_t *d, const spl_dbg_node_t *loc, const char *fn_name,
const char *label) {
spl_diag_frame_t f = {0};
if (loc)
f.loc = *loc;
f.fn_name = fn_name ? diag_strdup(fn_name) : NULL;
f.label = label ? diag_strdup(label) : NULL;
vec_push(d->ctx, f);
}
void spl_diag_pop(spl_diag_t *d) {
if (vec_size(d->ctx) == 0)
return;
frame_free(&vec_at(d->ctx, vec_size(d->ctx) - 1));
d->ctx.size--;
}
usize spl_diag_depth(const spl_diag_t *d) { return vec_size(d->ctx); }
static spl_diag_frame_vec_t ctx_snapshot(const spl_diag_t *d) {
spl_diag_frame_vec_t snap;
vec_init(snap);
for (usize i = 0; i < vec_size(d->ctx); ++i) {
spl_diag_frame_t *src = &vec_at(d->ctx, i);
spl_diag_frame_t f = {0};
f.loc = src->loc;
f.fn_name = src->fn_name ? diag_strdup(src->fn_name) : NULL;
f.label = src->label ? diag_strdup(src->label) : NULL;
vec_push(snap, f);
}
return snap;
}
static void frame_desc(const spl_diag_frame_t *f, char *buf, usize cap) {
if (f->fn_name && f->label)
snprintf(buf, cap, "%s %s", f->label, f->fn_name);
else if (f->fn_name)
snprintf(buf, cap, "%s", f->fn_name);
else if (f->label)
snprintf(buf, cap, "%s", f->label);
else
snprintf(buf, cap, "?");
}
static void print_loc(FILE *out, const spl_dbg_node_t *loc) {
if (loc && loc->fname)
fprintf(out, "%s:%d:%d", loc->fname, loc->line, loc->col);
else
fprintf(out, "<no-loc>");
}
static void print_record(const spl_diag_t *d, const spl_diag_record_t *r) {
FILE *out = (FILE *)d->fout;
if (!out)
return;
const char *col = d->color ? level_color(r->level) : "";
const char *rst = d->color ? ANSI_NONE : "";
fprintf(out, "%s%s[%s:%s]%s: ", col, spl_diag_level_name(r->level),
spl_diag_stage_name(r->stage), spl_diag_kind_name(r->kind), rst);
print_loc(out, &r->loc);
fputc('\n', out);
fprintf(out, " %s\n", r->message ? r->message : "");
for (usize i = vec_size(r->ctx); i > 0; --i) {
char buf[256];
frame_desc(&vec_at(r->ctx, i - 1), buf, sizeof buf);
fprintf(out, " in %s at ", buf);
print_loc(out, &vec_at(r->ctx, i - 1).loc);
fputc('\n', out);
}
for (usize i = 0; i < vec_size(r->notes); ++i) {
spl_diag_note_t *n = &vec_at(r->notes, i);
const char *ncol = d->color ? ANSI_FG_CYAN : "";
fprintf(out, "%snote%s: ", ncol, rst);
print_loc(out, &n->loc);
fputc('\n', out);
fprintf(out, " %s\n", n->message ? n->message : "");
}
}
static void emit(spl_diag_t *d, spl_diag_level_t level, spl_diag_kind_t kind,
const spl_dbg_node_t *loc, const char *fmt, va_list ap) {
va_list ap2;
va_copy(ap2, ap);
int need = vsnprintf(NULL, 0, fmt, ap);
if (need < 0)
need = 0;
char *msg = malloc((usize)need + 1);
if (msg)
vsnprintf(msg, (usize)need + 1, fmt, ap2);
va_end(ap2);
spl_diag_record_t rec = {0};
rec.level = level;
rec.stage = d->stage;
rec.kind = kind;
if (loc)
rec.loc = *loc;
rec.message = msg;
rec.ctx = ctx_snapshot(d);
vec_init(rec.notes);
if (level == SPL_DIAG_LEVEL_ERROR)
d->n_errors++;
else if (level == SPL_DIAG_LEVEL_FATAL) {
d->n_errors++;
d->n_fatals++;
} else if (level == SPL_DIAG_LEVEL_WARN)
d->n_warns++;
if (d->fout) {
print_record(d, &rec);
d->num_printed++;
}
if (d->collect)
vec_push(d->records, rec);
else
record_free(&rec);
}
void spl_diag_note(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...) {
va_list ap;
va_start(ap, fmt);
emit(d, SPL_DIAG_LEVEL_NOTE, kind, loc, fmt, ap);
va_end(ap);
}
void spl_diag_warn(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...) {
va_list ap;
va_start(ap, fmt);
emit(d, SPL_DIAG_LEVEL_WARN, kind, loc, fmt, ap);
va_end(ap);
}
void spl_diag_error(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...) {
va_list ap;
va_start(ap, fmt);
emit(d, SPL_DIAG_LEVEL_ERROR, kind, loc, fmt, ap);
va_end(ap);
}
void spl_diag_fatal(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...) {
va_list ap;
va_start(ap, fmt);
emit(d, SPL_DIAG_LEVEL_FATAL, kind, loc, fmt, ap);
va_end(ap);
}
void spl_diag_attach_note(spl_diag_t *d, const spl_dbg_node_t *loc, const char *fmt, ...) {
if (vec_size(d->records) == 0)
return;
spl_diag_record_t *last = &vec_at(d->records, vec_size(d->records) - 1);
va_list ap;
va_start(ap, fmt);
int need = vsnprintf(NULL, 0, fmt, ap);
va_end(ap);
if (need < 0)
need = 0;
char *msg = malloc((usize)need + 1);
if (msg) {
va_start(ap, fmt);
vsnprintf(msg, (usize)need + 1, fmt, ap);
va_end(ap);
}
spl_diag_note_t n = {0};
if (loc)
n.loc = *loc;
n.message = msg;
vec_push(last->notes, n);
}
bool spl_diag_has_error(const spl_diag_t *d) { return d->n_errors > 0; }
bool spl_diag_has_fatal(const spl_diag_t *d) { return d->n_fatals > 0; }
usize spl_diag_error_count(const spl_diag_t *d) { return d->n_errors; }
usize spl_diag_warn_count(const spl_diag_t *d) { return d->n_warns; }
void spl_diag_summary(const spl_diag_t *d) {
FILE *out = (FILE *)d->fout;
if (!out)
return;
/* 把还没实时打印过的记录补打一遍。
collect == false 时 records 是空的,num_printed 可能非零,
用 records.size 兜底避免越界。 */
usize printed_limit = d->num_printed;
if (printed_limit > vec_size(d->records))
printed_limit = vec_size(d->records);
for (usize i = printed_limit; i < vec_size(d->records); ++i)
print_record(d, &vec_at(d->records, i));
/* 计数 */
const char *ecol = d->color && d->n_errors > 0 ? ANSI_FG_RED : "";
const char *rst = d->color ? ANSI_NONE : "";
fprintf(out, "%s%zu error%s, %zu warning%s%s\n", ecol, d->n_errors, d->n_errors == 1 ? "" : "s",
d->n_warns, d->n_warns == 1 ? "" : "s", rst);
}
+165
View File
@@ -0,0 +1,165 @@
#ifndef __SPL_DIAG_H__
#define __SPL_DIAG_H__
#include "../stage0/include/utils.h"
#include "spl_dbg.h"
typedef enum {
SPL_DIAG_LEVEL_NOTE = 0,
SPL_DIAG_LEVEL_WARN,
SPL_DIAG_LEVEL_ERROR,
SPL_DIAG_LEVEL_FATAL,
} spl_diag_level_t;
typedef enum {
SPL_STAGE_NONE = 0,
SPL_STAGE_LEX,
SPL_STAGE_PARSE,
SPL_STAGE_SEMA,
SPL_STAGE_AST2IR,
SPL_STAGE_IR2VM,
SPL_STAGE_DRIVER,
} spl_diag_stage_t;
/* kind 枚举:边写边补。新增时放对应分组末尾即可。 */
typedef enum {
SPL_DIAG_KIND_NONE = 0,
/* 词法 / 语法 */
SPL_DIAG_KIND_LEX_UNEXPECTED,
SPL_DIAG_KIND_PARSE_EXPECTED,
SPL_DIAG_KIND_PARSE_UNRECOGNIZED,
/* sema */
SPL_DIAG_KIND_UNDEFINED_SYMBOL,
SPL_DIAG_KIND_DUPLICATE_SYMBOL,
SPL_DIAG_KIND_TYPE_MISMATCH,
SPL_DIAG_KIND_ARG_COUNT_MISMATCH,
SPL_DIAG_KIND_NOT_A_FUNCTION,
SPL_DIAG_KIND_NO_FIELD,
SPL_DIAG_KIND_NO_METHOD,
SPL_DIAG_KIND_INDEX_BASE_INVALID,
SPL_DIAG_KIND_TUPLE_INDEX_OOB,
SPL_DIAG_KIND_FITS_OVERFLOW,
SPL_DIAG_KIND_CIRCULAR_DEP,
SPL_DIAG_KIND_BREAK_OUTSIDE_LOOP,
SPL_DIAG_KIND_CONTINUE_OUTSIDE_LOOP,
SPL_DIAG_KIND_UNDEFINED_LABEL,
SPL_DIAG_KIND_CAST_INVALID,
SPL_DIAG_KIND_UNKNOWN_ATTR,
SPL_DIAG_KIND_UNKNOWN_INTRIN,
SPL_DIAG_KIND_INTRIN_ARG_COUNT,
SPL_DIAG_KIND_VAR_UNINITIALIZED,
SPL_DIAG_KIND_CANNOT_INFER,
SPL_DIAG_KIND_MUST_RETURN_VALUE,
/* ast2ir */
SPL_DIAG_KIND_UNHANDLED_NODE,
SPL_DIAG_KIND_IMPLICIT_CAST_FAIL,
SPL_DIAG_KIND_NO_LVALUE,
SPL_DIAG_KIND_BAD_FIELD_INDEX,
SPL_DIAG_KIND_BAD_BLOCK,
/* ir2vm */
SPL_DIAG_KIND_IR_UNKNOWN_KIND,
SPL_DIAG_KIND_FRAME_OVERFLOW,
/* 通用 */
SPL_DIAG_KIND_INTERNAL,
} spl_diag_kind_t;
typedef struct {
spl_dbg_node_t loc;
char *fn_name;
char *label;
} spl_diag_frame_t;
typedef VEC(spl_diag_frame_t) spl_diag_frame_vec_t;
typedef struct {
spl_dbg_node_t loc;
char *message;
} spl_diag_note_t;
typedef VEC(spl_diag_note_t) spl_diag_note_vec_t;
typedef struct {
spl_diag_level_t level;
spl_diag_stage_t stage;
spl_diag_kind_t kind;
spl_dbg_node_t loc;
char *message;
spl_diag_frame_vec_t ctx;
spl_diag_note_vec_t notes;
} spl_diag_record_t;
typedef VEC(spl_diag_record_t) spl_diag_record_vec_t;
typedef struct spl_diag {
spl_diag_frame_vec_t ctx;
spl_diag_record_vec_t records;
usize num_printed;
bool collect;
usize n_errors;
usize n_warns;
usize n_fatals;
spl_diag_stage_t stage;
void *fout;
bool color;
} spl_diag_t;
void spl_diag_init(spl_diag_t *d, void *fout);
void spl_diag_drop(spl_diag_t *d);
void spl_diag_reset(spl_diag_t *d);
void spl_diag_set_stage(spl_diag_t *d, spl_diag_stage_t stage);
void spl_diag_set_output(spl_diag_t *d, FILE *out);
void spl_diag_set_color(spl_diag_t *d, bool enabled);
void spl_diag_set_collect(spl_diag_t *d, bool enabled);
void spl_diag_push(spl_diag_t *d, const spl_dbg_node_t *loc, const char *fn_name,
const char *label);
void spl_diag_pop(spl_diag_t *d);
usize spl_diag_depth(const spl_diag_t *d);
/* ============================================================
* 发射
*
* 每个级别都生成独立的 spl_diag_record_t:
* - 计入 records(collect=true 时)
* - error/fatal 计入 n_errors,warn 计入 n_warns
* - 立刻输出到 out(如果非 NULL)
*
* 四种级别的语义区别:
* note —— 一般信息;不阻塞;用在前序诊断之外的独立说明
* warn —— 警告;不阻塞;driver 可忽略
* error —— 用户代码错误;调用者应 return 0
* fatal —— 用户代码错误到数据结构已损坏;调用者必须 return 0
* ============================================================ */
void spl_diag_note(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...);
void spl_diag_warn(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...);
void spl_diag_error(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...);
void spl_diag_fatal(spl_diag_t *d, spl_diag_kind_t kind, const spl_dbg_node_t *loc, const char *fmt,
...);
/* 挂到最近一条记录(records 末尾)的 notes 列表下。
* 不生成独立记录、不计入计数,输出时显示为:
* note: <loc>
* <msg>
* 使用场景:辅助说明前一条诊断,例如
* spl_diag_error(d, DUPLICATE_SYMBOL, &n->dbg, "duplicate symbol `foo`");
* spl_diag_attach_note(d, &prev->dbg, "previously defined here");
* 约束:只在 records 非空时生效;否则静默丢弃,不报错。 */
void spl_diag_attach_note(spl_diag_t *d, const spl_dbg_node_t *loc, const char *fmt, ...);
bool spl_diag_has_error(const spl_diag_t *d);
bool spl_diag_has_fatal(const spl_diag_t *d);
usize spl_diag_error_count(const spl_diag_t *d);
usize spl_diag_warn_count(const spl_diag_t *d);
void spl_diag_summary(const spl_diag_t *d);
const char *spl_diag_kind_name(spl_diag_kind_t k);
const char *spl_diag_stage_name(spl_diag_stage_t s);
const char *spl_diag_level_name(spl_diag_level_t l);
#endif /* __SPL_DIAG_H__ */
+26
View File
@@ -0,0 +1,26 @@
/* spl_dumptree.c 可配置的树形打印模块(只用基本 ASCII)*/
#include "spl_dumptree.h"
#include <stdarg.h>
const spl_dumptree_style_t spl_dumptree_ascii_style = {
"| ",
"|-",
"`-",
" ",
};
void spl_dumptree_print(const spl_dumptree_style_t *st, const char *prefix, int is_last,
const char *fmt, ...) {
va_list ap;
printf("%s%s ", prefix, is_last ? st->last_branch : st->branch);
va_start(ap, fmt);
vprintf(fmt, ap);
va_end(ap);
printf("\n");
}
void spl_dumptree_child_prefix(const spl_dumptree_style_t *st, const char *prefix, int is_last,
char *out, size_t cap) {
snprintf(out, cap, "%s%s", prefix, is_last ? st->space : st->vertical);
}
+31
View File
@@ -0,0 +1,31 @@
/* spl_dumptree.h 可配置的树形打印模块(只用基本 ASCII)*/
#ifndef __SPL_DUMPTREE_H__
#define __SPL_DUMPTREE_H__
#include <stddef.h>
#include <stdio.h>
/* 可配置的缩进字符串 */
typedef struct {
const char *vertical; /* "| " */
const char *branch; /* "|-" */
const char *last_branch; /* "`-" */
const char *space; /* " " */
} spl_dumptree_style_t;
/* 默认 ASCII 风格 */
extern const spl_dumptree_style_t spl_dumptree_ascii_style;
/* 打印一行节点标签:prefix + 分支符 + label
* prefix 已累积的缩进骨架(不含分支符)
* is_last 本节点是否为同级最后一个子节点
* fmt printf 风格 label */
void spl_dumptree_print(const spl_dumptree_style_t *st, const char *prefix, int is_last,
const char *fmt, ...);
/* 生成子节点的缩进骨架:parent_prefix + (parent_is_last ? space : vertical) */
void spl_dumptree_child_prefix(const spl_dumptree_style_t *st, const char *prefix, int is_last,
char *out, size_t cap);
#endif /* __SPL_DUMPTREE_H__ */
+4
View File
@@ -0,0 +1,4 @@
#ifndef __SPL_EMIT_H__
#define __SPL_EMIT_H__
#endif /* __SPL_EMIT_H__ */
+34
View File
@@ -0,0 +1,34 @@
#include "spl_fold.h"
static usize spl_fold_bucket_hash(usize k) { return MAP_HASH_INT(k); }
static int spl_fold_bucket_cmp(usize a, usize b) { return MAP_CMP_INT(a, b); }
void spl_fold_init(spl_fold_t *fold, void *ctx, spl_fold_eq_fn eq, spl_fold_next_fn next,
spl_fold_set_next_fn set_next) {
map_init(fold->buckets, spl_fold_bucket_hash, spl_fold_bucket_cmp);
fold->ctx = ctx;
fold->eq = eq;
fold->next = next;
fold->set_next = set_next;
}
void spl_fold_drop(spl_fold_t *fold) { map_free(fold->buckets); }
spl_fold_id_t spl_fold_find(const spl_fold_t *fold, usize hash, const void *probe) {
spl_fold_id_t cur = 0;
if (!map_get(fold->buckets, hash, &cur))
return 0;
while (cur) {
if (fold->eq(fold->ctx, cur, probe))
return cur;
cur = fold->next(fold->ctx, cur);
}
return 0;
}
void spl_fold_insert(spl_fold_t *fold, usize hash, spl_fold_id_t id) {
spl_fold_id_t head = 0;
map_get(fold->buckets, hash, &head);
fold->set_next(fold->ctx, id, head);
map_put(fold->buckets, hash, id);
}
+36
View File
@@ -0,0 +1,36 @@
#ifndef __SPL_FOLD_H__
#define __SPL_FOLD_H__
#include "../stage0/include/utils.h"
/* 通用 intrusive 哈希集合,对应 LLVM FoldingSet 的桶链部分。
- 节点表由调用方持有,节点自带 next 字段;
- hash 只用于选择桶(本实现以完整 hash 值作桶 map 的 key),
相等始终由 eq 回调做结构比较;
- 只增不删,适合类型 intern。 */
typedef usize spl_fold_id_t;
/* 相等返回非零;probe 指向调用方的临时(尚未入表)节点。 */
typedef int (*spl_fold_eq_fn)(void *ctx, spl_fold_id_t node, const void *probe);
typedef spl_fold_id_t (*spl_fold_next_fn)(void *ctx, spl_fold_id_t node);
typedef void (*spl_fold_set_next_fn)(void *ctx, spl_fold_id_t node, spl_fold_id_t next);
typedef struct {
MAP(usize, spl_fold_id_t) buckets;
void *ctx;
spl_fold_eq_fn eq;
spl_fold_next_fn next;
spl_fold_set_next_fn set_next;
} spl_fold_t;
void spl_fold_init(spl_fold_t *fold, void *ctx, spl_fold_eq_fn eq, spl_fold_next_fn next,
spl_fold_set_next_fn set_next);
void spl_fold_drop(spl_fold_t *fold);
/* 命中返回已存在的 id,否则返回 0。 */
spl_fold_id_t spl_fold_find(const spl_fold_t *fold, usize hash, const void *probe);
/* 把已分配 id 的节点挂到对应桶头。 */
void spl_fold_insert(spl_fold_t *fold, usize hash, spl_fold_id_t id);
#endif /* __SPL_FOLD_H__ */
+108
View File
@@ -0,0 +1,108 @@
#include "spl_intrin.h"
static const spl_intrin_info_t g_intrin_table[] = {
[SPL_INTRIN_NONE] = {0},
[SPL_INTRIN_BITSIZEOF] = {"@bitsizeof", SPL_INTRIN_BITSIZEOF, SPL_INTRIN_FORM_CALL, 1, 1,
SPL_INTRIN_RESULT_USIZE},
[SPL_INTRIN_SIZEOF] = {"@sizeof", SPL_INTRIN_SIZEOF, SPL_INTRIN_FORM_CALL, 1, 1,
SPL_INTRIN_RESULT_USIZE},
[SPL_INTRIN_ALIGNOF] = {"@alignof", SPL_INTRIN_ALIGNOF, SPL_INTRIN_FORM_CALL, 1, 1,
SPL_INTRIN_RESULT_USIZE},
[SPL_INTRIN_ASSERT] = {"@assert", SPL_INTRIN_ASSERT, SPL_INTRIN_FORM_CALL, 1, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_BREAKPOINT] = {"@breakpoint", SPL_INTRIN_BREAKPOINT, SPL_INTRIN_FORM_CALL, 0, 0,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_LEN] = {"len", SPL_INTRIN_LEN, SPL_INTRIN_FORM_FIELD, 0, 0,
SPL_INTRIN_RESULT_USIZE},
[SPL_INTRIN_INT_CAST] = {"@int_cast", SPL_INTRIN_INT_CAST, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_TRUNCATE] = {"@truncate", SPL_INTRIN_TRUNCATE, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_BIT_CAST] = {"@bit_cast", SPL_INTRIN_BIT_CAST, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_FLOAT_CAST] = {"@float_cast", SPL_INTRIN_FLOAT_CAST, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_FLOAT2INT] = {"@float2int", SPL_INTRIN_FLOAT2INT, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_INT2FLOAT] = {"@int2float", SPL_INTRIN_INT2FLOAT, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_BOOL2INT] = {"@bool2int", SPL_INTRIN_BOOL2INT, SPL_INTRIN_FORM_CALL, 1, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_PTR2INT] = {"@ptr2int", SPL_INTRIN_PTR2INT, SPL_INTRIN_FORM_CALL, 1, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_INT2PTR] = {"@int2ptr", SPL_INTRIN_INT2PTR, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_PTR_CAST] = {"@ptr_cast", SPL_INTRIN_PTR_CAST, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_UNIT},
[SPL_INTRIN_ENUM2INT] = {"@enum2int", SPL_INTRIN_ENUM2INT, SPL_INTRIN_FORM_CALL, 1, 1,
SPL_INTRIN_RESULT_USIZE},
[SPL_INTRIN_OFFSETOF] = {"@offsetof", SPL_INTRIN_OFFSETOF, SPL_INTRIN_FORM_CALL, 2, 2,
SPL_INTRIN_RESULT_USIZE},
[SPL_INTRIN_FIELD_COUNT] = {"@field_count", SPL_INTRIN_FIELD_COUNT, SPL_INTRIN_FORM_CALL, 1, 1,
SPL_INTRIN_RESULT_USIZE},
};
static const usize g_intrin_count = sizeof(g_intrin_table) / sizeof(g_intrin_table[0]);
const spl_intrin_info_t *spl_intrin_info(spl_intrin_t kind) {
if ((usize)kind >= g_intrin_count)
return NULL;
return &g_intrin_table[kind];
}
spl_intrin_t spl_intrin_lookup_call(const char *name) {
if (!name)
return SPL_INTRIN_NONE;
const char *n = name[0] == '@' ? name + 1 : name;
for (usize i = 1; i < g_intrin_count; ++i) {
const spl_intrin_info_t *d = &g_intrin_table[i];
if (d->form != SPL_INTRIN_FORM_CALL)
continue;
const char *dn = d->name[0] == '@' ? d->name + 1 : d->name;
if (strcmp(dn, n) == 0)
return d->kind;
}
return SPL_INTRIN_NONE;
}
spl_intrin_t spl_intrin_lookup_field(spl_lang_type_kind_t recv_kind, const char *field) {
if (!field)
return SPL_INTRIN_NONE;
if (strcmp(field, "len") == 0) {
if (recv_kind == SPL_LANG_TYPE_ARRAY || recv_kind == SPL_LANG_TYPE_SLICE)
return SPL_INTRIN_LEN;
}
return SPL_INTRIN_NONE;
}
spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type_id_t tt) {
/* 这是 `as` 的展开规则表。要调整 as 的语义,改这里。 */
spl_type_node_t *f = spl_type_node(type, ft);
spl_type_node_t *t = spl_type_node(type, tt);
if (!f || !t)
return SPL_INTRIN_NONE;
if (f->kind == SPL_TYPE_INT && t->kind == SPL_TYPE_INT) {
usize fb = f->int_type.bits;
usize tb = t->int_type.bits;
if (fb == tb)
return SPL_INTRIN_BIT_CAST;
if (fb > tb)
return SPL_INTRIN_TRUNCATE;
return SPL_INTRIN_INT_CAST;
}
if (f->kind == SPL_TYPE_FLOAT && t->kind == SPL_TYPE_FLOAT)
return SPL_INTRIN_FLOAT_CAST;
if (f->kind == SPL_TYPE_BOOL && t->kind == SPL_TYPE_INT)
return SPL_INTRIN_BOOL2INT;
if (f->kind == SPL_TYPE_PTR && t->kind == SPL_TYPE_INT)
return SPL_INTRIN_PTR2INT;
if (f->kind == SPL_TYPE_INT && t->kind == SPL_TYPE_PTR)
return SPL_INTRIN_INT2PTR;
if (f->kind == SPL_TYPE_PTR && t->kind == SPL_TYPE_PTR)
return SPL_INTRIN_PTR_CAST;
/* int float 刻意不在这里:只能通过显式 builtin 调用。
enum<->int 也刻意禁止(用 @enum2int 取 tag)。 */
return SPL_INTRIN_NONE;
}
+60
View File
@@ -0,0 +1,60 @@
#ifndef __SPL_INTRIN_H__
#define __SPL_INTRIN_H__
#include "../stage0/include/utils.h"
#include "spl_lang_type.h"
typedef enum {
SPL_INTRIN_NONE = 0,
SPL_INTRIN_BITSIZEOF,
SPL_INTRIN_SIZEOF,
SPL_INTRIN_ALIGNOF,
SPL_INTRIN_ASSERT,
SPL_INTRIN_BREAKPOINT,
SPL_INTRIN_LEN,
SPL_INTRIN_INT_CAST,
SPL_INTRIN_TRUNCATE,
SPL_INTRIN_BIT_CAST,
SPL_INTRIN_FLOAT_CAST,
SPL_INTRIN_FLOAT2INT,
SPL_INTRIN_INT2FLOAT,
SPL_INTRIN_BOOL2INT,
SPL_INTRIN_PTR2INT,
SPL_INTRIN_INT2PTR,
SPL_INTRIN_PTR_CAST,
SPL_INTRIN_ENUM2INT,
SPL_INTRIN_OFFSETOF,
SPL_INTRIN_FIELD_COUNT,
} spl_intrin_t;
typedef enum {
SPL_INTRIN_FORM_CALL = 1, /* @sizeof(...) @assert(...) */
SPL_INTRIN_FORM_FIELD = 2, /* recv.len */
} spl_intrin_form_t;
typedef enum {
SPL_INTRIN_RESULT_UNIT,
SPL_INTRIN_RESULT_BOOL,
SPL_INTRIN_RESULT_USIZE,
} spl_intrin_result_t;
typedef struct {
const char *name;
spl_intrin_t kind;
spl_intrin_form_t form;
int min_args; /* FIELD 形态忽略 */
int max_args; /* -1 = variadic */
spl_intrin_result_t result;
} spl_intrin_info_t;
spl_intrin_t spl_intrin_lookup_call(const char *name);
spl_intrin_t spl_intrin_lookup_field(spl_lang_type_kind_t recv_kind, const char *field);
spl_intrin_t spl_intrin_lookup_cast(spl_type_t *type, spl_type_id_t ft, spl_type_id_t tt);
const spl_intrin_info_t *spl_intrin_info(spl_intrin_t kind);
/* ---- 与 IR 侧共享的类型布局约定 ---- */
#define SPL_SLICE_PTR_FIELD_IDX 0
#define SPL_SLICE_LEN_FIELD_IDX 1
#endif /* __SPL_INTRIN_H__ */
+847
View File
@@ -0,0 +1,847 @@
#include "spl_ir.h"
const char *spl_ir_kind_name(spl_ir_kind_t kind) {
static const char *const names[] = {
#define X(a, b, c) #a,
SPL_IR_FN_TABLE
#undef X
};
if ((usize)kind < sizeof(names) / sizeof(names[0]))
return names[kind];
return "?";
}
void spl_ir_init(spl_ir_t *ir) {
vec_init(ir->funcs);
vec_push(ir->funcs, (spl_ir_func_t){0});
// vec_init(ir->gdata);
// vec_push(ir->gdata, (spl_ir_node_t){0});
}
static void node_drop_vecs(spl_ir_node_t *n) {
if (!n)
return;
switch (n->kind) {
case SPL_IR_AGG_CONSTRUCT:
vec_free(n->agg_construct.fields);
break;
case SPL_IR_CONTROL_CALL:
vec_free(n->control_call.params);
break;
case SPL_IR_DBG_PANIC:
free((char *)n->dbg_panic.msg);
break;
default:
break;
}
}
void spl_ir_drop(spl_ir_t *ir) {
vec_for(ir->funcs, i) {
spl_ir_func_t *f = &vec_at(ir->funcs, i);
vec_for(f->nodes, j) {
vec_free(vec_at(f->nodes, j).attrs);
node_drop_vecs(&vec_at(f->nodes, j));
}
vec_free(f->attrs);
vec_free(f->nodes);
}
vec_free(ir->funcs);
// vec_for(ir->gdata, i) { node_drop_vecs(&vec_at(ir->gdata, i)); }
// vec_free(ir->gdata);
}
// 申请空的 ir_func 返回 id
spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir) {
if (ir == NULL) {
return 0;
}
spl_ir_func_t f = {0};
vec_init(f.nodes);
vec_push(f.nodes, (spl_ir_node_t){0});
vec_push(ir->funcs, f);
return vec_size(ir->funcs) - 1;
}
// 从 fn_id 申请空的 ir_node 返回 id
spl_ir_node_ref_t spl_ir_alloc_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id) {
if (!fn_id || fn_id >= vec_size(ir->funcs)) {
return 0;
}
spl_ir_func_t *f = &vec_at(ir->funcs, fn_id);
spl_ir_node_t n = {0};
vec_push(f->nodes, n);
return vec_size(f->nodes) - 1;
}
// 从 fn_id 里通过 node_id 获取 ir_node
spl_ir_node_t *spl_ir_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_node_ref_t node_id) {
if (!fn_id || fn_id >= vec_size(ir->funcs)) {
return NULL;
}
spl_ir_func_t *f = &vec_at(ir->funcs, fn_id);
if (!node_id || node_id >= vec_size(f->nodes)) {
return NULL;
}
return &vec_at(f->nodes, node_id);
}
// 从 fn_id 获取 ir_func
spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id) {
if (!fn_id || fn_id >= vec_size(ir->funcs)) {
return NULL;
}
return &vec_at(ir->funcs, fn_id);
}
static inline void ir_dump_type(const spl_type_t *ty, spl_type_id_t tid) {
printf("(");
spl_type_pure_dump((spl_type_t *)ty, tid);
printf(")");
}
static inline void ir_dump_ref(spl_ir_node_ref_t ref) {
if (ref == 0) {
printf(" _");
} else {
printf(" %%%zu", ref);
}
}
static void ir_dump_node(const spl_type_t *ty, spl_ir_node_t *n) {
switch (n->kind) {
case SPL_IR_ARITH_ADD:
case SPL_IR_ARITH_SUB:
case SPL_IR_ARITH_MUL:
case SPL_IR_ARITH_DIV:
case SPL_IR_ARITH_REM:
case SPL_IR_ARITH_AND:
case SPL_IR_ARITH_OR:
case SPL_IR_ARITH_XOR:
case SPL_IR_ARITH_SHL:
case SPL_IR_ARITH_SHR:
ir_dump_type(ty, n->arith.tid);
ir_dump_ref(n->arith.left);
ir_dump_ref(n->arith.right);
break;
case SPL_IR_ARITH_NEG:
case SPL_IR_ARITH_ABS:
case SPL_IR_ARITH_NOT:
ir_dump_type(ty, n->arith.tid);
ir_dump_ref(n->arith.left);
break;
case SPL_IR_CMP_EQ:
case SPL_IR_CMP_NE:
case SPL_IR_CMP_LT:
case SPL_IR_CMP_LE:
case SPL_IR_CMP_GT:
case SPL_IR_CMP_GE:
ir_dump_type(ty, n->cmp.tid);
ir_dump_ref(n->cmp.a);
ir_dump_ref(n->cmp.b);
break;
case SPL_IR_CAST_TRUNC:
case SPL_IR_CAST_ZEXT:
case SPL_IR_CAST_SEXT:
case SPL_IR_CAST_FEXT:
case SPL_IR_CAST_FTRUNC:
case SPL_IR_CAST_BITCAST:
case SPL_IR_CAST_PTR2INT:
case SPL_IR_CAST_INT2PTR:
case SPL_IR_CAST_BOOL2INT:
case SPL_IR_CASE_INT2FLOAT:
case SPL_IR_CASE_FLOAT2INT:
printf(" ");
spl_type_pure_dump((spl_type_t *)ty, n->cast.from_tid);
printf(" -> ");
spl_type_pure_dump((spl_type_t *)ty, n->cast.to_tid);
ir_dump_ref(n->cast.val);
break;
case SPL_IR_MEM_ALLOCA:
ir_dump_type(ty, n->mem_alloc.tid);
ir_dump_ref(n->mem_alloc.count);
break;
case SPL_IR_MEM_GLOBAL_ALLOC:
ir_dump_type(ty, n->mem_global_alloc.tid);
printf(" g#%zu", n->mem_global_alloc.const_node);
break;
case SPL_IR_MEM_LOAD:
ir_dump_type(ty, n->mem_load.tid);
ir_dump_ref(n->mem_load.ptr);
break;
case SPL_IR_MEM_STORE:
ir_dump_type(ty, n->mem_store.tid);
ir_dump_ref(n->mem_store.ptr);
ir_dump_ref(n->mem_store.val);
break;
case SPL_IR_MEM_OFFSET:
ir_dump_type(ty, n->mem_offset.tid);
ir_dump_ref(n->mem_offset.ptr);
ir_dump_ref(n->mem_offset.offset);
break;
case SPL_IR_MEM_FIELD_PTR:
ir_dump_type(ty, n->mem_field_ptr.tid);
ir_dump_ref(n->mem_field_ptr.agg);
printf(" #%zu", n->mem_field_ptr.field_idx);
break;
case SPL_IR_MEM_COPY:
ir_dump_type(ty, n->mem_copy.tid);
ir_dump_ref(n->mem_copy.dst);
ir_dump_ref(n->mem_copy.src);
ir_dump_ref(n->mem_copy.size);
break;
case SPL_IR_MEM_SET:
ir_dump_type(ty, n->mem_set.tid);
ir_dump_ref(n->mem_set.dst);
ir_dump_ref(n->mem_set.val);
ir_dump_ref(n->mem_set.size);
break;
case SPL_IR_TYPE_CONST: {
ir_dump_type(ty, n->type_const.tid);
spl_type_node_t *t = spl_type_node((spl_type_t *)ty, n->type_const.tid);
if (t && t->kind == SPL_TYPE_FLOAT) {
printf(" float=%f", n->type_const.float_lit);
} else if (t && t->kind == SPL_TYPE_FN) {
printf(" fn#%zu", n->type_const.fn);
// } else if (t && t->kind == SPL_TYPE_PTR) {
// printf(" str=\"%s\"", n->type_const.cstr_lit ? n->type_const.cstr_lit : "?");
} else if (t && t->kind == SPL_TYPE_INT && t->int_type.bits == 8) {
printf(" char='%c'", n->type_const.ch_lit);
} else {
printf(" int=%zu", n->type_const.int_lit);
}
break;
}
case SPL_IR_TYPE_BITSIZEOF:
ir_dump_type(ty, n->bitsizeof.tid);
break;
case SPL_IR_TYPE_SIZEOF:
ir_dump_type(ty, n->ir_sizeof.tid);
break;
case SPL_IR_TYPE_ALIGNOF:
ir_dump_type(ty, n->ir_alignof.tid);
break;
case SPL_IR_TYPE_OFFSETOF:
ir_dump_type(ty, n->ir_offsetof.tid);
ir_dump_ref(n->ir_offsetof.field_idx);
break;
case SPL_IR_TYPE_FIELD_COUNT:
ir_dump_type(ty, n->field_count.tid);
break;
case SPL_IR_AGG_CONSTRUCT:
ir_dump_type(ty, n->agg_construct.tid);
vec_for(n->agg_construct.fields, i) ir_dump_ref(vec_at(n->agg_construct.fields, i));
break;
case SPL_IR_AGG_EXTRACT:
ir_dump_type(ty, n->agg_extract.tid);
printf(" #%zu", n->agg_extract.field_idx);
ir_dump_ref(n->agg_extract.val);
break;
case SPL_IR_AGG_INSERT:
ir_dump_type(ty, n->agg_insert.tid);
printf(" #%zu", n->agg_insert.field_idx);
ir_dump_ref(n->agg_insert.agg);
ir_dump_ref(n->agg_insert.field);
break;
case SPL_IR_CONTROL_SELECT:
ir_dump_type(ty, n->control_select.tid);
ir_dump_ref(n->control_select.cond);
ir_dump_ref(n->control_select.true_val);
ir_dump_ref(n->control_select.false_val);
break;
case SPL_IR_CONTROL_BR:
ir_dump_ref(n->control_br.cond);
ir_dump_ref(n->control_br.true_label);
ir_dump_ref(n->control_br.false_label);
break;
case SPL_IR_CONTROL_JMP:
ir_dump_ref(n->control_jmp.label);
break;
case SPL_IR_CONTROL_CALL:
ir_dump_type(ty, n->control_call.tid);
ir_dump_ref(n->control_call.func);
vec_for(n->control_call.params, i) ir_dump_ref(vec_at(n->control_call.params, i));
break;
case SPL_IR_CONTROL_PARAM:
ir_dump_type(ty, n->control_param.tid);
ir_dump_ref(n->control_param.idx);
break;
case SPL_IR_CONTROL_RET:
ir_dump_type(ty, n->control_ret.tid);
ir_dump_ref(n->control_ret.val);
break;
case SPL_IR_CONTROL_UNREACHABLE:
case SPL_IR_CONTROL_TRAP:
case SPL_IR_DBG_BREAKPOINT:
break;
case SPL_IR_DBG_PANIC:
printf(" \"%.*s\"", (int)n->dbg_panic.len, n->dbg_panic.msg);
break;
}
}
static void ir_dump_attr_list(const spl_attr_t *attr, spl_attr_id_vec_t *ids) {
if (!attr || !ids || vec_size(*ids) == 0)
return;
printf(" attrs=[");
for (usize i = 0; i < vec_size(*ids); ++i) {
if (i > 0)
printf(", ");
spl_attr_dump_id(attr, vec_at(*ids, i));
}
printf("]");
}
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty, const spl_attr_t *attr) {
vec_for(ir->funcs, i) {
if (i == 0)
continue;
spl_ir_func_t *func = &vec_at(ir->funcs, i);
printf("func %s %%%zu", func->name ? func->name : "?", i);
printf(" tid = ");
spl_type_pure_dump((spl_type_t *)ty, func->fn_tid);
ir_dump_attr_list(attr, &func->attrs);
printf("\n");
vec_for(func->nodes, j) {
if (j == 0)
continue;
spl_ir_node_t *node = &vec_at(func->nodes, j);
printf(" #%zu ", j);
printf("%s", spl_ir_kind_name(node->kind));
ir_dump_node(ty, node);
ir_dump_attr_list(attr, &node->attrs);
printf("\n");
}
}
// if (vec_size(ir->gdata) > 1) {
// printf("gdata:\n");
// vec_for(ir->gdata, i) {
// if (i == 0)
// continue;
// spl_ir_node_t *node = &vec_at(ir->gdata, i);
// printf(" #%zu ", i);
// printf("%s", spl_ir_kind_name(node->kind));
// ir_dump_node(ty, node);
// printf("\n");
// }
// }
}
// IR Builder
// 从当前 fn 申请新的 node 并注入到当前基本块
static spl_ir_node_ref_t builder_alloc_node(spl_ir_builder_t *b, spl_ir_kind_t kind) {
Assert(!b->terminated && "emit into a terminated block");
spl_ir_node_ref_t ref = spl_ir_alloc_node(&b->ir, b->current_fn);
Assert(ref != 0);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->kind = kind;
n->dbg = b->dbg;
vec_init(n->attrs);
if (b->current_block >= vec_size(b->blocks)) {
Panic("unknown bblock");
return 0;
}
spl_ir_node_ref_t *slot = &vec_at(b->blocks, b->current_block);
if (*slot == 0)
*slot = ref;
return ref;
}
void spl_ir_builder_init(spl_ir_builder_t *b) {
spl_ir_init(&b->ir);
b->current_fn = 0;
b->dbg = (spl_dbg_node_t){0};
vec_init(b->blocks);
b->current_block = 0;
vec_init(b->fixups);
b->terminated = false;
}
void spl_ir_builder_drop(spl_ir_builder_t *b) {
spl_ir_drop(&b->ir);
vec_free(b->blocks);
vec_free(b->fixups);
}
spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid) {
if (b->current_fn) {
spl_ir_builder_fn_end(b);
}
spl_ir_func_ref_t fid = spl_ir_alloc_fn(&b->ir);
spl_ir_func_t *f = spl_ir_func(&b->ir, fid);
f->name = name;
vec_init(f->attrs);
f->fn_tid = fn_tid;
b->current_fn = fid;
b->current_block = 0;
b->blocks.size = 0;
b->fixups.size = 0;
b->terminated = false;
return fid;
}
spl_ir_func_ref_t spl_ir_builder_fn_reserve(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid) {
spl_ir_func_ref_t fid = spl_ir_alloc_fn(&b->ir);
spl_ir_func_t *f = spl_ir_func(&b->ir, fid);
f->name = name;
vec_init(f->attrs);
f->fn_tid = fn_tid;
return fid;
}
void spl_ir_builder_fn_begin_at(spl_ir_builder_t *b, spl_ir_func_ref_t fid) {
if (b->current_fn && b->current_fn != fid) {
spl_ir_builder_fn_end(b);
}
b->current_fn = fid;
b->current_block = 0;
b->blocks.size = 0;
b->fixups.size = 0;
b->terminated = false;
}
void spl_ir_builder_fn_end(spl_ir_builder_t *b) {
spl_ir_func_t *f = spl_ir_func(&b->ir, b->current_fn);
if (!f) {
Panic("ir func not found");
return;
}
vec_for(b->fixups, i) {
spl_ir_fix_t *fx = &vec_at(b->fixups, i);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, fx->node);
if (!n) {
SPL_ERROR(&n->dbg, "unknown node in func");
continue;
}
spl_ir_node_ref_t target = 0;
if (fx->block < vec_size(b->blocks)) {
target = vec_at(b->blocks, fx->block);
}
if (target == 0) {
Panic("reloc to empty/unknown bblock #%zu", fx->block);
}
switch (fx->slot) {
case SPL_IR_FIX_BR_TRUE:
n->control_br.true_label = target;
break;
case SPL_IR_FIX_BR_FALSE:
n->control_br.false_label = target;
break;
case SPL_IR_FIX_JMP:
n->control_jmp.label = target;
break;
}
}
b->current_block = 0;
b->blocks.size = 0;
b->fixups.size = 0;
b->terminated = false;
}
usize spl_ir_builder_block_begin(spl_ir_builder_t *b) {
vec_push(b->blocks, (spl_ir_block_t){0});
usize block = vec_size(b->blocks) - 1;
b->current_block = block;
b->terminated = false;
return block;
}
void spl_ir_builder_block_end(spl_ir_builder_t *b) {
if (!b->terminated) {
Panic("bblock must be end of terminated");
}
if (b->current_block != 0 && b->current_block < vec_size(b->blocks) &&
vec_at(b->blocks, b->current_block) == 0) {
Panic("bblock #%zu is empty (no entry node emitted)", b->current_block);
}
}
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_left, spl_ir_node_ref_t x_right) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->arith.tid = x_tid; \
n->arith.left = x_left; \
n->arith.right = x_right; \
return ref; \
}
SPL_IR_BIN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_val) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->arith.tid = x_tid; \
n->arith.left = x_val; \
n->arith.right = 0; \
return ref; \
}
SPL_IR_UN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_tid, \
spl_ir_node_ref_t x_a, spl_ir_node_ref_t x_b) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->cmp.tid = x_tid; \
n->cmp.a = x_a; \
n->cmp.b = x_b; \
return ref; \
}
SPL_IR_CMP_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t x_from, \
spl_type_id_t x_to, spl_ir_node_ref_t x_val) { \
spl_ir_node_ref_t ref = builder_alloc_node(builder, kind); \
spl_ir_node_t *n = spl_ir_node(&builder->ir, builder->current_fn, ref); \
n->cast.from_tid = x_from; \
n->cast.to_tid = x_to; \
n->cast.val = x_val; \
return ref; \
}
SPL_IR_CAST_TABLE
#undef X
spl_ir_node_ref_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t count) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_ALLOCA);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_alloc.tid = tid;
n->mem_alloc.count = count;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_global_alloc(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t const_node) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_GLOBAL_ALLOC);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_global_alloc.tid = tid;
n->mem_global_alloc.const_node = const_node;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_LOAD);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_load.tid = tid;
n->mem_load.ptr = ptr;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_STORE);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_store.tid = tid;
n->mem_store.ptr = ptr;
n->mem_store.val = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t offset) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_OFFSET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_offset.tid = tid;
n->mem_offset.ptr = ptr;
n->mem_offset.offset = offset;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t agg, usize field_idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_FIELD_PTR);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_field_ptr.tid = tid;
n->mem_field_ptr.agg = agg;
n->mem_field_ptr.field_idx = field_idx;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t src,
spl_ir_node_ref_t size) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_COPY);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_copy.tid = tid;
n->mem_copy.dst = dst;
n->mem_copy.src = src;
n->mem_copy.size = size;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t val,
spl_ir_node_ref_t size) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_MEM_SET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->mem_set.tid = tid;
n->mem_set.dst = dst;
n->mem_set.val = val;
n->mem_set.size = size;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_bool(spl_ir_builder_t *b, spl_type_id_t tid, bool val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.bool_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_ptr(spl_ir_builder_t *b, spl_type_id_t tid, void *val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ptr_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_int(spl_ir_builder_t *b, spl_type_id_t tid, usize val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.int_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_float(spl_ir_builder_t *b, spl_type_id_t tid,
double val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.float_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_bytes(spl_ir_builder_t *b, spl_type_id_t tid,
const void *data, usize len) {
(void)len;
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ptr_lit = (void *)data;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_char(spl_ir_builder_t *b, spl_type_id_t tid, char val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.ch_lit = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_const_fn(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_func_ref_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_CONST);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->type_const.tid = tid;
n->type_const.fn = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_BITSIZEOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->bitsizeof.tid = tid;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_SIZEOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_sizeof.tid = tid;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_ALIGNOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_alignof.tid = tid;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t field_idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_OFFSETOF);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->ir_offsetof.tid = tid;
n->ir_offsetof.field_idx = field_idx;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_TYPE_FIELD_COUNT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->field_count.tid = tid;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_t tid) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_CONSTRUCT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_construct.tid = tid;
vec_init(n->agg_construct.fields);
return ref;
}
void spl_ir_builder_agg_construct_field(spl_ir_builder_t *b, spl_ir_node_ref_t node,
spl_ir_node_ref_t field) {
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, node);
Assert(n != NULL);
vec_push(n->agg_construct.fields, field);
}
spl_ir_node_ref_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_type_id_t tid,
spl_type_id_t field_tid, usize field_idx,
spl_ir_node_ref_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_EXTRACT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_extract.tid = tid;
n->agg_extract.field_tid = field_tid;
n->agg_extract.field_idx = field_idx;
n->agg_extract.val = val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_type_id_t tid, usize field_idx,
spl_ir_node_ref_t agg, spl_ir_node_ref_t field) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_AGG_INSERT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->agg_insert.tid = tid;
n->agg_insert.field_idx = field_idx;
n->agg_insert.agg = agg;
n->agg_insert.field = field;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t cond, spl_ir_node_ref_t true_val,
spl_ir_node_ref_t false_val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_SELECT);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_select.tid = tid;
n->control_select.cond = cond;
n->control_select.true_val = true_val;
n->control_select.false_val = false_val;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_node_ref_t cond) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_BR);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_br.cond = cond;
n->control_br.true_label = 0;
n->control_br.false_label = 0;
b->terminated = true;
return ref;
}
void spl_ir_builder_control_br_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref, usize true_block,
usize false_block) {
spl_ir_node_t *node = spl_ir_node(&b->ir, b->current_fn, ref);
if (!(node && node->kind == SPL_IR_CONTROL_BR)) {
Panic("fixup must be valid jmp ir node");
}
spl_ir_fix_t f1 = {.node = ref, .slot = SPL_IR_FIX_BR_TRUE, .block = true_block};
vec_push(b->fixups, f1);
spl_ir_fix_t f2 = {.node = ref, .slot = SPL_IR_FIX_BR_FALSE, .block = false_block};
vec_push(b->fixups, f2);
}
spl_ir_node_ref_t spl_ir_builder_control_jmp(spl_ir_builder_t *b) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_JMP);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_jmp.label = 0;
b->terminated = true;
return ref;
}
void spl_ir_builder_control_jmp_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref,
usize target_block) {
spl_ir_node_t *node = spl_ir_node(&b->ir, b->current_fn, ref);
if (!(node && node->kind == SPL_IR_CONTROL_JMP)) {
Panic("fixup must be valid jmp ir node");
}
spl_ir_fix_t fx = {.node = ref, .slot = SPL_IR_FIX_JMP, .block = target_block};
vec_push(b->fixups, fx);
}
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t func) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_CALL);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_call.tid = tid;
n->control_call.func = func;
vec_init(n->control_call.params);
return ref;
}
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t call_node,
spl_ir_node_ref_t arg) {
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, call_node);
Assert(n != NULL);
vec_push(n->control_call.params, arg);
}
spl_ir_node_ref_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t idx) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_PARAM);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_param.tid = tid;
n->control_param.idx = idx;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t val) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_RET);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->control_ret.tid = tid;
n->control_ret.val = val;
b->terminated = true;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_control_unreachable(spl_ir_builder_t *b) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_UNREACHABLE);
b->terminated = true;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_control_trap(spl_ir_builder_t *b) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_CONTROL_TRAP);
b->terminated = true;
return ref;
}
spl_ir_node_ref_t spl_ir_builder_dbg_breakpoint(spl_ir_builder_t *b) {
return builder_alloc_node(b, SPL_IR_DBG_BREAKPOINT);
}
spl_ir_node_ref_t spl_ir_builder_dbg_panic(spl_ir_builder_t *b, const char *msg, usize len) {
spl_ir_node_ref_t ref = builder_alloc_node(b, SPL_IR_DBG_PANIC);
spl_ir_node_t *n = spl_ir_node(&b->ir, b->current_fn, ref);
n->dbg_panic.msg = msg;
n->dbg_panic.len = len;
return ref;
}
+424
View File
@@ -0,0 +1,424 @@
#ifndef __SPL_IR_H__
#define __SPL_IR_H__
#include "../stage0/include/utils.h"
#include "spl_attr.h"
#include "spl_dbg.h"
#include "spl_type.h"
/* clang-format off */
#define SPL_IR_FN_TABLE \
X(arith.add, V0, SPL_IR_ARITH_ADD) \
X(arith.sub, V0, SPL_IR_ARITH_SUB) \
X(arith.mul, V0, SPL_IR_ARITH_MUL) \
X(arith.div, V0, SPL_IR_ARITH_DIV) \
X(arith.rem, V0, SPL_IR_ARITH_REM) \
X(arith.neg, V0, SPL_IR_ARITH_NEG) \
X(arith.abs, V0, SPL_IR_ARITH_ABS) \
X(arith.and, V0, SPL_IR_ARITH_AND) \
X(arith.or, V0, SPL_IR_ARITH_OR) \
X(arith.xor, V0, SPL_IR_ARITH_XOR) \
X(arith.shl, V0, SPL_IR_ARITH_SHL) \
X(arith.shr, V0, SPL_IR_ARITH_SHR) \
X(arith.not, V0, SPL_IR_ARITH_NOT) \
X(cmp.eq, V0, SPL_IR_CMP_EQ) \
X(cmp.ne, V0, SPL_IR_CMP_NE) \
X(cmp.lt, V0, SPL_IR_CMP_LT) \
X(cmp.le, V0, SPL_IR_CMP_LE) \
X(cmp.gt, V0, SPL_IR_CMP_GT) \
X(cmp.ge, V0, SPL_IR_CMP_GE) \
X(cast.trunc, V0, SPL_IR_CAST_TRUNC) \
X(cast.zext, V0, SPL_IR_CAST_ZEXT) \
X(cast.sext, V0, SPL_IR_CAST_SEXT) \
X(cast.fext, V0, SPL_IR_CAST_FEXT) \
X(cast.ftrunc, V0, SPL_IR_CAST_FTRUNC) \
X(cast.bitcast, V0, SPL_IR_CAST_BITCAST) \
X(cast.ptr2int, V0, SPL_IR_CAST_PTR2INT) \
X(cast.int2ptr, V0, SPL_IR_CAST_INT2PTR) \
X(cast.bool2int, V0, SPL_IR_CAST_BOOL2INT) \
X(case.int2float, V0, SPL_IR_CASE_INT2FLOAT) \
X(case.float2int, V0, SPL_IR_CASE_FLOAT2INT) \
X(mem.alloca, V0, SPL_IR_MEM_ALLOCA) \
X(mem.global_alloc, V0, SPL_IR_MEM_GLOBAL_ALLOC) \
X(mem.load, V0, SPL_IR_MEM_LOAD) \
X(mem.store, V0, SPL_IR_MEM_STORE) \
X(mem.offset, V0, SPL_IR_MEM_OFFSET) \
X(mem.field, V0, SPL_IR_MEM_FIELD_PTR) \
X(mem.copy, V0, SPL_IR_MEM_COPY) \
X(mem.set, V0, SPL_IR_MEM_SET) \
X(type.const, V0, SPL_IR_TYPE_CONST) \
X(type.bitsizeof, V0, SPL_IR_TYPE_BITSIZEOF) \
X(type.sizeof, V0, SPL_IR_TYPE_SIZEOF) \
X(type.alignof, V0, SPL_IR_TYPE_ALIGNOF) \
X(type.offsetof, V0, SPL_IR_TYPE_OFFSETOF) \
X(type.field_count, V0, SPL_IR_TYPE_FIELD_COUNT) \
X(agg.construct, V0, SPL_IR_AGG_CONSTRUCT) \
X(agg.extract, V0, SPL_IR_AGG_EXTRACT) \
X(agg.insert, V0, SPL_IR_AGG_INSERT) \
X(control.select, V0, SPL_IR_CONTROL_SELECT) \
X(control.br, V0, SPL_IR_CONTROL_BR) \
X(control.jmp, V0, SPL_IR_CONTROL_JMP) \
X(control.call, V0, SPL_IR_CONTROL_CALL) \
X(control.param, V0, SPL_IR_CONTROL_PARAM) \
X(control.ret, V0, SPL_IR_CONTROL_RET) \
X(control.unreachable, V0, SPL_IR_CONTROL_UNREACHABLE) \
X(control.trap, V0, SPL_IR_CONTROL_TRAP) \
X(dbg.breakpoint, V0, SPL_IR_DBG_BREAKPOINT) \
X(dbg.panic, V0, SPL_IR_DBG_PANIC) \
typedef enum {
#ifdef X
#undef X
#endif
#define X(a, b, c) c,
SPL_IR_FN_TABLE
#undef X
} spl_ir_kind_t;
/* clang-format on */
typedef usize spl_ir_node_ref_t; /* 0 is error */
typedef VEC(spl_ir_node_ref_t) spl_ir_node_ref_vec_t;
typedef usize spl_ir_func_ref_t; /* 0 is error */
#define SPL_ENUM_TAG_FIELD_IDX 0
typedef struct {
spl_ir_kind_t kind;
spl_dbg_node_t dbg;
spl_attr_id_vec_t attrs;
union {
spl_type_id_t tid;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t left;
spl_ir_node_ref_t right;
} arith;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t a;
spl_ir_node_ref_t b;
} cmp;
struct {
spl_type_id_t from_tid;
spl_type_id_t to_tid;
spl_ir_node_ref_t val;
} cast;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t count;
} mem_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t const_node;
} mem_global_alloc;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
} mem_load;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t val;
} mem_store;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t ptr;
spl_ir_node_ref_t offset;
} mem_offset;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t agg;
usize field_idx;
} mem_field_ptr;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t src;
spl_ir_node_ref_t size;
} mem_copy;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t dst;
spl_ir_node_ref_t val;
spl_ir_node_ref_t size;
} mem_set;
struct {
spl_type_id_t tid;
union {
bool bool_lit;
void *ptr_lit;
usize int_lit;
double float_lit;
// const char *cstr_lit;
char ch_lit;
spl_ir_func_ref_t fn;
};
} type_const;
struct {
spl_type_id_t tid;
} bitsizeof;
struct {
spl_type_id_t tid;
} ir_sizeof;
struct {
spl_type_id_t tid;
} ir_alignof;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t field_idx;
} ir_offsetof;
struct {
spl_type_id_t tid;
} field_count;
struct {
spl_type_id_t tid;
spl_ir_node_ref_vec_t fields;
} agg_construct;
struct {
spl_type_id_t tid;
spl_type_id_t field_tid;
usize field_idx;
spl_ir_node_ref_t val;
} agg_extract;
struct {
spl_type_id_t tid;
usize field_idx;
spl_ir_node_ref_t agg;
spl_ir_node_ref_t field;
} agg_insert;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t cond;
spl_ir_node_ref_t true_val;
spl_ir_node_ref_t false_val;
} control_select;
struct {
spl_ir_node_ref_t cond;
spl_ir_node_ref_t true_label;
spl_ir_node_ref_t false_label;
} control_br;
struct {
spl_ir_node_ref_t label;
} control_jmp;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t func;
spl_ir_node_ref_vec_t params;
} control_call;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t idx;
} control_param;
struct {
spl_type_id_t tid;
spl_ir_node_ref_t val;
} control_ret;
struct {
const char *msg;
usize len;
} dbg_panic;
};
} spl_ir_node_t;
typedef VEC(spl_ir_node_t) spl_ir_node_vec_t;
typedef struct {
const char *name;
spl_attr_id_vec_t attrs;
spl_type_id_t fn_tid;
spl_ir_node_vec_t nodes;
} spl_ir_func_t;
typedef VEC(spl_ir_func_t) spl_ir_func_vec_t;
typedef spl_ir_node_ref_t spl_ir_block_t;
typedef VEC(spl_ir_block_t) spl_ir_block_vec_t;
typedef struct {
spl_ir_node_ref_t node;
enum { SPL_IR_FIX_BR_TRUE, SPL_IR_FIX_BR_FALSE, SPL_IR_FIX_JMP } slot;
spl_ir_node_ref_t block;
} spl_ir_fix_t;
typedef VEC(spl_ir_fix_t) spl_ir_fix_vec_t;
typedef struct {
spl_ir_func_vec_t funcs;
} spl_ir_t;
void spl_ir_init(spl_ir_t *ir);
void spl_ir_drop(spl_ir_t *ir);
spl_ir_node_ref_t spl_ir_alloc_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
spl_ir_func_ref_t spl_ir_alloc_fn(spl_ir_t *ir);
spl_ir_node_t *spl_ir_node(spl_ir_t *ir, spl_ir_func_ref_t fn_id, spl_ir_node_ref_t node_id);
spl_ir_func_t *spl_ir_func(spl_ir_t *ir, spl_ir_func_ref_t fn_id);
void spl_ir_dump(spl_ir_t *ir, const spl_type_t *ty, const spl_attr_t *attr);
const char *spl_ir_kind_name(spl_ir_kind_t kind);
typedef struct {
spl_ir_t ir;
spl_dbg_node_t dbg;
spl_ir_func_ref_t current_fn; /* 当前函数 */
spl_ir_node_ref_t current_block; /* 当前发射块(0 = 未设) */
spl_ir_block_vec_t blocks; /* 当前函数的基本块表 */
spl_ir_fix_vec_t fixups; /* 跳转回填表 */
bool terminated; /* 当前块已以 br/jmp/ret 终止 */
} spl_ir_builder_t;
/* clang-format off */
#define SPL_IR_BIN_ARITH_TABLE \
X(arith_add, SPL_IR_ARITH_ADD) \
X(arith_sub, SPL_IR_ARITH_SUB) \
X(arith_mul, SPL_IR_ARITH_MUL) \
X(arith_div, SPL_IR_ARITH_DIV) \
X(arith_rem, SPL_IR_ARITH_REM) \
X(arith_and, SPL_IR_ARITH_AND) \
X(arith_or, SPL_IR_ARITH_OR) \
X(arith_xor, SPL_IR_ARITH_XOR) \
X(arith_shl, SPL_IR_ARITH_SHL) \
X(arith_shr, SPL_IR_ARITH_SHR)
#define SPL_IR_UN_ARITH_TABLE \
X(arith_neg, SPL_IR_ARITH_NEG) \
X(arith_abs, SPL_IR_ARITH_ABS) \
X(arith_not, SPL_IR_ARITH_NOT)
#define SPL_IR_CMP_TABLE \
X(cmp_eq, SPL_IR_CMP_EQ) \
X(cmp_ne, SPL_IR_CMP_NE) \
X(cmp_lt, SPL_IR_CMP_LT) \
X(cmp_le, SPL_IR_CMP_LE) \
X(cmp_gt, SPL_IR_CMP_GT) \
X(cmp_ge, SPL_IR_CMP_GE)
#define SPL_IR_CAST_TABLE \
X(cast_trunc, SPL_IR_CAST_TRUNC) \
X(cast_zext, SPL_IR_CAST_ZEXT) \
X(cast_sext, SPL_IR_CAST_SEXT) \
X(cast_fext, SPL_IR_CAST_FEXT) \
X(cast_ftrunc, SPL_IR_CAST_FTRUNC) \
X(cast_bitcast, SPL_IR_CAST_BITCAST) \
X(cast_ptr2int, SPL_IR_CAST_PTR2INT) \
X(cast_int2ptr, SPL_IR_CAST_INT2PTR) \
X(cast_bool2int, SPL_IR_CAST_BOOL2INT) \
X(case_int2float, SPL_IR_CASE_INT2FLOAT) \
X(case_float2int, SPL_IR_CASE_FLOAT2INT)
/* clang-format on */
void spl_ir_builder_init(spl_ir_builder_t *b);
void spl_ir_builder_drop(spl_ir_builder_t *b);
spl_ir_func_ref_t spl_ir_builder_fn_begin(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid);
spl_ir_func_ref_t spl_ir_builder_fn_reserve(spl_ir_builder_t *b, const char *name,
spl_type_id_t fn_tid);
void spl_ir_builder_fn_begin_at(spl_ir_builder_t *b, spl_ir_func_ref_t fid);
void spl_ir_builder_fn_end(spl_ir_builder_t *b);
usize spl_ir_builder_block_begin(spl_ir_builder_t *b);
void spl_ir_builder_block_end(spl_ir_builder_t *b);
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
spl_ir_node_ref_t left, spl_ir_node_ref_t right);
SPL_IR_BIN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t tid, \
spl_ir_node_ref_t val);
SPL_IR_UN_ARITH_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *builder, spl_type_id_t tid, \
spl_ir_node_ref_t a, spl_ir_node_ref_t b);
SPL_IR_CMP_TABLE
#undef X
#define X(name, kind) \
spl_ir_node_ref_t spl_ir_builder_##name(spl_ir_builder_t *b, spl_type_id_t from_tid, \
spl_type_id_t to_tid, spl_ir_node_ref_t val);
SPL_IR_CAST_TABLE
#undef X
/* memory */
spl_ir_node_ref_t spl_ir_builder_mem_alloca(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t count);
spl_ir_node_ref_t spl_ir_builder_mem_global_alloc(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t const_node);
spl_ir_node_ref_t spl_ir_builder_mem_load(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr);
spl_ir_node_ref_t spl_ir_builder_mem_store(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t val);
spl_ir_node_ref_t spl_ir_builder_mem_offset(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t ptr, spl_ir_node_ref_t offset);
spl_ir_node_ref_t spl_ir_builder_mem_field(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t agg, usize field_idx);
spl_ir_node_ref_t spl_ir_builder_mem_copy(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t src,
spl_ir_node_ref_t size);
spl_ir_node_ref_t spl_ir_builder_mem_set(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t dst, spl_ir_node_ref_t val,
spl_ir_node_ref_t size);
/* type const */
spl_ir_node_ref_t spl_ir_builder_type_const_ptr(spl_ir_builder_t *b, spl_type_id_t tid, void *val);
spl_ir_node_ref_t spl_ir_builder_type_const_bool(spl_ir_builder_t *b, spl_type_id_t tid, bool val);
spl_ir_node_ref_t spl_ir_builder_type_const_int(spl_ir_builder_t *b, spl_type_id_t tid, usize val);
spl_ir_node_ref_t spl_ir_builder_type_const_float(spl_ir_builder_t *b, spl_type_id_t tid,
double val);
spl_ir_node_ref_t spl_ir_builder_type_const_bytes(spl_ir_builder_t *b, spl_type_id_t tid,
const void *data, usize len);
spl_ir_node_ref_t spl_ir_builder_type_const_char(spl_ir_builder_t *b, spl_type_id_t tid, char val);
spl_ir_node_ref_t spl_ir_builder_type_const_fn(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_func_ref_t val);
/* type */
spl_ir_node_ref_t spl_ir_builder_type_bitsizeof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_sizeof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_alignof(spl_ir_builder_t *b, spl_type_id_t tid);
spl_ir_node_ref_t spl_ir_builder_type_offsetof(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t field_idx);
spl_ir_node_ref_t spl_ir_builder_type_field_count(spl_ir_builder_t *b, spl_type_id_t tid);
/* agg */
spl_ir_node_ref_t spl_ir_builder_agg_construct(spl_ir_builder_t *b, spl_type_id_t tid);
void spl_ir_builder_agg_construct_field(spl_ir_builder_t *b, spl_ir_node_ref_t node,
spl_ir_node_ref_t field);
spl_ir_node_ref_t spl_ir_builder_agg_extract(spl_ir_builder_t *b, spl_type_id_t tid,
spl_type_id_t field_tid, usize field_idx,
spl_ir_node_ref_t val);
spl_ir_node_ref_t spl_ir_builder_agg_insert(spl_ir_builder_t *b, spl_type_id_t tid, usize field_idx,
spl_ir_node_ref_t agg, spl_ir_node_ref_t field);
/* control */
spl_ir_node_ref_t spl_ir_builder_control_select(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t cond, spl_ir_node_ref_t true_val,
spl_ir_node_ref_t false_val);
spl_ir_node_ref_t spl_ir_builder_control_br(spl_ir_builder_t *b, spl_ir_node_ref_t cond);
void spl_ir_builder_control_br_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref, usize true_block,
usize false_block);
spl_ir_node_ref_t spl_ir_builder_control_jmp(spl_ir_builder_t *b);
void spl_ir_builder_control_jmp_fixup(spl_ir_builder_t *b, spl_ir_node_ref_t ref,
usize target_block);
spl_ir_node_ref_t spl_ir_builder_control_call(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t func);
void spl_ir_builder_control_call_param(spl_ir_builder_t *b, spl_ir_node_ref_t call_node,
spl_ir_node_ref_t arg);
spl_ir_node_ref_t spl_ir_builder_control_param(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t idx);
spl_ir_node_ref_t spl_ir_builder_control_ret(spl_ir_builder_t *b, spl_type_id_t tid,
spl_ir_node_ref_t val);
spl_ir_node_ref_t spl_ir_builder_control_unreachable(spl_ir_builder_t *b);
spl_ir_node_ref_t spl_ir_builder_control_trap(spl_ir_builder_t *b);
spl_ir_node_ref_t spl_ir_builder_dbg_breakpoint(spl_ir_builder_t *b);
spl_ir_node_ref_t spl_ir_builder_dbg_panic(spl_ir_builder_t *b, const char *msg, usize len);
#endif /* __SPL_IR_H__ */
+1206
View File
File diff suppressed because it is too large. Load diff
+38
View File
@@ -0,0 +1,38 @@
#ifndef __SPL_IR2VM_H__
#define __SPL_IR2VM_H__
#include "spl_diag.h"
#include "spl_ir.h"
#include "spl_layout.h"
#include "spl_type.h"
#include "../stage0/spl_mcode.h"
typedef struct {
spl_ir_func_ref_t fid;
VEC(usize) node_first_ip;
} spl_ir2vm_fdbg_t;
typedef VEC(spl_ir2vm_fdbg_t) spl_ir2vm_fdbg_vec_t;
typedef MAP(spl_ir_func_ref_t, isize) spl_extern_idx_map_t;
typedef struct {
const spl_ir_t *ir;
const spl_type_t *type;
const spl_attr_t *attr;
spl_extern_idx_map_t extern_native;
spl_prog_t prog;
spl_layout_t *layout; /* 借用 splc0 的 layout(size/align/offset 唯一来源) */
spl_diag_t *diag;
} spl_ir2vm_t;
void spl_ir2vm_init(spl_ir2vm_t *ctx, const spl_ir_t *ir, const spl_type_t *type,
spl_layout_t *layout, const spl_attr_t *attr);
void spl_ir2vm_drop(spl_ir2vm_t *ctx);
int spl_ir2vm_run_func(spl_ir2vm_t *ctx, spl_ir_func_ref_t ref);
int spl_ir2vm_run(spl_ir2vm_t *ctx);
void spl_ir2vm_dump(spl_ir2vm_t *ctx);
#endif /* __SPL_IR2VM_H__ */
+836
View File
@@ -0,0 +1,836 @@
#include "spl_lang_type.h"
static usize spl_lang_type_hash(spl_lang_type_node_t n) {
usize hash = spl_hash_seed();
hash = spl_hash_mix(hash, (usize)n.kind);
hash = spl_hash_mix(hash, n.ir_type_id);
switch (n.kind) {
case SPL_LANG_TYPE_PTR:
case SPL_LANG_TYPE_SLICE:
case SPL_LANG_TYPE_RANGE:
hash = spl_hash_mix(hash, n.extra.elem);
break;
case SPL_LANG_TYPE_TUPLE:
hash = spl_hash_mix(hash, vec_size(n.extra.elems));
for (usize i = 0; i < vec_size(n.extra.elems); i++) {
hash = spl_hash_mix(hash, vec_at(n.extra.elems, i));
}
break;
case SPL_LANG_TYPE_FN:
hash = spl_hash_mix(hash, n.extra.fn.ret);
hash = spl_hash_mix(hash, vec_size(n.extra.fn.params));
for (usize i = 0; i < vec_size(n.extra.fn.params); i++) {
hash = spl_hash_mix(hash, vec_at(n.extra.fn.params, i));
}
break;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
hash = spl_hash_mix(hash, vec_size(n.methods));
for (usize i = 0; i < vec_size(n.methods); i++) {
spl_lang_method_t *m = &vec_at(n.methods, i);
hash = spl_hash_mix(hash, m->def_id);
hash = spl_hash_mix_str(hash, m->name);
}
break;
default:
break;
}
return hash;
}
static int spl_lang_type_eq(spl_lang_type_node_t n1, spl_lang_type_node_t n2) {
if (n1.kind != n2.kind || n1.ir_type_id != n2.ir_type_id)
return 1;
switch (n1.kind) {
case SPL_LANG_TYPE_PTR:
case SPL_LANG_TYPE_SLICE:
case SPL_LANG_TYPE_RANGE:
return n1.extra.elem != n2.extra.elem;
case SPL_LANG_TYPE_TUPLE:
if (vec_size(n1.extra.elems) != vec_size(n2.extra.elems))
return 1;
for (usize i = 0; i < vec_size(n1.extra.elems); i++) {
if (vec_at(n1.extra.elems, i) != vec_at(n2.extra.elems, i))
return 1;
}
return 0;
case SPL_LANG_TYPE_FN:
if (n1.extra.fn.ret != n2.extra.fn.ret)
return 1;
if (vec_size(n1.extra.fn.params) != vec_size(n2.extra.fn.params))
return 1;
for (usize i = 0; i < vec_size(n1.extra.fn.params); i++) {
if (vec_at(n1.extra.fn.params, i) != vec_at(n2.extra.fn.params, i))
return 1;
}
return 0;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
if (vec_size(n1.methods) != vec_size(n2.methods))
return 1;
for (usize i = 0; i < vec_size(n1.methods); i++) {
spl_lang_method_t *a = &vec_at(n1.methods, i);
spl_lang_method_t *b = &vec_at(n2.methods, i);
if (a->def_id != b->def_id)
return 1;
if ((a->name == NULL) != (b->name == NULL))
return 1;
if (a->name && strcmp(a->name, b->name) != 0)
return 1;
}
return 0;
default:
return 0;
}
}
static void spl_lang_node_free_extra(spl_lang_type_node_t *n) {
switch (n->kind) {
case SPL_LANG_TYPE_TUPLE:
vec_free(n->extra.elems);
break;
case SPL_LANG_TYPE_FN:
vec_free(n->extra.fn.params);
break;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
vec_free(n->methods);
break;
default:
break;
}
}
/* spl_fold 回调:只在链内做结构比较(同桶已保证 hash 相同)。 */
static int spl_lang_fold_eq(void *ctx, spl_fold_id_t node, const void *probe) {
spl_lang_type_t *type = (spl_lang_type_t *)ctx;
return spl_lang_type_eq(vec_at(type->lang_table, node),
*(const spl_lang_type_node_t *)probe) == 0;
}
static spl_fold_id_t spl_lang_fold_next(void *ctx, spl_fold_id_t node) {
spl_lang_type_t *type = (spl_lang_type_t *)ctx;
return vec_at(type->lang_table, node).hash_next;
}
static void spl_lang_fold_set_next(void *ctx, spl_fold_id_t node, spl_fold_id_t next) {
spl_lang_type_t *type = (spl_lang_type_t *)ctx;
vec_at(type->lang_table, node).hash_next = next;
}
spl_lang_type_id_t spl_lang_node_push(spl_lang_type_t *type, spl_lang_type_node_t *node) {
usize hash = spl_lang_type_hash(*node);
spl_lang_type_id_t existing = spl_fold_find(&type->lang_fold, hash, node);
if (existing) {
spl_lang_node_free_extra(node);
return existing;
}
spl_lang_type_id_t id = vec_size(type->lang_table);
vec_push(type->lang_table, *node);
spl_fold_insert(&type->lang_fold, hash, id);
node->kind = SPL_LANG_TYPE_ERROR;
return id;
}
void spl_lang_type_init(spl_lang_type_t *type) {
spl_type_init(&type->ir);
vec_init(type->lang_table);
spl_lang_type_node_t lang_node = {0};
vec_push(type->lang_table, lang_node);
spl_fold_init(&type->lang_fold, type, spl_lang_fold_eq, spl_lang_fold_next,
spl_lang_fold_set_next);
vec_init(type->def_table);
vec_push(type->def_table, (spl_def_node_t){0});
}
void spl_lang_type_drop(spl_lang_type_t *type) {
for (usize i = 0; i < vec_size(type->lang_table); i++) {
spl_lang_type_node_t *n = &vec_at(type->lang_table, i);
spl_lang_node_free_extra(n);
}
spl_fold_drop(&type->lang_fold);
vec_free(type->lang_table);
vec_free(type->def_table);
spl_type_drop(&type->ir);
}
spl_lang_type_node_t *spl_lang_type_node(const spl_lang_type_t *type, spl_lang_type_id_t id) {
if (!id || id >= vec_size(type->lang_table))
return NULL;
return &vec_at(type->lang_table, id);
}
spl_def_node_t *spl_def_node(const spl_lang_type_t *type, spl_def_id_t id) {
if (!id || id >= vec_size(type->def_table))
return NULL;
return &vec_at(type->def_table, id);
}
spl_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id) {
spl_lang_type_node_t *n = spl_lang_type_node(type, lang_id);
return n ? n->ir_type_id : 0;
}
spl_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type) {
spl_type_node_t empty = {0};
empty.kind = SPL_TYPE_ERROR;
empty.layout.mode = SPL_TYPE_LAYOUT_AUTO;
vec_push(type->ir.type_table, empty);
return vec_size(type->ir.type_table) - 1;
}
void spl_lang_define_ir(spl_lang_type_t *type, spl_type_id_t id, spl_type_node_t *node) {
if (!id || id >= vec_size(type->ir.type_table))
return;
spl_type_node_t *slot = &vec_at(type->ir.type_table, id);
/* slot 原是空 ERROR 节点,无 vec 字段可释放。node 的 vec 字段 move 进 slot。
占位 id 不写 type_fold,不参与 hash-consing。 */
*slot = *node;
node->kind = SPL_TYPE_ERROR;
}
static spl_lang_type_id_t spl_lang_node_simple(spl_lang_type_t *type,
spl_lang_type_kind_t lang_kind,
spl_type_id_t ir_type_id) {
spl_lang_type_node_t node = {0};
node.kind = lang_kind;
node.ir_type_id = ir_type_id;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_error(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_ERROR);
return spl_lang_node_simple(type, SPL_LANG_TYPE_ERROR, ir);
}
spl_lang_type_id_t spl_lang_make_infer(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_INFER);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INFER, ir);
}
spl_lang_type_id_t spl_lang_make_never(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_NEVER);
return spl_lang_node_simple(type, SPL_LANG_TYPE_NEVER, ir);
}
spl_lang_type_id_t spl_lang_make_any(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_ANY);
return spl_lang_node_simple(type, SPL_LANG_TYPE_ANY, ir);
}
spl_lang_type_id_t spl_lang_make_unit(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_UNIT);
return spl_lang_node_simple(type, SPL_LANG_TYPE_UNIT, ir);
}
spl_lang_type_id_t spl_lang_make_bool(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_BOOL);
return spl_lang_node_simple(type, SPL_LANG_TYPE_BOOL, ir);
}
spl_lang_type_id_t spl_lang_make_int(spl_lang_type_t *type, usize bits, int is_signed) {
spl_type_id_t ir = spl_type_builder_int(&type->ir, bits, is_signed);
return spl_lang_node_simple(type, SPL_LANG_TYPE_INT, ir);
}
spl_lang_type_id_t spl_lang_make_float(spl_lang_type_t *type, usize bits) {
spl_type_id_t ir = spl_type_builder_float(&type->ir, bits);
return spl_lang_node_simple(type, SPL_LANG_TYPE_FLOAT, ir);
}
spl_lang_type_id_t spl_lang_make_array(spl_lang_type_t *type, spl_lang_type_id_t elem_lang,
usize len) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_type_id_t ir = spl_type_builder_array(&type->ir, elem_ir, len);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_ARRAY;
node.ir_type_id = ir;
node.extra.elem = elem_lang;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_ptr(spl_lang_type_t *type, spl_lang_type_id_t pointee_lang) {
spl_type_id_t pointee_ir = spl_lang_type_get_ir_type(type, pointee_lang);
if (!pointee_ir)
return 0;
spl_type_id_t ir = spl_type_builder_ptr(&type->ir, pointee_ir);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_PTR;
node.ir_type_id = ir;
node.extra.elem = pointee_lang;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_slice(spl_lang_type_t *type, spl_lang_type_id_t elem_lang) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_lang_type_id_t ptr_lang = spl_lang_make_ptr(type, elem_lang);
spl_lang_type_id_t usize_lang = spl_lang_make_int(type, sizeof(void *) * 8, 0);
spl_type_id_t ptr_ir = spl_lang_type_get_ir_type(type, ptr_lang);
spl_type_id_t usize_ir = spl_lang_type_get_ir_type(type, usize_lang);
spl_type_member_vec_t members;
vec_init(members);
spl_type_member_t m1 = {.name = "ptr", .type_id = ptr_ir};
spl_type_member_t m2 = {.name = "len", .type_id = usize_ir};
vec_push(members, m1);
vec_push(members, m2);
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_SLICE;
node.ir_type_id = struct_ir;
node.extra.elem = elem_lang;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_tuple(spl_lang_type_t *type, const spl_lang_type_id_t *elems,
usize count) {
spl_type_member_vec_t members;
vec_init(members);
for (usize i = 0; i < count; i++) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elems[i]);
if (!elem_ir) {
vec_free(members);
return 0;
}
char name[32];
snprintf(name, sizeof(name), "%zu", i);
spl_type_member_t m = {.name = strdup(name), .type_id = elem_ir};
vec_push(members, m);
}
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_TUPLE;
node.ir_type_id = struct_ir;
vec_init(node.extra.elems);
for (usize i = 0; i < count; i++) {
vec_push(node.extra.elems, elems[i]);
}
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_range(spl_lang_type_t *type, spl_lang_type_id_t elem_lang) {
spl_type_id_t elem_ir = spl_lang_type_get_ir_type(type, elem_lang);
if (!elem_ir)
return 0;
spl_type_member_vec_t members;
vec_init(members);
spl_type_member_t m1 = {.name = "start", .type_id = elem_ir};
spl_type_member_t m2 = {.name = "end", .type_id = elem_ir};
vec_push(members, m1);
vec_push(members, m2);
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t struct_ir = spl_type_builder_agg(&type->ir, SPL_TYPE_STRUCT, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_RANGE;
node.ir_type_id = struct_ir;
node.extra.elem = elem_lang;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_fn(spl_lang_type_t *type, spl_lang_type_id_t ret_lang,
const spl_lang_type_id_t *params_lang, usize nparams) {
spl_type_id_t ret_ir = spl_lang_type_get_ir_type(type, ret_lang);
if (!ret_ir)
return 0;
spl_type_id_vec_t param_irs;
vec_init(param_irs);
for (usize i = 0; i < nparams; i++) {
spl_type_id_t pir = spl_lang_type_get_ir_type(type, params_lang[i]);
if (!pir) {
vec_free(param_irs);
return 0;
}
vec_push(param_irs, pir);
}
spl_type_id_t fn_ir =
spl_type_builder_fn(&type->ir, ret_ir, param_irs.data, vec_size(param_irs));
vec_free(param_irs);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_FN;
node.ir_type_id = fn_ir;
node.extra.fn.ret = ret_lang;
vec_init(node.extra.fn.params);
for (usize i = 0; i < nparams; i++) {
vec_push(node.extra.fn.params, params_lang[i]);
}
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_aggregate(spl_lang_type_t *type, spl_lang_type_kind_t kind,
const char *name, const spl_lang_type_id_t *members_lang,
usize nmembers) {
(void)name; // TODO
spl_type_node_kind_t tk;
switch (kind) {
case SPL_LANG_TYPE_STRUCT:
tk = SPL_TYPE_STRUCT;
break;
case SPL_LANG_TYPE_UNION:
tk = SPL_TYPE_UNION;
break;
case SPL_LANG_TYPE_ENUM:
tk = SPL_TYPE_ENUM;
break;
case SPL_LANG_TYPE_SHAPE:
tk = SPL_TYPE_SHAPE;
break;
default:
return 0;
}
spl_type_member_vec_t members;
vec_init(members);
for (usize i = 0; i < nmembers; i++) {
spl_type_id_t member_ir = spl_lang_type_get_ir_type(type, members_lang[i]);
if (!member_ir) {
vec_free(members);
return 0;
}
char field_name[32];
snprintf(field_name, sizeof(field_name), "%zu", i);
spl_type_member_t m = {.name = strdup(field_name), .type_id = member_ir};
vec_push(members, m);
}
spl_type_layout_t layout = {.mode = SPL_TYPE_LAYOUT_AUTO, .fixed_align_bits = 0};
spl_type_id_t agg_ir = spl_type_builder_agg(&type->ir, tk, &members, 0, layout);
spl_lang_type_node_t node = {0};
node.kind = kind;
node.ir_type_id = agg_ir;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_lang_make_varargs(spl_lang_type_t *type) {
spl_type_id_t ir = spl_type_builder_simple(&type->ir, SPL_TYPE_UNIT);
spl_lang_type_node_t node = {0};
node.kind = SPL_LANG_TYPE_VARARGS;
node.ir_type_id = ir;
return spl_lang_node_push(type, &node);
}
spl_lang_type_id_t spl_type_lookup_builtin(spl_lang_type_t *type, const char *name) {
if (!name || !*name)
return 0;
if (strcmp(name, "bool") == 0)
return spl_lang_make_bool(type);
if (strcmp(name, "void") == 0)
return spl_lang_make_unit(type);
if (strcmp(name, "isize") == 0)
return spl_lang_make_int(type, sizeof(void *) * 8, 1);
if (strcmp(name, "usize") == 0)
return spl_lang_make_int(type, sizeof(void *) * 8, 0);
if (strcmp(name, "any") == 0)
return spl_lang_make_any(type);
char prefix = name[0];
if (prefix == 'i' || prefix == 'u' || prefix == 'f') {
const char *rest = name + 1;
char *end;
long bits = strtol(rest, &end, 10);
if (end != rest && *end == '\0' && bits > 0) {
if (prefix == 'i')
return spl_lang_make_int(type, (usize)bits, 1);
if (prefix == 'u')
return spl_lang_make_int(type, (usize)bits, 0);
if (prefix == 'f')
return spl_lang_make_float(type, (usize)bits);
}
}
return 0;
}
bool spl_lang_type_is_subtype(const spl_lang_type_t *type, spl_lang_type_id_t sub,
spl_lang_type_id_t super) {
if (sub == 0 || super == 0)
return false;
if (sub == super)
return true;
spl_lang_type_node_t *nsub = spl_lang_type_node(type, sub);
spl_lang_type_node_t *nsuper = spl_lang_type_node(type, super);
if (!nsub || !nsuper)
return false;
if (nsub->kind == SPL_LANG_TYPE_NEVER)
return true;
if (nsuper->kind == SPL_LANG_TYPE_ANY)
return true;
if (nsub->kind == SPL_LANG_TYPE_INT && nsuper->kind == SPL_LANG_TYPE_INT) {
spl_type_node_t *ir_sub = spl_type_node(&type->ir, nsub->ir_type_id);
if (!ir_sub)
return false;
return ir_sub->int_type.bits == 0;
}
if (nsub->kind == SPL_LANG_TYPE_FLOAT && nsuper->kind == SPL_LANG_TYPE_FLOAT) {
spl_type_node_t *ir_sub = spl_type_node(&type->ir, nsub->ir_type_id);
if (!ir_sub)
return false;
return ir_sub->float_type.bits == 0;
}
/* null(*never)可隐式转换为函数指针:函数值按指针布局,可空。 */
if (nsuper->kind == SPL_LANG_TYPE_FN && nsub->kind == SPL_LANG_TYPE_PTR) {
spl_lang_type_node_t *sub_elem = spl_lang_type_node(type, nsub->extra.elem);
if (sub_elem && sub_elem->kind == SPL_LANG_TYPE_NEVER)
return true;
}
if (nsub->kind == SPL_LANG_TYPE_PTR && nsuper->kind == SPL_LANG_TYPE_PTR) {
if (nsub->extra.elem == nsuper->extra.elem)
return true;
spl_lang_type_node_t *sub_elem = spl_lang_type_node(type, nsub->extra.elem);
spl_lang_type_node_t *super_elem = spl_lang_type_node(type, nsuper->extra.elem);
if (sub_elem && sub_elem->kind == SPL_LANG_TYPE_NEVER)
return true;
if (super_elem && super_elem->kind == SPL_LANG_TYPE_ANY)
return true;
return false;
}
return false;
}
spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type_id_t a,
spl_lang_type_id_t b) {
if (a == 0 || b == 0)
return 0;
if (a == b)
return a;
spl_lang_type_node_t *na = spl_lang_type_node(type, a);
spl_lang_type_node_t *nb = spl_lang_type_node(type, b);
if (!na || !nb)
return 0;
if (na->kind == SPL_LANG_TYPE_NEVER)
return b;
if (nb->kind == SPL_LANG_TYPE_NEVER)
return a;
if (na->kind == SPL_LANG_TYPE_ANY || nb->kind == SPL_LANG_TYPE_ANY)
return spl_lang_make_any((spl_lang_type_t *)type);
bool a_int = na->kind == SPL_LANG_TYPE_INT;
bool b_int = nb->kind == SPL_LANG_TYPE_INT;
bool a_flt = na->kind == SPL_LANG_TYPE_FLOAT;
bool b_flt = nb->kind == SPL_LANG_TYPE_FLOAT;
if (a_int && b_int) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (!ira || !irb)
return 0;
bool a_ct = ira->int_type.bits == 0;
bool b_ct = irb->int_type.bits == 0;
if (a_ct && b_ct)
return a;
if (a_ct)
return b;
if (b_ct)
return a;
return 0;
}
if (a_flt && b_flt) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (!ira || !irb)
return 0;
bool a_ct = ira->float_type.bits == 0;
bool b_ct = irb->float_type.bits == 0;
if (a_ct && b_ct)
return a;
if (a_ct)
return b;
if (b_ct)
return a;
return 0;
}
if (a_int && b_flt) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (ira && irb && ira->int_type.bits == 0 && irb->float_type.bits == 0)
return spl_lang_make_float((spl_lang_type_t *)type, 0);
return 0;
}
if (a_flt && b_int) {
spl_type_node_t *ira = spl_type_node(&type->ir, na->ir_type_id);
spl_type_node_t *irb = spl_type_node(&type->ir, nb->ir_type_id);
if (ira && irb && ira->float_type.bits == 0 && irb->int_type.bits == 0)
return spl_lang_make_float((spl_lang_type_t *)type, 0);
return 0;
}
/* 函数指针可空:fn 与 null(*never)求交得到 fn。 */
if (na->kind == SPL_LANG_TYPE_FN && nb->kind == SPL_LANG_TYPE_PTR) {
spl_lang_type_node_t *eb = spl_lang_type_node(type, nb->extra.elem);
if (eb && eb->kind == SPL_LANG_TYPE_NEVER)
return a;
}
if (na->kind == SPL_LANG_TYPE_PTR && nb->kind == SPL_LANG_TYPE_FN) {
spl_lang_type_node_t *ea = spl_lang_type_node(type, na->extra.elem);
if (ea && ea->kind == SPL_LANG_TYPE_NEVER)
return b;
}
if (na->kind == SPL_LANG_TYPE_PTR && nb->kind == SPL_LANG_TYPE_PTR) {
if (na->extra.elem == nb->extra.elem)
return a;
spl_lang_type_node_t *ea = spl_lang_type_node(type, na->extra.elem);
spl_lang_type_node_t *eb = spl_lang_type_node(type, nb->extra.elem);
if (ea && ea->kind == SPL_LANG_TYPE_NEVER)
return b;
if (eb && eb->kind == SPL_LANG_TYPE_NEVER)
return a;
if (ea && ea->kind == SPL_LANG_TYPE_ANY)
return a;
if (eb && eb->kind == SPL_LANG_TYPE_ANY)
return b;
return 0;
}
return 0;
}
bool spl_lang_mpa_int_fits(const spl_lang_type_t *type, spl_lang_type_id_t target,
spl_mpa_int_t v) {
spl_lang_type_node_t *nt = spl_lang_type_node(type, target);
if (!nt || nt->kind != SPL_LANG_TYPE_INT)
return false;
spl_type_node_t *ir = spl_type_node(&type->ir, nt->ir_type_id);
if (!ir)
return false;
uint32_t bits = (uint32_t)ir->int_type.bits;
if (bits == 0)
return true;
bool target_signed = ir->int_type.is_signed != 0;
uint64_t uval = v.bits;
if (target_signed) {
if (bits >= 64)
return true;
uint64_t hi = ((uint64_t)1 << (bits - 1)) - 1;
return uval <= hi;
}
if (bits >= 64)
return true;
uint64_t hi = ((uint64_t)1 << bits) - 1;
return uval <= hi;
}
spl_def_id_t spl_def_alloc(spl_lang_type_t *type, spl_def_node_kind_t kind, const char *name,
spl_dbg_node_t dbg, struct spl_ast *owner_ast, usize ast_node_ref) {
spl_def_node_t n = {0};
n.kind = kind;
n.name = name;
n.dbg_node = dbg;
n.lang_id = 0;
n.owner_ast = owner_ast;
n.ast_node_ref = ast_node_ref;
n.state = SPL_DECL_UNRESOLVED;
n.owner_def = 0;
vec_push(type->def_table, n);
return vec_size(type->def_table) - 1;
}
void spl_def_resolve(spl_lang_type_t *type, spl_def_id_t id, spl_lang_type_id_t lang_id) {
spl_def_node_t *d = spl_def_node(type, id);
if (d) {
d->lang_id = lang_id;
d->state = SPL_DECL_RESOLVED;
}
}
spl_lang_type_id_t spl_def_get_lang_id(spl_lang_type_t *type, spl_def_id_t def_id) {
spl_def_node_t *d = spl_def_node(type, def_id);
return d ? d->lang_id : 0;
}
spl_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id) {
spl_lang_type_id_t lang = spl_def_get_lang_id(type, def_id);
return lang ? spl_lang_type_get_ir_type(type, lang) : 0;
}
static void spl_lang_type_dump_rec(spl_lang_type_t *type, spl_lang_type_id_t id,
spl_lang_type_id_vec_t *stack) {
for (usize i = 0; i < vec_size(*stack); i++) {
if (vec_at(*stack, i) == id) {
printf("<rec#%zu>", id);
return;
}
}
if (vec_size(*stack) > 32) {
printf("...");
return;
}
vec_push(*stack, id);
spl_lang_type_node_t *n = spl_lang_type_node(type, id);
if (!n) {
printf("none");
(void)vec_pop(*stack);
return;
}
switch (n->kind) {
case SPL_LANG_TYPE_ERROR:
printf("error");
break;
case SPL_LANG_TYPE_INFER:
printf("infer");
break;
case SPL_LANG_TYPE_NEVER:
printf("never");
break;
case SPL_LANG_TYPE_ANY:
printf("any");
break;
case SPL_LANG_TYPE_UNIT:
printf("unit");
break;
case SPL_LANG_TYPE_BOOL:
printf("bool");
break;
case SPL_LANG_TYPE_VARARGS:
printf("...");
break;
case SPL_LANG_TYPE_INT: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
if (tn && tn->int_type.bits == 0)
printf("comptime_int");
else
spl_type_pure_dump(&type->ir, n->ir_type_id);
break;
}
case SPL_LANG_TYPE_FLOAT: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
if (tn && tn->float_type.bits == 0)
printf("comptime_float");
else
spl_type_pure_dump(&type->ir, n->ir_type_id);
break;
}
case SPL_LANG_TYPE_PTR:
printf("*");
spl_lang_type_dump_rec(type, n->extra.elem, stack);
break;
case SPL_LANG_TYPE_ARRAY: {
spl_type_node_t *tn = spl_type_node(&type->ir, n->ir_type_id);
printf("[%zu]", tn->array_type.len);
spl_type_pure_dump(&type->ir, n->ir_type_id);
} break;
case SPL_LANG_TYPE_SLICE:
printf("[]");
spl_lang_type_dump_rec(type, n->extra.elem, stack);
break;
case SPL_LANG_TYPE_TUPLE:
printf("(");
for (usize i = 0; i < vec_size(n->extra.elems); i++) {
if (i)
printf(",");
spl_lang_type_dump_rec(type, vec_at(n->extra.elems, i), stack);
}
printf(")");
break;
case SPL_LANG_TYPE_RANGE:
spl_lang_type_dump_rec(type, n->extra.elem, stack);
printf("..");
spl_lang_type_dump_rec(type, n->extra.elem, stack);
break;
case SPL_LANG_TYPE_FN:
printf("fn(");
for (usize i = 0; i < vec_size(n->extra.fn.params); i++) {
if (i)
printf(",");
spl_lang_type_dump_rec(type, vec_at(n->extra.fn.params, i), stack);
}
printf(")");
spl_lang_type_dump_rec(type, n->extra.fn.ret, stack);
break;
case SPL_LANG_TYPE_STRUCT:
case SPL_LANG_TYPE_UNION:
case SPL_LANG_TYPE_ENUM:
case SPL_LANG_TYPE_SHAPE:
spl_type_pure_dump(&type->ir, n->ir_type_id);
break;
}
(void)vec_pop(*stack);
}
void spl_lang_type_dump(spl_lang_type_t *type, spl_lang_type_id_t id) {
spl_lang_type_id_vec_t stack;
vec_init(stack);
spl_lang_type_dump_rec(type, id, &stack);
vec_free(stack);
}
void spl_type_def_dump(spl_lang_type_t *type, spl_def_id_t id) {
spl_def_node_t *node = spl_def_node(type, id);
if (!node) {
printf("none");
return;
}
const char *def_kind_name = "unknown";
switch (node->kind) {
case SPL_DEF_ERROR:
def_kind_name = "error";
break;
case SPL_DEF_SCALAR:
def_kind_name = "scalar";
break;
case SPL_DEF_MEMBER:
def_kind_name = "member";
break;
case SPL_DEF_VAR:
def_kind_name = "var";
break;
case SPL_DEF_FN:
def_kind_name = "fn";
break;
case SPL_DEF_AGG:
def_kind_name = "agg";
break;
case SPL_DEF_BUILTIN:
def_kind_name = "builtin";
break;
case SPL_DEF_DISTINCT:
def_kind_name = "distinct";
break;
case SPL_DEF_ALIAS:
def_kind_name = "alias";
break;
}
printf("kind=%s lang_id=%zu name=%s", def_kind_name, node->lang_id,
node->name ? node->name : "?");
}
+153
View File
@@ -0,0 +1,153 @@
#ifndef __SPL_LANG_TYPE_H__
#define __SPL_LANG_TYPE_H__
#include "../stage0/include/utils.h"
#include "spl_dbg.h"
#include "spl_mpa.h"
#include "spl_type.h"
typedef usize spl_lang_type_id_t;
typedef VEC(spl_lang_type_id_t) spl_lang_type_id_vec_t;
typedef usize spl_def_id_t;
typedef VEC(spl_def_id_t) spl_def_id_vec_t;
typedef enum {
SPL_LANG_TYPE_ERROR,
SPL_LANG_TYPE_INFER,
SPL_LANG_TYPE_NEVER,
SPL_LANG_TYPE_ANY,
SPL_LANG_TYPE_UNIT,
SPL_LANG_TYPE_BOOL,
SPL_LANG_TYPE_INT,
SPL_LANG_TYPE_FLOAT,
SPL_LANG_TYPE_PTR,
SPL_LANG_TYPE_ARRAY,
SPL_LANG_TYPE_SLICE,
SPL_LANG_TYPE_TUPLE,
SPL_LANG_TYPE_RANGE,
SPL_LANG_TYPE_FN,
SPL_LANG_TYPE_STRUCT,
SPL_LANG_TYPE_UNION,
SPL_LANG_TYPE_ENUM,
SPL_LANG_TYPE_SHAPE,
SPL_LANG_TYPE_VARARGS,
} spl_lang_type_kind_t;
typedef struct {
const char *name;
spl_def_id_t def_id;
} spl_lang_method_t;
typedef VEC(spl_lang_method_t) spl_lang_method_vec_t;
typedef struct {
spl_lang_type_kind_t kind;
spl_type_id_t ir_type_id;
spl_lang_method_vec_t methods;
union {
spl_lang_type_id_t elem;
spl_lang_type_id_vec_t elems;
struct {
spl_lang_type_id_vec_t params;
spl_lang_type_id_t ret;
} fn;
} extra;
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_lang_type_node_t;
typedef VEC(spl_lang_type_node_t) spl_lang_type_vec_t;
typedef enum {
SPL_DEF_ERROR,
SPL_DEF_SCALAR,
SPL_DEF_MEMBER,
SPL_DEF_VAR,
SPL_DEF_FN,
SPL_DEF_AGG,
SPL_DEF_DISTINCT,
SPL_DEF_ALIAS,
SPL_DEF_BUILTIN,
} spl_def_node_kind_t;
typedef enum {
SPL_DECL_UNRESOLVED,
SPL_DECL_RESOLVING,
SPL_DECL_RESOLVED,
SPL_DECL_ERROR,
} spl_decl_state_t;
struct spl_ast;
typedef struct {
spl_def_node_kind_t kind;
const char *name;
spl_dbg_node_t dbg_node;
spl_lang_type_id_t lang_id;
struct spl_ast *owner_ast;
usize ast_node_ref;
spl_decl_state_t state;
spl_def_id_t owner_def;
} spl_def_node_t;
typedef VEC(spl_def_node_t) spl_def_node_vec_t;
typedef struct {
spl_type_t ir;
spl_lang_type_vec_t lang_table;
spl_fold_t lang_fold;
spl_def_node_vec_t def_table;
} spl_lang_type_t;
void spl_lang_type_init(spl_lang_type_t *type);
void spl_lang_type_drop(spl_lang_type_t *type);
spl_lang_type_node_t *spl_lang_type_node(const spl_lang_type_t *type, spl_lang_type_id_t id);
spl_lang_type_id_t spl_lang_node_push(spl_lang_type_t *type, spl_lang_type_node_t *node);
spl_type_id_t spl_lang_type_get_ir_type(spl_lang_type_t *type, spl_lang_type_id_t lang_id);
/* 前向引用支持:reserve 一个 type_table 空槽位(kind=ERROR)作为身份锚点,
让 *Node / []Node 这类成员能拿到稳定 pointee;成员解析完后再调 define
把真实内容填进去。占位槽位**不写 type_fold**,不参与 hash-consing——
后续相同形状的类型走 spl_type_node_push 会生成独立 id,语义等价。 */
spl_type_id_t spl_lang_reserve_ir(spl_lang_type_t *type);
void spl_lang_define_ir(spl_lang_type_t *type, spl_type_id_t id, spl_type_node_t *node);
spl_lang_type_id_t spl_lang_make_error(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_infer(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_never(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_any(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_unit(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_bool(spl_lang_type_t *type);
spl_lang_type_id_t spl_lang_make_int(spl_lang_type_t *type, usize bits, int is_signed);
spl_lang_type_id_t spl_lang_make_float(spl_lang_type_t *type, usize bits);
spl_lang_type_id_t spl_lang_make_ptr(spl_lang_type_t *type, spl_lang_type_id_t pointee);
spl_lang_type_id_t spl_lang_make_array(spl_lang_type_t *type, spl_lang_type_id_t elem, usize len);
spl_lang_type_id_t spl_lang_make_slice(spl_lang_type_t *type, spl_lang_type_id_t elem);
spl_lang_type_id_t spl_lang_make_tuple(spl_lang_type_t *type, const spl_lang_type_id_t *elems,
usize count);
spl_lang_type_id_t spl_lang_make_range(spl_lang_type_t *type, spl_lang_type_id_t elem);
spl_lang_type_id_t spl_lang_make_fn(spl_lang_type_t *type, spl_lang_type_id_t ret,
const spl_lang_type_id_t *params, usize nparams);
spl_lang_type_id_t spl_lang_make_aggregate(spl_lang_type_t *type, spl_lang_type_kind_t kind,
const char *name, const spl_lang_type_id_t *members,
usize nmembers);
spl_lang_type_id_t spl_lang_make_varargs(spl_lang_type_t *type);
spl_lang_type_id_t spl_type_lookup_builtin(spl_lang_type_t *type, const char *name);
bool spl_lang_type_is_subtype(const spl_lang_type_t *type, spl_lang_type_id_t sub,
spl_lang_type_id_t super);
spl_lang_type_id_t spl_lang_type_join(const spl_lang_type_t *type, spl_lang_type_id_t a,
spl_lang_type_id_t b);
bool spl_lang_mpa_int_fits(const spl_lang_type_t *type, spl_lang_type_id_t target, spl_mpa_int_t v);
spl_def_id_t spl_def_alloc(spl_lang_type_t *type, spl_def_node_kind_t kind, const char *name,
spl_dbg_node_t dbg, struct spl_ast *owner_ast, usize ast_node_ref);
void spl_def_resolve(spl_lang_type_t *type, spl_def_id_t id, spl_lang_type_id_t lang_id);
spl_def_node_t *spl_def_node(const spl_lang_type_t *type, spl_def_id_t id);
spl_lang_type_id_t spl_def_get_lang_id(spl_lang_type_t *type, spl_def_id_t def_id);
spl_type_id_t spl_def_get_type_id(spl_lang_type_t *type, spl_def_id_t def_id);
void spl_lang_type_dump(spl_lang_type_t *type, spl_lang_type_id_t id);
void spl_type_def_dump(spl_lang_type_t *type, spl_def_id_t id);
#endif /* __SPL_LANG_TYPE_H__ */
+324
View File
@@ -0,0 +1,324 @@
#include "spl_layout.h"
static void infos_grow(spl_layout_t *layout, usize n) {
while (vec_size(layout->infos) < n) {
spl_layout_info_t info = {0};
vec_init(info.field_bit_offsets);
vec_init(info.field_bit_sizes);
vec_push(layout->infos, info);
}
}
static spl_layout_info_t *infos_at(spl_layout_t *layout, spl_type_id_t id) {
if (id == 0 || id >= vec_size(layout->infos))
return NULL;
return &vec_at(layout->infos, id);
}
void spl_layout_add_scalar(spl_layout_t *layout, usize size, usize abi_align) {
spl_layout_scalar_t s = {0};
s.size = size;
s.abi_align = abi_align;
s.pref_align = abi_align;
vec_init(s.invalid_values);
vec_push(layout->scalars, s);
}
void spl_layout_add_ptr(spl_layout_t *layout, usize addr_space, usize size, usize align) {
spl_layout_ptr_t p = {0};
p.add_space = addr_space;
p.ptr_size = size;
p.ptr_align = align;
vec_push(layout->pointers, p);
}
void spl_layout_init(spl_layout_t *layout, spl_layout_target_t *target) {
vec_init(layout->scalars);
vec_init(layout->pointers);
vec_init(layout->infos);
layout->target = target;
/* 默认聚合策略:按最大字段对齐,不允许重排 */
layout->aggregate.allow_field_reordering = false;
layout->aggregate.align_rule = ALIGN_MAX;
layout->aggregate.fixed_align = 0;
/* 常见 64 位平台的默认布局。
若目标平台不适用,调用者 clear 后自行 add_*。 */
spl_layout_add_scalar(layout, 1, 1); /* i8 / u8 / bool */
spl_layout_add_scalar(layout, 2, 2); /* i16 / u16 */
spl_layout_add_scalar(layout, 4, 4); /* i32 / u32 / f32 */
spl_layout_add_scalar(layout, 8, 8); /* i64 / u64 / f64 */
usize ps = target && target->ptr_size ? target->ptr_size : sizeof(void *);
usize pa = target && target->ptr_align ? target->ptr_align : sizeof(void *);
spl_layout_add_ptr(layout, 0, ps, pa);
}
void spl_layout_drop(spl_layout_t *layout) {
for (usize i = 0; i < vec_size(layout->scalars); ++i)
vec_free(vec_at(layout->scalars, i).invalid_values);
vec_free(layout->scalars);
vec_free(layout->pointers);
for (usize i = 0; i < vec_size(layout->infos); ++i) {
vec_free(vec_at(layout->infos, i).field_bit_offsets);
vec_free(vec_at(layout->infos, i).field_bit_sizes);
}
vec_free(layout->infos);
}
static const spl_layout_scalar_t *scalar_for_size(spl_layout_t *layout, usize size_bytes) {
for (usize i = 0; i < vec_size(layout->scalars); ++i) {
spl_layout_scalar_t *s = &vec_at(layout->scalars, i);
if (s->size == size_bytes)
return s;
}
return NULL;
}
static const spl_layout_ptr_t *default_ptr(spl_layout_t *layout) {
if (vec_size(layout->pointers) == 0)
return NULL;
return &vec_at(layout->pointers, 0);
}
static bool layout_scalar(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_info_t *out) {
usize size_bits = 0;
switch (tn->kind) {
case SPL_TYPE_INT:
if (tn->int_type.bits == 0)
return false; /* comptime_int 未落地 */
size_bits = tn->int_type.bits;
break;
case SPL_TYPE_FLOAT:
if (tn->float_type.bits == 0)
return false; /* comptime_float 未落地 */
size_bits = tn->float_type.bits;
break;
case SPL_TYPE_BOOL:
size_bits = 8;
break;
default:
return false;
}
usize size_bytes = (size_bits + 7) / 8;
const spl_layout_scalar_t *sl = scalar_for_size(layout, size_bytes);
if (!sl)
return false;
out->size_bits = sl->size * 8;
out->align_bits = sl->abi_align * 8;
return true;
}
static bool layout_ptr(spl_layout_t *layout, spl_layout_info_t *out) {
const spl_layout_ptr_t *pl = default_ptr(layout);
if (!pl)
return false;
out->size_bits = pl->ptr_size * 8;
out->align_bits = pl->ptr_align * 8;
return true;
}
static usize round_up_bits(usize x, usize align_bits) {
if (align_bits <= 1)
return x;
usize a = align_bits;
return (x + a - 1) / a * a;
}
static bool layout_agg(spl_layout_t *layout, spl_type_node_t *tn, spl_layout_info_t *out) {
usize n = vec_size(tn->agg_type.variants);
if (tn->kind == SPL_TYPE_ENUM) {
spl_type_id_t tag_tid = tn->agg_type.tag_type;
if (!tag_tid)
return false;
spl_layout_info_t *tag_info = infos_at(layout, tag_tid);
if (!tag_info || !tag_info->resolved)
return false;
usize tag_align_bits = tag_info->align_bits ? tag_info->align_bits : 8;
usize payload_align_bits = 8;
usize payload_size_bits = 0;
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
if (m->type_id == 0) /* 无载荷变体 */
continue;
spl_layout_info_t *fi = infos_at(layout, m->type_id);
if (!fi || !fi->resolved)
return false;
usize fa = fi->align_bits ? fi->align_bits : 8;
if (fa > payload_align_bits)
payload_align_bits = fa;
if (fi->size_bits > payload_size_bits)
payload_size_bits = fi->size_bits;
}
usize payload_off = round_up_bits(tag_info->size_bits, payload_align_bits);
usize final_align_bits =
tag_align_bits > payload_align_bits ? tag_align_bits : payload_align_bits;
out->size_bits = round_up_bits(payload_off + payload_size_bits, final_align_bits);
out->align_bits = final_align_bits;
/* 字段索引约定(与 ir2vm 一致):0 = tag,1..n = 各变体载荷(同一偏移)。 */
vec_push(out->field_bit_offsets, 0);
vec_push(out->field_bit_sizes, tag_info->size_bits);
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
usize fsize = 0;
if (m->type_id) {
spl_layout_info_t *fi = infos_at(layout, m->type_id);
if (fi)
fsize = fi->size_bits;
}
vec_push(out->field_bit_offsets, payload_off);
vec_push(out->field_bit_sizes, fsize);
}
return true;
}
if (n == 0) {
out->size_bits = 0;
out->align_bits = 8;
return true;
}
usize max_align_bits = 8;
usize offset_bits = 0;
bool is_union = (tn->kind == SPL_TYPE_UNION);
for (usize i = 0; i < n; ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
usize fsize_bits = 0;
usize fsize_align = 8;
if (m->type_id) {
spl_layout_info_t *fi = infos_at(layout, m->type_id);
if (!fi || !fi->resolved)
return false;
fsize_bits = fi->size_bits;
fsize_align = fi->align_bits ? fi->align_bits : 8;
}
usize field_align_bits = fsize_align;
if (is_union) {
vec_push(out->field_bit_offsets, 0);
vec_push(out->field_bit_sizes, fsize_bits);
if (fsize_bits > out->size_bits)
out->size_bits = fsize_bits;
} else {
offset_bits = round_up_bits(offset_bits, field_align_bits);
vec_push(out->field_bit_offsets, offset_bits);
vec_push(out->field_bit_sizes, fsize_bits);
offset_bits += fsize_bits;
}
if (field_align_bits > max_align_bits)
max_align_bits = field_align_bits;
}
usize final_align_bits = max_align_bits;
if (layout->aggregate.align_rule == ALIGN_FIXED) {
final_align_bits = layout->aggregate.fixed_align * 8;
} else if (layout->aggregate.align_rule == ALIGN_MAX_WITH_MIN) {
usize min_bits = layout->aggregate.fixed_align * 8;
if (final_align_bits < min_bits)
final_align_bits = min_bits;
}
if (is_union)
out->size_bits = round_up_bits(out->size_bits, final_align_bits);
else
out->size_bits = round_up_bits(offset_bits, final_align_bits);
out->align_bits = final_align_bits;
return true;
}
static void resolve_type(spl_layout_t *layout, spl_type_t *type, spl_type_id_t id) {
spl_layout_info_t *info = infos_at(layout, id);
if (!info || info->resolved)
return;
spl_type_node_t *tn = spl_type_node(type, id);
if (!tn)
return;
/* 先标记已解析:自引用类型(通过 ptr)不会无限递归,
但保持防御性写法。 */
info->resolved = true;
switch (tn->kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_INFER:
case SPL_TYPE_FORALL:
case SPL_TYPE_EXISTS:
case SPL_TYPE_NEVER:
case SPL_TYPE_UNIT:
info->size_bits = 0;
info->align_bits = 8;
return;
case SPL_TYPE_ANY:
/* 顶层类型:stage1 按不透明指针处理 */
layout_ptr(layout, info);
return;
case SPL_TYPE_BOOL:
case SPL_TYPE_INT:
case SPL_TYPE_FLOAT:
layout_scalar(layout, tn, info);
return;
case SPL_TYPE_PTR:
layout_ptr(layout, info);
return;
case SPL_TYPE_ARRAY: {
resolve_type(layout, type, tn->array_type.element);
spl_layout_info_t *elem = infos_at(layout, tn->array_type.element);
if (!elem || !elem->resolved)
return;
info->size_bits = elem->size_bits * tn->array_type.len;
info->align_bits = elem->align_bits;
return;
}
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE: {
if (tn->kind == SPL_TYPE_ENUM && tn->agg_type.tag_type)
resolve_type(layout, type, tn->agg_type.tag_type);
for (usize i = 0; i < vec_size(tn->agg_type.variants); ++i) {
spl_type_member_t *m = &vec_at(tn->agg_type.variants, i);
if (m->type_id)
resolve_type(layout, type, m->type_id);
}
layout_agg(layout, tn, info);
return;
}
case SPL_TYPE_FN:
/* 函数类型按函数指针布局 */
for (usize i = 0; i < vec_size(tn->fn_type.params); ++i)
resolve_type(layout, type, vec_at(tn->fn_type.params, i));
resolve_type(layout, type, tn->fn_type.ret);
layout_ptr(layout, info);
return;
}
}
void spl_layout_resolve(spl_layout_t *layout, spl_type_t *type) {
infos_grow(layout, vec_size(type->type_table));
for (usize i = 1; i < vec_size(type->type_table); ++i)
resolve_type(layout, type, i);
}
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_type_id_t id) {
spl_layout_info_t *info = infos_at(layout, id);
if (!info || !info->resolved)
return NULL;
return info;
}
+57
View File
@@ -0,0 +1,57 @@
#ifndef __SPL_LAYOUT_H__
#define __SPL_LAYOUT_H__
#include "spl_type.h"
typedef struct {
usize size;
usize abi_align;
usize pref_align;
VEC(usize) invalid_values;
} spl_layout_scalar_t;
typedef struct {
usize add_space;
usize ptr_size;
usize ptr_align;
} spl_layout_ptr_t;
typedef struct {
bool allow_field_reordering;
enum { ALIGN_MAX, ALIGN_FIXED, ALIGN_MAX_WITH_MIN } align_rule;
usize fixed_align;
} spl_layout_agg_t;
typedef struct {
usize size_bits;
usize align_bits;
VEC(usize) field_bit_offsets;
VEC(usize) field_bit_sizes;
bool resolved;
} spl_layout_info_t;
typedef struct {
enum { SPL_BIG_ENDIAN, SPL_LITTLE_ENDIAN } endian; // TODO 更多位存储方式
usize ptr_size;
usize ptr_align;
} spl_layout_target_t;
typedef struct {
VEC(spl_layout_scalar_t) scalars;
VEC(spl_layout_ptr_t) pointers;
spl_layout_agg_t aggregate;
VEC(spl_layout_info_t) infos;
spl_layout_target_t *target;
} spl_layout_t;
void spl_layout_init(spl_layout_t *layout, spl_layout_target_t *target);
void spl_layout_drop(spl_layout_t *layout);
void spl_layout_resolve(spl_layout_t *layout, spl_type_t *type);
void spl_layout_add_scalar(spl_layout_t *layout, usize size, usize abi_align);
void spl_layout_add_ptr(spl_layout_t *layout, usize addr_space, usize size, usize align);
const spl_layout_info_t *spl_layout_info_of(spl_layout_t *layout, spl_type_id_t id);
#endif /* __SPL_LAYOUT_H__ */
+499
View File
@@ -0,0 +1,499 @@
/* spl_lexer.c - SPL lexical analyzer */
#include "spl_lexer.h"
#include "spl_tok.h"
#include <ctype.h>
#include <stdlib.h>
#include <string.h>
/* Character classification */
static int is_ident_start(char c) { return isalpha((unsigned char)c) || c == '_'; }
static int is_ident_cont(char c) { return isalnum((unsigned char)c) || c == '_'; }
/* Keyword lookup: if ident is a keyword, return its token type, else TOK_IDENT */
static spl_tok_type_t keyword_type(const char *ident, usize len) {
#define X(name, enum_name, dummy) \
if (len == sizeof(#name) - 1 && memcmp(ident, #name, len) == 0) \
return enum_name;
KEYWORD_TABLE
#undef X
return TOK_IDENT;
}
/* Escape sequence decoder - returns the decoded character,
* advances *s past the escape sequence, returns 0 on success,
* non-zero on error. */
int spl_decode_escape(const char **s, char *out) {
if (**s != '\\') {
*out = **s;
(*s)++;
return 0;
}
(*s)++; /* skip backslash */
switch (**s) {
case 'n':
*out = '\n';
break;
case 't':
*out = '\t';
break;
case 'r':
*out = '\r';
break;
case '\\':
*out = '\\';
break;
case '"':
*out = '"';
break;
case '\'':
*out = '\'';
break;
case '0':
*out = '\0';
break;
case 'x': {
(*s)++;
char hex[3] = {0, 0, 0};
int i;
for (i = 0; i < 2 && isxdigit((unsigned char)**s); i++, (*s)++) {
hex[i] = **s;
}
if (i == 0)
return -1;
*out = (char)strtol(hex, NULL, 16);
return 0;
}
default:
return -1;
}
(*s)++;
return 0;
}
spl_tok_vec_t spl_lex(const char *source, const char *fname) {
spl_tok_vec_t toks;
vec_init(toks);
usize line = 1;
usize col = 1;
usize offset = 0;
usize len = strlen(source);
while (offset < len) {
const char *start = source + offset;
char c = *start;
/* Skip whitespace (but not newlines - emit TOK_ENDLINE) */
if (c == ' ' || c == '\t' || c == '\r') {
offset++;
col++;
continue;
}
/* Newline */
if (c == '\n') {
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_ENDLINE;
tok.lexeme = start;
tok.len = 1;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
offset++;
line++;
col = 1;
continue;
}
/* Line comment */
if (c == '/' && offset + 1 < len && source[offset + 1] == '/') {
const char *nl = (const char *)memchr(start, '\n', len - offset);
usize clen = nl ? (usize)(nl - start) : (len - offset);
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_LINE_COMMENT;
tok.lexeme = start;
tok.len = clen;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
offset += clen;
col += clen;
continue;
}
/* Block comment */
if (c == '/' && offset + 1 < len && source[offset + 1] == '*') {
offset += 2;
col += 2;
usize depth = 1;
while (offset + 1 < len && depth > 0) {
if (source[offset] == '*' && source[offset + 1] == '/') {
depth--;
offset += 2;
col += 2;
if (depth == 0)
break;
} else if (source[offset] == '/' && source[offset + 1] == '*') {
depth++;
offset += 2;
col += 2;
} else {
if (source[offset] == '\n') {
line++;
col = 1;
} else {
col++;
}
offset++;
}
}
continue;
}
/* Char literal: 'x' */
if (c == '\'') {
offset++;
col++;
char buf[16];
int bi = 0;
memset(buf, 0, sizeof(buf));
if (offset < len) {
const char *cp = source + offset;
if (spl_decode_escape(&cp, &buf[bi])) {
buf[bi] = source[offset];
cp = source + offset + 1;
}
bi++;
offset = (usize)(cp - source);
col += (usize)(cp - (start + 1));
}
if (offset < len && source[offset] == '\'') {
offset++;
col++;
}
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_CHAR_LITERAL;
tok.lexeme = start;
tok.len = (usize)((source + offset) - start);
tok.fname = fname;
tok.offset = start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
/* String literal: "..." */
if (c == '"') {
offset++;
col++;
while (offset < len) {
if (source[offset] == '\\') {
offset++;
col++;
if (offset < len) {
offset++;
col++;
}
} else if (source[offset] == '"') {
offset++;
col++;
break;
} else if (source[offset] == '\n') {
line++;
col = 1;
offset++;
} else {
offset++;
col++;
}
}
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_STRING_LITERAL;
tok.lexeme = start;
tok.len = (usize)((source + offset) - start);
tok.fname = fname;
tok.offset = start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
/* Identifiers and keywords */
if (is_ident_start(c)) {
const char *id_start = start;
usize id_len = 0;
while (offset < len && is_ident_cont(source[offset])) {
offset++;
id_len++;
col++;
}
spl_tok_type_t tt = keyword_type(id_start, id_len);
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = tt;
tok.lexeme = id_start;
tok.len = id_len;
tok.fname = fname;
tok.offset = id_start - source;
tok.line = line;
tok.col = col - id_len;
vec_push(toks, tok);
continue;
}
/* Numbers: integers and floats */
if (isdigit((unsigned char)c)) {
const char *num_start = start;
int is_float = 0;
/* Check for hex/bin/oct prefix */
if (c == '0' && offset + 1 < len) {
char nc = source[offset + 1];
if (nc == 'x' || nc == 'X') {
/* Hex literal */
offset += 2;
col += 2;
while (offset < len &&
(isxdigit((unsigned char)source[offset]) || source[offset] == '_')) {
offset++;
col++;
}
goto emit_int;
}
if (nc == 'b' || nc == 'B') {
/* Binary literal */
offset += 2;
col += 2;
while (offset < len && (source[offset] == '0' || source[offset] == '1' ||
source[offset] == '_')) {
offset++;
col++;
}
goto emit_int;
}
if (nc == 'o' || nc == 'O') {
/* Octal literal */
offset += 2;
col += 2;
while (offset < len && ((source[offset] >= '0' && source[offset] <= '7') ||
source[offset] == '_')) {
offset++;
col++;
}
goto emit_int;
}
}
/* Decimal integer or float */
while (offset < len &&
(isdigit((unsigned char)source[offset]) || source[offset] == '_')) {
offset++;
col++;
}
if (offset < len && source[offset] == '.' && offset + 1 < len &&
isdigit((unsigned char)source[offset + 1])) {
is_float = 1;
offset++;
col++;
while (offset < len && isdigit((unsigned char)source[offset])) {
offset++;
col++;
}
}
if (is_float) {
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_FLOAT_LITERAL;
tok.lexeme = num_start;
tok.len = (usize)((source + offset) - num_start);
tok.fname = fname;
tok.offset = num_start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
emit_int:
{
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_INT_LITERAL;
tok.lexeme = num_start;
tok.len = (usize)((source + offset) - num_start);
tok.fname = fname;
tok.offset = num_start - source;
tok.line = line;
tok.col = col - tok.len;
vec_push(toks, tok);
continue;
}
}
/* Multi-character operators (longest match) */
#define TRY_OP1(c1, tok1) \
if (c == (c1)) { \
spl_tok_t tok; \
memset(&tok, 0, sizeof(tok)); \
tok.type = (tok1); \
tok.lexeme = start; \
tok.len = 1; \
tok.fname = fname; \
tok.offset = offset; \
tok.line = line; \
tok.col = col; \
vec_push(toks, tok); \
offset++; \
col++; \
continue; \
}
/* Helper: try to match a two-char operator */
#define TRY_OP2(c1, c2, tok2, tok1) \
if (c == (c1) && offset + 1 < len && source[offset + 1] == (c2)) { \
spl_tok_type_t op_type = (tok2); \
usize op_len = 2; \
spl_tok_t tok; \
memset(&tok, 0, sizeof(tok)); \
tok.type = op_type; \
tok.lexeme = start; \
tok.len = op_len; \
tok.fname = fname; \
tok.offset = offset; \
tok.line = line; \
tok.col = col; \
vec_push(toks, tok); \
offset += op_len; \
col += op_len; \
continue; \
}
#define TRY_OP3(c1, c2, c3, tok3, tok2, tok1) \
if (c == (c1) && offset + 1 < len && source[offset + 1] == (c2)) { \
spl_tok_type_t op_type = (tok2); \
usize op_len = 2; \
if (offset + 2 < len && source[offset + 2] == (c3)) { \
op_type = (tok3); \
op_len = 3; \
} \
spl_tok_t tok; \
memset(&tok, 0, sizeof(tok)); \
tok.type = op_type; \
tok.lexeme = start; \
tok.len = op_len; \
tok.fname = fname; \
tok.offset = offset; \
tok.line = line; \
tok.col = col; \
vec_push(toks, tok); \
offset += op_len; \
col += op_len; \
continue; \
}
/* Three-char operators first */
TRY_OP3('<', '-', '>', TOK_ARROW_BOTH, TOK_LEFT_ARROW, TOK_LT)
TRY_OP3('<', '=', '>', TOK_FAT_ARROW_BOTH, TOK_LE, TOK_LT)
TRY_OP3('<', '<', '=', TOK_ASSIGN_L_SH, TOK_L_SH, TOK_LT)
TRY_OP3('>', '>', '=', TOK_ASSIGN_R_SH, TOK_R_SH, TOK_GT)
TRY_OP3('.', '.', '.', TOK_ELLIPSIS, TOK_RANGE, TOK_DOT)
/* Two-char operators */
TRY_OP2('=', '=', TOK_EQ, TOK_ASSIGN)
TRY_OP2('=', '>', TOK_RIGHT_FAT_ARROW, TOK_ASSIGN)
TRY_OP2('!', '=', TOK_NEQ, TOK_NOT)
TRY_OP2('<', '=', TOK_LE, TOK_LT)
TRY_OP2('>', '=', TOK_GE, TOK_GT)
TRY_OP2('&', '&', TOK_AND_AND, TOK_AND)
TRY_OP2('|', '|', TOK_OR_OR, TOK_OR)
TRY_OP2('+', '=', TOK_ASSIGN_ADD, TOK_ADD)
TRY_OP2('-', '=', TOK_ASSIGN_SUB, TOK_SUB)
TRY_OP2('*', '=', TOK_ASSIGN_MUL, TOK_MUL)
TRY_OP2('/', '=', TOK_ASSIGN_DIV, TOK_DIV)
TRY_OP2('%', '=', TOK_ASSIGN_MOD, TOK_MOD)
TRY_OP2('&', '=', TOK_ASSIGN_AND, TOK_AND)
TRY_OP2('|', '=', TOK_ASSIGN_OR, TOK_OR)
TRY_OP2('^', '=', TOK_ASSIGN_XOR, TOK_XOR)
TRY_OP2('-', '>', TOK_RIGHT_ARROW, TOK_SUB)
TRY_OP2(':', '=', TOK_COLON_ASSIGN, TOK_COLON)
/* Single-character operators */
TRY_OP1('+', TOK_ADD);
TRY_OP1('-', TOK_SUB);
TRY_OP1('*', TOK_MUL);
TRY_OP1('/', TOK_DIV);
TRY_OP1('%', TOK_MOD);
TRY_OP1('&', TOK_AND);
TRY_OP1('|', TOK_OR);
TRY_OP1('^', TOK_XOR);
TRY_OP1('~', TOK_BIT_NOT);
TRY_OP1('!', TOK_NOT);
TRY_OP1('<', TOK_LT);
TRY_OP1('>', TOK_GT);
TRY_OP1('=', TOK_ASSIGN);
TRY_OP1('.', TOK_DOT);
TRY_OP1(',', TOK_COMMA);
TRY_OP1(';', TOK_SEMICOLON);
TRY_OP1(':', TOK_COLON);
TRY_OP1('(', TOK_L_PAREN);
TRY_OP1(')', TOK_R_PAREN);
TRY_OP1('[', TOK_L_BRACKET);
TRY_OP1(']', TOK_R_BRACKET);
TRY_OP1('{', TOK_L_BRACE);
TRY_OP1('}', TOK_R_BRACE);
TRY_OP1('#', TOK_SHARP);
TRY_OP1('@', TOK_AT);
TRY_OP1('$', TOK_DOLLAR);
TRY_OP1('?', TOK_COND);
// TODO
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_UNKNOWN;
tok.lexeme = start;
tok.len = 1;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
offset++;
col++;
continue;
}
/* EOF token */
{
spl_tok_t tok;
memset(&tok, 0, sizeof(tok));
tok.type = TOK_EOF;
tok.lexeme = source + offset;
tok.len = 0;
tok.fname = fname;
tok.offset = offset;
tok.line = line;
tok.col = col;
vec_push(toks, tok);
}
return toks;
}
+13
View File
@@ -0,0 +1,13 @@
/* spl_lexer.h - 独立词法分析器 */
#ifndef __SPL_LEXER_H__
#define __SPL_LEXER_H__
#include "spl_tok.h"
/* Lexer entry point */
spl_tok_vec_t spl_lex(const char *source, const char *fname);
/* Decode escape sequence, advance *s past it. Returns 0 on success. */
int spl_decode_escape(const char **s, char *out);
#endif /* __SPL_LEXER_H__ */
+14
View File
@@ -0,0 +1,14 @@
#ifndef __SPL_MPA_H__
#define __SPL_MPA_H__
#include <stdint.h>
typedef struct {
uint64_t bits;
} spl_mpa_int_t;
typedef struct {
double bits;
} spl_mpa_float_t;
#endif /* __SPL_MPA_H__ */
+2291
View File
File diff suppressed because it is too large. Load diff
+21
View File
@@ -0,0 +1,21 @@
#ifndef __SPL_PARSER_H__
#define __SPL_PARSER_H__
#include "spl_ast.h"
#include "spl_diag.h"
typedef struct spl_parser {
spl_ast_t *ast;
spl_diag_t *diag;
usize pos;
int failed;
int stop_agg;
usize error_count;
} spl_parser_t;
void spl_parser_init(spl_parser_t *p);
void spl_parser_drop(spl_parser_t *p);
void spl_ast_parse(spl_parser_t *p, spl_ast_t *ast);
#endif /* __SPL_PARSER_H__ */
+46
View File
@@ -0,0 +1,46 @@
#include "spl_scope.h"
void spl_scope_init(spl_scope_t *scope) {
vec_init(scope->scopes);
vec_push(scope->scopes, (spl_scope_node_t){0});
scope->current_scope = 0;
scope->root_scope = 0;
}
void spl_scope_drop(spl_scope_t *scope) {
for (usize i = 0; i < vec_size(scope->scopes); ++i) {
map_free(vec_at(scope->scopes, i).symbols);
}
vec_free(scope->scopes);
scope->current_scope = 0;
scope->root_scope = 0;
}
spl_scope_id_t spl_scope_alloc(spl_scope_t *scope) {
spl_scope_node_t n = {0};
n.parent = scope->current_scope;
map_init(n.symbols, MAP_HASH_STR, MAP_CMP_STR);
vec_push(scope->scopes, n);
return vec_size(scope->scopes) - 1;
}
bool spl_scope_insert(spl_scope_t *scope, spl_scope_id_t id, spl_symbol_t symbol) {
Assert(id != 0 && id < vec_size(scope->scopes));
spl_scope_node_t *node = &vec_at(scope->scopes, id);
spl_symbol_t old = {0};
if (map_get(node->symbols, symbol.name, &old))
return false;
map_put(node->symbols, symbol.name, symbol);
return true;
}
bool spl_scope_find(spl_scope_t *scope, const char *name, spl_symbol_t *out) {
if (!scope || !name || !out)
return false;
for (spl_scope_id_t id = scope->current_scope; id != 0; id = vec_at(scope->scopes, id).parent) {
spl_scope_node_t *s = &vec_at(scope->scopes, id);
if (map_get(s->symbols, name, out))
return true;
}
return false;
}
+42
View File
@@ -0,0 +1,42 @@
#ifndef __SPL_SCOPE_H__
#define __SPL_SCOPE_H__
#include "spl_lang_type.h"
typedef usize spl_scope_id_t;
typedef enum {
SPL_SYMBOL_KIND_ERROR,
SPL_SYMBOL_KIND_VAR,
SPL_SYMBOL_KIND_MEMBER,
SPL_SYMBOL_KIND_FN,
SPL_SYMBOL_KIND_TYPE,
} spl_symbol_kind_t;
typedef struct {
const char *name;
spl_symbol_kind_t kind;
spl_def_id_t node;
} spl_symbol_t;
typedef VEC(const char *) spl_symbol_path_t;
typedef struct {
spl_scope_id_t parent;
MAP(const char *, spl_symbol_t) symbols;
} spl_scope_node_t;
typedef VEC(spl_scope_node_t) spl_scope_node_vec_t;
typedef struct {
spl_scope_node_vec_t scopes;
spl_scope_id_t root_scope;
spl_scope_id_t current_scope;
} spl_scope_t;
void spl_scope_init(spl_scope_t *scope);
void spl_scope_drop(spl_scope_t *scope);
spl_scope_id_t spl_scope_alloc(spl_scope_t *scope);
bool spl_scope_insert(spl_scope_t *scope, spl_scope_id_t id, spl_symbol_t symbol);
bool spl_scope_find(spl_scope_t *scop, const char *symbol_name, spl_symbol_t *out);
#endif /* __SPL_SCOPE_H__ */
+2876
View File
File diff suppressed because it is too large. Load diff
+45
View File
@@ -0,0 +1,45 @@
#ifndef __SPL_SEMA_H__
#define __SPL_SEMA_H__
#include "spl_ast.h"
#include "spl_attr.h"
#include "spl_diag.h"
#include "spl_lang_type.h"
#include "spl_layout.h"
#include "spl_mpa.h"
#include "spl_scope.h"
#include "spl_type.h"
typedef struct spl_module_loader spl_module_loader_t;
struct spl_module_loader {
/* 从 from_fname 所在目录解析 path;返回该文件的 ast(已 init + parse)。
失败(文件不存在 / parse 错误 / 环)返回 NULL。
loader 拥有 ast 的生命周期;sema 不负责释放。 */
spl_ast_t *(*load)(void *user, const char *from_fname, const char *path, spl_diag_t *diag);
void *user;
};
typedef struct {
spl_ast_t *ast;
spl_lang_type_t *type;
spl_layout_t *layout; /* 由 splc0 拥有并解析;sema 仅借用 */
spl_scope_t *scope;
spl_symbol_t root;
spl_attr_t *attr;
spl_lang_type_id_t current_aggregate_lang;
spl_lang_type_id_t current_fn_ret_tid;
spl_lang_type_id_t current_loop_break_tid;
spl_symbol_path_t label_stack;
const spl_module_loader_t *loader;
spl_diag_t *diag;
} spl_sema_t;
void spl_sema_init(spl_sema_t *sema, spl_ast_t *ast, spl_lang_type_t *type,
spl_layout_t *layout, spl_scope_t *scope, spl_attr_t *attr);
void spl_sema_drop(spl_sema_t *sema);
void spl_sema_run_module(spl_sema_t *sema, spl_ast_node_ref_t module_ref);
void spl_sema_run(spl_sema_t *sema);
void spl_sema_dump(spl_sema_t *sema);
#endif /* __SPL_SEMA_H__ */
+15
View File
@@ -0,0 +1,15 @@
#include "spl_tok.h"
const char *spl_tok_type_name(spl_tok_type_t t) {
static const char *const names[] = {
#define X(name, enum_name, dummy) #enum_name,
KEYWORD_TABLE
#undef X
#define X(name, enum_name, dummy) #enum_name,
TOKEN_TABLE
#undef X
};
if ((usize)t < sizeof(names) / sizeof(names[0]))
return names[t];
return "?";
}
+132
View File
@@ -0,0 +1,132 @@
/* spl_tok.h - Token type definitions (extracted from spl_lexer.h) */
#ifndef __SPL_TOK_H__
#define __SPL_TOK_H__
#include "../stage0/include/utils.h"
/* clang-format off */
#define KEYWORD_TABLE \
X(any , KW_ANY , SPL_V0) \
X(as , KW_AS , SPL_V0) \
X(bool , KW_BOOL , SPL_V0) \
X(break , KW_BREAK , SPL_V0) \
X(catch , KW_CATCH , SPL_V0) \
X(comptime , KW_COMPTIME , SPL_V0) \
X(const , KW_CONST , SPL_V0) \
X(continue , KW_CONTINUE , SPL_V0) \
X(defer , KW_DEFER , SPL_V0) \
X(else , KW_ELSE , SPL_V0) \
X(enum , KW_ENUM , SPL_V0) \
X(errdefer , KW_ERRDEFER , SPL_V0) \
X(false , KW_FALSE , SPL_V0) \
X(fn , KW_FN , SPL_V0) \
X(for , KW_FOR , SPL_V0) \
X(if , KW_IF , SPL_V0) \
X(loop , KW_LOOP , SPL_V0) \
X(match , KW_MATCH , SPL_V0) \
X(null , KW_NULL , SPL_V0) \
X(ret , KW_RET , SPL_V0) \
X(shape , KW_SHAPE , SPL_V0) \
X(struct , KW_STRUCT , SPL_V0) \
X(true , KW_TRUE , SPL_V0) \
X(try , KW_TRY , SPL_V0) \
X(type , KW_TYPE , SPL_V0) \
X(undefined , KW_UNDEFINED , SPL_V0) \
X(union , KW_UNION , SPL_V0) \
X(var , KW_VAR , SPL_V0) \
X(while , KW_WHILE , SPL_V0) \
X(_ , KW_UNDERSCORE , SPL_V0) \
// KEYWORD_TABLE
#define TOKEN_TABLE \
X(unknown , TOK_UNKNOWN , SPL_V0 ) \
X(EOF , TOK_EOF , SPL_V0 ) \
X(blank , TOK_BLANK , SPL_V0 ) \
X(endline , TOK_ENDLINE , SPL_V0 ) \
X("#" , TOK_SHARP , SPL_V0 ) \
X("@" , TOK_AT , SPL_V0 ) \
X("$" , TOK_DOLLAR , SPL_V0 ) \
X("==" , TOK_EQ , SPL_V0 ) \
X("=" , TOK_ASSIGN , SPL_V0 ) \
X("+=" , TOK_ASSIGN_ADD , SPL_V0 ) \
X("+" , TOK_ADD , SPL_V0 ) \
X("-=" , TOK_ASSIGN_SUB , SPL_V0 ) \
X("->" , TOK_RIGHT_ARROW , SPL_V0 ) \
X("<-" , TOK_LEFT_ARROW , SPL_V0 ) \
X("<->" , TOK_ARROW_BOTH , SPL_V0 ) \
X("<=>" , TOK_FAT_ARROW_BOTH , SPL_V0 ) \
X("=>" , TOK_RIGHT_FAT_ARROW , SPL_V0 ) \
X("-" , TOK_SUB , SPL_V0 ) \
X("*=" , TOK_ASSIGN_MUL , SPL_V0 ) \
X("*" , TOK_MUL , SPL_V0 ) \
X("/=" , TOK_ASSIGN_DIV , SPL_V0 ) \
X("/" , TOK_DIV , SPL_V0 ) \
X("//" , TOK_LINE_COMMENT , SPL_V0 ) \
X("/* */" , TOK_BLOCK_COMMENT , SPL_V0 ) \
X("%=" , TOK_ASSIGN_MOD , SPL_V0 ) \
X("%" , TOK_MOD , SPL_V0 ) \
X("&&" , TOK_AND_AND , SPL_V0 ) \
X("&=" , TOK_ASSIGN_AND , SPL_V0 ) \
X("&" , TOK_AND , SPL_V0 ) \
X("||" , TOK_OR_OR , SPL_V0 ) \
X("|=" , TOK_ASSIGN_OR , SPL_V0 ) \
X("|" , TOK_OR , SPL_V0 ) \
X("^=" , TOK_ASSIGN_XOR , SPL_V0 ) \
X("^" , TOK_XOR , SPL_V0 ) \
X("<<=" , TOK_ASSIGN_L_SH , SPL_V0 ) \
X("<<" , TOK_L_SH , SPL_V0 ) \
X("<=" , TOK_LE , SPL_V0 ) \
X("<" , TOK_LT , SPL_V0 ) \
X(">>=" , TOK_ASSIGN_R_SH , SPL_V0 ) \
X(">>" , TOK_R_SH , SPL_V0 ) \
X(">=" , TOK_GE , SPL_V0 ) \
X(">" , TOK_GT , SPL_V0 ) \
X("!" , TOK_NOT , SPL_V0 ) \
X("!=" , TOK_NEQ , SPL_V0 ) \
X("~" , TOK_BIT_NOT , SPL_V0 ) \
X("[" , TOK_L_BRACKET , SPL_V0 ) \
X("]" , TOK_R_BRACKET , SPL_V0 ) \
X("(" , TOK_L_PAREN , SPL_V0 ) \
X(")" , TOK_R_PAREN , SPL_V0 ) \
X("{" , TOK_L_BRACE , SPL_V0 ) \
X("}" , TOK_R_BRACE , SPL_V0 ) \
X(";" , TOK_SEMICOLON , SPL_V0 ) \
X("," , TOK_COMMA , SPL_V0 ) \
X(":" , TOK_COLON , SPL_V0 ) \
X(":=" , TOK_COLON_ASSIGN , SPL_V0 ) \
X("." , TOK_DOT , SPL_V0 ) \
X(".." , TOK_RANGE , SPL_V0 ) \
X("..." , TOK_ELLIPSIS , SPL_V0 ) \
X("?" , TOK_COND , SPL_V0 ) \
X(ident , TOK_IDENT , SPL_V0 ) \
X(int , TOK_INT_LITERAL , SPL_V0 ) \
X(float , TOK_FLOAT_LITERAL , SPL_V0 ) \
X(char , TOK_CHAR_LITERAL , SPL_V0 ) \
X(string , TOK_STRING_LITERAL , SPL_V0 ) \
// TOKEN_TABLE
/* clang-format on */
typedef enum {
#define X(name, enum_name, dummy) enum_name,
KEYWORD_TABLE
#undef X
#define X(name, enum_name, dummy) enum_name,
TOKEN_TABLE
#undef X
} spl_tok_type_t;
typedef struct {
spl_tok_type_t type;
const char *lexeme;
usize len;
const char *fname;
usize offset;
usize line;
usize col;
} spl_tok_t;
typedef VEC(spl_tok_t) spl_tok_vec_t;
const char *spl_tok_type_name(spl_tok_type_t t);
#endif /* __SPL_TOK_H__ */
+431
View File
@@ -0,0 +1,431 @@
#include "spl_type.h"
static usize spl_type_hash(spl_type_node_t n) {
usize hash = spl_hash_seed();
hash = spl_hash_mix(hash, (usize)n.kind);
switch (n.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_UNIT:
case SPL_TYPE_ANY:
case SPL_TYPE_NEVER:
case SPL_TYPE_INFER:
case SPL_TYPE_FORALL:
case SPL_TYPE_EXISTS:
case SPL_TYPE_BOOL:
break;
case SPL_TYPE_INT:
hash = spl_hash_mix(hash, n.int_type.bits);
hash = spl_hash_mix(hash, (usize)n.int_type.is_signed);
break;
case SPL_TYPE_FLOAT:
hash = spl_hash_mix(hash, n.float_type.bits);
break;
case SPL_TYPE_PTR:
hash = spl_hash_mix(hash, n.ptr_type.pointee);
break;
case SPL_TYPE_ARRAY:
hash = spl_hash_mix(hash, n.array_type.element);
hash = spl_hash_mix(hash, n.array_type.len);
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
hash = spl_hash_mix(hash, (usize)n.layout.mode);
hash = spl_hash_mix(hash, n.layout.fixed_align_bits);
hash = spl_hash_mix(hash, n.agg_type.tag_type);
hash = spl_hash_mix(hash, vec_size(n.agg_type.variants));
for (usize i = 0; i < vec_size(n.agg_type.variants); i++) {
spl_type_member_t *m = &vec_at(n.agg_type.variants, i);
hash = spl_hash_mix(hash, m->type_id);
hash = spl_hash_mix_str(hash, m->name);
}
break;
case SPL_TYPE_FN:
hash = spl_hash_mix(hash, n.fn_type.ret);
hash = spl_hash_mix(hash, vec_size(n.fn_type.params));
for (usize i = 0; i < vec_size(n.fn_type.params); i++) {
hash = spl_hash_mix(hash, vec_at(n.fn_type.params, i));
}
break;
}
return hash;
}
static int spl_type_eq(spl_type_node_t n1, spl_type_node_t n2) {
if (n1.kind != n2.kind)
return 1;
switch (n1.kind) {
case SPL_TYPE_ERROR:
case SPL_TYPE_UNIT:
case SPL_TYPE_ANY:
case SPL_TYPE_NEVER:
case SPL_TYPE_INFER:
case SPL_TYPE_FORALL:
case SPL_TYPE_EXISTS:
case SPL_TYPE_BOOL:
return 0;
case SPL_TYPE_INT:
return (n1.int_type.bits != n2.int_type.bits) ||
(n1.int_type.is_signed != n2.int_type.is_signed);
case SPL_TYPE_FLOAT:
return n1.float_type.bits != n2.float_type.bits;
case SPL_TYPE_PTR:
return n1.ptr_type.pointee != n2.ptr_type.pointee;
case SPL_TYPE_ARRAY:
return (n1.array_type.element != n2.array_type.element) ||
(n1.array_type.len != n2.array_type.len);
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
if (n1.layout.mode != n2.layout.mode ||
n1.layout.fixed_align_bits != n2.layout.fixed_align_bits)
return 1;
if (n1.agg_type.tag_type != n2.agg_type.tag_type)
return 1;
if (vec_size(n1.agg_type.variants) != vec_size(n2.agg_type.variants))
return 1;
for (usize i = 0; i < vec_size(n1.agg_type.variants); i++) {
spl_type_member_t *a = &n1.agg_type.variants.data[i];
spl_type_member_t *b = &n2.agg_type.variants.data[i];
if (a->type_id != b->type_id)
return 1;
if ((a->name == NULL) != (b->name == NULL))
return 1;
if (a->name && strcmp(a->name, b->name) != 0)
return 1;
}
return 0;
case SPL_TYPE_FN:
if (n1.fn_type.ret != n2.fn_type.ret)
return 1;
if (vec_size(n1.fn_type.params) != vec_size(n2.fn_type.params))
return 1;
for (usize i = 0; i < vec_size(n1.fn_type.params); i++) {
if (vec_at(n1.fn_type.params, i) != vec_at(n2.fn_type.params, i))
return 1;
}
return 0;
}
return 1;
}
static void spl_type_node_free_vecs(spl_type_node_t *tn) {
switch (tn->kind) {
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE:
vec_free(tn->agg_type.variants);
break;
case SPL_TYPE_FN:
vec_free(tn->fn_type.params);
break;
default:
break;
}
}
/* spl_fold 回调:只在链内做结构比较(同桶已保证 hash 相同)。 */
static int spl_type_fold_eq(void *ctx, spl_fold_id_t node, const void *probe) {
spl_type_t *type = (spl_type_t *)ctx;
return spl_type_eq(vec_at(type->type_table, node), *(const spl_type_node_t *)probe) == 0;
}
static spl_fold_id_t spl_type_fold_next(void *ctx, spl_fold_id_t node) {
spl_type_t *type = (spl_type_t *)ctx;
return vec_at(type->type_table, node).hash_next;
}
static void spl_type_fold_set_next(void *ctx, spl_fold_id_t node, spl_fold_id_t next) {
spl_type_t *type = (spl_type_t *)ctx;
vec_at(type->type_table, node).hash_next = next;
}
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *tn) {
usize hash = spl_type_hash(*tn);
spl_type_id_t existing = spl_fold_find(&type->type_fold, hash, tn);
if (existing) {
spl_type_node_free_vecs(tn);
return existing;
}
spl_type_id_t id = vec_size(type->type_table);
vec_push(type->type_table, *tn);
spl_fold_insert(&type->type_fold, hash, id);
tn->kind = SPL_TYPE_ERROR;
return id;
}
void spl_type_init(spl_type_t *type) {
vec_init(type->type_table);
spl_type_node_t type_node = {0};
vec_push(type->type_table, type_node);
spl_fold_init(&type->type_fold, type, spl_type_fold_eq, spl_type_fold_next,
spl_type_fold_set_next);
}
void spl_type_drop(spl_type_t *type) {
for (usize i = 0; i < vec_size(type->type_table); i++) {
spl_type_node_t *n = &vec_at(type->type_table, i);
spl_type_node_free_vecs(n);
}
spl_fold_drop(&type->type_fold);
vec_free(type->type_table);
}
spl_type_node_t *spl_type_node(const spl_type_t *type, spl_type_id_t id) {
if (!id || id >= vec_size(type->type_table))
return NULL;
return &vec_at(type->type_table, id);
}
bool spl_type_is_subtype(const spl_type_t *type, spl_type_id_t sub, spl_type_id_t super) {
if (sub == 0 || super == 0)
return false;
if (sub == super)
return true;
spl_type_node_t *nsub = spl_type_node(type, sub);
spl_type_node_t *nsuper = spl_type_node(type, super);
if (!nsub || !nsuper)
return false;
if (nsub->kind == SPL_TYPE_NEVER)
return true;
if (nsuper->kind == SPL_TYPE_ANY)
return true;
if (nsub->kind == SPL_TYPE_INT && nsuper->kind == SPL_TYPE_INT) {
if (nsub->int_type.bits == 0)
return true;
if (nsub->int_type.is_signed == nsuper->int_type.is_signed) {
return nsub->int_type.bits <= nsuper->int_type.bits;
}
if (!nsub->int_type.is_signed && nsuper->int_type.is_signed) {
return nsuper->int_type.bits > nsub->int_type.bits;
}
return false;
}
if (nsub->kind == SPL_TYPE_FLOAT && nsuper->kind == SPL_TYPE_FLOAT) {
if (nsub->float_type.bits == 0)
return true;
return nsub->float_type.bits <= nsuper->float_type.bits;
}
return false;
}
static void spl_type_pure_dump_rec(spl_type_t *type, spl_type_id_t id, spl_type_id_vec_t *stack) {
for (usize i = 0; i < vec_size(*stack); i++) {
if (vec_at(*stack, i) == id) {
printf("<rec#%zu>", id);
return;
}
}
if (vec_size(*stack) > 32) {
printf("...");
return;
}
vec_push(*stack, id);
spl_type_node_t *n = spl_type_node(type, id);
if (!n) {
printf("none");
(void)vec_pop(*stack);
return;
}
switch (n->kind) {
case SPL_TYPE_ERROR:
printf("error");
break;
case SPL_TYPE_UNIT:
printf("unit");
break;
case SPL_TYPE_ANY:
printf("any");
break;
case SPL_TYPE_NEVER:
printf("never");
break;
case SPL_TYPE_INFER:
printf("infer");
break;
case SPL_TYPE_FORALL:
case SPL_TYPE_EXISTS:
printf("quant");
break;
case SPL_TYPE_BOOL:
printf("bool");
break;
case SPL_TYPE_INT:
if (n->int_type.bits == 0)
printf("comptime_int");
else
printf("%s%zu", n->int_type.is_signed ? "i" : "u", n->int_type.bits);
break;
case SPL_TYPE_FLOAT:
if (n->float_type.bits == 0)
printf("comptime_float");
else
printf("f%zu", n->float_type.bits);
break;
case SPL_TYPE_PTR:
printf("*");
spl_type_pure_dump_rec(type, n->ptr_type.pointee, stack);
break;
case SPL_TYPE_ARRAY:
printf("[%zu]", n->array_type.len);
spl_type_pure_dump_rec(type, n->array_type.element, stack);
break;
case SPL_TYPE_STRUCT:
case SPL_TYPE_UNION:
case SPL_TYPE_ENUM:
case SPL_TYPE_SHAPE: {
const char *kw = "struct";
if (n->kind == SPL_TYPE_UNION)
kw = "union";
else if (n->kind == SPL_TYPE_ENUM)
kw = "enum";
else if (n->kind == SPL_TYPE_SHAPE)
kw = "shape";
printf("%s{", kw);
for (usize i = 0; i < vec_size(n->agg_type.variants); i++) {
if (i)
printf(", ");
spl_type_member_t *m = &n->agg_type.variants.data[i];
printf("%s:", m->name ? m->name : "?");
spl_type_pure_dump_rec(type, m->type_id, stack);
}
printf("}");
break;
}
case SPL_TYPE_FN:
printf("fn(");
for (usize i = 0; i < vec_size(n->fn_type.params); i++) {
if (i)
printf(",");
spl_type_pure_dump_rec(type, vec_at(n->fn_type.params, i), stack);
}
printf(")");
spl_type_pure_dump_rec(type, n->fn_type.ret, stack);
break;
}
(void)vec_pop(*stack);
}
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id) {
spl_type_id_vec_t stack;
vec_init(stack);
spl_type_pure_dump_rec(type, id, &stack);
vec_free(stack);
}
spl_type_id_t spl_type_fn_param_tid(spl_type_t *type, spl_type_id_t fn_tid, usize idx) {
spl_type_node_t *n = spl_type_node(type, fn_tid);
if (!n || n->kind != SPL_TYPE_FN || idx >= vec_size(n->fn_type.params))
return 0;
return vec_at(n->fn_type.params, idx);
}
static const spl_type_member_t *spl_type_agg_member_find(spl_type_t *type, spl_type_id_t tid,
const char *name, usize *out_idx) {
spl_type_node_t *n = spl_type_node(type, tid);
if (!n || !name)
return NULL;
if (n->kind == SPL_TYPE_STRUCT || n->kind == SPL_TYPE_UNION || n->kind == SPL_TYPE_ENUM ||
n->kind == SPL_TYPE_SHAPE) {
for (usize i = 0; i < vec_size(n->agg_type.variants); i++) {
spl_type_member_t *m = &n->agg_type.variants.data[i];
if (m->name && strcmp(m->name, name) == 0) {
if (out_idx)
*out_idx = i;
return m;
}
}
}
return NULL;
}
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid,
const char *name) {
return spl_type_agg_member_find(type, tid, name, NULL);
}
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name,
usize *out_idx) {
return spl_type_agg_member_find(type, tid, name, out_idx) != NULL;
}
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind) {
spl_type_node_t tn = {0};
tn.kind = kind;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_INT;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
tn.int_type.bits = bits;
tn.int_type.is_signed = is_signed;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FLOAT;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
tn.float_type.bits = bits;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_PTR;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
tn.ptr_type.pointee = pointee;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_ARRAY;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
tn.array_type.element = element;
tn.array_type.len = len;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
usize nparams) {
spl_type_node_t tn = {0};
tn.kind = SPL_TYPE_FN;
tn.layout.mode = SPL_TYPE_LAYOUT_AUTO;
vec_init(tn.fn_type.params);
for (usize i = 0; i < nparams; i++) {
vec_push(tn.fn_type.params, params[i]);
}
tn.fn_type.ret = ret;
return spl_type_node_push(type, &tn);
}
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
spl_type_member_vec_t *variants, spl_type_id_t tag_type,
spl_type_layout_t layout) {
spl_type_node_t tn = {0};
tn.kind = tk;
tn.layout = layout;
tn.agg_type.variants = *variants;
vec_init(*variants);
if (tk == SPL_TYPE_ENUM) {
tn.agg_type.tag_type = tag_type;
} else {
tn.agg_type.tag_type = 0;
}
return spl_type_node_push(type, &tn);
}
+131
View File
@@ -0,0 +1,131 @@
#ifndef __SPL_TYPE_H__
#define __SPL_TYPE_H__
#include "../stage0/include/utils.h"
#include "spl_fold.h"
/* 类型 intern 用的哈希混合(FNV-1a 风格,顺序敏感)。
hash 只用于选择桶;相等判定始终由结构比较完成。 */
static inline usize spl_hash_mix(usize h, usize x) {
h ^= x;
h *= (usize)1099511628211ULL;
return h;
}
static inline usize spl_hash_mix_str(usize h, const char *s) {
if (!s)
return spl_hash_mix(h, 0);
while (*s) {
h = spl_hash_mix(h, (usize)(unsigned char)*s);
s++;
}
return spl_hash_mix(h, 0); /* 终止符参与混合,避免名称拼接歧义 */
}
static inline usize spl_hash_seed(void) { return (usize)14695981039346656037ULL; }
typedef usize spl_type_id_t;
typedef VEC(spl_type_id_t) spl_type_id_vec_t;
typedef enum {
SPL_TYPE_ERROR,
SPL_TYPE_NEVER, // bottom type
SPL_TYPE_ANY, // top type
SPL_TYPE_UNIT,
SPL_TYPE_INFER,
SPL_TYPE_BOOL,
SPL_TYPE_INT,
SPL_TYPE_FLOAT,
SPL_TYPE_PTR,
SPL_TYPE_ARRAY,
SPL_TYPE_STRUCT,
SPL_TYPE_UNION,
SPL_TYPE_ENUM,
SPL_TYPE_FN,
SPL_TYPE_FORALL, // TODO delete
SPL_TYPE_EXISTS, // TODO delete
SPL_TYPE_SHAPE,
} spl_type_node_kind_t;
typedef enum {
SPL_TYPE_LAYOUT_AUTO,
SPL_TYPE_LAYOUT_EXTERN_C,
SPL_TYPE_LAYOUT_PACKED,
} spl_type_layout_mode_t;
typedef struct {
spl_type_layout_mode_t mode;
usize fixed_align_bits;
} spl_type_layout_t;
typedef struct {
const char *name;
spl_type_id_t type_id;
usize ast_node_ref;
} spl_type_member_t;
typedef VEC(spl_type_member_t) spl_type_member_vec_t;
typedef struct {
spl_type_node_kind_t kind;
spl_type_layout_t layout;
union {
struct {
usize bits;
int is_signed;
} int_type;
struct {
usize bits;
} float_type;
struct {
spl_type_id_t pointee;
} ptr_type;
struct {
spl_type_id_t element;
usize len;
} array_type;
struct {
spl_type_member_vec_t variants;
spl_type_id_t tag_type;
} agg_type;
struct {
spl_type_id_vec_t params;
spl_type_id_t ret;
} fn_type;
struct {
} shape_type;
};
usize hash_next; /* 同 hash 桶内下一个类型 id;0 表示链尾。不参与相等比较。 */
} spl_type_node_t;
typedef VEC(spl_type_node_t) spl_type_node_vec_t;
typedef struct {
spl_type_node_vec_t type_table;
spl_fold_t type_fold;
} spl_type_t;
void spl_type_init(spl_type_t *type);
void spl_type_drop(spl_type_t *type);
spl_type_node_t *spl_type_node(const spl_type_t *type, spl_type_id_t id);
spl_type_id_t spl_type_node_push(spl_type_t *type, spl_type_node_t *type_node);
spl_type_id_t spl_type_builder_simple(spl_type_t *type, spl_type_node_kind_t kind);
spl_type_id_t spl_type_builder_int(spl_type_t *type, usize bits, int is_signed);
spl_type_id_t spl_type_builder_float(spl_type_t *type, usize bits);
spl_type_id_t spl_type_builder_ptr(spl_type_t *type, spl_type_id_t pointee);
spl_type_id_t spl_type_builder_array(spl_type_t *type, spl_type_id_t element, usize len);
spl_type_id_t spl_type_builder_fn(spl_type_t *type, spl_type_id_t ret, const spl_type_id_t *params,
usize nparams);
spl_type_id_t spl_type_builder_agg(spl_type_t *type, spl_type_node_kind_t tk,
spl_type_member_vec_t *variants, spl_type_id_t tag_type,
spl_type_layout_t layout);
void spl_type_pure_dump(spl_type_t *type, spl_type_id_t id);
bool spl_type_is_subtype(const spl_type_t *type, spl_type_id_t sub, spl_type_id_t super);
spl_type_id_t spl_type_fn_param_tid(spl_type_t *type, spl_type_id_t fn_tid, usize idx);
const spl_type_member_t *spl_type_agg_member(spl_type_t *type, spl_type_id_t tid, const char *name);
bool spl_type_agg_member_idx(spl_type_t *type, spl_type_id_t tid, const char *name, usize *out_idx);
#endif /* __SPL_TYPE_H__ */
+426
View File
@@ -0,0 +1,426 @@
/* splc0.c - SPL compiler CLI (stage 1, 引导用)
*
* splc0 --dump tokens|ast|sema|ir|vm <file> dump 前端产物
* splc0 <in> <out> 编译
*/
#define __SCC_LOG_IMPL_IMPORT_SRC__
#include "../stage0/include/utils.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "spl_ast.h"
#include "spl_ast2ir.h"
#include "spl_diag.h"
#include "spl_ir2vm.h"
#include "spl_lexer.h"
#include "spl_parser.h"
#include "spl_sema.h"
#include "spl_tok.h"
typedef enum {
DUMP_NONE,
DUMP_TOKEN,
DUMP_AST,
DUMP_SEMA,
DUMP_IR,
DUMP_VM,
} dump_t;
typedef struct {
spl_ast_t *ast;
char *abs_path;
char *src;
} spl_driver_module_t;
typedef VEC(spl_driver_module_t) spl_driver_module_vec_t;
typedef struct {
spl_ast_t main_ast;
spl_tok_vec_t main_toks;
char *main_path;
spl_driver_module_vec_t modules;
MAP(const char *, usize) path_to_idx;
spl_diag_t *diag;
} spl_driver_t;
static char *read_file(const char *path, long *out_len) {
FILE *f = fopen(path, "rb");
if (!f) {
fprintf(stderr, "path `%s` ", path);
perror("fopen");
return NULL;
}
fseek(f, 0, SEEK_END);
long len = ftell(f);
fseek(f, 0, SEEK_SET);
char *buf = malloc((size_t)len + 1);
if (!buf) {
fclose(f);
return NULL;
}
size_t nread = fread(buf, 1, (size_t)len, f);
fclose(f);
buf[nread] = '\0';
if (out_len)
*out_len = (long)nread;
return buf;
}
/* 注意:按值接收,内部 vec_free 释放与调用方共享的 data 指针。
调用后原 vec 视为已消费,不要再使用。 */
static void dump_tokens(spl_tok_vec_t toks) {
printf("tokens got (%zu)\n", toks.size);
for (usize i = 0; i < toks.size; i++) {
const spl_tok_t *t = &toks.data[i];
printf("[%s] %.*s (%zu:%zu)\n", spl_tok_type_name(t->type), (int)t->len, t->lexeme, t->line,
t->col);
}
vec_free(toks);
}
/* 折叠重复分隔符并去掉 "." 路径分量,使同一模块的 import 解析结果唯一。
就地重写,'\' 统一成 '/';保留前导分隔符(绝对路径)。 */
static void normalize_import_path(char *p) {
usize n = strlen(p);
char *out = malloc(n + 1);
if (!out)
return;
char *w = out;
if (p[0] == '/' || p[0] == '\\')
*w++ = '/';
char *r = p;
while (*r) {
while (*r == '/' || *r == '\\')
r++;
if (!*r)
break;
char *seg = r;
while (*r && *r != '/' && *r != '\\')
r++;
usize len = (usize)(r - seg);
if (len == 1 && seg[0] == '.')
continue;
if (w != out && w[-1] != '/')
*w++ = '/';
memcpy(w, seg, len);
w += len;
}
*w = 0;
strcpy(p, out);
free(out);
}
/* 把 import_path 拼接到 importing_file 所在目录。
from_fname 为空时按相对 cwd 处理。绝对路径直接透传。 */
static void resolve_relative(const char *from, const char *path, char *out, usize cap) {
if (!from || !path) {
if (cap)
out[0] = 0;
return;
}
if (path[0] == '/' || path[0] == '\\' || (path[0] && path[1] == ':')) {
snprintf(out, cap, "%s", path);
normalize_import_path(out);
return;
}
const char *last_sep = NULL;
for (const char *p = from; *p; ++p)
if (*p == '/' || *p == '\\')
last_sep = p;
if (!last_sep) {
snprintf(out, cap, "%s", path);
normalize_import_path(out);
return;
}
usize dir_len = (usize)(last_sep - from) + 1;
snprintf(out, cap, "%.*s%s", (int)dir_len, from, path);
normalize_import_path(out);
}
static spl_ast_t *driver_load(void *user, const char *from_fname, const char *path,
spl_diag_t *diag) {
spl_driver_t *d = user;
char abs[1024];
resolve_relative(from_fname, path, abs, sizeof abs);
usize idx;
if (map_get(d->path_to_idx, abs, &idx)) {
spl_ast_t *a = vec_at(d->modules, idx).ast;
if (!a) {
spl_diag_error(diag, SPL_DIAG_KIND_CIRCULAR_DEP, NULL, "circular import: `%s`", abs);
return NULL;
}
return a;
}
/* 先登记 ast=NULL 占位:若后续解析过程中又有 @import 指回本路径,
会命中这里,判定为环。 */
char *key = strdup(abs);
idx = vec_size(d->modules);
spl_driver_module_t placeholder = {.ast = NULL, .abs_path = key, .src = NULL};
vec_push(d->modules, placeholder);
map_put(d->path_to_idx, key, idx);
long len = 0;
char *src = read_file(abs, &len);
if (!src) {
spl_diag_error(diag, SPL_DIAG_KIND_LEX_UNEXPECTED, NULL, "@import: cannot open `%s`", abs);
return NULL;
}
(void)len;
/* key 同时用作 lexer 的 fname:token.fname 与 map key 共享一份 strdup,
减少一次分配;cleanup 时只 free module.abs_path */
spl_tok_vec_t toks = spl_lex(src, key);
spl_ast_t *ast = malloc(sizeof *ast);
spl_ast_init(ast, &toks);
spl_parser_t parser;
spl_parser_init(&parser);
parser.diag = diag;
spl_ast_parse(&parser, ast);
spl_parser_drop(&parser);
vec_at(d->modules, idx).ast = ast;
vec_at(d->modules, idx).src = src;
return ast;
}
static int compile_spl(const char *src, const char *fname, const char *outpath, int gen_debug,
dump_t dump) {
(void)gen_debug;
spl_diag_t diag;
spl_diag_init(&diag, stderr);
spl_driver_t drv = {0};
drv.diag = &diag;
drv.main_path = strdup(fname);
drv.main_toks = spl_lex(src, drv.main_path);
spl_ast_init(&drv.main_ast, &drv.main_toks);
map_init(drv.path_to_idx, MAP_HASH_STR, MAP_CMP_STR);
vec_init(drv.modules);
int rc = 0;
/* dump_tokens 消费 drv.main_toks(共享 data),之后 main_ast.input 悬空,
所以这条分支必须在 spl_ast_parse 之前、且不能再 drop main_ast。 */
if (dump == DUMP_TOKEN) {
dump_tokens(drv.main_toks);
free(drv.main_path);
map_free(drv.path_to_idx);
spl_diag_drop(&diag);
return 0;
}
spl_attr_t attr;
spl_lang_type_t lang_type;
spl_layout_target_t layout_target;
spl_layout_t layout;
spl_scope_t scope;
spl_sema_t sema;
spl_ast2ir_t a2ir;
spl_ir_builder_t ir_builder;
spl_ir2vm_t ir2vm;
spl_ast_ptr_vec_t all_asts;
int attr_ok = 0, lang_type_ok = 0, layout_ok = 0, scope_ok = 0;
int sema_ok = 0, a2ir_ok = 0, irb_ok = 0, ir2vm_ok = 0;
spl_diag_set_stage(&diag, SPL_STAGE_PARSE);
spl_parser_t parser;
spl_parser_init(&parser);
parser.diag = &diag;
spl_ast_parse(&parser, &drv.main_ast);
spl_parser_drop(&parser);
if (spl_diag_has_error(&diag) || spl_diag_has_fatal(&diag)) {
spl_diag_summary(&diag);
rc = 1;
goto cleanup;
}
if (dump == DUMP_AST) {
spl_ast_dump(&drv.main_ast, drv.main_ast.root);
goto cleanup;
}
spl_attr_init(&attr);
attr_ok = 1;
spl_lang_type_init(&lang_type);
lang_type_ok = 1;
/* 目标描述符:剥离目标机器细节,layout 是 size/align/offset 的唯一来源。 */
memset(&layout_target, 0, sizeof layout_target);
layout_target.endian = SPL_LITTLE_ENDIAN;
layout_target.ptr_size = sizeof(void *);
layout_target.ptr_align = sizeof(void *);
spl_layout_init(&layout, &layout_target);
layout_ok = 1;
spl_scope_init(&scope);
scope_ok = 1;
spl_sema_init(&sema, &drv.main_ast, &lang_type, &layout, &scope, &attr);
sema_ok = 1;
spl_module_loader_t loader = {.load = driver_load, .user = &drv};
sema.loader = &loader;
spl_diag_set_stage(&diag, SPL_STAGE_SEMA);
sema.diag = &diag;
spl_sema_run(&sema);
if (spl_diag_has_error(&diag) || spl_diag_has_fatal(&diag)) {
spl_diag_summary(&diag);
rc = 1;
goto cleanup;
}
if (dump == DUMP_SEMA) {
spl_sema_dump(&sema);
spl_ast_dump(&drv.main_ast, drv.main_ast.root);
goto cleanup;
}
/* 收集所有 ast:主文件在前,被 import 的文件按加载顺序在后。
ast2ir 内部会 vec_free(all_asts)。 */
vec_init(all_asts);
vec_push(all_asts, &drv.main_ast);
for (usize i = 0; i < vec_size(drv.modules); ++i)
vec_push(all_asts, vec_at(drv.modules, i).ast);
spl_ir_builder_init(&ir_builder);
irb_ok = 1;
spl_ast2ir_init(&a2ir, &ir_builder, &layout, &sema);
a2ir_ok = 1;
spl_diag_set_stage(&diag, SPL_STAGE_AST2IR);
a2ir.diag = &diag;
spl_ast2ir_run(&a2ir, all_asts);
if (spl_diag_has_error(&diag) || spl_diag_has_fatal(&diag)) {
spl_diag_summary(&diag);
rc = 1;
goto cleanup;
}
if (dump == DUMP_IR) {
spl_ir_dump(&ir_builder.ir, &lang_type.ir, &attr);
goto cleanup;
}
/* 类型已全部就绪:解析 layout,供 ir2vm 的 size/align/offset 使用。 */
spl_layout_resolve(&layout, &lang_type.ir);
spl_ir2vm_init(&ir2vm, &a2ir.ir->ir, &lang_type.ir, &layout, &attr);
ir2vm_ok = 1;
spl_diag_set_stage(&diag, SPL_STAGE_IR2VM);
ir2vm.diag = &diag;
rc = spl_ir2vm_run(&ir2vm);
if (spl_diag_has_error(&diag) || spl_diag_has_fatal(&diag)) {
spl_diag_summary(&diag);
goto cleanup;
}
if (dump == DUMP_VM) {
spl_prog_dump(&ir2vm.prog);
goto cleanup;
}
spl_prog_store_to_file(outpath, &ir2vm.prog);
rc = 0;
cleanup:
if (ir2vm_ok)
spl_ir2vm_drop(&ir2vm);
if (a2ir_ok)
spl_ast2ir_drop(&a2ir);
if (irb_ok)
spl_ir_builder_drop(&ir_builder);
if (sema_ok)
spl_sema_drop(&sema);
if (scope_ok)
spl_scope_drop(&scope);
if (layout_ok)
spl_layout_drop(&layout);
if (lang_type_ok)
spl_lang_type_drop(&lang_type);
if (attr_ok)
spl_attr_drop(&attr);
spl_ast_drop(&drv.main_ast);
for (usize i = 0; i < vec_size(drv.modules); ++i) {
spl_ast_t *a = vec_at(drv.modules, i).ast;
if (a) {
spl_ast_drop(a);
free(a);
}
free(vec_at(drv.modules, i).abs_path);
free(vec_at(drv.modules, i).src);
}
vec_free(drv.modules);
/* map 的 key 是 module 里 strdup 出的 abs_path,已随 module 释放 */
map_free(drv.path_to_idx);
free(drv.main_path);
spl_diag_drop(&diag);
return rc;
}
int main(int argc, char **argv) {
if (argc < 2) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
if (strcmp(argv[1], "--help") == 0 || strcmp(argv[1], "-h") == 0) {
LOG_INFO("splc0 <in> <out> compile (.spl -> .sir, stage B)");
LOG_INFO("splc0 --dump <flags> <file> dump: lex,ast,sema,ir,vm,none");
return 0;
}
int argi = 1;
if (argi >= argc) {
LOG_FATAL("Usage: splc0 [--dump <flags>] <in> [out]");
return 1;
}
dump_t dump = DUMP_NONE;
if (strcmp(argv[argi], "--dump") == 0) {
if (argc < argi + 3) {
LOG_INFO("splc0: --dump need <flags> <file>");
return 1;
}
const char *flags = argv[argi + 1];
if (strcmp(flags, "lex") == 0) {
dump = DUMP_TOKEN;
} else if (strcmp(flags, "ast") == 0) {
dump = DUMP_AST;
} else if (strcmp(flags, "sema") == 0) {
dump = DUMP_SEMA;
} else if (strcmp(flags, "ir") == 0) {
dump = DUMP_IR;
} else if (strcmp(flags, "vm") == 0) {
dump = DUMP_VM;
} else if (strcmp(flags, "none") == 0) {
dump = DUMP_NONE;
} else {
LOG_FATAL("splc0: --dump takes one of lex|ast|sema|ir|vm|none, got `%s`", flags);
return 1;
}
argi += 2;
}
/* splc0 [-g] <in> <out> */
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] or splc0 --dump <flags> <file>\n");
return 1;
}
int gen_debug = 0;
if (strcmp(argv[argi], "-g") == 0) {
gen_debug = 1;
argi++;
}
if (argc < argi + 2) {
LOG_FATAL("Usage: splc0 <in> <out> [-g] or splc0 --dump <flags> <file>\n");
return 1;
}
long len;
char *src = read_file(argv[argi], &len);
if (!src)
return 1;
int rc = compile_spl(src, argv[argi], argv[argi + 1], gen_debug, dump);
free(src);
return rc;
}
+642
View File
@@ -0,0 +1,642 @@
// Expect retcode = 0
// AST:用 ADT(enum 带载荷)表达节点,节点引用是 arena 序号 usize。
// stage1 的 C 结构只是「手写 union 模拟 ADT」;这里直接用 SPL 的 enum 载荷,
// 不照抄 union 布局,只要求最终 dump / 语义与 stage1 一致。
// 索引 0 为 NONE 哨兵(与 stage1 一致)。
type .{ .Error } = @import("utils/error.spl");
type .{ .Vec } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .ByteBuffer } = @import("utils/byte_buffer.spl");
type .{ .append_usize } = @import("utils/fmt.spl");
type .{ .Punct } = @import("token.spl");
type BigInt = @import("utils/mp.spl");
type .{ .Span, .span_none, .span_make, .span_is_none } = @import("./diag.spl");
type .{ .Sources, .Source, .set_at } = @import("utils/source.spl");
// 算子不另立 enum:AST 直接存词法 Punct。一元/二元由节点 kind 区分
// (一元:Sub=负 / Not=! / BitNot=~ / And=& / Mul=.*;二元即对应 Punct)。
// ---- 节点体(ADT;variant 名 = stage1 的 kind 名;载荷用内联匿名 struct)----
type Body = enum {
None,
Root: struct { members: usize },
ContainerMembers: struct { external_tags: Vec, declarations: Vec },
ExternalTagItem: struct { is_at: bool, is_external: bool, name: ByteView, args: Vec },
TagItem: struct { is_at: bool, is_external: bool, name: ByteView, args: Vec },
ComptimeDecl: struct { body: usize },
TopLevelBlock: struct { tag_list: Vec, block: usize },
FnDecl: struct {
tag_list: Vec,
is_comptime: bool,
name: ByteView,
params: Vec,
ret_type: usize,
body: usize,
},
VarDecl: struct { attr_list: Vec, pattern: usize, type_expr: usize, init_expr: usize },
ConstDecl: struct { attr_list: Vec, pattern: usize, type_expr: usize, init_expr: usize },
TypeDecl: struct { attr_list: Vec, pattern: usize, type_expr: usize },
MemberDecl: struct {
attr_list: Vec,
name: ByteView,
type_expr: usize,
init_expr: usize,
},
ParamDecl: struct { attr_list: Vec, name: ByteView, type_expr: usize },
StatementRet: struct { expr: usize },
StatementBreak: struct { label: usize, expr: usize },
StatementContinue: struct { label: usize },
StatementDefer: struct { body: usize },
StatementComptime: struct { body: usize },
StatementDecl: struct { decl: usize },
StatementExpr: struct { expr: usize },
AggregateMember: struct {
attr_list: Vec,
name: ByteView,
type_expr: usize,
init_expr: usize,
},
StructInitItem: struct { name: ByteView, expr: usize },
MatchArm: struct { pattern: usize, body: usize },
Label: struct { name: ByteView },
ExprIntLit: struct { value: BigInt }, // 任意宽度(mp),解析后由 Ast 拥有
ExprFloatLit: struct { text: ByteView },
ExprCharLit: struct { value: u8 },
ExprStringLit: struct { data: ByteView },
ExprBoolLit: struct { value: bool },
ExprNullLit,
ExprUndefinedLit,
ExprIdent: struct { name: ByteView },
ExprUnary: struct { op: Punct, operand: usize },
ExprBinary: struct { op: Punct, left: usize, right: usize },
ExprCall: struct { callee: usize, args: Vec },
ExprField: struct { obj: usize, name: ByteView },
ExprIndex: struct { obj: usize, index: usize },
ExprSlice: struct { obj: usize, begin: usize, end: usize },
ExprCast: struct { expr: usize, type_expr: usize },
ExprTuple: struct { items: Vec },
ExprArrayLit: struct {
has_len: bool,
len: usize,
is_underscore_len: bool,
elem_type: usize,
elems: Vec,
},
ExprAggregateLit: struct { name: ByteView, fields: Vec },
ExprComptimeCall: struct { name: ByteView, args: Vec },
ExprBlock: struct { stmts: Vec, tail_expr: usize },
ExprIf: struct { cond: usize, then_block: usize, else_branch: usize },
ExprIfvar: struct { var_decl: usize, then_block: usize, else_branch: usize },
ExprWhile: struct { label: usize, cond: usize, body: usize, else_branch: usize },
ExprLoop: struct { label: usize, body: usize },
ExprFor: struct {
label: usize,
iter_exprs: Vec,
pattern: usize,
body: usize,
else_branch: usize,
},
ExprMatch: struct { matched_expr: usize, arms: Vec },
ExprFnType: struct { is_comptime: bool, params: Vec, ret_type: usize },
TypePath: struct { name: ByteView, generic_args: Vec },
TypePointer: struct { pointee: usize },
TypeArray: struct {
has_len: bool,
len: isize,
is_underscore_len: bool,
elem_type: usize,
},
TypeSlice: struct { elem_type: usize },
TypeFn: struct { is_comptime: bool, params: Vec, ret_type: usize },
TypeParen: struct { types: Vec },
TypeAggregate: struct { kind_name: ByteView, members: Vec },
TypeComptimeCall: struct { name: ByteView, args: Vec },
PatternIdent: struct { name: ByteView },
PatternUnderscore,
PatternDot: struct { name: ByteView, sub_pattern: usize },
PatternTuple: struct { items: Vec },
PatternList: struct { items: Vec },
PatternAggregate: struct { items: Vec },
PatternField: struct { name: ByteView, pattern: usize },
}
fn kind_name(body: Body): []u8 {
match body {
.None => { ret "none"; },
.Root(_) => { ret "root"; },
.ContainerMembers(_) => { ret "container_members"; },
.ExternalTagItem(_) => { ret "external_tag_item"; },
.TagItem(_) => { ret "tag_item"; },
.ComptimeDecl(_) => { ret "comptime_decl"; },
.TopLevelBlock(_) => { ret "top_level_block"; },
.FnDecl(_) => { ret "fn_decl"; },
.VarDecl(_) => { ret "var_decl"; },
.ConstDecl(_) => { ret "const_decl"; },
.TypeDecl(_) => { ret "type_decl"; },
.MemberDecl(_) => { ret "member_decl"; },
.ParamDecl(_) => { ret "param_decl"; },
.StatementRet(_) => { ret "statement_ret"; },
.StatementBreak(_) => { ret "statement_break"; },
.StatementContinue(_) => { ret "statement_continue"; },
.StatementDefer(_) => { ret "statement_defer"; },
.StatementComptime(_) => { ret "statement_comptime"; },
.StatementDecl(_) => { ret "statement_decl"; },
.StatementExpr(_) => { ret "statement_expr"; },
.AggregateMember(_) => { ret "aggregate_member"; },
.StructInitItem(_) => { ret "struct_init_item"; },
.MatchArm(_) => { ret "match_arm"; },
.Label(_) => { ret "label"; },
.ExprIntLit(_) => { ret "int_lit"; },
.ExprFloatLit(_) => { ret "float_lit"; },
.ExprCharLit(_) => { ret "char_lit"; },
.ExprStringLit(_) => { ret "string_lit"; },
.ExprBoolLit(_) => { ret "bool_lit"; },
.ExprNullLit => { ret "null_lit"; },
.ExprUndefinedLit => { ret "undefined_lit"; },
.ExprIdent(_) => { ret "ident"; },
.ExprUnary(_) => { ret "unary"; },
.ExprBinary(_) => { ret "binary"; },
.ExprCall(_) => { ret "call"; },
.ExprField(_) => { ret "field"; },
.ExprIndex(_) => { ret "index"; },
.ExprSlice(_) => { ret "slice"; },
.ExprCast(_) => { ret "cast"; },
.ExprTuple(_) => { ret "tuple"; },
.ExprArrayLit(_) => { ret "array_literal"; },
.ExprAggregateLit(_) => { ret "aggregate_literal"; },
.ExprComptimeCall(_) => { ret "comptime_call"; },
.ExprBlock(_) => { ret "block"; },
.ExprIf(_) => { ret "if_expr"; },
.ExprIfvar(_) => { ret "ifvar_expr"; },
.ExprWhile(_) => { ret "while_expr"; },
.ExprLoop(_) => { ret "loop_expr"; },
.ExprFor(_) => { ret "for_expr"; },
.ExprMatch(_) => { ret "match_expr"; },
.ExprFnType(_) => { ret "fn_type"; },
.TypePath(_) => { ret "type_path"; },
.TypePointer(_) => { ret "type_pointer"; },
.TypeArray(_) => { ret "type_array"; },
.TypeSlice(_) => { ret "type_slice"; },
.TypeFn(_) => { ret "type_fn"; },
.TypeParen(_) => { ret "type_paren"; },
.TypeAggregate(_) => { ret "type_aggregate"; },
.TypeComptimeCall(_) => { ret "type_comptime_call"; },
.PatternIdent(_) => { ret "pattern_ident"; },
.PatternUnderscore => { ret "pattern_underscore"; },
.PatternDot(_) => { ret "pattern_dot"; },
.PatternTuple(_) => { ret "pattern_tuple"; },
.PatternList(_) => { ret "pattern_list"; },
.PatternAggregate(_) => { ret "pattern_aggregate"; },
.PatternField(_) => { ret "pattern_field"; },
}
ret "?";
}
type Node = struct {
span: Span,
resolved_def_id: usize,
resolved_lang_tid: usize,
expected_lang_tid: usize,
attrs: Vec,
body: Body,
}
type Ast = @self;
nodes: Vec, // Node
root: usize,
sources: *Sources, // 借用;可为 null(dump 时不解析行列)
type AstResult = enum {
Ok: Ast,
Err: Error,
}
fn new_node(body: Body, span: Span): Node {
ret Node {
.span = span,
.resolved_def_id = 0,
.resolved_lang_tid = 0,
.expected_lang_tid = 0,
.attrs = Vec.blank(@sizeof(usize), @alignof(usize)),
.body = body,
};
}
fn new(sources: *Sources): AstResult {
var ast = Ast {
.nodes = Vec.blank(@sizeof(Node), @alignof(Node)),
.root = 0,
.sources = sources,
};
var sentinel = new_node(.None, span_none());
match Vec.push(&ast.nodes, &sentinel as *u8) {
.Ok => {},
.Err(error) => {
Vec.drop(&ast.nodes);
ret .Err(error);
},
}
ret .Ok(ast);
}
fn drop(self: *Ast) {
var i: usize = 0;
while i < self.nodes.len {
var n = node(self, i);
if n != null {
Vec.drop(&n.attrs);
match n.body {
.ExprIntLit(x) => { BigInt.drop(&x.value); },
_ => {},
}
}
i = i + 1;
}
Vec.drop(&self.nodes);
self.root = 0;
}
fn node(self: *Ast, ref: usize): *Node {
match Vec.get(&self.nodes, ref) {
.Ok(ptr) => { ret ptr as *Node; },
.Err(error) => { ret null; },
}
ret null;
}
// 追加节点,返回其引用(失败返回 0)。
fn alloc(self: *Ast, body: Body, span: Span): usize {
var n = new_node(body, span);
match Vec.push(&self.nodes, &n as *u8) {
.Ok => {},
.Err(error) => {
Vec.drop(&n.attrs);
ret 0;
},
}
ret self.nodes.len - 1;
}
fn count(self: *Ast): usize {
ret self.nodes.len;
}
fn ref_vec(): Vec {
ret Vec.blank(@sizeof(usize), @alignof(usize));
}
// ---- dump(镜像 stage1 spl_ast_dump)----
//
// AST:
// <indent>`-/|-kind #ref [line:col]
// indent:栈上每层 last 为真输出 " ",否则 "| "。
fn push(buf: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(buf, bytes) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
fn push_byte(buf: *ByteBuffer, byte: u8): bool {
match ByteBuffer.append_byte(buf, byte) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
fn push_usize(buf: *ByteBuffer, value: usize): bool {
match append_usize(buf, value, 10, false) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
fn ref_at(list: Vec, index: usize): usize {
match Vec.get(&list, index) {
.Ok(ptr) => { ret (ptr as *usize).*; },
.Err(error) => { ret 0; },
}
ret 0;
}
fn dump_opt(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool): bool {
if ref == 0 { ret true; }
ret dump_node(ast, buf, stack, ref, last);
}
fn dump_list(ast: *Ast, buf: *ByteBuffer, stack: *Vec, list: Vec): bool {
var i: usize = 0;
while i < list.len {
var last = (i + 1 == list.len);
if !dump_node(ast, buf, stack, ref_at(list, i), last) { ret false; }
i = i + 1;
}
ret true;
}
fn dump_node(ast: *Ast, buf: *ByteBuffer, stack: *Vec, ref: usize, last: bool): bool {
var n = node(ast, ref);
if n == null { ret false; }
var i: usize = 0;
while i < stack.len {
var flag: u8 = 0;
match Vec.get(stack, i) {
.Ok(ptr) => { flag = ptr.*; },
.Err(error) => { ret false; },
}
if !push(buf, if flag != 0 { " " } else { "| " }) { ret false; }
i = i + 1;
}
if !push(buf, if last { "`-" } else { "|-" }) { ret false; }
if !push(buf, kind_name(n.body)) { ret false; }
if !push(buf, " #") { ret false; }
if !push_usize(buf, ref) { ret false; }
if !span_is_none(n.span) && ast.sources != null {
var src = set_at(ast.sources, n.span.file);
if src != null {
var pos = Source.line_col(src.*, n.span.start);
if !push(buf, " [") { ret false; }
if !push_usize(buf, pos.line) { ret false; }
if !push_byte(buf, ':') { ret false; }
if !push_usize(buf, pos.col) { ret false; }
if !push_byte(buf, ']') { ret false; }
}
}
if !push_byte(buf, '\n') { ret false; }
var l: u8 = 0;
if last { l = 1; }
match Vec.push(stack, &l as *u8) {
.Ok => {},
.Err(error) => { ret false; },
}
var ok = true;
match n.body {
.None => {},
.Root(r) => { ok = dump_opt(ast, buf, stack, r.members, true); },
.ContainerMembers(c) => {
ok = dump_list(ast, buf, stack, c.external_tags) &&
dump_list(ast, buf, stack, c.declarations);
},
.ExternalTagItem(t) => { ok = dump_list(ast, buf, stack, t.args); },
.TagItem(t) => { ok = dump_list(ast, buf, stack, t.args); },
.ComptimeDecl(x) => { ok = dump_opt(ast, buf, stack, x.body, true); },
.TopLevelBlock(t) => {
ok = dump_list(ast, buf, stack, t.tag_list) &&
dump_opt(ast, buf, stack, t.block, true);
},
.FnDecl(f) => {
ok = dump_list(ast, buf, stack, f.tag_list) &&
dump_list(ast, buf, stack, f.params) &&
dump_opt(ast, buf, stack, f.ret_type, false) &&
dump_opt(ast, buf, stack, f.body, true);
},
.VarDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list) &&
dump_opt(ast, buf, stack, d.pattern, false) &&
dump_opt(ast, buf, stack, d.type_expr, false) &&
dump_opt(ast, buf, stack, d.init_expr, true);
},
.ConstDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list) &&
dump_opt(ast, buf, stack, d.pattern, false) &&
dump_opt(ast, buf, stack, d.type_expr, false) &&
dump_opt(ast, buf, stack, d.init_expr, true);
},
.TypeDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list) &&
dump_opt(ast, buf, stack, d.pattern, false) &&
dump_opt(ast, buf, stack, d.type_expr, true);
},
.MemberDecl(d) => {
ok = dump_list(ast, buf, stack, d.attr_list) &&
dump_opt(ast, buf, stack, d.type_expr, false) &&
dump_opt(ast, buf, stack, d.init_expr, true);
},
.ParamDecl(p) => {
ok = dump_list(ast, buf, stack, p.attr_list) &&
dump_opt(ast, buf, stack, p.type_expr, true);
},
.StatementRet(e) => { ok = dump_opt(ast, buf, stack, e.expr, true); },
.StatementBreak(b) => {
ok = dump_opt(ast, buf, stack, b.label, false) &&
dump_opt(ast, buf, stack, b.expr, true);
},
.StatementContinue(x) => { ok = dump_opt(ast, buf, stack, x.label, true); },
.StatementDefer(x) => { ok = dump_opt(ast, buf, stack, x.body, true); },
.StatementComptime(x) => { ok = dump_opt(ast, buf, stack, x.body, true); },
.StatementDecl(d) => { ok = dump_opt(ast, buf, stack, d.decl, true); },
.StatementExpr(e) => { ok = dump_opt(ast, buf, stack, e.expr, true); },
.AggregateMember(d) => {
ok = dump_list(ast, buf, stack, d.attr_list) &&
dump_opt(ast, buf, stack, d.type_expr, false) &&
dump_opt(ast, buf, stack, d.init_expr, true);
},
.StructInitItem(s) => { ok = dump_opt(ast, buf, stack, s.expr, true); },
.MatchArm(m) => {
ok = dump_opt(ast, buf, stack, m.pattern, false) &&
dump_opt(ast, buf, stack, m.body, true);
},
.Label(x) => {},
.ExprIntLit(x) => {},
.ExprFloatLit(x) => {},
.ExprCharLit(x) => {},
.ExprStringLit(x) => {},
.ExprBoolLit(x) => {},
.ExprNullLit => {},
.ExprUndefinedLit => {},
.ExprIdent(x) => {},
.ExprUnary(u) => { ok = dump_opt(ast, buf, stack, u.operand, true); },
.ExprBinary(b) => {
ok = dump_opt(ast, buf, stack, b.left, false) &&
dump_opt(ast, buf, stack, b.right, true);
},
.ExprCall(c) => {
ok = dump_opt(ast, buf, stack, c.callee, false) &&
dump_list(ast, buf, stack, c.args);
},
.ExprField(f) => { ok = dump_opt(ast, buf, stack, f.obj, true); },
.ExprIndex(x) => {
ok = dump_opt(ast, buf, stack, x.obj, false) &&
dump_opt(ast, buf, stack, x.index, true);
},
.ExprSlice(s) => {
ok = dump_opt(ast, buf, stack, s.obj, false) &&
dump_opt(ast, buf, stack, s.begin, false) &&
dump_opt(ast, buf, stack, s.end, true);
},
.ExprCast(c) => {
ok = dump_opt(ast, buf, stack, c.expr, false) &&
dump_opt(ast, buf, stack, c.type_expr, true);
},
.ExprTuple(v) => { ok = dump_list(ast, buf, stack, v.items); },
.ExprArrayLit(a) => {
ok = dump_opt(ast, buf, stack, a.elem_type, false) &&
dump_list(ast, buf, stack, a.elems);
},
.ExprAggregateLit(a) => { ok = dump_list(ast, buf, stack, a.fields); },
.ExprComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); },
.ExprBlock(b) => {
ok = dump_list(ast, buf, stack, b.stmts) &&
dump_opt(ast, buf, stack, b.tail_expr, true);
},
.ExprIf(x) => {
ok = dump_opt(ast, buf, stack, x.cond, false) &&
dump_opt(ast, buf, stack, x.then_block, false) &&
dump_opt(ast, buf, stack, x.else_branch, true);
},
.ExprIfvar(x) => {
ok = dump_opt(ast, buf, stack, x.var_decl, false) &&
dump_opt(ast, buf, stack, x.then_block, false) &&
dump_opt(ast, buf, stack, x.else_branch, true);
},
.ExprWhile(w) => {
ok = dump_opt(ast, buf, stack, w.label, false) &&
dump_opt(ast, buf, stack, w.cond, false) &&
dump_opt(ast, buf, stack, w.body, false) &&
dump_opt(ast, buf, stack, w.else_branch, true);
},
.ExprLoop(x) => {
ok = dump_opt(ast, buf, stack, x.label, false) &&
dump_opt(ast, buf, stack, x.body, true);
},
.ExprFor(f) => {
ok = dump_opt(ast, buf, stack, f.label, false) &&
dump_list(ast, buf, stack, f.iter_exprs) &&
dump_opt(ast, buf, stack, f.pattern, false) &&
dump_opt(ast, buf, stack, f.body, false) &&
dump_opt(ast, buf, stack, f.else_branch, true);
},
.ExprMatch(m) => {
ok = dump_opt(ast, buf, stack, m.matched_expr, false) &&
dump_list(ast, buf, stack, m.arms);
},
.ExprFnType(f) => {
ok = dump_list(ast, buf, stack, f.params) &&
dump_opt(ast, buf, stack, f.ret_type, true);
},
.TypePath(p) => {},
.TypePointer(p) => { ok = dump_opt(ast, buf, stack, p.pointee, true); },
.TypeArray(a) => { ok = dump_opt(ast, buf, stack, a.elem_type, true); },
.TypeSlice(s) => { ok = dump_opt(ast, buf, stack, s.elem_type, true); },
.TypeFn(f) => {
ok = dump_list(ast, buf, stack, f.params) &&
dump_opt(ast, buf, stack, f.ret_type, true);
},
.TypeParen(p) => { ok = dump_list(ast, buf, stack, p.types); },
.TypeAggregate(a) => { ok = dump_list(ast, buf, stack, a.members); },
.TypeComptimeCall(c) => { ok = dump_list(ast, buf, stack, c.args); },
.PatternIdent(x) => {},
.PatternUnderscore => {},
.PatternDot(p) => { ok = dump_opt(ast, buf, stack, p.sub_pattern, true); },
.PatternTuple(v) => { ok = dump_list(ast, buf, stack, v.items); },
.PatternList(v) => { ok = dump_list(ast, buf, stack, v.items); },
.PatternAggregate(v) => { ok = dump_list(ast, buf, stack, v.items); },
.PatternField(p) => { ok = dump_opt(ast, buf, stack, p.pattern, true); },
}
stack.len = stack.len - 1;
ret ok;
}
// 把整棵树 dump 到 out(追加,不 clear)。
fn dump(ast: *Ast, out: *ByteBuffer): bool {
if !push(out, "AST:\n") { ret false; }
var stack = Vec.blank(1, 1);
defer { Vec.drop(&stack); }
ret dump_node(ast, out, &stack, ast.root, true);
}
// ---- 测试 ----
fn test_kind_names() {
@assert(ByteView.eq(ByteView.from_slice(kind_name(.None)), ByteView.from_slice("none")),
"none name");
@assert(ByteView.eq(ByteView.from_slice(kind_name(.ExprBinary(.{
.op = .Add,
.left = 0,
.right = 0,
}))),
ByteView.from_slice("binary")),
"binary name");
}
fn test_alloc_and_payload() {
var ast: Ast = undefined;
match new(null) {
.Ok(v) => { ast = v; },
.Err(error) => { @assert(false, "ast new failed"); },
}
defer { drop(&ast); }
@assert(count(&ast) == 1, "sentinel only");
var r = alloc(&ast, .ExprIdent(.{ .name = ByteView.from_slice("main") }), span_make(0, 5, 9));
@assert(r == 1, "first alloc is 1");
var n = node(&ast, r);
n.resolved_def_id = 99;
@assert(n.span.file == 0 && n.span.start == 5 && n.span.end == 9, "span stored");
@assert(n.resolved_def_id == 99, "header field");
match n.body {
.ExprIdent(i) => {
@assert(ByteView.eq(i.name, ByteView.from_slice("main")), "payload name");
},
_ => { @assert(false, "expected ident"); },
}
}
fn expect_bytes(buf: *ByteBuffer, expected: []u8) {
var actual = ByteBuffer.as_slice(buf.*);
@assert(actual.len == expected.len, "dump length");
var i: usize = 0;
while i < expected.len {
@assert(actual.ptr[i] == expected.ptr[i], "dump byte");
i = i + 1;
}
}
fn test_dump() {
var ast: Ast = undefined;
match new(null) {
.Ok(v) => { ast = v; },
.Err(error) => { @assert(false, "ast new failed"); },
}
defer { drop(&ast); }
var id_ref = alloc(&ast, .ExprIdent(.{ .name = ByteView.from_slice("main") }), span_none()); // #1
var decls = ref_vec();
match Vec.push(&decls, &id_ref as *u8) {
.Ok => {},
.Err(error) => { @assert(false, "push decl"); },
}
var cm_ref = alloc(&ast, .ContainerMembers(.{
.external_tags = ref_vec(),
.declarations = decls,
}), span_none()); // #2
var root_ref = alloc(&ast, .Root(.{ .members = cm_ref }), span_none()); // #3
ast.root = root_ref;
var buf = ByteBuffer.new();
defer { ByteBuffer.drop(&buf); }
@assert(dump(&ast, &buf), "dump ok");
// sources=null → 不解析行列;无 span 时也不打印。
expect_bytes(&buf, "AST:\n`-root #3\n `-container_members #2\n `-ident #1\n");
}
fn main() {
test_kind_names();
test_alloc_and_payload();
test_dump();
}
+791
View File
@@ -0,0 +1,791 @@
// Expect retcode = 0
// 丰富诊断(参考 rustc / Clang / Swift 的设计,不照搬 stage1 C 实现):
// Severity Note/Help/Warning/Error/Fatal
// Code 固定语义枚举 + 稳定 E 码;集中管理,利于 diff
// Span 字节区间 {file,start,end};file 是 Sources 的下标,NO_FILE 表示无位置
// Label 主/次标签(span + 文本),可多个
// Child 子诊断(note/help,可带 span),挂在条目上
// 渲染:人类可读(源码行 + caret 下划线)与 JSON(字段稳定)双格式。
// 位置只存下标,渲染时经 Sources 解析行列/取行,避免复制文件名。
// 消息按拥有型 Str 保存;条目拥有其 labels/children;clear/drop 释放全部内部资源。
type .{ .Error, .Status, .make } = @import("./utils/error.spl");
type .{ .Vec } = @import("./utils/vec.spl");
type .{ .ByteBuffer } = @import("./utils/byte_buffer.spl");
type .{ .Str } = @import("./utils/str.spl");
type .{ .ByteView } = @import("./utils/byte_view.spl");
type .{ .append_usize } = @import("./utils/fmt.spl");
type .{ .Sources, .Source, .set_new, .set_add, .set_at, .set_drop } = @import("./utils/source.spl");
type Severity = enum {
Note,
Help,
Warning,
Error,
Fatal,
}
type Stage = enum {
None,
Lex,
Parse,
Sema,
Lower,
Vm,
Driver,
}
type Code = enum {
None,
// 词法 / 语法
LexUnexpected,
ParseExpected,
ParseUnrecognized,
// sema
UndefinedSymbol,
DuplicateSymbol,
TypeMismatch,
ArgCountMismatch,
NotAFunction,
NoField,
NoMethod,
IndexBaseInvalid,
TupleIndexOob,
FitsOverflow,
CircularDep,
BreakOutsideLoop,
ContinueOutsideLoop,
UndefinedLabel,
CastInvalid,
UnknownAttr,
UnknownIntrin,
IntrinArgCount,
VarUninitialized,
CannotInfer,
MustReturnValue,
// lowering
UnhandledNode,
ImplicitCastFail,
NoLvalue,
BadFieldIndex,
BadBlock,
// vm
IrUnknownKind,
FrameOverflow,
// 通用
Internal,
}
// file 下标不可用时的哨兵。
fn no_file(): usize {
ret ~(0 as usize);
}
type Span = struct {
file: usize,
start: usize,
end: usize,
}
fn span_none(): Span {
ret Span { .file = no_file(), .start = 0, .end = 0 };
}
fn span_make(file: usize, start: usize, end: usize): Span {
ret Span { .file = file, .start = start, .end = end };
}
fn span_is_none(span: Span): bool {
ret span.file == no_file();
}
type Label = struct {
span: Span,
message: Str,
primary: bool,
}
type Child = struct {
severity: Severity,
span: Span,
message: Str,
}
type Item = struct {
severity: Severity,
stage: Stage,
code: Code,
span: Span,
message: Str,
labels: Vec, // Label
children: Vec, // Child
}
type Diag = @self;
items: Vec, // Item
sources: *Sources, // 借用;可为 null(则只输出消息)
errors: usize,
warnings: usize,
fatals: usize,
fn new(sources: *Sources): Diag {
ret Diag {
.items = Vec.blank(@sizeof(Item), @alignof(Item)),
.sources = sources,
.errors = 0,
.warnings = 0,
.fatals = 0,
};
}
fn item_at(self: *Diag, index: usize): *Item {
match Vec.get(&self.items, index) {
.Ok(ptr) => { ret ptr as *Item; },
.Err(error) => { ret null; },
}
ret null;
}
fn label_at(it: *Item, index: usize): *Label {
match Vec.get(&it.labels, index) {
.Ok(ptr) => { ret ptr as *Label; },
.Err(error) => { ret null; },
}
ret null;
}
fn child_at(it: *Item, index: usize): *Child {
match Vec.get(&it.children, index) {
.Ok(ptr) => { ret ptr as *Child; },
.Err(error) => { ret null; },
}
ret null;
}
fn last(self: *Diag): usize {
if self.items.len == 0 { ret no_file(); }
ret self.items.len - 1;
}
fn count(self: Diag): usize { ret self.items.len; }
fn error_count(self: Diag): usize { ret self.errors; }
fn warning_count(self: Diag): usize { ret self.warnings; }
fn fatal_count(self: Diag): usize { ret self.fatals; }
fn has_error(self: Diag): bool { ret self.errors > 0; }
fn has_fatal(self: Diag): bool { ret self.fatals > 0; }
// ---- 采集 ----
// 追加一条诊断,返回其下标(失败返回 no_file())。span 为主位置。
fn emit(self: *Diag, severity: Severity, stage: Stage, code: Code, span: Span,
msg: []u8): usize {
var message = Str.new();
match Str.from_slice(msg) {
.Ok(v) => { message = v; },
.Err(error) => { ret no_file(); },
}
var item = Item {
.severity = severity,
.stage = stage,
.code = code,
.span = span,
.message = message,
.labels = Vec.blank(@sizeof(Label), @alignof(Label)),
.children = Vec.blank(@sizeof(Child), @alignof(Child)),
};
match Vec.push(&self.items, &item as *u8) {
.Ok => {},
.Err(error) => { Str.drop(&item.message); ret no_file(); },
}
match severity {
.Error => { self.errors = self.errors + 1; },
.Fatal => { self.errors = self.errors + 1; self.fatals = self.fatals + 1; },
.Warning => { self.warnings = self.warnings + 1; },
_ => {},
}
ret self.items.len - 1;
}
fn err(self: *Diag, span: Span, code: Code, msg: []u8): usize {
ret emit(self, .Error, .None, code, span, msg);
}
fn warn(self: *Diag, span: Span, code: Code, msg: []u8): usize {
ret emit(self, .Warning, .None, code, span, msg);
}
fn note(self: *Diag, span: Span, code: Code, msg: []u8): usize {
ret emit(self, .Note, .None, code, span, msg);
}
// 给最近一条诊断附加标签(primary 决定主/次)。
fn attach_label(self: *Diag, span: Span, msg: []u8, primary: bool): Status {
var idx = last(self);
if idx == no_file() { ret .Err(make(.OutOfRange)); }
var it = item_at(self, idx);
if it == null { ret .Err(make(.OutOfRange)); }
var message = Str.new();
match Str.from_slice(msg) {
.Ok(v) => { message = v; },
.Err(error) => { ret .Err(error); },
}
var lab = Label { .span = span, .message = message, .primary = primary };
match Vec.push(&it.labels, &lab as *u8) {
.Ok => {},
.Err(error) => { Str.drop(&lab.message); ret .Err(error); },
}
ret .Ok;
}
// 给最近一条诊断附加子诊断(note/help 等)。
fn attach_child(self: *Diag, severity: Severity, span: Span, msg: []u8): Status {
var idx = last(self);
if idx == no_file() { ret .Err(make(.OutOfRange)); }
var it = item_at(self, idx);
if it == null { ret .Err(make(.OutOfRange)); }
var message = Str.new();
match Str.from_slice(msg) {
.Ok(v) => { message = v; },
.Err(error) => { ret .Err(error); },
}
var ch = Child { .severity = severity, .span = span, .message = message };
match Vec.push(&it.children, &ch as *u8) {
.Ok => {},
.Err(error) => { Str.drop(&ch.message); ret .Err(error); },
}
ret .Ok;
}
// ---- 名称 ----
fn severity_name(severity: Severity): []u8 {
match severity {
.Note => { ret "note"; },
.Help => { ret "help"; },
.Warning => { ret "warning"; },
.Error => { ret "error"; },
.Fatal => { ret "fatal"; },
}
ret "?";
}
fn stage_name(stage: Stage): []u8 {
match stage {
.None => { ret "none"; },
.Lex => { ret "lex"; },
.Parse => { ret "parse"; },
.Sema => { ret "sema"; },
.Lower => { ret "lower"; },
.Vm => { ret "vm"; },
.Driver => { ret "driver"; },
}
ret "?";
}
// 稳定 E 码(diff 依赖;新增 Code 时分配新码,勿改旧值)。
fn code_str(code: Code): []u8 {
match code {
.None => { ret "E0000"; },
.LexUnexpected => { ret "E0001"; },
.ParseExpected => { ret "E0002"; },
.ParseUnrecognized => { ret "E0003"; },
.UndefinedSymbol => { ret "E0101"; },
.DuplicateSymbol => { ret "E0102"; },
.TypeMismatch => { ret "E0103"; },
.ArgCountMismatch => { ret "E0104"; },
.NotAFunction => { ret "E0105"; },
.NoField => { ret "E0106"; },
.NoMethod => { ret "E0107"; },
.IndexBaseInvalid => { ret "E0108"; },
.TupleIndexOob => { ret "E0109"; },
.FitsOverflow => { ret "E0110"; },
.CircularDep => { ret "E0111"; },
.BreakOutsideLoop => { ret "E0112"; },
.ContinueOutsideLoop => { ret "E0113"; },
.UndefinedLabel => { ret "E0114"; },
.CastInvalid => { ret "E0115"; },
.UnknownAttr => { ret "E0116"; },
.UnknownIntrin => { ret "E0117"; },
.IntrinArgCount => { ret "E0118"; },
.VarUninitialized => { ret "E0119"; },
.CannotInfer => { ret "E0120"; },
.MustReturnValue => { ret "E0121"; },
.UnhandledNode => { ret "E0201"; },
.ImplicitCastFail => { ret "E0202"; },
.NoLvalue => { ret "E0203"; },
.BadFieldIndex => { ret "E0204"; },
.BadBlock => { ret "E0205"; },
.IrUnknownKind => { ret "E0301"; },
.FrameOverflow => { ret "E0302"; },
.Internal => { ret "E9000"; },
}
ret "E0000";
}
fn code_name(code: Code): []u8 {
match code {
.None => { ret "none"; },
.LexUnexpected => { ret "lex_unexpected"; },
.ParseExpected => { ret "parse_expected"; },
.ParseUnrecognized => { ret "parse_unrecognized"; },
.UndefinedSymbol => { ret "undefined_symbol"; },
.DuplicateSymbol => { ret "duplicate_symbol"; },
.TypeMismatch => { ret "type_mismatch"; },
.ArgCountMismatch => { ret "arg_count_mismatch"; },
.NotAFunction => { ret "not_a_function"; },
.NoField => { ret "no_field"; },
.NoMethod => { ret "no_method"; },
.IndexBaseInvalid => { ret "index_base_invalid"; },
.TupleIndexOob => { ret "tuple_index_oob"; },
.FitsOverflow => { ret "fits_overflow"; },
.CircularDep => { ret "circular_dep"; },
.BreakOutsideLoop => { ret "break_outside_loop"; },
.ContinueOutsideLoop => { ret "continue_outside_loop"; },
.UndefinedLabel => { ret "undefined_label"; },
.CastInvalid => { ret "cast_invalid"; },
.UnknownAttr => { ret "unknown_attr"; },
.UnknownIntrin => { ret "unknown_intrin"; },
.IntrinArgCount => { ret "intrin_arg_count"; },
.VarUninitialized => { ret "var_uninitialized"; },
.CannotInfer => { ret "cannot_infer"; },
.MustReturnValue => { ret "must_return_value"; },
.UnhandledNode => { ret "unhandled_node"; },
.ImplicitCastFail => { ret "implicit_cast_fail"; },
.NoLvalue => { ret "no_lvalue"; },
.BadFieldIndex => { ret "bad_field_index"; },
.BadBlock => { ret "bad_block"; },
.IrUnknownKind => { ret "ir_unknown_kind"; },
.FrameOverflow => { ret "frame_overflow"; },
.Internal => { ret "internal"; },
}
ret "none";
}
// ---- 渲染:公共小工具 ----
fn append_num(out: *ByteBuffer, value: usize): Status {
ret append_usize(out, value, 10, false);
}
fn append_str(out: *ByteBuffer, s: *Str): Status {
ret ByteBuffer.append(out, Str.as_slice(s));
}
fn append_view(out: *ByteBuffer, view: ByteView): Status {
ret ByteBuffer.append(out, ByteView.as_slice(view));
}
type Resolved = struct {
ok: bool,
fname: ByteView,
line: usize,
col: usize,
text: ByteView,
width: usize,
}
fn resolve(self: *Diag, span: Span): Resolved {
var r = Resolved {
.ok = false,
.fname = ByteView.empty(),
.line = 0,
.col = 0,
.text = ByteView.empty(),
.width = 1,
};
if self.sources == null { ret r; }
if span_is_none(span) { ret r; }
var src = set_at(self.sources, span.file);
if src == null { ret r; }
var pos = Source.line_col(src.*, span.start);
var width: usize = 1;
if span.end > span.start { width = span.end - span.start; }
r.ok = true;
r.fname = src.fname;
r.line = pos.line;
r.col = pos.col;
r.text = Source.line_text(src.*, pos.line);
r.width = width;
ret r;
}
fn render_header(it: *Item, r: *Resolved, out: *ByteBuffer): Status {
if r.ok {
match append_view(out, r.fname) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, ':') { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_num(out, r.line) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, ':') { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_num(out, r.col) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ": ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
match ByteBuffer.append(out, severity_name(it.severity)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, '[') { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, code_str(it.code)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, "]: ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_str(out, &it.message) { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append_byte(out, '\n');
}
// 输出一行源码 + caret 下划线(列范围按字节;制表符不特殊处理)。
fn render_span_visual(self: *Diag, span: Span, out: *ByteBuffer): Status {
var r = resolve(self, span);
if !r.ok { ret .Ok; }
match ByteBuffer.append(out, " ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_view(out, r.text) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, '\n') { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, " ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
var pad: usize = 0;
if r.col > 0 { pad = r.col - 1; }
match ByteBuffer.append_repeat(out, ' ', pad) { .Ok => {}, .Err(e) => { ret .Err(e); } }
var width = r.width;
if width == 0 { width = 1; }
if r.col > 0 {
var room: usize = 0;
if r.text.len >= pad { room = r.text.len - pad; }
if room == 0 { room = 1; }
if width > room { width = room; }
}
var k: usize = 0;
while k < width {
var ch: u8 = '~';
if k == 0 { ch = '^'; }
match ByteBuffer.append_byte(out, ch) { .Ok => {}, .Err(e) => { ret .Err(e); } }
k = k + 1;
}
ret ByteBuffer.append_byte(out, '\n');
}
fn render_child_line(ch: *Child, out: *ByteBuffer): Status {
match ByteBuffer.append(out, " ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, severity_name(ch.severity)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ": ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_str(out, &ch.message) { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append_byte(out, '\n');
}
fn render_human(self: *Diag, out: *ByteBuffer): Status {
var i: usize = 0;
while i < self.items.len {
var it = item_at(self, i);
if it == null { ret .Err(make(.OutOfRange)); }
var r = resolve(self, it.span);
match render_header(it, &r, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match render_span_visual(self, it.span, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
var j: usize = 0;
while j < it.labels.len {
var lab = label_at(it, j);
if lab != null {
match render_span_visual(self, lab.span, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
if Str.size(lab.message) != 0 {
match ByteBuffer.append(out, " ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_str(out, &lab.message) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, '\n') { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
}
j = j + 1;
}
var c: usize = 0;
while c < it.children.len {
var ch = child_at(it, c);
if ch != null {
match render_child_line(ch, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match render_span_visual(self, ch.span, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
c = c + 1;
}
if i + 1 < self.items.len {
match ByteBuffer.append_byte(out, '\n') { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
i = i + 1;
}
ret .Ok;
}
// ---- JSON 渲染(字段稳定,供 LSP / diff 工具)----
fn append_json_hex4(out: *ByteBuffer, b: u8): Status {
var hex: []u8 = "0123456789abcdef";
match ByteBuffer.append(out, "\\u00") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, hex[(b >> 4) as usize]) { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append_byte(out, hex[(b & 15) as usize]);
}
fn append_json_str(out: *ByteBuffer, bytes: []u8): Status {
match ByteBuffer.append_byte(out, '"') { .Ok => {}, .Err(e) => { ret .Err(e); } }
var i: usize = 0;
while i < bytes.len {
var b = bytes[i];
if b == '"' {
match ByteBuffer.append(out, "\\\"") { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else if b == '\\' {
match ByteBuffer.append(out, "\\\\") { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else if b == '\n' {
match ByteBuffer.append(out, "\\n") { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else if b == '\r' {
match ByteBuffer.append(out, "\\r") { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else if b == '\t' {
match ByteBuffer.append(out, "\\t") { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else if b < ' ' {
match append_json_hex4(out, b) { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else {
match ByteBuffer.append_byte(out, b) { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
i = i + 1;
}
ret ByteBuffer.append_byte(out, '"');
}
fn append_str_json(out: *ByteBuffer, s: *Str): Status {
ret append_json_str(out, Str.as_slice(s));
}
fn append_bool(out: *ByteBuffer, value: bool): Status {
if value { ret ByteBuffer.append(out, "true"); }
ret ByteBuffer.append(out, "false");
}
fn append_loc_json(self: *Diag, span: Span, out: *ByteBuffer): Status {
var r = resolve(self, span);
match ByteBuffer.append(out, "{\"file\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
if r.ok {
match append_json_str(out, ByteView.as_slice(r.fname)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else {
match ByteBuffer.append(out, "null") { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
match ByteBuffer.append(out, ",\"start\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_num(out, span.start) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"end\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_num(out, span.end) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"line\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
if r.ok {
match append_num(out, r.line) { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else {
match ByteBuffer.append(out, "null") { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
match ByteBuffer.append(out, ",\"col\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
if r.ok {
match append_num(out, r.col) { .Ok => {}, .Err(e) => { ret .Err(e); } }
} else {
match ByteBuffer.append(out, "null") { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
ret ByteBuffer.append_byte(out, '}');
}
fn render_item_json(self: *Diag, it: *Item, out: *ByteBuffer): Status {
match ByteBuffer.append(out, "{\"severity\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_json_str(out, severity_name(it.severity)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"stage\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_json_str(out, stage_name(it.stage)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"code\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_json_str(out, code_str(it.code)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"name\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_json_str(out, code_name(it.code)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"message\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_str_json(out, &it.message) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"span\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_loc_json(self, it.span, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"labels\":[") { .Ok => {}, .Err(e) => { ret .Err(e); } }
var j: usize = 0;
while j < it.labels.len {
var lab = label_at(it, j);
if lab != null {
if j != 0 {
match ByteBuffer.append_byte(out, ',') { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
match ByteBuffer.append(out, "{\"message\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_str_json(out, &lab.message) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"primary\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_bool(out, lab.primary) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"span\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_loc_json(self, lab.span, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, '}') { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
j = j + 1;
}
match ByteBuffer.append_byte(out, ']') { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"children\":[") { .Ok => {}, .Err(e) => { ret .Err(e); } }
var c: usize = 0;
while c < it.children.len {
var ch = child_at(it, c);
if ch != null {
if c != 0 {
match ByteBuffer.append_byte(out, ',') { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
match ByteBuffer.append(out, "{\"severity\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_json_str(out, severity_name(ch.severity)) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"message\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_str_json(out, &ch.message) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, ",\"span\":") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_loc_json(self, ch.span, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, '}') { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
c = c + 1;
}
match ByteBuffer.append_byte(out, ']') { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append_byte(out, '}');
}
fn render_json(self: *Diag, out: *ByteBuffer): Status {
match ByteBuffer.append_byte(out, '[') { .Ok => {}, .Err(e) => { ret .Err(e); } }
var i: usize = 0;
while i < self.items.len {
var it = item_at(self, i);
if it == null { ret .Err(make(.OutOfRange)); }
if i != 0 {
match ByteBuffer.append_byte(out, ',') { .Ok => {}, .Err(e) => { ret .Err(e); } }
}
match render_item_json(self, it, out) { .Ok => {}, .Err(e) => { ret .Err(e); } }
i = i + 1;
}
ret ByteBuffer.append_byte(out, ']');
}
// ---- 生命周期 ----
fn drop_item(it: *Item) {
Str.drop(&it.message);
var j: usize = 0;
while j < it.labels.len {
var lab = label_at(it, j);
if lab != null { Str.drop(&lab.message); }
j = j + 1;
}
Vec.drop(&it.labels);
var c: usize = 0;
while c < it.children.len {
var ch = child_at(it, c);
if ch != null { Str.drop(&ch.message); }
c = c + 1;
}
Vec.drop(&it.children);
}
fn clear(self: *Diag) {
var i: usize = 0;
while i < self.items.len {
var it = item_at(self, i);
if it != null { drop_item(it); }
i = i + 1;
}
Vec.clear(&self.items);
self.errors = 0;
self.warnings = 0;
self.fatals = 0;
}
fn drop(self: *Diag) {
clear(self);
Vec.drop(&self.items);
self.sources = null;
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
}
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected diag error"); },
}
}
fn has_bytes(out: *ByteBuffer, needle: []u8): bool {
ret ByteView.contains(ByteView.from_slice(ByteBuffer.as_slice(out.*)), view(needle));
}
fn test_collect_render_human() {
var sources = set_new();
match set_add(&sources, view("a.spl"), view("fn main() {\n y;\n}\n")) {
.Ok(index) => {},
.Err(error) => { @assert(false, "add source"); },
}
var d = new(&sources);
var idx = err(&d, span_make(0, 16, 17), .UndefinedSymbol, "undefined symbol `y`");
@assert(idx != no_file(), "emit");
expect_ok(attach_label(&d, span_make(0, 16, 17), "not found in scope", false));
expect_ok(attach_child(&d, .Note, span_none(), "did you mean `x`?"));
@assert(count(d) == 1, "count");
@assert(error_count(d) == 1 && has_error(d), "errors");
@assert(warning_count(d) == 0 && !has_fatal(d), "warnings/fatal");
var out = ByteBuffer.new();
expect_ok(render_human(&d, &out));
@assert(has_bytes(&out, "a.spl:2:5: error[E0101]: undefined symbol `y`"), "human header");
@assert(has_bytes(&out, " y;"), "human source line");
@assert(has_bytes(&out, " ^"), "human caret");
@assert(has_bytes(&out, "not found in scope"), "human label");
@assert(has_bytes(&out, "note: did you mean `x`?"), "human child");
ByteBuffer.drop(&out);
clear(&d);
@assert(count(d) == 0 && error_count(d) == 0, "clear");
drop(&d);
set_drop(&sources);
}
fn test_render_json() {
var sources = set_new();
match set_add(&sources, view("b.spl"), view("let z = 1;\n")) {
.Ok(index) => {},
.Err(error) => { @assert(false, "add source"); },
}
var d = new(&sources);
err(&d, span_make(0, 4, 5), .TypeMismatch, "expected i32, got bool");
expect_ok(attach_child(&d, .Help, span_none(), "annotate the type"));
var out = ByteBuffer.new();
expect_ok(render_json(&d, &out));
@assert(has_bytes(&out, "\"severity\":\"error\""), "json severity");
@assert(has_bytes(&out, "\"code\":\"E0103\""), "json code");
@assert(has_bytes(&out, "\"name\":\"type_mismatch\""), "json name");
@assert(has_bytes(&out, "\"line\":1"), "json line");
@assert(has_bytes(&out, "\"col\":5"), "json col");
@assert(has_bytes(&out, "\"children\":[{\"severity\":\"help\""), "json child");
ByteBuffer.drop(&out);
drop(&d);
set_drop(&sources);
}
fn test_empty_and_headerless() {
var d = new(null);
err(&d, span_none(), .Internal, "no location");
var out = ByteBuffer.new();
expect_ok(render_human(&d, &out));
@assert(has_bytes(&out, "error[E9000]: no location"), "headerless");
ByteBuffer.drop(&out);
drop(&d);
}
fn main() {
test_collect_render_human();
test_render_json();
test_empty_and_headerless();
}
+719
View File
@@ -0,0 +1,719 @@
// Expect retcode = 0
// 词法分析器:字节流 -> Vec<Token>。镜像 stage1/spl_lexer.c 的行为:
// 行注释作为 token 产出;块注释(可嵌套)整体跳过;换行产出 Endline;EOF 产出 Eof。
// 复用 utils/ascii 做字符分类;整型/字符在词法期解码后放进 TokenKind 载荷。
// Token.text 借用输入字节,不复制。
type .{ .Vec, .VecResult } = @import("utils/vec.spl");
type .{ .ByteView } = @import("utils/byte_view.spl");
type .{ .is_digit, .is_alpha, .is_alnum, .is_hex_digit, .digit_value } = @import("utils/ascii.spl");
type .{
.Token, .TokenKind, .Radix, .Keyword, .Punct, .keyword_of
} = @import("token.spl");
type .{ .Span, .span_make } = @import("./diag.spl");
type Diag = @import("./diag.spl");
type Lexer = @self;
src: ByteView,
pos: usize,
line: usize,
col: usize,
diag: *Diag, // 借用;可为 null(合法输入不产生诊断)
file: usize,
fn new(src: ByteView, diag: *Diag, file: usize): Lexer {
ret Lexer { .src = src, .pos = 0, .line = 1, .col = 1, .diag = diag, .file = file };
}
// 记录一条词法诊断(非法输入路径)。合法输入不应触发。
fn report(self: *Lexer, start: usize, end: usize, message: []u8) {
if self.diag == null { ret; }
Diag.err(self.diag, span_make(self.file, start, end), .LexUnexpected, message);
}
fn is_ident_start(c: u8): bool { ret is_alpha(c) || c == '_'; }
fn is_ident_cont(c: u8): bool { ret is_alnum(c) || c == '_'; }
fn hex_val(c: u8): u8 {
match digit_value(c, 16) {
.Ok(v) => { ret v; },
.Err(error) => { ret 0; },
}
ret 0;
}
// 文本形如 'a' / '\n' / '\x41';返回解码后的字节。
fn decode_char(text: ByteView): u8 {
var start: usize = 1;
var end = text.len;
if text.len >= 2 && text.ptr[text.len - 1] == '\'' { end = text.len - 1; }
if end <= start { ret 0; }
var b = text.ptr[start];
if b != '\\' { ret b; }
start = start + 1;
if start >= end { ret 0; }
var e = text.ptr[start];
if e == 'n' { ret '\n'; }
if e == 't' { ret '\t'; }
if e == 'r' { ret '\r'; }
if e == '\\' { ret '\\'; }
if e == '"' { ret '"'; }
if e == '\'' { ret '\''; }
if e == '0' { ret 0; }
if e == 'x' || e == 'X' {
var q = start + 1;
var value: u8 = 0;
var digits: usize = 0;
while q < end && digits < 2 && is_hex_digit(text.ptr[q]) {
value = value * 16 + hex_val(text.ptr[q]);
q = q + 1;
digits = digits + 1;
}
if digits == 0 { ret e; }
ret value;
}
ret e;
}
// ---- 读取辅助 ----
fn has2(self: *Lexer, ch: u8): bool {
ret self.pos + 1 < self.src.len && self.src.ptr[self.pos + 1] == ch;
}
fn has3(self: *Lexer, ch1: u8, ch2: u8): bool {
ret self.pos + 2 < self.src.len && self.src.ptr[self.pos + 1] == ch1 &&
self.src.ptr[self.pos + 2] == ch2;
}
fn sub(self: *Lexer, start: usize, end: usize): ByteView {
match ByteView.slice(self.src, start, end) {
.Ok(v) => { ret v; },
.Err(error) => { ret ByteView.empty(); },
}
ret ByteView.empty();
}
// 产出 token 并把 pos/col 推进到 end。Vec.push 失败视为致命(同 vec.make_vec 风格)。
fn emit_to(self: *Lexer, out: *Vec, kind: TokenKind, start: usize, end: usize, line: usize,
col: usize) {
var t = Token.make(kind, sub(self, start, end), line, col, start);
match Vec.push(out, &t as *u8) {
.Ok => {},
.Err(error) => { @assert(false, "lexer: Vec.push failed"); },
}
self.pos = end;
self.col = col + (end - start);
}
fn op1(self: *Lexer, out: *Vec, punct: Punct, start: usize, line: usize, col: usize) {
emit_to(self, out, .Punct(punct), start, start + 1, line, col);
}
fn op2(self: *Lexer, out: *Vec, punct: Punct, start: usize, line: usize, col: usize) {
emit_to(self, out, .Punct(punct), start, start + 2, line, col);
}
fn op3(self: *Lexer, out: *Vec, punct: Punct, start: usize, line: usize, col: usize) {
emit_to(self, out, .Punct(punct), start, start + 3, line, col);
}
// ---- 复合扫描 ----
fn scan_int(self: *Lexer, out: *Vec, start: usize, line: usize, col: usize) {
var p = self.pos;
if self.src.ptr[p] == '0' && p + 1 < self.src.len {
var nc = self.src.ptr[p + 1];
if nc == 'x' || nc == 'X' {
p = p + 2;
while p < self.src.len && (is_hex_digit(self.src.ptr[p]) || self.src.ptr[p] == '_') {
p = p + 1;
}
emit_to(self, out, .Int(.Hex), start, p, line, col);
ret;
}
if nc == 'b' || nc == 'B' {
p = p + 2;
while p < self.src.len && (self.src.ptr[p] == '0' || self.src.ptr[p] == '1' ||
self.src.ptr[p] == '_') {
p = p + 1;
}
emit_to(self, out, .Int(.Bin), start, p, line, col);
ret;
}
if nc == 'o' || nc == 'O' {
p = p + 2;
while p < self.src.len &&
((self.src.ptr[p] >= '0' && self.src.ptr[p] <= '7') ||
self.src.ptr[p] == '_') {
p = p + 1;
}
emit_to(self, out, .Int(.Oct), start, p, line, col);
ret;
}
}
while p < self.src.len && (is_digit(self.src.ptr[p]) || self.src.ptr[p] == '_') { p = p + 1; }
if p + 1 < self.src.len && self.src.ptr[p] == '.' && is_digit(self.src.ptr[p + 1]) {
p = p + 1;
// 小数部分允许下划线分隔(Rust 风格)。
while p < self.src.len && (is_digit(self.src.ptr[p]) || self.src.ptr[p] == '_') {
p = p + 1;
}
// 可选指数:e/E [+-] 数字(数字允许下划线);仅当确有数字时纳入。
if p < self.src.len && (self.src.ptr[p] == 'e' || self.src.ptr[p] == 'E') {
var q = p + 1;
if q < self.src.len && (self.src.ptr[q] == '+' || self.src.ptr[q] == '-') { q = q + 1; }
if q < self.src.len && is_digit(self.src.ptr[q]) {
p = q + 1;
while p < self.src.len && (is_digit(self.src.ptr[p]) || self.src.ptr[p] == '_') {
p = p + 1;
}
}
}
emit_to(self, out, .Float, start, p, line, col);
ret;
}
emit_to(self, out, .Int(.Dec), start, p, line, col);
}
fn scan_char(self: *Lexer, out: *Vec, start: usize, line: usize, col: usize) {
var p = self.pos + 1;
var closed = false;
var escape_ok = true;
if p < self.src.len {
if self.src.ptr[p] == '\\' {
p = p + 1;
if p < self.src.len && (self.src.ptr[p] == 'x' || self.src.ptr[p] == 'X') {
p = p + 1;
var digits: usize = 0;
while p < self.src.len && digits < 2 && is_hex_digit(self.src.ptr[p]) {
p = p + 1;
digits = digits + 1;
}
if digits == 0 { escape_ok = false; }
} else if p < self.src.len {
var e = self.src.ptr[p];
if !(e == 'n' || e == 't' || e == 'r' || e == '\\' || e == '"' || e == '\'' ||
e == '0') {
escape_ok = false;
}
p = p + 1;
} else {
escape_ok = false;
}
} else {
p = p + 1;
}
}
if p < self.src.len && self.src.ptr[p] == '\'' {
p = p + 1;
closed = true;
}
if !closed {
report(self, start, p, "unterminated character literal");
} else if !escape_ok {
report(self, start, p, "invalid escape in character literal");
}
emit_to(self, out, .Char(decode_char(sub(self, start, p))), start, p, line, col);
}
fn scan_string(self: *Lexer, out: *Vec, start: usize, line: usize, col: usize) {
var p = self.pos + 1;
var l = line;
var cc = col + 1;
var closed = false;
while p < self.src.len {
var b = self.src.ptr[p];
if b == '\\' {
p = p + 1;
cc = cc + 1;
if p < self.src.len {
p = p + 1;
cc = cc + 1;
}
} else if b == '"' {
p = p + 1;
cc = cc + 1;
closed = true;
break;
} else if b == '\n' {
l = l + 1;
cc = 1;
p = p + 1;
} else {
p = p + 1;
cc = cc + 1;
}
}
if !closed { report(self, start, p, "unterminated string literal"); }
emit_to(self, out, .Str, start, p, line, col);
self.line = l;
self.col = cc;
}
fn scan_ident(self: *Lexer, out: *Vec, start: usize, line: usize, col: usize) {
var p = self.pos;
while p < self.src.len && is_ident_cont(self.src.ptr[p]) { p = p + 1; }
var text = sub(self, start, p);
match keyword_of(text) {
.Yes(kw) => { emit_to(self, out, .Keyword(kw), start, p, line, col); },
.No => { emit_to(self, out, .Ident, start, p, line, col); },
}
}
// 块注释:可嵌套,整体跳过(不产出 token)。未闭合时报诊断。
fn skip_block_comment(self: *Lexer, start: usize) {
self.pos = self.pos + 2;
self.col = self.col + 2;
var depth: usize = 1;
while self.pos + 1 < self.src.len && depth > 0 {
if self.src.ptr[self.pos] == '*' && self.src.ptr[self.pos + 1] == '/' {
depth = depth - 1;
self.pos = self.pos + 2;
self.col = self.col + 2;
} else if self.src.ptr[self.pos] == '/' && self.src.ptr[self.pos + 1] == '*' {
depth = depth + 1;
self.pos = self.pos + 2;
self.col = self.col + 2;
} else {
if self.src.ptr[self.pos] == '\n' {
self.line = self.line + 1;
self.col = 1;
} else {
self.col = self.col + 1;
}
self.pos = self.pos + 1;
}
}
if depth > 0 {
report(self, start, self.src.len, "unterminated block comment");
}
}
fn run(self: *Lexer, out: *Vec) {
while self.pos < self.src.len {
var start = self.pos;
var line = self.line;
var col = self.col;
var c = self.src.ptr[self.pos];
if c == ' ' || c == '\t' || c == '\r' {
self.pos = self.pos + 1;
self.col = self.col + 1;
continue;
}
if c == '\n' {
emit_to(self, out, .Endline, start, start + 1, line, col);
self.line = line + 1;
self.col = 1;
continue;
}
if c == '/' && has2(self, '/') {
var p = self.pos;
while p < self.src.len && self.src.ptr[p] != '\n' { p = p + 1; }
emit_to(self, out, .LineComment, start, p, line, col);
continue;
}
if c == '/' && has2(self, '*') {
skip_block_comment(self, start);
continue;
}
if c == '\'' {
scan_char(self, out, start, line, col);
continue;
}
if c == '"' {
scan_string(self, out, start, line, col);
continue;
}
if is_ident_start(c) {
scan_ident(self, out, start, line, col);
continue;
}
if is_digit(c) {
scan_int(self, out, start, line, col);
continue;
}
if c == '<' {
if has3(self, '-', '>') { op3(self, out, .ArrowBoth, start, line, col); continue; }
if has3(self, '=', '>') { op3(self, out, .FatArrowBoth, start, line, col); continue; }
if has3(self, '<', '=') { op3(self, out, .LShAssign, start, line, col); continue; }
if has2(self, '<') { op2(self, out, .LSh, start, line, col); continue; }
if has2(self, '-') { op2(self, out, .LeftArrow, start, line, col); continue; }
if has2(self, '=') { op2(self, out, .Le, start, line, col); continue; }
op1(self, out, .Lt, start, line, col);
continue;
}
if c == '>' {
if has3(self, '>', '=') { op3(self, out, .RShAssign, start, line, col); continue; }
if has2(self, '>') { op2(self, out, .RSh, start, line, col); continue; }
if has2(self, '=') { op2(self, out, .Ge, start, line, col); continue; }
op1(self, out, .Gt, start, line, col);
continue;
}
if c == '.' {
if has3(self, '.', '.') { op3(self, out, .Ellipsis, start, line, col); continue; }
if has2(self, '.') { op2(self, out, .Range, start, line, col); continue; }
op1(self, out, .Dot, start, line, col);
continue;
}
if c == '=' {
if has2(self, '=') { op2(self, out, .Eq, start, line, col); continue; }
if has2(self, '>') { op2(self, out, .RightFatArrow, start, line, col); continue; }
op1(self, out, .Assign, start, line, col);
continue;
}
if c == '!' {
if has2(self, '=') { op2(self, out, .Neq, start, line, col); continue; }
op1(self, out, .Not, start, line, col);
continue;
}
if c == '&' {
if has2(self, '&') { op2(self, out, .AndAnd, start, line, col); continue; }
if has2(self, '=') { op2(self, out, .AndAssign, start, line, col); continue; }
op1(self, out, .And, start, line, col);
continue;
}
if c == '|' {
if has2(self, '|') { op2(self, out, .OrOr, start, line, col); continue; }
if has2(self, '=') { op2(self, out, .OrAssign, start, line, col); continue; }
op1(self, out, .Or, start, line, col);
continue;
}
if c == '+' {
if has2(self, '=') { op2(self, out, .AddAssign, start, line, col); continue; }
op1(self, out, .Add, start, line, col);
continue;
}
if c == '-' {
if has2(self, '=') { op2(self, out, .SubAssign, start, line, col); continue; }
if has2(self, '>') { op2(self, out, .RightArrow, start, line, col); continue; }
op1(self, out, .Sub, start, line, col);
continue;
}
if c == '*' {
if has2(self, '=') { op2(self, out, .MulAssign, start, line, col); continue; }
op1(self, out, .Mul, start, line, col);
continue;
}
if c == '/' {
if has2(self, '=') { op2(self, out, .DivAssign, start, line, col); continue; }
op1(self, out, .Div, start, line, col);
continue;
}
if c == '%' {
if has2(self, '=') { op2(self, out, .ModAssign, start, line, col); continue; }
op1(self, out, .Mod, start, line, col);
continue;
}
if c == '^' {
if has2(self, '=') { op2(self, out, .XorAssign, start, line, col); continue; }
op1(self, out, .Xor, start, line, col);
continue;
}
if c == ':' {
if has2(self, '=') { op2(self, out, .ColonAssign, start, line, col); continue; }
op1(self, out, .Colon, start, line, col);
continue;
}
if c == '~' { op1(self, out, .BitNot, start, line, col); continue; }
if c == ',' { op1(self, out, .Comma, start, line, col); continue; }
if c == ';' { op1(self, out, .Semicolon, start, line, col); continue; }
if c == '(' { op1(self, out, .LParen, start, line, col); continue; }
if c == ')' { op1(self, out, .RParen, start, line, col); continue; }
if c == '[' { op1(self, out, .LBracket, start, line, col); continue; }
if c == ']' { op1(self, out, .RBracket, start, line, col); continue; }
if c == '{' { op1(self, out, .LBrace, start, line, col); continue; }
if c == '}' { op1(self, out, .RBrace, start, line, col); continue; }
if c == '#' { op1(self, out, .Sharp, start, line, col); continue; }
if c == '@' { op1(self, out, .At, start, line, col); continue; }
if c == '$' { op1(self, out, .Dollar, start, line, col); continue; }
if c == '?' { op1(self, out, .Cond, start, line, col); continue; }
report(self, start, start + 1, "unexpected character");
emit_to(self, out, .Unknown(c), start, start + 1, line, col);
}
var end = self.src.len;
emit_to(self, out, .Eof, end, end, self.line, self.col);
}
fn lex(src: ByteView, diag: *Diag, file: usize): VecResult {
var out = Vec.blank(@sizeof(Token), @alignof(Token));
match Vec.new(@sizeof(Token), @alignof(Token)) {
.Ok(v) => { out = v; },
.Err(error) => { ret .Err(error); },
}
var self = new(src, diag, file);
run(&self, &out);
ret .Ok(out);
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
}
fn lex_ok(src: []u8): Vec {
var out = Vec.blank(@sizeof(Token), @alignof(Token));
match lex(view(src), null, 0) {
.Ok(v) => { out = v; },
.Err(error) => { @assert(false, "lex failed"); },
}
ret out;
}
fn at(v: *Vec, index: usize): Token {
match Vec.get(v, index) {
.Ok(ptr) => { ret (ptr as *Token).*; },
.Err(error) => { ret Token.make(.Unknown(0), ByteView.empty(), 0, 0, 0); },
}
ret Token.make(.Unknown(0), ByteView.empty(), 0, 0, 0);
}
fn expect_punct(tok: Token, expected: Punct) {
match tok.kind {
.Punct(p) => { @assert(@enum2int(p) == @enum2int(expected), "punct kind"); },
_ => { @assert(false, "expected punct"); },
}
}
fn expect_keyword(tok: Token, expected: Keyword) {
match tok.kind {
.Keyword(k) => { @assert(@enum2int(k) == @enum2int(expected), "keyword kind"); },
_ => { @assert(false, "expected keyword"); },
}
}
fn expect_ident(tok: Token) {
match tok.kind {
.Ident => {},
_ => { @assert(false, "expected ident"); },
}
}
fn expect_int(tok: Token, radix: Radix) {
match tok.kind {
.Int(r) => {
@assert(@enum2int(r) == @enum2int(radix), "int radix");
},
_ => { @assert(false, "expected int"); },
}
}
fn expect_char(tok: Token, value: u8) {
match tok.kind {
.Char(v) => { @assert(v == value, "char value"); },
_ => { @assert(false, "expected char"); },
}
}
fn expect_endline(tok: Token) {
match tok.kind {
.Endline => {},
_ => { @assert(false, "expected endline"); },
}
}
fn expect_eof(tok: Token) {
match tok.kind {
.Eof => {},
_ => { @assert(false, "expected eof"); },
}
}
fn expect_text(tok: Token, literal: []u8) {
@assert(ByteView.eq(tok.text, view(literal)), "token text");
}
fn expect_pos(tok: Token, line: usize, col: usize) {
@assert(tok.line == line && tok.col == col, "token position");
}
fn test_basic() {
var v = lex_ok("fn main() {\n ret 0;\n}\n");
defer { Vec.drop(&v); }
@assert(v.len == 13, "basic token count");
var t0 = at(&v, 0);
expect_keyword(t0, .Fn);
expect_text(t0, "fn");
expect_pos(t0, 1, 1);
expect_ident(at(&v, 1));
expect_text(at(&v, 1), "main");
expect_punct(at(&v, 2), .LParen);
expect_punct(at(&v, 3), .RParen);
expect_punct(at(&v, 4), .LBrace);
expect_endline(at(&v, 5));
expect_keyword(at(&v, 6), .Ret);
expect_pos(at(&v, 6), 2, 5);
expect_int(at(&v, 7), .Dec);
expect_punct(at(&v, 8), .Semicolon);
expect_endline(at(&v, 9));
expect_punct(at(&v, 10), .RBrace);
expect_endline(at(&v, 11));
expect_eof(at(&v, 12));
}
fn test_operators() {
var v = lex_ok("<-> <- -> <=> <<= << >>= ... .. . := == != < <= > >= && || & | ^ + - * / % ~ ! ? # @ $ , ; : ( ) [ ] { }");
defer { Vec.drop(&v); }
@assert(v.len == 43, "operator token count");
expect_punct(at(&v, 0), .ArrowBoth);
expect_text(at(&v, 0), "<->");
expect_punct(at(&v, 1), .LeftArrow);
expect_punct(at(&v, 2), .RightArrow);
expect_punct(at(&v, 3), .FatArrowBoth);
expect_punct(at(&v, 4), .LShAssign);
expect_punct(at(&v, 5), .LSh);
expect_text(at(&v, 5), "<<");
expect_punct(at(&v, 6), .RShAssign);
expect_punct(at(&v, 7), .Ellipsis);
expect_punct(at(&v, 8), .Range);
expect_punct(at(&v, 9), .Dot);
expect_punct(at(&v, 10), .ColonAssign);
expect_punct(at(&v, 11), .Eq);
expect_punct(at(&v, 12), .Neq);
expect_punct(at(&v, 13), .Lt);
expect_punct(at(&v, 14), .Le);
expect_punct(at(&v, 15), .Gt);
expect_punct(at(&v, 16), .Ge);
expect_punct(at(&v, 17), .AndAnd);
expect_punct(at(&v, 18), .OrOr);
expect_punct(at(&v, 19), .And);
expect_punct(at(&v, 20), .Or);
expect_punct(at(&v, 21), .Xor);
expect_punct(at(&v, 22), .Add);
expect_punct(at(&v, 23), .Sub);
expect_punct(at(&v, 24), .Mul);
expect_punct(at(&v, 25), .Div);
expect_punct(at(&v, 26), .Mod);
expect_punct(at(&v, 27), .BitNot);
expect_punct(at(&v, 28), .Not);
expect_punct(at(&v, 29), .Cond);
expect_punct(at(&v, 30), .Sharp);
expect_punct(at(&v, 31), .At);
expect_punct(at(&v, 32), .Dollar);
expect_punct(at(&v, 33), .Comma);
expect_punct(at(&v, 34), .Semicolon);
expect_punct(at(&v, 35), .Colon);
expect_punct(at(&v, 36), .LParen);
expect_punct(at(&v, 37), .RParen);
expect_punct(at(&v, 38), .LBracket);
expect_punct(at(&v, 39), .RBracket);
expect_punct(at(&v, 40), .LBrace);
expect_punct(at(&v, 41), .RBrace);
expect_eof(at(&v, 42));
}
fn test_comments_and_literals() {
var v = lex_ok("// c\n/* a /* nested */ b */\n'a' '\\n' '\\x41' \"hi\\n\" 0xFF 0b1010 0o17 1_000 3.14");
defer { Vec.drop(&v); }
@assert(v.len == 13, "literal token count");
var comment = at(&v, 0);
match comment.kind {
.LineComment => {},
_ => { @assert(false, "expected line comment"); },
}
expect_text(comment, "// c");
expect_pos(comment, 1, 1);
expect_endline(at(&v, 1));
expect_endline(at(&v, 2));
var ch3 = at(&v, 3);
expect_char(ch3, 'a');
@assert(ByteView.eq(ch3.text, view("'a'")), "char text");
expect_pos(ch3, 3, 1);
expect_char(at(&v, 4), '\n');
expect_char(at(&v, 5), 0x41);
var s = at(&v, 6);
match s.kind {
.Str => {},
_ => { @assert(false, "expected string"); },
}
expect_text(s, "\"hi\\n\"");
expect_int(at(&v, 7), .Hex);
expect_int(at(&v, 8), .Bin);
expect_int(at(&v, 9), .Oct);
expect_int(at(&v, 10), .Dec);
var fl = at(&v, 11);
match fl.kind {
.Float => {},
_ => { @assert(false, "expected float"); },
}
expect_eof(at(&v, 12));
}
// 非法输入走 diag:仍产出 token 以便继续收集错误,但 diag 必须记录。
// Rust 风格数字字面量:分隔符下划线 + 多进制 + 小数/指数字面量。
fn test_number_forms() {
var v = lex_ok("1_000_000 0xFF_FF 0x_ff 0b_1010 0o_7 1_000.5 1.5_0 1_000.500 1.5e-3 1_0.5_0E2");
defer { Vec.drop(&v); }
@assert(v.len == 11, "number token count");
expect_int(at(&v, 0), .Dec);
expect_text(at(&v, 0), "1_000_000");
expect_int(at(&v, 1), .Hex);
expect_text(at(&v, 1), "0xFF_FF");
expect_int(at(&v, 2), .Hex);
expect_text(at(&v, 2), "0x_ff");
expect_int(at(&v, 3), .Bin);
expect_text(at(&v, 3), "0b_1010");
expect_int(at(&v, 4), .Oct);
expect_text(at(&v, 4), "0o_7");
var i: usize = 5;
while i < 10 {
match at(&v, i).kind {
.Float => {},
_ => { @assert(false, "expected float"); },
}
i = i + 1;
}
expect_text(at(&v, 5), "1_000.5");
expect_text(at(&v, 6), "1.5_0");
expect_text(at(&v, 7), "1_000.500");
expect_text(at(&v, 8), "1.5e-3");
expect_text(at(&v, 9), "1_0.5_0E2");
expect_eof(at(&v, 10));
}
fn test_diag_errors() {
var diag = Diag.new(null);
defer { Diag.drop(&diag); }
match lex(view("'\\q' \"abc"), &diag, 0) {
.Ok(v) => { Vec.drop(&v); },
.Err(error) => { @assert(false, "lex should return tokens"); },
}
@assert(Diag.has_error(diag), "lex errors recorded");
var clean = Diag.new(null);
defer { Diag.drop(&clean); }
match lex(view("fn main() { ret 0; }"), &clean, 0) {
.Ok(v) => { Vec.drop(&v); },
.Err(error) => { @assert(false, "legal lex failed"); },
}
@assert(!Diag.has_error(clean), "legal input has no diagnostics");
}
fn main() {
test_basic();
test_operators();
test_comments_and_literals();
test_number_forms();
test_diag_errors();
}
+2192
View File
File diff suppressed because it is too large. Load diff
+239
View File
@@ -0,0 +1,239 @@
// Expect retcode = 0
// splc1 (stage2 自举编译器入口)。
// 当前仅实现 `--dump lex <file> [out]`:读取源文件,词法分析,按与 stage1
// splc0 完全一致的格式打印 token 列表,供 diff 测试逐字节比对。
type .{ .ByteView } = @import("./utils/byte_view.spl");
type .{ .ByteBuffer } = @import("./utils/byte_buffer.spl");
type .{ .Vec } = @import("./utils/vec.spl");
type .{ .Token, .kind_name } = @import("./token.spl");
type .{ .Lexer } = @import("./lexer.spl");
type Ast = @import("./ast.spl");
type Parser = @import("./parser.spl");
type .{ .append_usize } = @import("./utils/fmt.spl");
type .{ .read_all, .print, .eprint } = @import("./utils/io.spl");
type .{ .set_new, .set_add, .set_drop } = @import("./utils/source.spl");
type Diag = @import("./diag.spl");
type Logger = @import("./utils/log.spl");
fn token_at(tokens: *Vec, index: usize): Token {
match Vec.get(tokens, index) {
.Ok(ptr) => { ret (ptr as *Token).*; },
.Err(error) => { ret Token.make(.Unknown(0), ByteView.empty(), 0, 0, 0); },
}
ret Token.make(.Unknown(0), ByteView.empty(), 0, 0, 0);
}
// 追加成功返回 true;失败(仅 OOM)返回 false。
fn push(out: *ByteBuffer, bytes: []u8): bool {
match ByteBuffer.append(out, bytes) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
fn push_byte(out: *ByteBuffer, byte: u8): bool {
match ByteBuffer.append_byte(out, byte) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
fn push_usize(out: *ByteBuffer, value: usize): bool {
match append_usize(out, value, 10, false) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
// 输出格式与 splc0.c 的 dump_tokens 一致:
// tokens got (N)\n
// [TOK_TYPE] <lexeme> (line:col)\n
fn dump_tokens(tokens: *Vec): bool {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
if !push(&out, "tokens got (") { ret false; }
if !push_usize(&out, tokens.len) { ret false; }
if !push(&out, ")\n") { ret false; }
var i: usize = 0;
while i < tokens.len {
var tok = token_at(tokens, i);
if !push(&out, "[") { ret false; }
if !push(&out, kind_name(tok.kind)) { ret false; }
if !push(&out, "] ") { ret false; }
if !push(&out, ByteView.as_slice(tok.text)) { ret false; }
if !push(&out, " (") { ret false; }
if !push_usize(&out, tok.line) { ret false; }
if !push_byte(&out, ':') { ret false; }
if !push_usize(&out, tok.col) { ret false; }
if !push(&out, ")\n") { ret false; }
i = i + 1;
}
match print(ByteBuffer.as_slice(out)) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
fn dump_lex(log: *Logger, path: ByteView): i32 {
var content = ByteBuffer.new();
defer { ByteBuffer.drop(&content); }
match read_all(path, &content) {
.Ok => {},
.Err(error) => {
Logger.error(log, "cannot read input file");
ret 1;
},
}
var text = ByteView.from_slice(ByteBuffer.as_slice(content));
var sources = set_new();
defer { set_drop(&sources); }
match set_add(&sources, path, text) {
.Ok(index) => {},
.Err(error) => {
Logger.error(log, "cannot register source");
ret 1;
},
}
var diag = Diag.new(&sources);
defer { Diag.drop(&diag); }
var tokens = Vec.blank(@sizeof(Token), @alignof(Token));
match Lexer.lex(text, &diag, 0) {
.Ok(v) => { tokens = v; },
.Err(error) => {
Logger.error(log, "lex failed");
ret 1;
},
}
defer { Vec.drop(&tokens); }
// 非法输入:走诊断(stage1 在此处是宽容无视,stage2 显式报错)。
if Diag.has_error(diag) {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) {
.Ok => {},
.Err(error) => {},
}
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
if !dump_tokens(&tokens) {
Logger.fatal(log, "out of memory while dumping tokens");
ret 1;
}
ret 0;
}
fn dump_ast(log: *Logger, path: ByteView): i32 {
var content = ByteBuffer.new();
defer { ByteBuffer.drop(&content); }
match read_all(path, &content) {
.Ok => {},
.Err(error) => {
Logger.error(log, "cannot read input file");
ret 1;
},
}
var text = ByteView.from_slice(ByteBuffer.as_slice(content));
var sources = set_new();
defer { set_drop(&sources); }
match set_add(&sources, path, text) {
.Ok(index) => {},
.Err(error) => {
Logger.error(log, "cannot register source");
ret 1;
},
}
var diag = Diag.new(&sources);
defer { Diag.drop(&diag); }
var tokens = Vec.blank(@sizeof(Token), @alignof(Token));
match Lexer.lex(text, &diag, 0) {
.Ok(v) => { tokens = v; },
.Err(error) => {
Logger.error(log, "lex failed");
ret 1;
},
}
defer { Vec.drop(&tokens); }
var ast: Ast = undefined;
match Ast.new(&sources) {
.Ok(v) => { ast = v; },
.Err(error) => {
Logger.error(log, "ast init failed");
ret 1;
},
}
defer { Ast.drop(&ast); }
var p = Parser.new(&ast, tokens, &diag);
Parser.parse(&p);
if Diag.has_error(diag) || p.failed {
var rendered = ByteBuffer.new();
defer { ByteBuffer.drop(&rendered); }
match Diag.render_human(&diag, &rendered) {
.Ok => {},
.Err(error) => {},
}
eprint(ByteBuffer.as_slice(rendered));
ret 1;
}
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
if !Ast.dump(&ast, &out) {
Logger.fatal(log, "out of memory while dumping ast");
ret 1;
}
match print(ByteBuffer.as_slice(out)) {
.Ok => {},
.Err(error) => { ret 1; },
}
ret 0;
}
fn main(argc: i32, argv: **u8): i32 {
// 无参数:自测运行(`nob test stage2`)视为成功。
if argc <= 1 { ret 0; }
var log = Logger.new(ByteView.from_slice("splc1"));
if argc < 4 {
Logger.fatal(&log, "usage: splc1 --dump <lex|ast> <file> [out]");
ret 1;
}
var arg1 = ByteView.from_cstr(argv[1]);
var mode = ByteView.from_cstr(argv[2]);
var path = ByteView.from_cstr(argv[3]);
if !ByteView.eq(arg1, ByteView.from_slice("--dump")) {
Logger.fatal(&log, "usage: splc1 --dump <lex|ast> <file> [out]");
ret 1;
}
if ByteView.eq(mode, ByteView.from_slice("lex")) {
ret dump_lex(&log, path);
}
if ByteView.eq(mode, ByteView.from_slice("ast")) {
ret dump_ast(&log, path);
}
Logger.fatal(&log, "dump mode not implemented");
ret 1;
}
+22
View File
@@ -0,0 +1,22 @@
// Expect retcode = 6
// exit.spl
// usage: type exit = @import("exit.spl"); exit.ok();
#extern(vm) fn vm_exit(code: i32);
fn now(code: i32) {
vm_exit(code);
}
fn ok() {
vm_exit(0);
}
fn fail() {
vm_exit(1);
}
fn main(): void {
now(6);
}
+70
View File
@@ -0,0 +1,70 @@
#extern(vm) fn vm_fopen(path: *any, mode: *any): *any;
#extern(vm) fn vm_fclose(f: *any): i32;
#extern(vm) fn vm_fread(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fwrite(buf: *any, sz: usize, n: usize, f: *any): usize;
#extern(vm) fn vm_fsize(f: *any): usize;
#extern(vm) fn vm_stdin(): *any;
#extern(vm) fn vm_stdout(): *any;
#extern(vm) fn vm_stderr(): *any;
#extern(vm) fn vm_putchar(c: i32): i32;
#extern(vm) fn vm_getchar(): i32;
handle: *any,
type File = @self;
fn stdin(): File { ret File { .handle = vm_stdin() }; }
fn stdout(): File { ret File { .handle = vm_stdout() }; }
fn stderr(): File { ret File { .handle = vm_stderr() }; }
fn open(path: *u8, mode: *u8): File {
ret File { .handle = vm_fopen(path as *any, mode as *any) };
}
fn valid(f: *File): bool {
ret f.handle != null;
}
fn write(f: *File, data: *u8, n: u64): u64 {
if f.handle == null { ret 0; }
ret vm_fwrite(data as *any, 1, n, f.handle);
}
fn write_byte(f: *File, b: u8): u64 {
var tmp: u8 = b;
ret write(f, &tmp, 1);
}
fn read(f: *File, buf: *u8, n: usize): usize {
if f.handle == null { ret 0; }
ret vm_fread(buf as *any, 1, n, f.handle);
}
fn size(f: *File): usize {
if f.handle == null { ret 0; }
ret vm_fsize(f.handle);
}
fn close(f: *File): i32 {
if f.handle == null { ret -1; }
var r = vm_fclose(f.handle);
f.handle = null;
ret r;
}
fn putchar(c: u8) {
vm_putchar(c as i32);
}
fn getchar(): i32 {
ret vm_getchar();
}
fn main(): void {
var out = stdout();
@assert(out.handle != null, "stdout");
var msg = "file: ok\n";
var n = write(&out, msg.ptr, msg.len);
@assert(n == msg.len, "write");
putchar(46 as u8);
putchar(10 as u8);
}
+79
View File
@@ -0,0 +1,79 @@
#extern(vm) fn vm_alloc(sz: usize): *any;
#extern(vm) fn vm_free(p: *any);
#extern(vm) fn vm_realloc(p: *any, sz: usize): *any;
#extern(vm) fn vm_memcpy(dst: *any, src: *any, n: usize): *any;
#extern(vm) fn vm_memcmp(a: *any, b: *any, n: usize): isize;
fn alloc(sz: usize): *any {
if sz == 0 { ret null; }
ret vm_alloc(sz);
}
fn free(p: *any) {
if p == null { ret; }
vm_free(p);
}
fn realloc(p: *any, sz: usize): *any {
if p == null { ret alloc(sz); }
if sz == 0 { free(p); ret null; }
ret vm_realloc(p, sz);
}
fn copy(dst: *any, src: *any, n: usize): *any {
if n == 0 { ret dst; }
ret vm_memcpy(dst, src, n);
}
fn cmp(a: *any, b: *any, n: usize): isize {
if n == 0 { ret 0; }
ret vm_memcmp(a, b, n);
}
fn set(dst: *any, byte: u8, n: usize): *any {
var d = dst as *u8;
var i: usize = 0;
while i < n {
d[i] = byte;
i = i + 1;
}
ret dst;
}
fn zero(dst: *any, n: usize): *any {
ret set(dst, 0 as u8, n);
}
fn main(): void {
var p = alloc(16);
@assert(p != null, "alloc");
var q = alloc(16);
@assert(p != q, "distinct");
@assert(alloc(0) == null, "alloc(0)");
var a: u8 = 42;
var b: u8 = 0;
copy(&b as *any, &a as *any, 1);
@assert(b == 42, "copy");
var x: u8 = 1;
var y: u8 = 2;
@assert(cmp(&x as *any, &y as *any, 1) < 0, "cmp lt");
@assert(cmp(&y as *any, &x as *any, 1) > 0, "cmp gt");
@assert(cmp(&x as *any, &x as *any, 1) == 0, "cmp eq");
var buf = alloc(8);
zero(buf, 8);
var bp = buf as *u8;
@assert(bp[0] == 0, "zero");
@assert(bp[7] == 0, "zero end");
set(buf, 0xAB as u8, 8);
@assert(bp[0] == 0xAB as u8, "set");
var r = realloc(p, 32);
@assert(r != null, "realloc");
free(r);
free(q);
free(buf);
free(null);
}
+399
View File
@@ -0,0 +1,399 @@
// Expect retcode = 0
// 词法单元:用带载荷 ADT 表达 TokenKind;关键词/算符各自独立 enum。
// 整型与字符在词法期解码并随载荷携带;文本一律借用源切片(不复制)。
type .{ .ByteView } = @import("utils/byte_view.spl");
type Keyword = enum {
Any, As, Bool, Break, Catch, Comptime, Const, Continue, Defer, Else, Enum,
Errdefer, False, Fn, For, If, Loop, Match, Null, Ret, Shape, Struct, True,
Try, Type, Undefined, Union, Var, While, Underscore,
}
type KeywordResult = enum {
Yes: Keyword,
No,
}
type Punct = enum {
Eq, Assign, AddAssign, Add, SubAssign, Sub, MulAssign, Mul, DivAssign, Div,
ModAssign, Mod, RightArrow, LeftArrow, ArrowBoth, FatArrowBoth, RightFatArrow,
AndAnd, AndAssign, And, OrOr, OrAssign, Or, XorAssign, Xor,
LShAssign, LSh, Le, Lt, RShAssign, RSh, Ge, Gt, Not, Neq, BitNot,
LBracket, RBracket, LParen, RParen, LBrace, RBrace,
Semicolon, Comma, Colon, ColonAssign, Dot, Range, Ellipsis, Cond, Sharp, At, Dollar,
}
type Radix = enum {
Dec,
Bin,
Oct,
Hex,
}
type TokenKind = enum {
Keyword: Keyword,
Punct: Punct,
Ident,
Int: Radix, // 仅记进制;数值由 parser 按任意宽度(mp)解析
Float,
Char: u8,
Str,
LineComment,
Endline,
Eof,
Unknown: u8,
}
type Token = @self;
kind: TokenKind,
text: ByteView,
line: usize,
col: usize,
offset: usize, // 源文件字节偏移(供 AST Span 使用)
fn make(kind: TokenKind, text: ByteView, line: usize, col: usize, offset: usize): Token {
ret Token { .kind = kind, .text = text, .line = line, .col = col, .offset = offset };
}
fn is_trivia(kind: TokenKind): bool {
match kind {
.Endline => { ret true; },
.LineComment => { ret true; },
_ => { ret false; },
}
}
fn keyword_of(text: ByteView): KeywordResult {
if is(text, "any") { ret .Yes(.Any); }
if is(text, "as") { ret .Yes(.As); }
if is(text, "bool") { ret .Yes(.Bool); }
if is(text, "break") { ret .Yes(.Break); }
if is(text, "catch") { ret .Yes(.Catch); }
if is(text, "comptime") { ret .Yes(.Comptime); }
if is(text, "const") { ret .Yes(.Const); }
if is(text, "continue") { ret .Yes(.Continue); }
if is(text, "defer") { ret .Yes(.Defer); }
if is(text, "else") { ret .Yes(.Else); }
if is(text, "enum") { ret .Yes(.Enum); }
if is(text, "errdefer") { ret .Yes(.Errdefer); }
if is(text, "false") { ret .Yes(.False); }
if is(text, "fn") { ret .Yes(.Fn); }
if is(text, "for") { ret .Yes(.For); }
if is(text, "if") { ret .Yes(.If); }
if is(text, "loop") { ret .Yes(.Loop); }
if is(text, "match") { ret .Yes(.Match); }
if is(text, "null") { ret .Yes(.Null); }
if is(text, "ret") { ret .Yes(.Ret); }
if is(text, "shape") { ret .Yes(.Shape); }
if is(text, "struct") { ret .Yes(.Struct); }
if is(text, "true") { ret .Yes(.True); }
if is(text, "try") { ret .Yes(.Try); }
if is(text, "type") { ret .Yes(.Type); }
if is(text, "undefined") { ret .Yes(.Undefined); }
if is(text, "union") { ret .Yes(.Union); }
if is(text, "var") { ret .Yes(.Var); }
if is(text, "while") { ret .Yes(.While); }
if is(text, "_") { ret .Yes(.Underscore); }
ret .No;
}
// ---- token 类型名(与 stage1 spl_tok_type_name 逐字一致,供 dump/diff 使用)----
fn keyword_name(kw: Keyword): []u8 {
match kw {
.Any => { ret "KW_ANY"; },
.As => { ret "KW_AS"; },
.Bool => { ret "KW_BOOL"; },
.Break => { ret "KW_BREAK"; },
.Catch => { ret "KW_CATCH"; },
.Comptime => { ret "KW_COMPTIME"; },
.Const => { ret "KW_CONST"; },
.Continue => { ret "KW_CONTINUE"; },
.Defer => { ret "KW_DEFER"; },
.Else => { ret "KW_ELSE"; },
.Enum => { ret "KW_ENUM"; },
.Errdefer => { ret "KW_ERRDEFER"; },
.False => { ret "KW_FALSE"; },
.Fn => { ret "KW_FN"; },
.For => { ret "KW_FOR"; },
.If => { ret "KW_IF"; },
.Loop => { ret "KW_LOOP"; },
.Match => { ret "KW_MATCH"; },
.Null => { ret "KW_NULL"; },
.Ret => { ret "KW_RET"; },
.Shape => { ret "KW_SHAPE"; },
.Struct => { ret "KW_STRUCT"; },
.True => { ret "KW_TRUE"; },
.Try => { ret "KW_TRY"; },
.Type => { ret "KW_TYPE"; },
.Undefined => { ret "KW_UNDEFINED"; },
.Union => { ret "KW_UNION"; },
.Var => { ret "KW_VAR"; },
.While => { ret "KW_WHILE"; },
.Underscore => { ret "KW_UNDERSCORE"; },
}
ret "?";
}
fn punct_name(punct: Punct): []u8 {
match punct {
.Eq => { ret "TOK_EQ"; },
.Assign => { ret "TOK_ASSIGN"; },
.AddAssign => { ret "TOK_ASSIGN_ADD"; },
.Add => { ret "TOK_ADD"; },
.SubAssign => { ret "TOK_ASSIGN_SUB"; },
.Sub => { ret "TOK_SUB"; },
.MulAssign => { ret "TOK_ASSIGN_MUL"; },
.Mul => { ret "TOK_MUL"; },
.DivAssign => { ret "TOK_ASSIGN_DIV"; },
.Div => { ret "TOK_DIV"; },
.ModAssign => { ret "TOK_ASSIGN_MOD"; },
.Mod => { ret "TOK_MOD"; },
.RightArrow => { ret "TOK_RIGHT_ARROW"; },
.LeftArrow => { ret "TOK_LEFT_ARROW"; },
.ArrowBoth => { ret "TOK_ARROW_BOTH"; },
.FatArrowBoth => { ret "TOK_FAT_ARROW_BOTH"; },
.RightFatArrow => { ret "TOK_RIGHT_FAT_ARROW"; },
.AndAnd => { ret "TOK_AND_AND"; },
.AndAssign => { ret "TOK_ASSIGN_AND"; },
.And => { ret "TOK_AND"; },
.OrOr => { ret "TOK_OR_OR"; },
.OrAssign => { ret "TOK_ASSIGN_OR"; },
.Or => { ret "TOK_OR"; },
.XorAssign => { ret "TOK_ASSIGN_XOR"; },
.Xor => { ret "TOK_XOR"; },
.LShAssign => { ret "TOK_ASSIGN_L_SH"; },
.LSh => { ret "TOK_L_SH"; },
.Le => { ret "TOK_LE"; },
.Lt => { ret "TOK_LT"; },
.RShAssign => { ret "TOK_ASSIGN_R_SH"; },
.RSh => { ret "TOK_R_SH"; },
.Ge => { ret "TOK_GE"; },
.Gt => { ret "TOK_GT"; },
.Not => { ret "TOK_NOT"; },
.Neq => { ret "TOK_NEQ"; },
.BitNot => { ret "TOK_BIT_NOT"; },
.LBracket => { ret "TOK_L_BRACKET"; },
.RBracket => { ret "TOK_R_BRACKET"; },
.LParen => { ret "TOK_L_PAREN"; },
.RParen => { ret "TOK_R_PAREN"; },
.LBrace => { ret "TOK_L_BRACE"; },
.RBrace => { ret "TOK_R_BRACE"; },
.Semicolon => { ret "TOK_SEMICOLON"; },
.Comma => { ret "TOK_COMMA"; },
.Colon => { ret "TOK_COLON"; },
.ColonAssign => { ret "TOK_COLON_ASSIGN"; },
.Dot => { ret "TOK_DOT"; },
.Range => { ret "TOK_RANGE"; },
.Ellipsis => { ret "TOK_ELLIPSIS"; },
.Cond => { ret "TOK_COND"; },
.Sharp => { ret "TOK_SHARP"; },
.At => { ret "TOK_AT"; },
.Dollar => { ret "TOK_DOLLAR"; },
}
ret "?";
}
fn kind_name(kind: TokenKind): []u8 {
match kind {
.Keyword(kw) => { ret keyword_name(kw); },
.Punct(punct) => { ret punct_name(punct); },
.Ident => { ret "TOK_IDENT"; },
.Int(value) => { ret "TOK_INT_LITERAL"; },
.Float => { ret "TOK_FLOAT_LITERAL"; },
.Char(value) => { ret "TOK_CHAR_LITERAL"; },
.Str => { ret "TOK_STRING_LITERAL"; },
.LineComment => { ret "TOK_LINE_COMMENT"; },
.Endline => { ret "TOK_ENDLINE"; },
.Eof => { ret "TOK_EOF"; },
.Unknown(value) => { ret "TOK_UNKNOWN"; },
}
ret "?";
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
}
fn is(text: ByteView, literal: []u8): bool {
ret ByteView.eq(text, view(literal));
}
fn expect_keyword(result: KeywordResult, expected: Keyword) {
match result {
.Yes(kw) => { @assert(@enum2int(kw) == @enum2int(expected), "keyword"); },
.No => { @assert(false, "expected keyword"); },
}
}
fn test_keywords() {
expect_keyword(keyword_of(view("fn")), .Fn);
expect_keyword(keyword_of(view("while")), .While);
expect_keyword(keyword_of(view("_")), .Underscore);
match keyword_of(view("foo")) {
.Yes(kw) => { @assert(false, "foo is not a keyword"); },
.No => {},
}
match keyword_of(view("")) {
.Yes(kw) => { @assert(false, "empty is not a keyword"); },
.No => {},
}
}
fn test_adt_payloads() {
var t = make(.Int(.Hex), view("0xFF"), 3, 5, 0);
@assert(t.line == 3 && t.col == 5, "position");
match t.kind {
.Int(radix) => {
var hex: Radix = .Hex;
@assert(@enum2int(radix) == @enum2int(hex), "int radix");
},
_ => { @assert(false, "expected int"); },
}
var c = make(.Char('a'), view("'a'"), 1, 1, 0);
match c.kind {
.Char(value) => { @assert(value == 'a', "char value"); },
_ => { @assert(false, "expected char"); },
}
var p = make(.Punct(.ArrowBoth), view("<->"), 1, 1, 0);
match p.kind {
.Punct(punct) => {
var both: Punct = .ArrowBoth;
@assert(@enum2int(punct) == @enum2int(both), "punct");
},
_ => { @assert(false, "expected punct"); },
}
var k = make(.Keyword(.Ret), view("ret"), 1, 1, 0);
match k.kind {
.Keyword(kw) => {
var ret_kw: Keyword = .Ret;
@assert(@enum2int(kw) == @enum2int(ret_kw), "keyword kind");
},
_ => { @assert(false, "expected keyword"); },
}
}
fn test_trivia() {
@assert(is_trivia(.Endline), "endline trivia");
@assert(is_trivia(.LineComment), "comment trivia");
@assert(!is_trivia(.Ident), "ident not trivia");
@assert(!is_trivia(.Eof), "eof not trivia");
}
fn expect_kind_name(kind: TokenKind, expected: []u8) {
@assert(ByteView.eq(ByteView.from_slice(kind_name(kind)),
ByteView.from_slice(expected)),
"token kind name");
}
fn test_kind_names() {
expect_kind_name(.Keyword(.Any), "KW_ANY");
expect_kind_name(.Keyword(.As), "KW_AS");
expect_kind_name(.Keyword(.Bool), "KW_BOOL");
expect_kind_name(.Keyword(.Break), "KW_BREAK");
expect_kind_name(.Keyword(.Catch), "KW_CATCH");
expect_kind_name(.Keyword(.Comptime), "KW_COMPTIME");
expect_kind_name(.Keyword(.Const), "KW_CONST");
expect_kind_name(.Keyword(.Continue), "KW_CONTINUE");
expect_kind_name(.Keyword(.Defer), "KW_DEFER");
expect_kind_name(.Keyword(.Else), "KW_ELSE");
expect_kind_name(.Keyword(.Enum), "KW_ENUM");
expect_kind_name(.Keyword(.Errdefer), "KW_ERRDEFER");
expect_kind_name(.Keyword(.False), "KW_FALSE");
expect_kind_name(.Keyword(.Fn), "KW_FN");
expect_kind_name(.Keyword(.For), "KW_FOR");
expect_kind_name(.Keyword(.If), "KW_IF");
expect_kind_name(.Keyword(.Loop), "KW_LOOP");
expect_kind_name(.Keyword(.Match), "KW_MATCH");
expect_kind_name(.Keyword(.Null), "KW_NULL");
expect_kind_name(.Keyword(.Ret), "KW_RET");
expect_kind_name(.Keyword(.Shape), "KW_SHAPE");
expect_kind_name(.Keyword(.Struct), "KW_STRUCT");
expect_kind_name(.Keyword(.True), "KW_TRUE");
expect_kind_name(.Keyword(.Try), "KW_TRY");
expect_kind_name(.Keyword(.Type), "KW_TYPE");
expect_kind_name(.Keyword(.Undefined), "KW_UNDEFINED");
expect_kind_name(.Keyword(.Union), "KW_UNION");
expect_kind_name(.Keyword(.Var), "KW_VAR");
expect_kind_name(.Keyword(.While), "KW_WHILE");
expect_kind_name(.Keyword(.Underscore), "KW_UNDERSCORE");
expect_kind_name(.Punct(.Eq), "TOK_EQ");
expect_kind_name(.Punct(.Assign), "TOK_ASSIGN");
expect_kind_name(.Punct(.AddAssign), "TOK_ASSIGN_ADD");
expect_kind_name(.Punct(.Add), "TOK_ADD");
expect_kind_name(.Punct(.SubAssign), "TOK_ASSIGN_SUB");
expect_kind_name(.Punct(.Sub), "TOK_SUB");
expect_kind_name(.Punct(.MulAssign), "TOK_ASSIGN_MUL");
expect_kind_name(.Punct(.Mul), "TOK_MUL");
expect_kind_name(.Punct(.DivAssign), "TOK_ASSIGN_DIV");
expect_kind_name(.Punct(.Div), "TOK_DIV");
expect_kind_name(.Punct(.ModAssign), "TOK_ASSIGN_MOD");
expect_kind_name(.Punct(.Mod), "TOK_MOD");
expect_kind_name(.Punct(.RightArrow), "TOK_RIGHT_ARROW");
expect_kind_name(.Punct(.LeftArrow), "TOK_LEFT_ARROW");
expect_kind_name(.Punct(.ArrowBoth), "TOK_ARROW_BOTH");
expect_kind_name(.Punct(.FatArrowBoth), "TOK_FAT_ARROW_BOTH");
expect_kind_name(.Punct(.RightFatArrow), "TOK_RIGHT_FAT_ARROW");
expect_kind_name(.Punct(.AndAnd), "TOK_AND_AND");
expect_kind_name(.Punct(.AndAssign), "TOK_ASSIGN_AND");
expect_kind_name(.Punct(.And), "TOK_AND");
expect_kind_name(.Punct(.OrOr), "TOK_OR_OR");
expect_kind_name(.Punct(.OrAssign), "TOK_ASSIGN_OR");
expect_kind_name(.Punct(.Or), "TOK_OR");
expect_kind_name(.Punct(.XorAssign), "TOK_ASSIGN_XOR");
expect_kind_name(.Punct(.Xor), "TOK_XOR");
expect_kind_name(.Punct(.LShAssign), "TOK_ASSIGN_L_SH");
expect_kind_name(.Punct(.LSh), "TOK_L_SH");
expect_kind_name(.Punct(.Le), "TOK_LE");
expect_kind_name(.Punct(.Lt), "TOK_LT");
expect_kind_name(.Punct(.RShAssign), "TOK_ASSIGN_R_SH");
expect_kind_name(.Punct(.RSh), "TOK_R_SH");
expect_kind_name(.Punct(.Ge), "TOK_GE");
expect_kind_name(.Punct(.Gt), "TOK_GT");
expect_kind_name(.Punct(.Not), "TOK_NOT");
expect_kind_name(.Punct(.Neq), "TOK_NEQ");
expect_kind_name(.Punct(.BitNot), "TOK_BIT_NOT");
expect_kind_name(.Punct(.LBracket), "TOK_L_BRACKET");
expect_kind_name(.Punct(.RBracket), "TOK_R_BRACKET");
expect_kind_name(.Punct(.LParen), "TOK_L_PAREN");
expect_kind_name(.Punct(.RParen), "TOK_R_PAREN");
expect_kind_name(.Punct(.LBrace), "TOK_L_BRACE");
expect_kind_name(.Punct(.RBrace), "TOK_R_BRACE");
expect_kind_name(.Punct(.Semicolon), "TOK_SEMICOLON");
expect_kind_name(.Punct(.Comma), "TOK_COMMA");
expect_kind_name(.Punct(.Colon), "TOK_COLON");
expect_kind_name(.Punct(.ColonAssign), "TOK_COLON_ASSIGN");
expect_kind_name(.Punct(.Dot), "TOK_DOT");
expect_kind_name(.Punct(.Range), "TOK_RANGE");
expect_kind_name(.Punct(.Ellipsis), "TOK_ELLIPSIS");
expect_kind_name(.Punct(.Cond), "TOK_COND");
expect_kind_name(.Punct(.Sharp), "TOK_SHARP");
expect_kind_name(.Punct(.At), "TOK_AT");
expect_kind_name(.Punct(.Dollar), "TOK_DOLLAR");
expect_kind_name(.Ident, "TOK_IDENT");
expect_kind_name(.Int(.Dec), "TOK_INT_LITERAL");
expect_kind_name(.Float, "TOK_FLOAT_LITERAL");
expect_kind_name(.Char('a'), "TOK_CHAR_LITERAL");
expect_kind_name(.Str, "TOK_STRING_LITERAL");
expect_kind_name(.LineComment, "TOK_LINE_COMMENT");
expect_kind_name(.Endline, "TOK_ENDLINE");
expect_kind_name(.Eof, "TOK_EOF");
expect_kind_name(.Unknown(0), "TOK_UNKNOWN");
}
fn main() {
test_keywords();
test_adt_payloads();
test_trivia();
test_kind_names();
}
+326
View File
@@ -0,0 +1,326 @@
// Expect retcode = 0
// 类型擦除的搜索与稳定归并排序。元素由定长字节表示,比较回调负责解释元素和键;
// context 只借用,模块不持有元素、键或上下文。所有尺寸错误都在写入前返回。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .checked_mul } = @import("memory.spl");
type .{ .alloc, .copy, .free } = @import("../sys/mem.spl");
type SearchResult = enum {
Found: usize,
NotFound,
Err: Error,
}
fn validate_range(data: *u8, len: usize, elem_size: usize): Status {
if elem_size == 0 { ret .Err(make(.InvalidArgument)); }
match checked_mul(len, elem_size) {
.Ok(bytes) => {},
.Err(error) => { ret .Err(error); },
}
if len != 0 && data == null { ret .Err(make(.InvalidArgument)); }
ret .Ok;
}
// 返回首个相等元素。空范围不读取 data、key 或调用 compare。
fn linear_search(data: *u8, len: usize, elem_size: usize, key: *u8,
context: *u8, compare: fn(*u8, *u8, *u8): i32): SearchResult {
match validate_range(data, len, elem_size) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
if len == 0 { ret .NotFound; }
if key == null { ret .Err(make(.InvalidArgument)); }
var i: usize = 0;
while i < len {
if compare(data + i * elem_size, key, context) == 0 {
ret .Found(i);
}
i = i + 1;
}
ret .NotFound;
}
// data 必须按 compare 升序排列。存在重复值时返回首个相等元素。
fn binary_search(data: *u8, len: usize, elem_size: usize, key: *u8,
context: *u8, compare: fn(*u8, *u8, *u8): i32): SearchResult {
match validate_range(data, len, elem_size) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
if len == 0 { ret .NotFound; }
if key == null { ret .Err(make(.InvalidArgument)); }
var low: usize = 0;
var high = len;
while low < high {
var mid = low + (high - low) / 2;
if compare(data + mid * elem_size, key, context) < 0 {
low = mid + 1;
} else {
high = mid;
}
}
if low < len && compare(data + low * elem_size, key, context) == 0 {
ret .Found(low);
}
ret .NotFound;
}
fn min_size(a: usize, b: usize): usize {
if a < b { ret a; }
ret b;
}
fn merge_run(dst: *u8, src: *u8, elem_size: usize,
begin: usize, middle: usize, end: usize,
context: *u8, compare: fn(*u8, *u8, *u8): i32) {
var left = begin;
var right = middle;
var output = begin;
while left < middle && right < end {
var left_ptr = src + left * elem_size;
var right_ptr = src + right * elem_size;
// 相等时先取左侧元素,由此保证稳定性。
if compare(left_ptr, right_ptr, context) <= 0 {
copy((dst + output * elem_size) as *any, left_ptr as *any, elem_size);
left = left + 1;
} else {
copy((dst + output * elem_size) as *any, right_ptr as *any, elem_size);
right = right + 1;
}
output = output + 1;
}
while left < middle {
copy((dst + output * elem_size) as *any,
(src + left * elem_size) as *any, elem_size);
left = left + 1;
output = output + 1;
}
while right < end {
copy((dst + output * elem_size) as *any,
(src + right * elem_size) as *any, elem_size);
right = right + 1;
output = output + 1;
}
}
// 自底向上的稳定归并排序。分配失败及参数错误不改变输入。
fn stable_sort(data: *u8, len: usize, elem_size: usize,
context: *u8, compare: fn(*u8, *u8, *u8): i32): Status {
var bytes: usize = 0;
match validate_range(data, len, elem_size) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
match checked_mul(len, elem_size) {
.Ok(value) => { bytes = value; },
.Err(error) => { ret .Err(error); },
}
if len < 2 { ret .Ok; }
var scratch = alloc(bytes) as *u8;
if scratch == null { ret .Err(make(.Overflow)); }
defer { free(scratch as *any); }
var source = data;
var destination = scratch;
var width: usize = 1;
while width < len {
var begin: usize = 0;
while begin < len {
var left_width = min_size(width, len - begin);
var middle = begin + left_width;
var remaining = len - middle;
var right_width = min_size(width, remaining);
var end = middle + right_width;
merge_run(destination, source, elem_size, begin, middle, end,
context, compare);
begin = end;
}
var swap = source;
source = destination;
destination = swap;
if width > len / 2 {
width = len;
} else {
width = width * 2;
}
}
if source != data {
copy(data as *any, source as *any, bytes);
}
ret .Ok;
}
// ---- 测试 ----
type Item = struct {
key: i32,
sequence: i32,
}
fn compare_i32(a: *u8, b: *u8, context: *u8): i32 {
var av = (a as *i32).*;
var bv = (b as *i32).*;
if av < bv { ret -1; }
if av > bv { ret 1; }
ret 0;
}
fn compare_item(a: *u8, b: *u8, context: *u8): i32 {
var av = (a as *Item).*.key;
var bv = (b as *Item).*.key;
var direction: i32 = 1;
if context != null { direction = (context as *i32).*; }
if av < bv { ret -direction; }
if av > bv { ret direction; }
ret 0;
}
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected algorithm error"); },
}
}
fn expect_found(result: SearchResult, expected: usize) {
match result {
.Found(index) => { @assert(index == expected, "search index"); },
.NotFound => { @assert(false, "expected search match"); },
.Err(error) => { @assert(false, "unexpected search error"); },
}
}
fn expect_missing(result: SearchResult) {
match result {
.Found(index) => { @assert(false, "unexpected search match"); },
.NotFound => {},
.Err(error) => { @assert(false, "unexpected search error"); },
}
}
fn expect_search_error(result: SearchResult, overflow: bool) {
match result {
.Found(index) => { @assert(false, "expected search error"); },
.NotFound => { @assert(false, "expected search error"); },
.Err(error) => {
match error.kind {
.Overflow => { @assert(overflow); },
.InvalidArgument => { @assert(!overflow); },
_ => { @assert(false, "unexpected search error kind"); },
}
},
}
}
fn test_search() {
var values: [8]i32 = .[1, 2, 2, 2, 5, 8, 13, 21];
var two: i32 = 2;
var seven: i32 = 7;
expect_found(linear_search(&values[0] as *u8, 8, @sizeof(i32),
&two as *u8, null, compare_i32), 1);
expect_found(binary_search(&values[0] as *u8, 8, @sizeof(i32),
&two as *u8, null, compare_i32), 1);
expect_missing(linear_search(&values[0] as *u8, 8, @sizeof(i32),
&seven as *u8, null, compare_i32));
expect_missing(binary_search(&values[0] as *u8, 8, @sizeof(i32),
&seven as *u8, null, compare_i32));
expect_missing(linear_search(null, 0, @sizeof(i32), null, null, compare_i32));
expect_missing(binary_search(null, 0, @sizeof(i32), null, null, compare_i32));
expect_search_error(linear_search(&values[0] as *u8, 8, 0,
&two as *u8, null, compare_i32), false);
expect_search_error(binary_search(null, 1, @sizeof(i32),
&two as *u8, null, compare_i32), false);
var huge = (~(0 as usize)) / @sizeof(i32) + 1;
expect_search_error(linear_search(&values[0] as *u8, huge, @sizeof(i32),
&two as *u8, null, compare_i32), true);
}
fn test_stable_sort() {
var items: [8]Item = .[
.{ .key = 3, .sequence = 0 },
.{ .key = 1, .sequence = 1 },
.{ .key = 2, .sequence = 2 },
.{ .key = 1, .sequence = 3 },
.{ .key = 3, .sequence = 4 },
.{ .key = 2, .sequence = 5 },
.{ .key = 1, .sequence = 6 },
.{ .key = 2, .sequence = 7 },
];
var ascending: i32 = 1;
expect_ok(stable_sort(&items[0] as *u8, 8, @sizeof(Item),
&ascending as *u8, compare_item));
var expected_keys: [8]i32 = .[1, 1, 1, 2, 2, 2, 3, 3];
var expected_sequence: [8]i32 = .[1, 3, 6, 2, 5, 7, 0, 4];
var i: usize = 0;
while i < 8 {
@assert(items[i].key == expected_keys[i], "sorted key");
@assert(items[i].sequence == expected_sequence[i], "stable equal order");
i = i + 1;
}
var descending: i32 = -1;
expect_ok(stable_sort(&items[0] as *u8, 8, @sizeof(Item),
&descending as *u8, compare_item));
i = 1;
while i < 8 {
@assert(items[i - 1].key >= items[i].key, "context controls order");
if items[i - 1].key == items[i].key {
@assert(items[i - 1].sequence < items[i].sequence,
"second stable sort preserves group order");
}
i = i + 1;
}
expect_ok(stable_sort(null, 0, @sizeof(Item), null, compare_item));
expect_ok(stable_sort(&items[0] as *u8, 1, @sizeof(Item), null, compare_item));
// 非二次幂长度覆盖末尾不足一个完整归并段的路径。
var odd: [9]i32 = .[9, -1, 4, 4, 0, 8, 2, 7, 3];
var odd_expected: [9]i32 = .[-1, 0, 2, 3, 4, 4, 7, 8, 9];
expect_ok(stable_sort(&odd[0] as *u8, 9, @sizeof(i32), null, compare_i32));
i = 0;
while i < 9 {
@assert(odd[i] == odd_expected[i], "non-power-of-two length");
i = i + 1;
}
}
fn test_sort_failures_preserve_input() {
var values: [3]i32 = .[3, 1, 2];
match stable_sort(&values[0] as *u8, 3, 0, null, compare_i32) {
.Ok => { @assert(false, "zero element size"); },
.Err(error) => {
match error.kind {
.InvalidArgument => {},
_ => { @assert(false); },
}
},
}
@assert(values[0] == 3 && values[1] == 1 && values[2] == 2,
"validation failure preserves input");
var huge = (~(0 as usize)) / @sizeof(i32) + 1;
match stable_sort(&values[0] as *u8, huge, @sizeof(i32), null, compare_i32) {
.Ok => { @assert(false, "size overflow"); },
.Err(error) => {
match error.kind {
.Overflow => {},
_ => { @assert(false); },
}
},
}
@assert(values[0] == 3 && values[1] == 1 && values[2] == 2,
"overflow preserves input");
}
fn main() {
test_search();
test_stable_sort();
test_sort_failures_preserve_input();
}
+212
View File
@@ -0,0 +1,212 @@
// Expect retcode = 0
// 分块 bump 分配器:按块分配、块内顺序推进,只在 drop 时整体释放。
// 适合 AST/IR 这类生命周期一致的批量小对象;不支持单独 free。
// 分配失败通过 ArenaResult 区分原因:size==0/非法对齐/内存不足/地址溢出。
// 失败的 alloc 不改变已有分配。
type .{ .Vec } = @import("vec.spl");
type .{ .Error, .Kind, .Status } = @import("error.spl");
type .{ .checked_add, .align_up } = @import("memory.spl");
type Mem = @import("../sys/mem.spl");
type Chunk = struct {
base: *u8,
size: usize,
used: usize,
}
type ArenaResult = enum {
Ok: *u8,
Err: Error,
}
type Arena = @self;
chunk_size: usize,
chunks: Vec, // 元素类型 Chunk
current: usize,
fn new(chunk_size: usize): Arena {
var cs = chunk_size;
if cs == 0 { cs = 4096; }
ret Arena {
.chunk_size = cs,
.chunks = Vec.blank(@sizeof(Chunk), 8),
.current = 0,
};
}
fn chunk_at(self: *Arena, index: usize): *Chunk {
match Vec.get(&self.chunks, index) {
.Ok(ptr) => { ret ptr as *Chunk; },
// 越界/无效 Arena 统一返回 null;调用方负责判空,无资源需要释放。
.Err(error) => { ret null; },
}
ret null;
}
fn push_chunk(self: *Arena, size: usize): Status {
var base = Mem.alloc(size) as *u8;
if base == null { ret .Err(Error.make(.Overflow)); }
var c = Chunk { .base = base, .size = size, .used = 0 };
match Vec.push(&self.chunks, &c as *u8) {
.Ok => {},
.Err(error) => { Mem.free(base as *any); ret .Err(error); },
}
self.current = self.chunks.len - 1;
ret .Ok;
}
// 分配 size 字节,地址按 align(非零二次幂)对齐。失败返回 ArenaResult.Err。
fn alloc(self: *Arena, size: usize, align: usize): ArenaResult {
if size == 0 { ret .Err(Error.make(.InvalidArgument)); }
if align == 0 { align = 1; }
while true {
if self.current >= self.chunks.len {
var want = self.chunk_size;
var need: usize = 0;
match checked_add(size, align) {
.Ok(value) => { need = value; },
.Err(error) => { ret .Err(error); },
}
if need > want { want = need; }
match push_chunk(self, want) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
}
var c = chunk_at(self, self.current);
if c == null { ret .Err(Error.make(.InvalidArgument)); }
var addr = c.base as usize;
var used_addr: usize = 0;
match checked_add(addr, c.used) {
.Ok(value) => { used_addr = value; },
.Err(error) => { ret .Err(error); },
}
var aligned: usize = 0;
match align_up(used_addr, align) {
.Ok(value) => { aligned = value; },
.Err(error) => { ret .Err(error); }, // 非二次幂对齐或地址溢出
}
var offset = aligned - addr;
if offset <= c.size && size <= c.size - offset {
c.used = offset + size;
ret .Ok(aligned as *u8);
}
self.current = self.current + 1;
}
ret .Err(Error.make(.OutOfRange)); // 不可达:循环内所有路径均已返回
}
fn chunk_count(self: Arena): usize {
ret self.chunks.len;
}
// 复用已分配的块,不释放内存。
fn reset(self: *Arena) {
var i: usize = 0;
while i < self.chunks.len {
var c = chunk_at(self, i);
if c != null { c.used = 0; }
i = i + 1;
}
self.current = 0;
}
fn drop(self: *Arena) {
var i: usize = 0;
while i < self.chunks.len {
var c = chunk_at(self, i);
if c != null { Mem.free(c.base as *any); }
i = i + 1;
}
Vec.drop(&self.chunks);
self.current = 0;
}
// ---- 测试辅助 ----
fn is_aligned(p: *u8, align: usize): bool {
ret ((p as usize) & (align - 1)) == 0;
}
fn alloc_ok(a: *Arena, size: usize, align: usize): *u8 {
match alloc(a, size, align) {
.Ok(ptr) => { ret ptr; },
.Err(error) => { @assert(false, "unexpected arena alloc error"); },
}
ret null;
}
fn expect_alloc_error(result: ArenaResult, expected: Kind) {
match result {
.Ok(ptr) => { @assert(false, "expected arena alloc error"); },
.Err(error) => {
var want: Kind = expected;
@assert(@enum2int(error.kind) == @enum2int(want), "arena alloc error kind");
},
}
}
fn test_alloc_and_alignment() {
var a = new(64);
@assert(chunk_count(a) == 0, "lazy");
var p1 = alloc_ok(&a, 1, 1);
var p8 = alloc_ok(&a, 16, 8);
var p16 = alloc_ok(&a, 1, 16);
@assert(p1 != null && p8 != null && p16 != null, "alloc");
@assert(p1 != p8 && p8 != p16 && p1 != p16, "distinct");
@assert(is_aligned(p8, 8), "align 8");
@assert(is_aligned(p16, 16), "align 16");
p1[0] = 7;
@assert(p1[0] == 7, "writable");
@assert(p8[0] == p8[0], "no crash");
@assert(chunk_count(a) == 1, "one chunk");
reset(&a);
@assert(chunk_count(a) == 1, "reset keeps chunks");
var q = alloc_ok(&a, 1, 1);
@assert(q == p1, "reset reuses first chunk");
// drop 后还有断言,故保持手动释放,不改为 defer。
drop(&a);
@assert(chunk_count(a) == 0, "drop empties");
}
fn test_growth() {
var a = new(64);
defer { drop(&a); }
var i: i32 = 0;
while i < 100 {
var p = alloc_ok(&a, 16, 8);
@assert(p != null, "grow alloc");
@assert(is_aligned(p, 8), "grow align");
p[0] = i as u8;
i = i + 1;
}
@assert(chunk_count(a) > 1, "grew multiple chunks");
// 超过块大小的单次分配也能成功(新块按需放大)。
var big = alloc_ok(&a, 1024, 16);
@assert(big != null && is_aligned(big, 16), "oversized alloc");
}
fn test_failures() {
var a = new(64);
defer { drop(&a); }
expect_alloc_error(alloc(&a, 0, 1), .InvalidArgument);
var d = alloc_ok(&a, 8, 0);
@assert(d != null && is_aligned(d, 1), "align 0 defaults to 1");
expect_alloc_error(alloc(&a, 8, 3), .InvalidAlignment);
}
fn main() {
test_alloc_and_alignment();
test_growth();
test_failures();
}
+218
View File
@@ -0,0 +1,218 @@
// Expect retcode = 0
// ASCII 字符工具。输入和输出都是单个字节,不解释 UTF-8 或本地化规则。
type .{ .Error, .make } = @import("error.spl");
type DigitResult = enum {
Ok: u8,
Err: Error,
}
fn is_ascii(c: u8): bool {
ret c <= 127;
}
fn is_control(c: u8): bool {
ret c <= 31 || c == 127;
}
fn is_space(c: u8): bool {
ret c == ' ' || (c >= '\t' && c <= '\r');
}
fn is_blank(c: u8): bool {
ret c == ' ' || c == '\t';
}
fn is_digit(c: u8): bool {
ret c >= '0' && c <= '9';
}
fn is_lower(c: u8): bool {
ret c >= 'a' && c <= 'z';
}
fn is_upper(c: u8): bool {
ret c >= 'A' && c <= 'Z';
}
fn is_alpha(c: u8): bool {
ret is_lower(c) || is_upper(c);
}
fn is_alnum(c: u8): bool {
ret is_alpha(c) || is_digit(c);
}
fn is_hex_digit(c: u8): bool {
ret is_digit(c) || (c >= 'A' && c <= 'F') || (c >= 'a' && c <= 'f');
}
fn is_print(c: u8): bool {
ret c >= ' ' && c <= '~';
}
fn is_graph(c: u8): bool {
ret c >= '!' && c <= '~';
}
fn is_punct(c: u8): bool {
ret is_graph(c) && !is_alnum(c);
}
fn to_lower(c: u8): u8 {
if is_upper(c) { ret c + ('a' - 'A'); }
ret c;
}
fn to_upper(c: u8): u8 {
if is_lower(c) { ret c - ('a' - 'A'); }
ret c;
}
// radix 必须位于 2..36。大小写字母均表示 10..35。
fn digit_value(c: u8, radix: u8): DigitResult {
if radix < 2 || radix > 36 {
ret .Err(make(.InvalidArgument));
}
var value: u8 = 0;
if is_digit(c) {
value = c - '0';
} else if is_upper(c) {
value = c - 'A' + 10;
} else if is_lower(c) {
value = c - 'a' + 10;
} else {
ret .Err(make(.InvalidDigit));
}
if value >= radix { ret .Err(make(.InvalidDigit)); }
ret .Ok(value);
}
// value 必须位于 0..35。uppercase 只影响 10..35 的字母形式。
fn digit_char(value: u8, uppercase: bool): DigitResult {
if value >= 36 { ret .Err(make(.OutOfRange)); }
if value < 10 { ret .Ok(value + '0'); }
if uppercase { ret .Ok(value - 10 + 'A'); }
ret .Ok(value - 10 + 'a');
}
fn expect_digit(result: DigitResult, expected: u8) {
match result {
.Ok(value) => { @assert(value == expected, "digit value"); },
.Err(error) => { @assert(false, "unexpected digit error"); },
}
}
fn expect_error(result: DigitResult, expected_invalid_argument: bool) {
match result {
.Ok(value) => { @assert(false, "expected digit error"); },
.Err(error) => {
match error.kind {
.InvalidArgument => {
@assert(expected_invalid_argument, "unexpected invalid radix");
},
.InvalidDigit => {
@assert(!expected_invalid_argument, "unexpected invalid digit");
},
_ => { @assert(false, "unexpected digit error kind"); },
}
},
}
}
fn expect_range_error(result: DigitResult) {
match result {
.Ok(value) => { @assert(false, "expected digit range error"); },
.Err(error) => {
match error.kind {
.OutOfRange => {},
_ => { @assert(false, "unexpected digit range error kind"); },
}
},
}
}
fn test_all_bytes() {
var i: usize = 0;
while i < 256 {
var c = i as u8;
@assert(is_ascii(c) == (i <= 127), "ASCII boundary");
@assert(is_control(c) == (i <= 31 || i == 127), "control boundary");
@assert(is_print(c) == (c >= ' ' && c <= '~'), "print boundary");
@assert(is_graph(c) == (c >= '!' && c <= '~'), "graph boundary");
@assert(is_blank(c) == (c == '\t' || c == ' '), "blank set");
@assert(is_space(c) == (c == '\t' || c == '\n' || c == '\x0B' || c == '\x0C' ||
c == '\r' || c == ' '),
"space set");
@assert(is_digit(c) == (c >= '0' && c <= '9'), "digit set");
@assert(is_upper(c) == (c >= 'A' && c <= 'Z'), "upper set");
@assert(is_lower(c) == (c >= 'a' && c <= 'z'), "lower set");
@assert(is_hex_digit(c) == ((c >= '0' && c <= '9') ||
(c >= 'A' && c <= 'F') ||
(c >= 'a' && c <= 'f')),
"hex digit set");
@assert(is_alpha(c) == (is_upper(c) || is_lower(c)), "alpha relation");
@assert(is_alnum(c) == (is_alpha(c) || is_digit(c)), "alnum relation");
@assert(is_punct(c) == (is_graph(c) && !is_alnum(c)), "punct relation");
if is_upper(c) {
@assert(to_lower(c) == c + ('a' - 'A'), "upper to lower");
@assert(to_upper(to_lower(c)) == c, "case round trip");
} else if is_lower(c) {
@assert(to_upper(c) == c - ('a' - 'A'), "lower to upper");
@assert(to_lower(to_upper(c)) == c, "case round trip");
} else {
@assert(to_lower(c) == c, "lower preserves non-letter");
@assert(to_upper(c) == c, "upper preserves non-letter");
}
i = i + 1;
}
}
fn test_digits() {
var radix: usize = 2;
while radix <= 36 {
var value: usize = 0;
while value < radix {
var lower: u8 = 0;
match digit_char(value as u8, false) {
.Ok(c) => { lower = c; },
.Err(error) => { @assert(false, "lower digit generation"); },
}
expect_digit(digit_value(lower, radix as u8), value as u8);
var upper: u8 = 0;
match digit_char(value as u8, true) {
.Ok(c) => { upper = c; },
.Err(error) => { @assert(false, "upper digit generation"); },
}
expect_digit(digit_value(upper, radix as u8), value as u8);
if value < 10 {
@assert(lower == upper, "decimal digits ignore case");
} else {
@assert(lower == upper + ('a' - 'A'), "letter digit case distance");
}
value = value + 1;
}
radix = radix + 1;
}
expect_error(digit_value('0', 0), true);
expect_error(digit_value('0', 1), true);
expect_error(digit_value('0', 37), true);
expect_error(digit_value('/', 10), false);
expect_error(digit_value(':', 10), false);
expect_error(digit_value('2', 2), false);
expect_error(digit_value('g', 16), false);
expect_range_error(digit_char(36, false));
expect_range_error(digit_char(255, true));
}
fn main() {
test_all_bytes();
test_digits();
}
+317
View File
@@ -0,0 +1,317 @@
// Expect retcode = 0
// 拥有字节存储的动态缓冲区。普通赋值会复制所有权,转移必须使用 take。
// 借用切片和 z_ptr 返回的指针在下一次可能扩容的操作或 drop 后失效。
type .{ .Error, .Status } = @import("error.spl");
type .{ .checked_add, .move } = @import("memory.spl");
type .{ .Vec } = @import("vec.spl");
type ByteBuffer = @self;
storage: Vec,
type PtrResult = enum {
Ok: *u8,
Err: Error,
}
fn new(): ByteBuffer {
match Vec.new(1, 1) {
.Ok(value) => { ret ByteBuffer { .storage = value }; },
.Err(error) => { @assert(false, "fixed byte layout is valid"); },
}
ret ByteBuffer { .storage = Vec.blank(1, 1) };
}
fn size(self: ByteBuffer): usize {
ret self.storage.len;
}
fn capacity(self: ByteBuffer): usize {
ret self.storage.cap;
}
fn is_empty(self: ByteBuffer): bool {
ret self.storage.len == 0;
}
fn as_slice(self: ByteBuffer): []u8 {
ret .{ .ptr = self.storage.data, .len = self.storage.len };
}
fn reserve(self: *ByteBuffer, capacity_needed: usize): Status {
ret Vec.reserve(&self.storage, capacity_needed);
}
fn append(self: *ByteBuffer, bytes: []u8): Status {
ret Vec.append(&self.storage, bytes.ptr, bytes.len);
}
fn append_byte(self: *ByteBuffer, byte: u8): Status {
ret Vec.push(&self.storage, &byte);
}
fn append_repeat(self: *ByteBuffer, byte: u8, count: usize): Status {
if count == 0 { ret .Ok; }
var new_len: usize = 0;
match checked_add(self.storage.len, count) {
.Ok(value) => { new_len = value; },
.Err(error) => { ret .Err(error); },
}
match reserve(self, new_len) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
var i = self.storage.len;
while i < new_len {
self.storage.data[i] = byte;
i = i + 1;
}
self.storage.len = new_len;
ret .Ok;
}
// 扩展时用 fill 初始化新增字节;缩短只改变逻辑长度。
fn resize(self: *ByteBuffer, new_len: usize, fill: u8): Status {
if new_len <= self.storage.len {
self.storage.len = new_len;
ret .Ok;
}
var count = new_len - self.storage.len;
ret append_repeat(self, fill, count);
}
fn clear(self: *ByteBuffer) {
Vec.clear(&self.storage);
}
// 保证 data[len] 为零并返回 data。终止零不属于逻辑内容。
// 缓冲区内容可以包含更早的零字节,调用方决定是否适合作为 C 字符串。
fn z_ptr(self: *ByteBuffer): PtrResult {
var needed: usize = 0;
match checked_add(self.storage.len, 1) {
.Ok(value) => { needed = value; },
.Err(error) => { ret .Err(error); },
}
match reserve(self, needed) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
self.storage.data[self.storage.len] = 0;
ret .Ok(self.storage.data);
}
// 成功时替换 out 的旧内容;失败保持 out 不变。允许 bytes 借用 out 自身。
fn assign(out: *ByteBuffer, bytes: []u8): Status {
if bytes.len == 0 {
clear(out);
ret .Ok;
}
if bytes.ptr == null { ret .Err(Error.make(.InvalidArgument)); }
var used = out.storage.len;
if used != 0 {
var base = out.storage.data as usize;
var source = bytes.ptr as usize;
if source >= base && source - base < used {
var offset = source - base;
if bytes.len > used - offset {
ret .Err(Error.make(.OutOfRange));
}
match move(out.storage.data[0..bytes.len], bytes) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
out.storage.len = bytes.len;
ret .Ok;
}
}
var fresh = new();
match append(&fresh, bytes) {
.Ok => {},
.Err(error) => {
drop(&fresh);
ret .Err(error);
},
}
drop(out);
out.storage = Vec.take(&fresh.storage);
ret .Ok;
}
// 深复制;允许 out 与 source 是同一对象。
fn clone(out: *ByteBuffer, source: ByteBuffer): Status {
ret Vec.clone(&out.storage, source.storage);
}
fn take(source: *ByteBuffer): ByteBuffer {
ret ByteBuffer { .storage = Vec.take(&source.storage) };
}
fn drop(self: *ByteBuffer) {
Vec.drop(&self.storage);
}
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => {
match error.kind {
.InvalidArgument => { @assert(false, "unexpected invalid argument"); },
.OutOfRange => { @assert(false, "unexpected out of range"); },
.Overflow => { @assert(false, "unexpected overflow"); },
_ => { @assert(false, "unexpected byte buffer error"); },
}
},
}
}
fn expect_overflow(result: Status) {
match result {
.Ok => { @assert(false, "expected byte buffer overflow"); },
.Err(error) => {
match error.kind {
.Overflow => {},
_ => { @assert(false, "unexpected byte buffer error kind"); },
}
},
}
}
fn expect_bytes(self: ByteBuffer, expected: []u8) {
@assert(self.storage.len == expected.len, "byte buffer length");
var i: usize = 0;
while i < expected.len {
@assert(self.storage.data[i] == expected.ptr[i], "byte buffer content");
i = i + 1;
}
}
fn expect_z(self: *ByteBuffer) {
var old_len = self.storage.len;
match z_ptr(self) {
.Ok(ptr) => {
@assert(ptr != null, "zero terminated pointer");
@assert(ptr[old_len] == 0, "zero terminator");
},
.Err(error) => { @assert(false, "zero termination"); },
}
@assert(self.storage.len == old_len, "terminator is outside logical content");
}
fn test_append_and_resize() {
var buffer = new();
defer { drop(&buffer); }
@assert(is_empty(buffer));
@assert(size(buffer) == 0 && capacity(buffer) == 0);
expect_z(&buffer);
@assert(capacity(buffer) >= 1);
expect_ok(append(&buffer, "abc"));
expect_ok(append_byte(&buffer, '\0'));
expect_ok(append(&buffer, "de"));
@assert(buffer.storage.len == 6, "append logical length");
var embedded: [6]u8 = .[97, 98, 99, 0, 100, 101];
expect_bytes(buffer, embedded[0..6]);
expect_z(&buffer);
expect_ok(resize(&buffer, 9, 255));
@assert(buffer.storage.len == 9, "grow logical length");
var grown: [9]u8 = .[97, 98, 99, 0, 100, 101, 255, 255, 255];
expect_bytes(buffer, grown[0..9]);
expect_ok(resize(&buffer, 2, 17));
@assert(buffer.storage.len == 2, "shrink logical length");
expect_bytes(buffer, "ab");
expect_ok(append_repeat(&buffer, 120, 4));
@assert(buffer.storage.len == 6, "repeat logical length");
expect_bytes(buffer, "abxxxx");
clear(&buffer);
@assert(is_empty(buffer) && capacity(buffer) != 0, "clear retains allocation");
expect_z(&buffer);
}
fn test_growth_and_self_append() {
var buffer = new();
defer { drop(&buffer); }
var i: usize = 0;
while i < 8 {
expect_ok(append_byte(&buffer, (65 + i) as u8));
i = i + 1;
}
@assert(buffer.storage.cap == 8, "prepare byte buffer growth boundary");
var own = as_slice(buffer);
expect_ok(append(&buffer, own));
@assert(buffer.storage.len == 16);
i = 0;
while i < 16 {
@assert(buffer.storage.data[i] == (65 + i % 8) as u8, "self append content");
i = i + 1;
}
expect_z(&buffer);
}
fn test_ownership_and_failures() {
var source = new();
defer { drop(&source); }
expect_ok(append(&source, "owned"));
var copy = new();
defer { drop(&copy); }
expect_ok(clone(&copy, source));
@assert(copy.storage.len == 5, "clone logical length");
source.storage.data[0] = 79;
expect_bytes(copy, "owned");
var before_self_clone = copy.storage.raw;
expect_ok(clone(&copy, copy));
@assert(copy.storage.raw != before_self_clone, "self clone replaces nested allocation");
expect_bytes(copy, "owned");
var before_external_assign = copy.storage.data;
expect_ok(assign(&copy, "xyz"));
@assert(copy.storage.len == 3, "external assign logical length");
@assert(copy.storage.data != before_external_assign, "external assign replaces data");
expect_bytes(copy, "xyz");
before_external_assign = copy.storage.data;
expect_ok(assign(&copy, "owned"));
@assert(copy.storage.len == 5, "second external assign logical length");
@assert(copy.storage.data != before_external_assign, "second external assign replaces data");
// assign 的输入借用目标自身,提交前必须保持旧分配有效。
var middle = as_slice(copy);
middle.ptr = middle.ptr + 1;
middle.len = 3;
match assign(&copy, middle) {
.Ok => {},
.Err(error) => { @assert(false, "self assign failed"); },
}
@assert(copy.storage.len == 3, "assign logical length");
expect_bytes(copy, "wne");
var moved = take(&copy);
defer { drop(&moved); }
@assert(copy.storage.raw == null && copy.storage.len == 0 && copy.storage.cap == 0);
expect_bytes(moved, "wne");
var old_raw = moved.storage.raw;
var old_len = moved.storage.len;
var old_cap = moved.storage.cap;
expect_overflow(append_repeat(&moved, 1, ~(0 as usize)));
@assert(moved.storage.raw == old_raw && moved.storage.len == old_len &&
moved.storage.cap == old_cap,
"overflow preserves byte buffer");
expect_bytes(moved, "wne");
}
fn main() {
test_append_and_resize();
test_growth_and_self_append();
test_ownership_and_failures();
}
+285
View File
@@ -0,0 +1,285 @@
// Expect retcode = 0
// 借用的字节字符串视图;不拥有、不分配也不释放 ptr 指向的存储。
// 非空视图要求 ptr 在整个借用期内可读。空视图统一表示为 null/0。
type .{ .Error, .make } = @import("error.spl");
type ByteView = @self;
ptr: *u8,
len: usize,
type ByteResult = enum {
Ok: u8,
Err: Error,
}
type ViewResult = enum {
Ok: ByteView,
Err: Error,
}
type FindResult = enum {
Found: usize,
NotFound,
}
fn empty(): ByteView {
ret ByteView { .ptr = null, .len = 0 };
}
// 输入切片的存储仍由调用方拥有。零长度输入被规范化为空视图。
fn from_slice(bytes: []u8): ByteView {
if bytes.len == 0 { ret empty(); }
ret ByteView { .ptr = bytes.ptr, .len = bytes.len };
}
// 以 NUL 结尾的 C 字符串转为视图;不复制、不拥有。null 规范化为空视图。
fn from_cstr(text: *u8): ByteView {
if text == null { ret empty(); }
var len: usize = 0;
while text[len] != 0 { len = len + 1; }
ret from_slice(.{ .ptr = text, .len = len });
}
fn as_slice(self: ByteView): []u8 {
ret .{ .ptr = self.ptr, .len = self.len };
}
fn size(self: ByteView): usize {
ret self.len;
}
fn is_empty(self: ByteView): bool {
ret self.len == 0;
}
fn byte_at(self: ByteView, index: usize): ByteResult {
if index >= self.len { ret .Err(make(.OutOfRange)); }
if self.ptr == null { ret .Err(make(.InvalidArgument)); }
ret .Ok(self.ptr[index]);
}
fn eq(a: ByteView, b: ByteView): bool {
if a.len != b.len { ret false; }
var i: usize = 0;
while i < a.len {
if a.ptr[i] != b.ptr[i] { ret false; }
i = i + 1;
}
ret true;
}
// 按无符号字节进行字典序比较,结果只承诺小于、等于或大于零。
fn cmp(a: ByteView, b: ByteView): i32 {
var count = a.len;
if b.len < count { count = b.len; }
var i: usize = 0;
while i < count {
var av = a.ptr[i];
var bv = b.ptr[i];
if av < bv { ret -1; }
if av > bv { ret 1; }
i = i + 1;
}
if a.len < b.len { ret -1; }
if a.len > b.len { ret 1; }
ret 0;
}
// 返回半开区间 [start, end)。失败不会产生部分视图。
fn slice(self: ByteView, start: usize, end: usize): ViewResult {
if start > end || end > self.len {
ret .Err(make(.OutOfRange));
}
if start == end { ret .Ok(empty()); }
if self.ptr == null { ret .Err(make(.InvalidArgument)); }
var address = self.ptr as usize;
var limit: usize = ~(0 as usize);
if start > limit - address { ret .Err(make(.Overflow)); }
ret .Ok(ByteView { .ptr = (address + start) as *u8, .len = end - start });
}
fn find(haystack: ByteView, needle: ByteView): FindResult {
if needle.len == 0 { ret .Found(0); }
if needle.len > haystack.len { ret .NotFound; }
var last = haystack.len - needle.len;
var start: usize = 0;
while start <= last {
var i: usize = 0;
while i < needle.len && haystack.ptr[start + i] == needle.ptr[i] {
i = i + 1;
}
if i == needle.len { ret .Found(start); }
start = start + 1;
}
ret .NotFound;
}
fn contains(haystack: ByteView, needle: ByteView): bool {
match find(haystack, needle) {
.Found(index) => { ret true; },
.NotFound => { ret false; },
}
}
fn starts_with(self: ByteView, prefix: ByteView): bool {
if prefix.len > self.len { ret false; }
var i: usize = 0;
while i < prefix.len {
if self.ptr[i] != prefix.ptr[i] { ret false; }
i = i + 1;
}
ret true;
}
fn ends_with(self: ByteView, suffix: ByteView): bool {
if suffix.len > self.len { ret false; }
var start = self.len - suffix.len;
var i: usize = 0;
while i < suffix.len {
if self.ptr[start + i] != suffix.ptr[i] { ret false; }
i = i + 1;
}
ret true;
}
fn expect_byte(result: ByteResult, expected: u8) {
match result {
.Ok(value) => { @assert(value == expected, "byte result"); },
.Err(error) => { @assert(false, "unexpected byte error"); },
}
}
fn expect_byte_error(result: ByteResult, out_of_range: bool) {
match result {
.Ok(value) => { @assert(false, "expected byte error"); },
.Err(error) => {
match error.kind {
.OutOfRange => { @assert(out_of_range, "unexpected byte range error"); },
.InvalidArgument => { @assert(!out_of_range, "unexpected invalid view"); },
_ => { @assert(false, "unexpected byte error kind"); },
}
},
}
}
fn expect_slice(result: ViewResult, expected: ByteView) {
match result {
.Ok(value) => { @assert(eq(value, expected), "slice result"); },
.Err(error) => { @assert(false, "unexpected slice error"); },
}
}
fn expect_slice_error(result: ViewResult) {
match result {
.Ok(value) => { @assert(false, "expected slice error"); },
.Err(error) => {
match error.kind {
.OutOfRange => {},
_ => { @assert(false, "unexpected slice error kind"); },
}
},
}
}
fn expect_found(result: FindResult, expected: usize) {
match result {
.Found(index) => { @assert(index == expected, "find position"); },
.NotFound => { @assert(false, "expected match"); },
}
}
fn expect_not_found(result: FindResult) {
match result {
.Found(index) => { @assert(false, "unexpected match"); },
.NotFound => {},
}
}
fn test_construction_and_access() {
var canonical = empty();
@assert(canonical.ptr == null && canonical.len == 0, "canonical empty");
var data: [5]u8 = .[104, 101, 0, 108, 111];
var text = from_slice(data[0..5]);
@assert(size(text) == 5);
@assert(!is_empty(text));
expect_byte(byte_at(text, 0), 104);
expect_byte(byte_at(text, 2), 0);
expect_byte(byte_at(text, 4), 111);
expect_byte_error(byte_at(text, 5), true);
var normalized = from_slice(data[3..3]);
@assert(normalized.ptr == null && normalized.len == 0, "empty input normalized");
expect_byte_error(byte_at(ByteView { .ptr = null, .len = 1 }, 0), false);
var bytes = as_slice(text);
@assert(bytes.ptr == text.ptr && bytes.len == text.len, "slice conversion borrows");
var cstr_data: [4]u8 = .[104, 105, 0, 88];
var cstr = from_cstr(&cstr_data[0]);
@assert(cstr.len == 2 && cstr.ptr[0] == 104 && cstr.ptr[1] == 105,
"from_cstr stops at NUL");
@assert(from_cstr(&cstr_data[2]).len == 0, "from_cstr at NUL is empty");
var none = from_cstr(null);
@assert(none.ptr == null && none.len == 0, "from_cstr null normalized");
}
fn test_compare_and_slice() {
var hello = from_slice("hello");
var same = from_slice("hello");
var help = from_slice("help");
var high_data: [1]u8 = .[255];
var low_data: [1]u8 = .[127];
@assert(eq(hello, same));
@assert(!eq(hello, help));
@assert(eq(empty(), from_slice("")));
@assert(cmp(hello, same) == 0);
@assert(cmp(hello, help) < 0);
@assert(cmp(help, hello) > 0);
@assert(cmp(from_slice(low_data[0..1]), from_slice(high_data[0..1])) < 0,
"comparison uses unsigned bytes");
expect_slice(slice(hello, 0, 5), hello);
expect_slice(slice(hello, 1, 4), from_slice("ell"));
match slice(hello, 2, 2) {
.Ok(value) => {
@assert(value.ptr == null && value.len == 0, "empty subslice normalized");
},
.Err(error) => { @assert(false, "empty subslice"); },
}
expect_slice_error(slice(hello, 4, 3));
expect_slice_error(slice(hello, 0, 6));
}
fn test_search() {
var text = from_slice("ababa");
expect_found(find(text, from_slice("aba")), 0);
expect_found(find(text, from_slice("bab")), 1);
expect_found(find(text, from_slice("ba")), 1);
expect_found(find(text, from_slice("")), 0);
expect_not_found(find(text, from_slice("abb")));
expect_not_found(find(text, from_slice("ababaa")));
@assert(contains(text, from_slice("aba")));
@assert(!contains(text, from_slice("xyz")));
@assert(starts_with(text, from_slice("ab")));
@assert(starts_with(text, empty()));
@assert(!starts_with(text, from_slice("ba")));
@assert(ends_with(text, from_slice("ba")));
@assert(ends_with(text, empty()));
@assert(!ends_with(text, from_slice("ab")));
}
fn main() {
test_construction_and_access();
test_compare_and_slice();
test_search();
}
+83
View File
@@ -0,0 +1,83 @@
// Expect retcode = 0
// 公共错误值不持有资源,可按值复制;不分配错误消息字符串。
// position 是调用方输入中的从零开始的位置;仅在 has_position 时有效。
// 未定位错误的 position 规范为 0,不能用 position == 0 判断是否有位置。
// 数值解析位置按输入字节计数。可用内存耗尽仍由现有 VM 终止处理。
type Error = @self;
type Kind = enum {
InvalidArgument,
OutOfRange,
Overflow,
DivisionByZero,
InvalidDigit,
InvalidFormat,
UnexpectedEnd,
InvalidAlignment,
WidthMismatch,
Io,
}
kind: Kind,
has_position: bool,
position: usize,
// 无成功载荷的结果。带成功值的模块定义自己的 Ok: T / Err: Error 枚举。
type Status = enum {
Ok,
Err: Error,
}
fn make(kind: Kind): Error {
ret Error { .kind = kind, .has_position = false, .position = 0 };
}
fn at(kind: Kind, position: usize): Error {
ret Error { .kind = kind, .has_position = true, .position = position };
}
fn test_status(result: Status, expected_error: bool) {
match result {
.Ok => {
@assert(!expected_error, "success variant");
},
.Err(error) => {
@assert(expected_error, "error variant");
@assert(!error.has_position, "unlocated error");
@assert(error.position == 0, "canonical absent position");
match error.kind {
.Overflow => {},
_ => { @assert(false, "error kind preserved in result"); },
}
},
}
}
fn main() {
var success: Status = .Ok;
test_status(success, false);
var failure: Status = .Err(make(.Overflow));
test_status(failure, true);
var first = at(.InvalidDigit, 0);
@assert(first.has_position, "byte zero is a valid position");
@assert(first.position == 0);
match first.kind {
.InvalidDigit => {},
_ => { @assert(false, "positioned error kind"); },
}
var original = at(.UnexpectedEnd, 17);
var copy = original;
copy.position = 3;
@assert(original.position == 17, "error copy has independent fields");
@assert(copy.position == 3);
@assert(copy.has_position);
var max_position: usize = ~0 as usize;
var last = at(.OutOfRange, max_position);
@assert(last.has_position, "no reserved position sentinel");
@assert(last.position == max_position);
}
+511
View File
@@ -0,0 +1,511 @@
// Expect retcode = 0
// 数值/布尔格式化,写入 ByteBuffer。radix 取值 2..36;uppercase 只影响 10..35 的字母形式。
// 整数转换统一复用 MPA。先在临时缓冲区完成转换,再一次性追加,失败不产生部分输出。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
type .{ .ByteView } = @import("byte_view.spl");
type .{ .Value, .int, .uint, .char, .str, .addr } = @import("value.spl");
type .{ .BigInt, .Bits } = @import("mp.spl");
// 注意:radix 边界直接用字面量。stage1 刻意不做常量求值/折叠,
// 顶层 const 不应用于运行时表达式。
fn valid_radix(radix: u8): bool {
ret radix >= 2 && radix <= 36;
}
fn append_big_int(out: *ByteBuffer, value: BigInt,
radix: u8, uppercase: bool): Status {
if !valid_radix(radix) { ret .Err(make(.InvalidArgument)); }
var text = ByteBuffer.new();
defer { ByteBuffer.drop(&text); }
match BigInt.format(&text, value, radix, uppercase) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret ByteBuffer.append(out, ByteBuffer.as_slice(text));
}
fn append_bits(out: *ByteBuffer, value: Bits, signed: bool,
radix: u8, uppercase: bool): Status {
var integer = BigInt.zero();
defer { BigInt.drop(&integer); }
match Bits.to_big(&integer, value, signed) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret append_big_int(out, integer, radix, uppercase);
}
fn append_u64(out: *ByteBuffer, value: u64, radix: u8, uppercase: bool): Status {
var integer = BigInt.zero();
defer { BigInt.drop(&integer); }
match BigInt.from_u64(&integer, value) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret append_big_int(out, integer, radix, uppercase);
}
fn append_i64(out: *ByteBuffer, value: i64, radix: u8, uppercase: bool): Status {
var integer = BigInt.zero();
defer { BigInt.drop(&integer); }
match BigInt.from_i64(&integer, value) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret append_big_int(out, integer, radix, uppercase);
}
fn append_usize(out: *ByteBuffer, value: usize, radix: u8, uppercase: bool): Status {
ret append_u64(out, value as u64, radix, uppercase);
}
fn append_isize(out: *ByteBuffer, value: isize, radix: u8, uppercase: bool): Status {
ret append_i64(out, value as i64, radix, uppercase);
}
fn append_bool(out: *ByteBuffer, value: bool): Status {
if value { ret ByteBuffer.append(out, "true"); }
ret ByteBuffer.append(out, "false");
}
// ---- 显式装箱值格式化 ----
// Int/Uint 落到整数;signed 仅对 Int 的十进制生效,其余按无符号位模式输出。
fn append_value_int(out: *ByteBuffer, value: Value, radix: u8, uppercase: bool,
signed: bool): Status {
match value {
.Int(v) => {
if signed && radix == 10 { ret append_i64(out, v, radix, uppercase); }
ret append_u64(out, v as u64, radix, uppercase);
},
.Uint(v) => { ret append_u64(out, v, radix, uppercase); },
_ => { ret .Err(make(.InvalidFormat)); },
}
}
fn append_value_char(out: *ByteBuffer, value: Value): Status {
match value {
.Char(c) => { ret ByteBuffer.append_byte(out, c); },
_ => { ret .Err(make(.InvalidFormat)); },
}
}
fn append_value_str(out: *ByteBuffer, value: Value): Status {
match value {
.Str(view) => { ret ByteBuffer.append(out, ByteView.as_slice(view)); },
_ => { ret .Err(make(.InvalidFormat)); },
}
}
fn append_value_ptr(out: *ByteBuffer, value: Value): Status {
match value {
.Ptr(p) => {
match ByteBuffer.append(out, "0x") {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret append_u64(out, p as usize, 16, false);
},
_ => { ret .Err(make(.InvalidFormat)); },
}
}
// {} 自动格式化:按 Value 变体选择默认表示。
fn append_value_auto(out: *ByteBuffer, value: Value): Status {
match value {
.Int(v) => { ret append_i64(out, v, 10, false); },
.Uint(v) => { ret append_u64(out, v, 10, false); },
.Bool(v) => { ret append_bool(out, v); },
.Char(c) => { ret ByteBuffer.append_byte(out, c); },
.Str(view) => { ret ByteBuffer.append(out, ByteView.as_slice(view)); },
.Ptr(p) => {
match ByteBuffer.append(out, "0x") {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret append_u64(out, p as usize, 16, false);
},
}
ret .Ok;
}
// {} 风格:{} 自动;{:d} {:i} {:u} {:x} {:X} {:o} {:b} {:c} {:s} {:p} 指定。
// {{ 与 }} 输出字面量括号。参数按序从 args 消费;数量不足、类型不符、未知转换
// 或括号不配返回 Err(.InvalidFormat)。失败不产生部分输出:先在临时缓冲完成。
fn format(out: *ByteBuffer, fmt: []u8, args: []Value): Status {
var temp = ByteBuffer.new();
defer { ByteBuffer.drop(&temp); }
var argi: usize = 0;
var i: usize = 0;
while i < fmt.len {
var c = fmt.ptr[i];
if c == '{' {
if i + 1 < fmt.len && fmt.ptr[i + 1] == '{' {
match ByteBuffer.append_byte(&temp, '{') {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
i = i + 2;
continue;
}
var j = i + 1;
if j < fmt.len && fmt.ptr[j] == ':' { j = j + 1; }
var has_spec = false;
var spec: u8 = 0;
if j < fmt.len && fmt.ptr[j] != '}' {
has_spec = true;
spec = fmt.ptr[j];
j = j + 1;
}
if j >= fmt.len || fmt.ptr[j] != '}' { ret .Err(make(.InvalidFormat)); }
i = j + 1;
if argi >= args.len { ret .Err(make(.InvalidFormat)); }
var value = args.ptr[argi];
argi = argi + 1;
var step: Status = .Ok;
if !has_spec {
step = append_value_auto(&temp, value);
} else if spec == 'd' || spec == 'i' {
step = append_value_int(&temp, value, 10, false, true);
} else if spec == 'u' {
step = append_value_int(&temp, value, 10, false, false);
} else if spec == 'x' {
step = append_value_int(&temp, value, 16, false, false);
} else if spec == 'X' {
step = append_value_int(&temp, value, 16, true, false);
} else if spec == 'o' {
step = append_value_int(&temp, value, 8, false, false);
} else if spec == 'b' {
step = append_value_int(&temp, value, 2, false, false);
} else if spec == 'c' {
step = append_value_char(&temp, value);
} else if spec == 's' {
step = append_value_str(&temp, value);
} else if spec == 'p' {
step = append_value_ptr(&temp, value);
} else {
ret .Err(make(.InvalidFormat));
}
match step {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
continue;
}
if c == '}' {
if i + 1 < fmt.len && fmt.ptr[i + 1] == '}' {
match ByteBuffer.append_byte(&temp, '}') {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
i = i + 2;
continue;
}
ret .Err(make(.InvalidFormat));
}
match ByteBuffer.append_byte(&temp, c) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
i = i + 1;
}
ret ByteBuffer.append(out, ByteBuffer.as_slice(temp));
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected fmt error"); },
}
}
fn expect_invalid(result: Status) {
match result {
.Ok => { @assert(false, "expected fmt error"); },
.Err(error) => {
match error.kind {
.InvalidArgument => {},
_ => { @assert(false, "unexpected fmt error kind"); },
}
},
}
}
fn expect_text(buffer: *ByteBuffer, expected: []u8) {
var actual = ByteBuffer.as_slice(buffer.*);
@assert(actual.len == expected.len, "formatted length");
var i: usize = 0;
while i < expected.len {
@assert(actual.ptr[i] == expected.ptr[i], "formatted byte");
i = i + 1;
}
}
fn test_unsigned() {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
expect_ok(append_u64(&b, 0, 10, false));
expect_text(&b, "0");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 42, 10, false));
expect_text(&b, "42");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 1234567890, 10, false));
expect_text(&b, "1234567890");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 18446744073709551615, 10, false));
expect_text(&b, "18446744073709551615");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 255, 16, false));
expect_text(&b, "ff");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 255, 16, true));
expect_text(&b, "FF");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 4096, 16, false));
expect_text(&b, "1000");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 170, 2, false));
expect_text(&b, "10101010");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 35, 36, false));
expect_text(&b, "z");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 18446744073709551615, 2, false));
expect_text(&b, "1111111111111111111111111111111111111111111111111111111111111111");
ByteBuffer.clear(&b);
}
fn test_signed() {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
expect_ok(append_i64(&b, 0, 10, false));
expect_text(&b, "0");
ByteBuffer.clear(&b);
expect_ok(append_i64(&b, -123, 10, false));
expect_text(&b, "-123");
ByteBuffer.clear(&b);
expect_ok(append_i64(&b, 9223372036854775807, 10, false));
expect_text(&b, "9223372036854775807");
ByteBuffer.clear(&b);
expect_ok(append_i64(&b, -9223372036854775808, 10, false));
expect_text(&b, "-9223372036854775808");
ByteBuffer.clear(&b);
expect_ok(append_isize(&b, -16, 16, false));
expect_text(&b, "-10");
ByteBuffer.clear(&b);
expect_ok(append_u64(&b, 48879, 16, true));
expect_text(&b, "BEEF");
ByteBuffer.clear(&b);
}
fn test_usize_bool_and_errors() {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
expect_ok(append_usize(&b, 1000 as usize, 10, false));
expect_text(&b, "1000");
ByteBuffer.clear(&b);
expect_ok(append_bool(&b, true));
expect_text(&b, "true");
ByteBuffer.clear(&b);
expect_ok(append_bool(&b, false));
expect_text(&b, "false");
ByteBuffer.clear(&b);
expect_invalid(append_u64(&b, 1, 0, false));
expect_invalid(append_u64(&b, 1, 1, false));
expect_invalid(append_u64(&b, 1, 37, false));
expect_invalid(append_i64(&b, -1, 0, false));
@assert(ByteBuffer.size(b) == 0, "invalid radix writes nothing");
expect_ok(ByteBuffer.append(&b, "prefix"));
expect_invalid(append_i64(&b, -123, 1, false));
expect_text(&b, "prefix");
}
fn test_mpa_integer_formatting() {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
var huge = BigInt.zero();
defer { BigInt.drop(&huge); }
expect_ok(BigInt.parse(&huge, "1234567890123456789012345678901234567890", 10));
expect_ok(append_big_int(&b, huge, 10, false));
expect_text(&b, "1234567890123456789012345678901234567890");
ByteBuffer.clear(&b);
expect_ok(BigInt.parse(&huge, "-ffffffffffffffffffffffffffffffff", 16));
expect_ok(append_big_int(&b, huge, 16, true));
expect_text(&b, "-FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF");
ByteBuffer.clear(&b);
var raw = BigInt.zero();
defer { BigInt.drop(&raw); }
expect_ok(BigInt.from_u64(&raw, 255));
var bits: Bits = undefined;
match Bits.new(8) {
.Ok(value) => { bits = value; },
.Err(error) => { @assert(false, "Bits construction"); },
}
defer { Bits.drop(&bits); }
expect_ok(Bits.from_big_checked(&bits, raw, 8, false));
expect_ok(append_bits(&b, bits, false, 10, false));
expect_text(&b, "255");
ByteBuffer.clear(&b);
expect_ok(append_bits(&b, bits, true, 10, false));
expect_text(&b, "-1");
}
fn test_composition_and_growth() {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
expect_ok(ByteBuffer.append(&b, "x="));
expect_ok(append_i64(&b, -42, 10, false));
expect_ok(ByteBuffer.append(&b, " hex="));
expect_ok(append_u64(&b, 255, 16, false));
expect_ok(ByteBuffer.append(&b, " ok="));
expect_ok(append_bool(&b, true));
expect_text(&b, "x=-42 hex=ff ok=true");
ByteBuffer.clear(&b);
// 反复写入触发 ByteBuffer 扩容,校验累积内容。
var i: i32 = 0;
while i < 200 {
expect_ok(append_i64(&b, i as i64, 10, false));
expect_ok(ByteBuffer.append_byte(&b, ',')); // ','
i = i + 1;
}
expect_ok(append_i64(&b, 200, 10, false));
@assert(ByteBuffer.size(b) > 0, "growth content");
var s = ByteBuffer.as_slice(b);
@assert(s.ptr[0] == '0', "starts with 0");
@assert(s.ptr[1] == ',', "0 then comma");
}
fn expect_format(fmt: []u8, args: []Value, expected: []u8) {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
expect_ok(format(&b, fmt, args));
expect_text(&b, expected);
}
fn expect_invalid_format(fmt: []u8, args: []Value) {
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
match format(&b, fmt, args) {
.Ok => { @assert(false, "expected invalid format"); },
.Err(error) => {
match error.kind {
.InvalidFormat => {},
_ => { @assert(false, "expected InvalidFormat kind"); },
}
},
}
}
fn test_format_specs() {
var one: [1]Value = .[int(-5)];
expect_format("{}", one[0..1], "-5");
expect_format("{d}", one[0..1], "-5");
expect_format("{i}", one[0..1], "-5");
var u: [1]Value = .[uint(7)];
expect_format("{}", u[0..1], "7");
expect_format("{u}", u[0..1], "7");
expect_format("{x}", u[0..1], "7");
expect_format("{o}", u[0..1], "7");
expect_format("{b}", u[0..1], "111");
var hex: [1]Value = .[uint(255)];
expect_format("{x}", hex[0..1], "ff");
expect_format("{X}", hex[0..1], "FF");
var oct: [1]Value = .[uint(8)];
expect_format("{o}", oct[0..1], "10");
var bits: [1]Value = .[uint(5)];
expect_format("{b}", bits[0..1], "101");
var ch: [1]Value = .[char('A')];
expect_format("{}", ch[0..1], "A");
expect_format("{c}", ch[0..1], "A");
var text: [1]Value = .[str("hi")];
expect_format("{}", text[0..1], "hi");
expect_format("{s}", text[0..1], "hi");
var nul: [1]Value = .[addr(null)];
expect_format("{p}", nul[0..1], "0x0");
var none: [1]Value = .[int(0)];
expect_format("100%", none[0..0], "100%");
expect_format("{{}}", none[0..0], "{}");
expect_format("plain", none[0..0], "plain");
}
fn test_format_mixed_and_failure() {
var args: [3]Value = .[int(42), str("x"), char('!')];
expect_format("n={} s={} c={}", args[0..3], "n=42 s=x c=!");
expect_format("n={} s={s} c={c}", args[0..3], "n=42 s=x c=!");
// 失败不改动输出,且不产生部分结果:前两个转换成功、第三个参数不足。
var b = ByteBuffer.new();
defer { ByteBuffer.drop(&b); }
expect_ok(ByteBuffer.append(&b, "prefix"));
var two: [2]Value = .[int(1), int(2)];
expect_invalid_format("a={} b={} c={}", two[0..2]);
expect_text(&b, "prefix");
var only_int: [1]Value = .[int(1)];
expect_invalid_format("{} {}", only_int[0..1]);
expect_invalid_format("{}", only_int[0..0]);
expect_invalid_format("trailing {", only_int[0..1]);
expect_invalid_format("dangling }", only_int[0..1]);
expect_invalid_format("{q}", only_int[0..1]);
expect_invalid_format("{s}", only_int[0..1]);
expect_invalid_format("{c}", only_int[0..1]);
}
fn main() {
test_unsigned();
test_signed();
test_usize_bool_and_errors();
test_mpa_integer_formatting();
test_composition_and_growth();
test_format_specs();
test_format_mixed_and_failure();
}
+91
View File
@@ -0,0 +1,91 @@
// Expect retcode = 0
// 哈希工具:FNV-1a 字节哈希 + 整型混合;并给出可直接交给 map 的回调
// (map 的 hash/eq 回调接收指向键字节的指针,这里按 usize / ByteView 解释)。
// 仅提供确定性哈希与等值,不承诺密码学性质。
type .{ .ByteView } = @import("byte_view.spl");
// FNV-1a 64 位,逐字节;空输入返回 offset basis。
fn hash_bytes(data: *u8, len: usize): usize {
var h: usize = 14695981039346656037; // FNV-1a 64 位 offset basis
var prime: usize = 1099511628211; // FNV 质数
var i: usize = 0;
while i < len {
h = (h ^ (data[i] as usize)) * prime;
i = i + 1;
}
ret h;
}
fn hash_byte_view(view: ByteView): usize {
ret hash_bytes(view.ptr, view.len);
}
// 整型混合(splitmix 风格的移位-乘法),保证非零与良好扩散。
fn hash_usize_value(value: usize): usize {
var prime: usize = 1099511628211; // splitmix 风格的混合乘子
var h = value;
h = (h ^ (h >> 30)) * prime;
h = h ^ (h >> 27);
h = h * prime;
h = h ^ (h >> 31);
if h == 0 { ret prime; } // 0 映射到非零
ret h;
}
// ---- map 回调 ----
// 键按 usize 解释。
fn hash_usize(key: *u8): usize {
ret hash_usize_value((key as *usize).*);
}
fn eq_usize(a: *u8, b: *u8): bool {
ret (a as *usize).* == (b as *usize).*;
}
// 键按 ByteView 解释,哈希其指向的字节。
fn hash_view(key: *u8): usize {
var view = (key as *ByteView).*;
ret hash_byte_view(view);
}
fn eq_view(a: *u8, b: *u8): bool {
ret ByteView.eq((a as *ByteView).*, (b as *ByteView).*);
}
// ---- 测试辅助 ----
fn expect_hash(view: []u8, expected: usize) {
var got = hash_bytes(view.ptr, view.len);
@assert(got == expected, "hash value");
}
fn test_fnv_vectors() {
expect_hash("", 14695981039346656037);
expect_hash("a", 12638187200555641996);
expect_hash("foobar", 9625390261332436968);
expect_hash("hello", 11831194018420276491);
// 同一输入稳定;不同输入不同。
var s1: []u8 = "abc";
var s2: []u8 = "abd";
@assert(hash_bytes(s1.ptr, 3) == hash_bytes(s1.ptr, 3), "deterministic");
@assert(hash_bytes(s1.ptr, 3) != hash_bytes(s2.ptr, 3), "distinct");
// ByteView 与 bytes 一致。
var v = ByteView.from_slice("foobar");
@assert(hash_byte_view(v) == hash_bytes(v.ptr, v.len), "view == bytes");
// 整型混合:0 不保持 0,且稳定/区分。
@assert(hash_usize_value(0) != 0, "zero mixed");
@assert(hash_usize_value(7) == hash_usize_value(7), "int stable");
@assert(hash_usize_value(7) != hash_usize_value(8), "int distinct");
}
// map 回调(hash_usize/eq_usize/hash_view/eq_view)由 map.spl 在自己的测试里验证。
fn main() {
test_fnv_vectors();
}
+244
View File
@@ -0,0 +1,244 @@
// Expect retcode = 0
// I/O 便利层(构建在 sys/file 之上):
// - C 字符串路径/模式的 open 包装
// - 精确读取、完整写入和普通文件整读
// - stdout/stderr 打印
// 说明:read_all 会按文件大小一次性读入 ByteBuffer;不处理增长中的文件。
// 短读、短写后的零进展及关闭失败返回 Err(.Io);文件写入不承诺回滚。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .ByteView } = @import("byte_view.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
type File = @import("../sys/file.spl");
type Mem = @import("../sys/mem.spl");
// 把 view 复制到以 NUL 结尾的临时缓冲,返回其 data(归属 tmp,调用后勿再用)。
fn cstr(tmp: *ByteBuffer, view: ByteView): *u8 {
ByteBuffer.clear(tmp);
if view.len != 0 {
match ByteBuffer.append(tmp, ByteView.as_slice(view)) {
.Ok => {},
.Err(error) => { ret null; },
}
}
match ByteBuffer.append_byte(tmp, '\0') {
.Ok => {},
.Err(error) => { ret null; },
}
ret tmp.storage.data;
}
fn open_cstr(path: ByteView, mode: ByteView): File {
var pbuf = ByteBuffer.new();
var mbuf = ByteBuffer.new();
var p = cstr(&pbuf, path);
var m = cstr(&mbuf, mode);
var f = File { .handle = null };
if p != null && m != null { f = File.open(p, m); }
ByteBuffer.drop(&pbuf);
ByteBuffer.drop(&mbuf);
ret f;
}
// 反复写入直到完成。发生错误时文件可能已经包含前缀,不承诺回滚。
fn write_all(f: *File, bytes: []u8): Status {
if f == null || !File.valid(f) { ret .Err(make(.Io)); }
if bytes.len != 0 && bytes.ptr == null { ret .Err(make(.InvalidArgument)); }
var total: usize = 0;
while total < bytes.len {
var written = File.write(f, bytes.ptr + total, (bytes.len - total) as u64);
if written == 0 || written > (bytes.len - total) as u64 {
ret .Err(make(.Io));
}
total = total + written as usize;
}
ret .Ok;
}
fn print(bytes: []u8): Status {
var out = File.stdout();
ret write_all(&out, bytes);
}
fn println(bytes: []u8): Status {
match print(bytes) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret print("\n");
}
fn eprint(bytes: []u8): Status {
var err = File.stderr();
ret write_all(&err, bytes);
}
// 仅供已经隔离的临时存储使用;失败时可能写入目标前缀。
fn read_fully(f: *File, data: *u8, len: usize): Status {
var total: usize = 0;
while total < len {
var got = File.read(f, data + total, len - total);
if got == 0 || got > len - total { ret .Err(make(.Io)); }
total = total + got;
}
ret .Ok;
}
// 精确读取 bytes.len 字节。短读返回 Err(.Io),失败保持 bytes 原内容不变。
fn read_exact(f: *File, bytes: []u8): Status {
if f == null || !File.valid(f) { ret .Err(make(.Io)); }
if bytes.len == 0 { ret .Ok; }
if bytes.ptr == null { ret .Err(make(.InvalidArgument)); }
var temporary = ByteBuffer.new();
defer { ByteBuffer.drop(&temporary); }
match ByteBuffer.reserve(&temporary, bytes.len) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
match read_fully(f, temporary.storage.data, bytes.len) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
Mem.copy(bytes.ptr as *any, temporary.storage.data as *any, bytes.len);
ret .Ok;
}
// 读取整个普通文件到 out。打开、短读或关闭失败时保持 out 不变。
fn read_all(path: ByteView, out: *ByteBuffer): Status {
if out == null { ret .Err(make(.InvalidArgument)); }
var f = open_cstr(path, ByteView.from_slice("rb"));
if !File.valid(&f) { ret .Err(make(.Io)); }
var sz = File.size(&f);
var fresh = ByteBuffer.new();
if sz != 0 {
match ByteBuffer.reserve(&fresh, sz) {
.Ok => {},
.Err(error) => { File.close(&f); ByteBuffer.drop(&fresh); ret .Err(error); },
}
match read_fully(&f, fresh.storage.data, sz) {
.Ok => {},
.Err(error) => { File.close(&f); ByteBuffer.drop(&fresh); ret .Err(error); },
}
fresh.storage.len = sz;
}
if File.close(&f) != 0 { ByteBuffer.drop(&fresh); ret .Err(make(.Io)); }
ByteBuffer.drop(out);
out.* = ByteBuffer.take(&fresh);
ret .Ok;
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
}
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected io error"); },
}
}
fn expect_io(result: Status) {
match result {
.Ok => { @assert(false, "expected io error"); },
.Err(error) => {
match error.kind {
.Io => {},
_ => { @assert(false, "expected Io kind"); },
}
},
}
}
fn test_roundtrip() {
var path = view("build/_io_roundtrip.tmp");
var f = open_cstr(path, view("wb"));
@assert(File.valid(&f), "open wb");
expect_ok(write_all(&f, "hello\nworld"));
@assert(File.close(&f) == 0, "close writer");
var out = ByteBuffer.new();
match read_all(path, &out) {
.Ok => {},
.Err(error) => { @assert(false, "read_all"); },
}
var got = ByteBuffer.as_slice(out);
@assert(got.len == 11, "roundtrip length");
@assert(got.ptr[0] == 'h' && got.ptr[5] == '\n' && got.ptr[10] == 'd', "roundtrip bytes");
ByteBuffer.drop(&out);
}
fn test_append_and_missing() {
var path = view("build/_io_append.tmp");
var f = open_cstr(path, view("wb"));
@assert(File.valid(&f), "open wb");
expect_ok(write_all(&f, "ab"));
@assert(File.close(&f) == 0, "close initial writer");
f = open_cstr(path, view("ab"));
@assert(File.valid(&f), "open ab");
expect_ok(write_all(&f, "cd"));
@assert(File.close(&f) == 0, "close append writer");
var out = ByteBuffer.new();
match read_all(path, &out) {
.Ok => {},
.Err(error) => { @assert(false, "read append"); },
}
var got = ByteBuffer.as_slice(out);
@assert(got.len == 4 && got.ptr[2] == 'c' && got.ptr[3] == 'd', "append content");
// 不存在的文件
match read_all(view("build/_io_no_such_file.tmp"), &out) {
.Ok => { @assert(false, "missing should fail"); },
.Err(error) => {
match error.kind { .Io => {}, _ => { @assert(false, "error kind"); } }
},
}
got = ByteBuffer.as_slice(out);
@assert(got.len == 4 && got.ptr[0] == 'a' && got.ptr[3] == 'd',
"failed read_all preserves output");
ByteBuffer.drop(&out);
}
fn test_read_exact_and_errors() {
var path = view("build/_io_exact.tmp");
var f = open_cstr(path, view("wb"));
@assert(File.valid(&f));
expect_ok(write_all(&f, "xyz"));
@assert(File.close(&f) == 0);
f = open_cstr(path, view("rb"));
@assert(File.valid(&f));
var too_long: [4]u8 = .[9, 8, 7, 6];
expect_io(read_exact(&f, too_long[0..4]));
@assert(too_long[0] == 9 && too_long[1] == 8 &&
too_long[2] == 7 && too_long[3] == 6,
"short read preserves destination");
@assert(File.close(&f) == 0);
f = open_cstr(path, view("rb"));
@assert(File.valid(&f));
var exact: [3]u8 = .[0, 0, 0];
expect_ok(read_exact(&f, exact[0..3]));
@assert(exact[0] == 'x' && exact[1] == 'y' && exact[2] == 'z');
@assert(File.close(&f) == 0);
var invalid = File { .handle = null };
expect_io(write_all(&invalid, "x"));
expect_io(read_exact(&invalid, exact[0..3]));
}
fn main() {
test_roundtrip();
test_append_and_missing();
test_read_exact_and_errors();
expect_ok(println("io: ok"));
}
+837
View File
@@ -0,0 +1,837 @@
// Expect retcode = 0
// 轻量 JSON 解析 / 输出器(递归下降 + 节点池),用于验证底层库的拼装,未来服务 LSP。
// 设计:
// - 输入 ByteView,字符串/数字以“源切片”借用,不做解码,round-trip 保真;
// - 节点池 Vec[JsonNode];数组/对象子项存 Vec[JsonChild],保留插入顺序;
// - 错误带字节位置(error.spl);输出写 ByteBuffer;缩进/数字用 ByteBuffer/fmt。
// 限制:不做字符串转义解码、数字不做数值化(原样保存);递归/输出深度上限见 max_depth()。
type .{ .Error, .Status, .make, .at } = @import("error.spl");
type .{ .ByteView, .ViewResult, .FindResult } = @import("byte_view.spl");
type .{ .Vec } = @import("vec.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
type .{ .is_digit, .is_hex_digit, .is_space } = @import("ascii.spl");
type .{ .checked_mul } = @import("memory.spl");
type .{ .append_i64, .append_u64 } = @import("fmt.spl");
type JsonKind = enum {
Null,
True,
False,
Number,
String,
Array,
Object,
}
// 数组元素或对象成员。数组时 key 为空视图;对象时 key 为源中的原始键文本。
type JsonChild = struct {
key: ByteView,
val: usize,
}
// 节点:kind 决定有效载荷字段,其余字段保持空。访问方必须按 kind 读取:
// Null/True/False -> text 空、children 空;
// Number/String -> text 为源切片、children 空;
// Array/Object -> children 保存子项、text 空。
type JsonNode = struct {
kind: JsonKind,
text: ByteView,
children: Vec,
}
// 解析结果文档:nodes 拥有全部节点;root 为根节点下标。
type Json = struct {
nodes: Vec,
root: usize,
}
type JsonResult = enum {
Ok: Json,
Err: Error,
}
type NodeResult = enum {
Ok: usize,
Err: Error,
}
type Parser = struct {
src: ByteView,
pos: usize,
nodes: Vec,
}
// 递归/输出深度上限:防止病态输入耗尽调用栈。256 层足够覆盖正常 JSON。
fn max_depth(): usize {
ret 256;
}
fn blank_node(kind: JsonKind): JsonNode {
ret JsonNode {
.kind = kind,
.text = ByteView.empty(),
.children = Vec.blank(@sizeof(JsonChild), 8),
};
}
fn intern_node(p: *Parser, node: JsonNode): NodeResult {
var index = p.nodes.len;
var n = node;
match Vec.push(&p.nodes, &n as *u8) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret .Ok(index);
}
fn node_at(doc: *Json, index: usize): *JsonNode {
match Vec.get(&doc.nodes, index) {
.Ok(ptr) => { ret ptr as *JsonNode; },
.Err(error) => { ret null; }, // 越界/无效池统一返回 null,调用方判空
}
ret null;
}
fn skip_ws(p: *Parser) {
while p.pos < p.src.len && is_space(p.src.ptr[p.pos]) {
p.pos = p.pos + 1;
}
}
// -1 表示 EOF。
fn peek(p: *Parser): i32 {
if p.pos >= p.src.len { ret -1; }
ret p.src.ptr[p.pos] as i32;
}
// 当前字符是否等于 ch(EOF 时 false)。
fn at_char(p: *Parser, ch: u8): bool {
var c = peek(p);
if c < 0 { ret false; }
ret (c as u8) == ch;
}
fn parse_string_raw(p: *Parser): ViewResult {
if !at_char(p, '"') { ret .Err(at(.InvalidFormat, p.pos)); }
p.pos = p.pos + 1;
var start = p.pos;
while p.pos < p.src.len {
var c = p.src.ptr[p.pos];
if c == '"' { break; }
if c == '\\' { // '\\'
p.pos = p.pos + 1;
if p.pos >= p.src.len { ret .Err(at(.UnexpectedEnd, p.pos)); }
if p.src.ptr[p.pos] == 'u' { // 'u'
var k: usize = 0;
while k < 4 {
p.pos = p.pos + 1;
if p.pos >= p.src.len { ret .Err(at(.UnexpectedEnd, p.pos)); }
if !is_hex_digit(p.src.ptr[p.pos]) { ret .Err(at(.InvalidDigit, p.pos)); }
k = k + 1;
}
}
} else if c < 32 {
// JSON 只禁止未转义的 U+0000..U+001F;0x7F 合法,不能用 ascii.is_control。
ret .Err(at(.InvalidFormat, p.pos));
}
p.pos = p.pos + 1;
}
if p.pos >= p.src.len { ret .Err(at(.UnexpectedEnd, p.pos)); }
var end = p.pos;
p.pos = p.pos + 1; // 收尾引号
ret ByteView.slice(p.src, start, end);
}
fn parse_literal(p: *Parser, word: []u8, kind: JsonKind): NodeResult {
var i: usize = 0;
while i < word.len {
if p.pos + i >= p.src.len { ret .Err(at(.UnexpectedEnd, p.src.len)); }
if p.src.ptr[p.pos + i] != word.ptr[i] {
ret .Err(at(.InvalidFormat, p.pos + i));
}
i = i + 1;
}
p.pos = p.pos + word.len;
var node = blank_node(kind);
ret intern_node(p, node);
}
fn parse_number(p: *Parser): NodeResult {
var start = p.pos;
if at_char(p, '-') { p.pos = p.pos + 1; } // '-'
if p.pos >= p.src.len || !is_digit(p.src.ptr[p.pos]) {
ret .Err(at(.InvalidDigit, p.pos));
}
if p.src.ptr[p.pos] == '0' { // 前导 0 后面不能接数字
p.pos = p.pos + 1;
} else {
while p.pos < p.src.len && is_digit(p.src.ptr[p.pos]) {
p.pos = p.pos + 1;
}
}
if p.pos < p.src.len && p.src.ptr[p.pos] == '.' { // '.'
p.pos = p.pos + 1;
if p.pos >= p.src.len || !is_digit(p.src.ptr[p.pos]) {
ret .Err(at(.InvalidDigit, p.pos));
}
while p.pos < p.src.len && is_digit(p.src.ptr[p.pos]) {
p.pos = p.pos + 1;
}
}
if p.pos < p.src.len && (p.src.ptr[p.pos] == 'e' || p.src.ptr[p.pos] == 'E') { // e/E
p.pos = p.pos + 1;
if p.pos < p.src.len && (p.src.ptr[p.pos] == '+' || p.src.ptr[p.pos] == '-') {
p.pos = p.pos + 1;
}
if p.pos >= p.src.len || !is_digit(p.src.ptr[p.pos]) {
ret .Err(at(.InvalidDigit, p.pos));
}
while p.pos < p.src.len && is_digit(p.src.ptr[p.pos]) {
p.pos = p.pos + 1;
}
}
var text = ByteView.slice(p.src, start, p.pos);
match text {
.Ok(v) => {
var node = blank_node(.Number);
node.text = v;
ret intern_node(p, node);
},
.Err(error) => { ret .Err(error); },
}
}
fn parse_array(p: *Parser, depth: usize): NodeResult {
if depth >= max_depth() { ret .Err(at(.OutOfRange, p.pos)); }
p.pos = p.pos + 1; // '['
var kids = Vec.blank(@sizeof(JsonChild), 8);
skip_ws(p);
if at_char(p, ']') { // ']'
p.pos = p.pos + 1;
var empty = blank_node(.Array);
empty.children = kids;
match intern_node(p, empty) {
.Ok(index) => { ret .Ok(index); },
.Err(error) => { Vec.drop(&empty.children); ret .Err(error); },
}
}
while true {
var element = parse_value(p, depth + 1);
var index: usize = 0;
match element {
.Ok(v) => { index = v; },
.Err(error) => { Vec.drop(&kids); ret .Err(error); },
}
var child = JsonChild { .key = ByteView.empty(), .val = index };
match Vec.push(&kids, &child as *u8) {
.Ok => {},
.Err(error) => { Vec.drop(&kids); ret .Err(error); },
}
skip_ws(p);
if at_char(p, ',') { // ','
p.pos = p.pos + 1;
continue;
}
if at_char(p, ']') { // ']'
p.pos = p.pos + 1;
break;
}
Vec.drop(&kids);
ret .Err(at(.InvalidFormat, p.pos));
}
var node = blank_node(.Array);
node.children = kids;
match intern_node(p, node) {
.Ok(index) => { ret .Ok(index); },
.Err(error) => { Vec.drop(&node.children); ret .Err(error); },
}
}
fn parse_object(p: *Parser, depth: usize): NodeResult {
if depth >= max_depth() { ret .Err(at(.OutOfRange, p.pos)); }
p.pos = p.pos + 1; // '{'
var kids = Vec.blank(@sizeof(JsonChild), 8);
skip_ws(p);
if at_char(p, '}') { // '}'
p.pos = p.pos + 1;
var empty = blank_node(.Object);
empty.children = kids;
match intern_node(p, empty) {
.Ok(index) => { ret .Ok(index); },
.Err(error) => { Vec.drop(&empty.children); ret .Err(error); },
}
}
while true {
skip_ws(p);
var key_view = ByteView.empty();
match parse_string_raw(p) {
.Ok(v) => { key_view = v; },
.Err(error) => { Vec.drop(&kids); ret .Err(error); },
}
skip_ws(p);
if !at_char(p, ':') { // ':'
Vec.drop(&kids);
ret .Err(at(.InvalidFormat, p.pos));
}
p.pos = p.pos + 1;
var value = parse_value(p, depth + 1);
var index: usize = 0;
match value {
.Ok(v) => { index = v; },
.Err(error) => { Vec.drop(&kids); ret .Err(error); },
}
var child = JsonChild { .key = key_view, .val = index };
match Vec.push(&kids, &child as *u8) {
.Ok => {},
.Err(error) => { Vec.drop(&kids); ret .Err(error); },
}
skip_ws(p);
if at_char(p, ',') { // ','
p.pos = p.pos + 1;
continue;
}
if at_char(p, '}') { // '}'
p.pos = p.pos + 1;
break;
}
Vec.drop(&kids);
ret .Err(at(.InvalidFormat, p.pos));
}
var node = blank_node(.Object);
node.children = kids;
match intern_node(p, node) {
.Ok(index) => { ret .Ok(index); },
.Err(error) => { Vec.drop(&node.children); ret .Err(error); },
}
}
fn parse_value(p: *Parser, depth: usize): NodeResult {
skip_ws(p);
var c = peek(p);
if c < 0 { ret .Err(at(.UnexpectedEnd, p.pos)); }
var ch = c as u8;
if ch == '"' { // '"'
var view = ByteView.empty();
match parse_string_raw(p) {
.Ok(v) => { view = v; },
.Err(error) => { ret .Err(error); },
}
var node = blank_node(.String);
node.text = view;
ret intern_node(p, node);
}
if ch == '{' { ret parse_object(p, depth); } // '{'
if ch == '[' { ret parse_array(p, depth); } // '['
if ch == 't' { ret parse_literal(p, "true", .True); }
if ch == 'f' { ret parse_literal(p, "false", .False); }
if ch == 'n' { ret parse_literal(p, "null", .Null); }
ret parse_number(p);
}
fn drop_node_pool(pool: *Vec) {
var i: usize = 0;
while i < pool.*.len {
match Vec.get(pool, i) {
.Ok(ptr) => {
var n = ptr as *JsonNode;
Vec.drop(&n.children);
},
// i < pool.len 且池有效,get 不会失败;失败时无额外资源可释放。
.Err(error) => {},
}
i = i + 1;
}
Vec.drop(pool);
}
fn parse(src: ByteView): JsonResult {
var p = Parser {
.src = src,
.pos = 0,
.nodes = Vec.blank(@sizeof(JsonNode), 8),
};
skip_ws(&p);
var root: usize = 0;
var result = parse_value(&p, 0);
match result {
.Ok(index) => { root = index; },
.Err(error) => {
drop_node_pool(&p.nodes);
ret .Err(error);
},
}
skip_ws(&p);
if p.pos != src.len {
drop_node_pool(&p.nodes);
ret .Err(at(.InvalidFormat, p.pos));
}
ret .Ok(Json { .nodes = p.nodes, .root = root });
}
fn drop(doc: *Json) {
drop_node_pool(&doc.nodes);
}
fn root_index(doc: *Json): usize {
ret doc.root;
}
// 枚举 tag 取整(stage1 枚举 == 有缺陷,用 @enum2int 比较更稳妥)。
fn kind_code(kind: JsonKind): usize {
ret @enum2int(kind) as usize;
}
fn text_of(doc: *Json, index: usize): ByteView {
var n = node_at(doc, index);
if n == null { ret ByteView.empty(); }
ret n.text;
}
fn array_count(doc: *Json, index: usize): usize {
var n = node_at(doc, index);
if n == null { ret 0; }
match n.kind {
.Array => { ret n.children.len; },
_ => { ret 0; },
}
ret 0;
}
fn array_at(doc: *Json, index: usize, i: usize): usize {
var n = node_at(doc, index);
if n == null { ret ~(0 as usize); }
match n.kind {
.Array => {
if i >= n.children.len { ret ~(0 as usize); }
match Vec.get(&n.children, i) {
.Ok(ptr) => { ret (ptr as *JsonChild).val; },
.Err(error) => { ret ~(0 as usize); },
}
},
_ => { ret ~(0 as usize); },
}
ret ~(0 as usize);
}
// 对象按键查找(线性,保持插入顺序)。找到返回节点下标。
fn object_find(doc: *Json, index: usize, key: ByteView): FindResult {
var n = node_at(doc, index);
if n == null { ret .NotFound; }
match n.kind {
.Object => {
var i: usize = 0;
var count = n.children.len;
while i < count {
match Vec.get(&n.children, i) {
.Ok(ptr) => {
var child = ptr as *JsonChild;
if ByteView.eq(child.key, key) { ret .Found(child.val); }
},
// i < count == children.len,get 不会失败。
.Err(error) => {},
}
i = i + 1;
}
ret .NotFound;
},
_ => { ret .NotFound; },
}
ret .NotFound;
}
fn emit_quoted(out: *ByteBuffer, text: ByteView): Status {
match ByteBuffer.append_byte(out, '"') { // '"'
.Ok => {},
.Err(error) => { ret .Err(error); },
}
match ByteBuffer.append(out, ByteView.as_slice(text)) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret ByteBuffer.append_byte(out, '"');
}
fn emit_indent(out: *ByteBuffer, indent: usize, depth: usize): Status {
match ByteBuffer.append_byte(out, '\n') { // '\n'
.Ok => {},
.Err(error) => { ret .Err(error); },
}
var spaces: usize = 0;
match checked_mul(depth, indent) {
.Ok(value) => { spaces = value; },
.Err(error) => { ret .Err(error); },
}
ret ByteBuffer.append_repeat(out, 32, spaces);
}
fn emit(out: *ByteBuffer, doc: *Json, index: usize, indent: usize, depth: usize): Status {
if depth >= max_depth() { ret .Err(make(.OutOfRange)); }
var n = node_at(doc, index);
if n == null { ret .Err(make(.OutOfRange)); }
match n.kind {
.Null => { ret ByteBuffer.append(out, "null"); },
.True => { ret ByteBuffer.append(out, "true"); },
.False => { ret ByteBuffer.append(out, "false"); },
.Number => { ret ByteBuffer.append(out, ByteView.as_slice(n.text)); },
.String => { ret emit_quoted(out, n.text); },
.Array => { ret emit_children(out, doc, n, false, indent, depth); },
.Object => { ret emit_children(out, doc, n, true, indent, depth); },
}
ret .Ok;
}
fn emit_children(out: *ByteBuffer, doc: *Json, n: *JsonNode, is_object: bool, indent: usize,
depth: usize): Status {
var open_byte: u8 = '['; // '['
var close_byte: u8 = ']'; // ']'
if is_object {
open_byte = '{'; // '{'
close_byte = '}'; // '}'
}
match ByteBuffer.append_byte(out, open_byte) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
var count = n.children.len;
if count == 0 {
ret ByteBuffer.append_byte(out, close_byte);
}
var i: usize = 0;
while i < count {
if i != 0 {
match ByteBuffer.append_byte(out, ',') { // ','
.Ok => {},
.Err(error) => { ret .Err(error); },
}
}
if indent != 0 {
match emit_indent(out, indent, depth + 1) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
}
match Vec.get(&n.children, i) {
.Ok(ptr) => {
var child = ptr as *JsonChild;
if is_object {
match emit_quoted(out, child.key) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
match ByteBuffer.append_byte(out, ':') { // ':'
.Ok => {},
.Err(error) => { ret .Err(error); },
}
if indent != 0 {
match ByteBuffer.append_byte(out, ' ') { // ' '
.Ok => {},
.Err(error) => { ret .Err(error); },
}
}
}
match emit(out, doc, child.val, indent, depth + 1) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
},
.Err(error) => { ret .Err(error); },
}
i = i + 1;
}
if indent != 0 {
match emit_indent(out, indent, depth) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
}
ret ByteBuffer.append_byte(out, close_byte);
}
fn emit_compact(out: *ByteBuffer, doc: *Json): Status {
ret emit(out, doc, doc.root, 0, 0);
}
fn emit_pretty(out: *ByteBuffer, doc: *Json, indent: usize): Status {
ret emit(out, doc, doc.root, indent, 0);
}
// ---- 构造辅助(写 JSON 片段;字符串需由调用方保证已转义)----
fn write_int(out: *ByteBuffer, value: i64): Status {
ret append_i64(out, value, 10, false);
}
fn write_u64(out: *ByteBuffer, value: u64): Status {
ret append_u64(out, value, 10, false);
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected json error"); },
}
}
fn expect_bytes(out: *ByteBuffer, expected: []u8) {
var actual = ByteBuffer.as_slice(out.*);
@assert(actual.len == expected.len, "emitted length");
var i: usize = 0;
while i < expected.len {
@assert(actual.ptr[i] == expected.ptr[i], "emitted byte");
i = i + 1;
}
}
fn expect_parse_error(result: JsonResult, pos: usize) {
match result {
.Ok(doc) => { @assert(false, "expected parse error"); },
.Err(error) => {
@assert(error.has_position, "positioned error");
@assert(error.position == pos, "error position");
},
}
}
fn expect_kind(doc: *Json, index: usize, kind: JsonKind) {
var n = node_at(doc, index);
@assert(n != null, "node exists");
@assert(kind_code(n.kind) == kind_code(kind), "node kind");
}
fn expect_text(doc: *Json, index: usize, expected: []u8) {
var got = text_of(doc, index);
var want = ByteView.from_slice(expected);
@assert(ByteView.eq(got, want), "node text");
}
fn test_scalars() {
var r = parse(ByteView.from_slice("null"));
match r {
.Ok(doc) => { expect_kind(&doc, root_index(&doc), .Null); drop(&doc); },
.Err(error) => { @assert(false, "parse null"); },
}
r = parse(ByteView.from_slice("true"));
match r {
.Ok(doc) => { expect_kind(&doc, root_index(&doc), .True); drop(&doc); },
.Err(error) => { @assert(false, "parse true"); },
}
r = parse(ByteView.from_slice("false"));
match r {
.Ok(doc) => { expect_kind(&doc, root_index(&doc), .False); drop(&doc); },
.Err(error) => { @assert(false, "parse false"); },
}
r = parse(ByteView.from_slice("-12.5e2"));
match r {
.Ok(doc) => {
var idx = root_index(&doc);
expect_kind(&doc, idx, .Number);
expect_text(&doc, idx, "-12.5e2");
drop(&doc);
},
.Err(error) => { @assert(false, "parse number"); },
}
r = parse(ByteView.from_slice("\"hi\\n\""));
match r {
.Ok(doc) => {
var idx = root_index(&doc);
expect_kind(&doc, idx, .String);
expect_text(&doc, idx, "hi\\n"); // 原始切片,未解码
drop(&doc);
},
.Err(error) => { @assert(false, "parse string"); },
}
}
fn test_containers_and_lookup() {
var text = "{\"a\":1,\"b\":[true,null,\"x\"],\"c\":{\"d\":2}}";
var r = parse(ByteView.from_slice(text));
match r {
.Ok(doc) => {
var root = root_index(&doc);
expect_kind(&doc, root, .Object);
var a = ByteView.from_slice("a");
match object_find(&doc, root, a) {
.Found(idx) => {
expect_kind(&doc, idx, .Number);
expect_text(&doc, idx, "1");
},
.NotFound => { @assert(false, "find a"); },
}
var b = ByteView.from_slice("b");
var bidx: usize = 0;
match object_find(&doc, root, b) {
.Found(idx) => { bidx = idx; },
.NotFound => { @assert(false, "find b"); },
}
expect_kind(&doc, bidx, .Array);
@assert(array_count(&doc, bidx) == 3, "array count");
expect_kind(&doc, array_at(&doc, bidx, 0), .True);
expect_kind(&doc, array_at(&doc, bidx, 1), .Null);
expect_text(&doc, array_at(&doc, bidx, 2), "x");
var c = ByteView.from_slice("c");
var cidx: usize = 0;
match object_find(&doc, root, c) {
.Found(idx) => { cidx = idx; },
.NotFound => { @assert(false, "find c"); },
}
var d = ByteView.from_slice("d");
match object_find(&doc, cidx, d) {
.Found(idx) => { expect_text(&doc, idx, "2"); },
.NotFound => { @assert(false, "find c.d"); },
}
var missing = ByteView.from_slice("zzz");
match object_find(&doc, root, missing) {
.Found(idx) => { @assert(false, "unexpected find"); },
.NotFound => {},
}
drop(&doc);
},
.Err(error) => { @assert(false, "parse object"); },
}
}
fn test_roundtrip_compact() {
var text = "{\"a\":1,\"b\":[true,null,\"x\\n\"],\"c\":{},\"d\":[],\"e\":-3.5e-2}";
var r = parse(ByteView.from_slice(text));
match r {
.Ok(doc) => {
var out = ByteBuffer.new();
expect_ok(emit_compact(&out, &doc));
expect_bytes(&out, text);
ByteBuffer.drop(&out);
drop(&doc);
},
.Err(error) => { @assert(false, "parse for roundtrip"); },
}
}
fn test_pretty() {
var text = "{\"a\":1,\"b\":[1,2]}";
var r = parse(ByteView.from_slice(text));
match r {
.Ok(doc) => {
var out = ByteBuffer.new();
expect_ok(emit_pretty(&out, &doc, 2));
var expected = "{\n \"a\": 1,\n \"b\": [\n 1,\n 2\n ]\n}";
expect_bytes(&out, expected);
ByteBuffer.drop(&out);
drop(&doc);
},
.Err(error) => { @assert(false, "parse pretty"); },
}
}
fn test_errors() {
expect_parse_error(parse(ByteView.from_slice("")), 0);
expect_parse_error(parse(ByteView.from_slice("\"abc")), 4);
expect_parse_error(parse(ByteView.from_slice("tru")), 3);
expect_parse_error(parse(ByteView.from_slice("[1,]")), 3);
expect_parse_error(parse(ByteView.from_slice("{\"a\":}")), 5);
expect_parse_error(parse(ByteView.from_slice("1 2")), 2);
expect_parse_error(parse(ByteView.from_slice("01")), 1);
}
fn test_depth_limit() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
var i: usize = 0;
while i < max_depth() + 8 {
expect_ok(ByteBuffer.append_byte(&out, '['));
i = i + 1;
}
i = 0;
while i < max_depth() + 8 {
expect_ok(ByteBuffer.append_byte(&out, ']'));
i = i + 1;
}
match parse(ByteView.from_slice(ByteBuffer.as_slice(out))) {
.Ok(doc) => { drop(&doc); @assert(false, "deep input should be rejected"); },
.Err(error) => {
match error.kind {
.OutOfRange => {},
_ => { @assert(false, "depth limit error kind"); },
}
},
}
}
fn test_construction_helpers() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
expect_ok(ByteBuffer.append(&out, "{\"id\":"));
expect_ok(write_u64(&out, 18446744073709551615));
expect_ok(ByteBuffer.append(&out, ",\"n\":"));
expect_ok(write_int(&out, -7));
expect_ok(ByteBuffer.append(&out, "}"));
expect_bytes(&out, "{\"id\":18446744073709551615,\"n\":-7}");
}
fn test_large_array() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
expect_ok(ByteBuffer.append_byte(&out, '[')); // '['
var i: usize = 0;
while i < 1000 {
if i != 0 { expect_ok(ByteBuffer.append_byte(&out, ',')); }
expect_ok(ByteBuffer.append_byte(&out, '1')); // '1'
i = i + 1;
}
expect_ok(ByteBuffer.append_byte(&out, ']')); // ']'
var text = ByteBuffer.as_slice(out);
var r = parse(ByteView.from_slice(text));
match r {
.Ok(doc) => {
expect_kind(&doc, root_index(&doc), .Array);
@assert(array_count(&doc, root_index(&doc)) == 1000, "large array count");
expect_kind(&doc, array_at(&doc, root_index(&doc), 999), .Number);
drop(&doc);
},
.Err(error) => { @assert(false, "parse large array"); },
}
}
fn main() {
test_scalars();
test_containers_and_lookup();
test_roundtrip_compact();
test_pretty();
test_errors();
test_depth_limit();
test_construction_helpers();
test_large_array();
}
+205
View File
@@ -0,0 +1,205 @@
// Expect retcode = 0
// 编译器自身日志(区别于 diag:diag 负责带源码位置的诊断)。
// 输出到 stderr,格式稳定:[LEVEL] name: message\n。
// 消息为借用;Logger 不拥有 name。fatal 打印后终止进程(退出码 1)。
// write 返回 Status;OOM 归类为 .Overflow(无独立内存耗尽错误码)。
type .{ .Status, .make } = @import("error.spl");
type .{ .ByteView } = @import("byte_view.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
type .{ .format } = @import("fmt.spl");
type .{ .Value, .int, .str } = @import("value.spl");
type .{ .eprint } = @import("io.spl");
type Exit = @import("../sys/exit.spl");
type Level = enum { Debug, Info, Warn, Error, Fatal }
fn level_name(level: Level): []u8 {
match level {
.Debug => { ret "DEBUG"; },
.Info => { ret "INFO "; },
.Warn => { ret "WARN "; },
.Error => { ret "ERROR"; },
.Fatal => { ret "FATAL"; },
}
ret "NOTSET";
}
type Logger = @self;
name: ByteView,
min_level: Level,
fn new(name: ByteView): Logger {
ret Logger { .name = name, .min_level = .Debug };
}
fn set_level(self: *Logger, level: Level) {
self.min_level = level;
}
fn enabled(self: Logger, level: Level): bool {
ret @enum2int(level) >= @enum2int(self.min_level);
}
// 追加成功返回 true;失败(仅 OOM)返回 false。
fn push(line: *ByteBuffer, text: []u8): bool {
match ByteBuffer.append(line, text) {
.Ok => { ret true; },
.Err(error) => { ret false; },
}
ret false;
}
// 低于 min_level 的日志不写出,直接成功。
fn write(self: *Logger, level: Level, message: []u8): Status {
if !enabled(self.*, level) { ret .Ok; }
var line = ByteBuffer.new();
defer { ByteBuffer.drop(&line); }
if !push(&line, "[") { ret .Err(make(.Overflow)); }
if !push(&line, level_name(level)) { ret .Err(make(.Overflow)); }
if !push(&line, "] ") { ret .Err(make(.Overflow)); }
if !push(&line, ByteView.as_slice(self.name)) { ret .Err(make(.Overflow)); }
if !push(&line, ": ") { ret .Err(make(.Overflow)); }
if !push(&line, message) { ret .Err(make(.Overflow)); }
if !push(&line, "\n") { ret .Err(make(.Overflow)); }
ret eprint(ByteBuffer.as_slice(line));
}
fn debug(self: *Logger, message: []u8): Status {
ret write(self, .Debug, message);
}
fn info(self: *Logger, message: []u8): Status {
ret write(self, .Info, message);
}
fn warn(self: *Logger, message: []u8): Status {
ret write(self, .Warn, message);
}
fn error(self: *Logger, message: []u8): Status {
ret write(self, .Error, message);
}
// 尽力写出后终止;写失败无法挽回,直接退出。
fn fatal(self: *Logger, message: []u8) {
write(self, .Fatal, message);
Exit.fail();
}
// ---- 格式化入口(显式装箱,见 value.spl / fmt.format)----
// 先格式化到临时缓冲;格式错误在写出前返回 Err(.InvalidFormat)。
fn logf(self: *Logger, level: Level, fmt: []u8, args: []Value): Status {
if !enabled(self.*, level) { ret .Ok; }
var message = ByteBuffer.new();
defer { ByteBuffer.drop(&message); }
match format(&message, fmt, args) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
ret write(self, level, ByteBuffer.as_slice(message));
}
fn debugf(self: *Logger, fmt: []u8, args: []Value): Status {
ret logf(self, .Debug, fmt, args);
}
fn infof(self: *Logger, fmt: []u8, args: []Value): Status {
ret logf(self, .Info, fmt, args);
}
fn warnf(self: *Logger, fmt: []u8, args: []Value): Status {
ret logf(self, .Warn, fmt, args);
}
fn errorf(self: *Logger, fmt: []u8, args: []Value): Status {
ret logf(self, .Error, fmt, args);
}
// 格式化后终止;格式化失败也要退出(避免吞掉致命错误)。
fn fatalf(self: *Logger, fmt: []u8, args: []Value) {
logf(self, .Fatal, fmt, args);
Exit.fail();
}
// ---- 测试 ----
fn expect_name(level: Level, expected: []u8) {
@assert(ByteView.eq(ByteView.from_slice(level_name(level)),
ByteView.from_slice(expected)),
"level name");
}
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected log error"); },
}
}
fn test_level_names() {
expect_name(.Debug, "DEBUG");
expect_name(.Info, "INFO ");
expect_name(.Warn, "WARN ");
expect_name(.Error, "ERROR");
expect_name(.Fatal, "FATAL");
var debug: Level = .Debug;
var info: Level = .Info;
var warn: Level = .Warn;
var err: Level = .Error;
var fatal: Level = .Fatal;
@assert(@enum2int(fatal) > @enum2int(err), "fatal above error");
@assert(@enum2int(err) > @enum2int(warn), "error above warn");
@assert(@enum2int(warn) > @enum2int(info), "warn above info");
@assert(@enum2int(info) > @enum2int(debug), "info above debug");
}
fn test_filter_and_write() {
var log = new(ByteView.from_slice("splc1"));
@assert(enabled(log, .Debug), "default shows debug");
@assert(enabled(log, .Fatal), "default shows fatal");
set_level(&log, .Warn);
@assert(!enabled(log, .Debug), "filtered debug");
@assert(!enabled(log, .Info), "filtered info");
@assert(enabled(log, .Warn), "warn passes");
@assert(enabled(log, .Error), "error passes");
// 被过滤的写入不产生输出,且返回成功。
expect_ok(debug(&log, "hidden"));
expect_ok(write(&log, .Info, "hidden too"));
expect_ok(error(&log, "visible"));
}
fn test_logf() {
var log = new(ByteView.from_slice("splc1"));
set_level(&log, .Error);
var args: [2]Value = .[int(3), str("x")];
// 被过滤的级别不写出,直接成功。
expect_ok(infof(&log, "n={} s={}", args[0..2]));
// 通过级别正常写出。
expect_ok(errorf(&log, "n={} s={}", args[0..2]));
// 格式化失败向上传播,且不产出消息。
match errorf(&log, "{} {}", args[0..1]) {
.Ok => { @assert(false, "expected invalid format"); },
.Err(error) => {
match error.kind {
.InvalidFormat => {},
_ => { @assert(false, "expected InvalidFormat"); },
}
},
}
}
fn main() {
test_level_names();
test_filter_and_write();
test_logf();
}
+197
View File
@@ -0,0 +1,197 @@
// Expect retcode = 0
// LSP 传输帧:Content-Length 头 + 空行 + 正文。
// 这里只做纯逻辑(写入/解析 ByteBuffer/ByteView),真正的 stdin/stdout I/O 由上层负责。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .ByteView } = @import("byte_view.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
type .{ .append_usize } = @import("fmt.spl");
type .{ .checked_add, .checked_mul } = @import("memory.spl");
type .{ .to_lower } = @import("ascii.spl");
type FrameResult = enum {
Ok: usize, // 消耗的字节数
Incomplete,
Err: Error,
}
// data[j..] 是否以 word 开头(ASCII 大小写不敏感)。
fn ci_prefix(data: *u8, len: usize, j: usize, word: []u8): bool {
if j + word.len > len { ret false; }
var i: usize = 0;
while i < word.len {
if to_lower(data[j + i]) != to_lower(word.ptr[i]) { ret false; }
i = i + 1;
}
ret true;
}
fn write_frame(out: *ByteBuffer, body: []u8): Status {
match ByteBuffer.append(out, "Content-Length: ") { .Ok => {}, .Err(e) => { ret .Err(e); } }
match append_usize(out, body.len, 10, false) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append(out, "\r\n\r\n") { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append(out, body);
}
// 从 input 解析一个帧;正文复制到 body_out。缺数据返回 Incomplete。
fn parse_frame(input: ByteView, body_out: *ByteBuffer): FrameResult {
var data = ByteView.as_slice(input);
var len = data.len;
// 找头结束标记 \r\n\r\n
var term = ~(0 as usize);
var i: usize = 0;
while i + 3 < len {
if data[i] == '\r' && data[i + 1] == '\n' && data[i + 2] == '\r' && data[i + 3] == '\n' {
term = i;
break;
}
i = i + 1;
}
if term == ~(0 as usize) { ret .Incomplete; }
// 在头内找 Content-Length(大小写不敏感)
var content_len: usize = 0;
var found = false;
var j: usize = 0;
while j + 15 <= term {
if ci_prefix(data.ptr, term, j, "content-length:") {
var k = j + 15;
while k < term && (data[k] == ' ' || data[k] == '\t') { k = k + 1; }
var n: usize = 0;
var digits = 0;
while k < term && data[k] >= '0' && data[k] <= '9' {
var digit = (data[k] - '0') as usize;
var scaled: usize = 0;
match checked_mul(n, 10) {
.Ok(value) => { scaled = value; },
.Err(error) => { ret .Err(error); },
}
match checked_add(scaled, digit) {
.Ok(value) => { n = value; },
.Err(error) => { ret .Err(error); },
}
digits = digits + 1;
k = k + 1;
}
if digits == 0 { ret .Err(make(.InvalidDigit)); }
content_len = n;
found = true;
break;
}
j = j + 1;
}
if !found { ret .Err(make(.InvalidFormat)); }
var body_start = term + 4;
if len < body_start || content_len > len - body_start { ret .Incomplete; }
// 先写入临时缓冲区,成功后再替换 body_out,失败不产生部分输出。
var fresh = ByteBuffer.new();
var body = data[body_start..body_start + content_len];
match ByteBuffer.append(&fresh, body) {
.Ok => {},
.Err(e) => { ByteBuffer.drop(&fresh); ret .Err(e); },
}
ByteBuffer.drop(body_out);
body_out.* = ByteBuffer.take(&fresh);
ret .Ok(body_start + content_len);
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected frame error"); },
}
}
fn expect_body(out: *ByteBuffer, expected: []u8) {
var actual = ByteBuffer.as_slice(out.*);
@assert(actual.len == expected.len, "body length");
var i: usize = 0;
while i < expected.len {
@assert(actual.ptr[i] == expected.ptr[i], "body byte");
i = i + 1;
}
}
fn test_roundtrip() {
var wire = ByteBuffer.new();
defer { ByteBuffer.drop(&wire); }
expect_ok(write_frame(&wire, "{\"jsonrpc\":\"2.0\"}"));
var bytes = ByteBuffer.as_slice(wire);
@assert(bytes.len == 16 + 2 + 4 + 17, "wire length"); // "Content-Length: 17\r\n\r\n" + body
var body = ByteBuffer.new();
defer { ByteBuffer.drop(&body); }
match parse_frame(ByteView.from_slice(bytes), &body) {
.Ok(used) => {
@assert(used == bytes.len, "consumed all");
expect_body(&body, "{\"jsonrpc\":\"2.0\"}");
},
.Incomplete => { @assert(false, "unexpected incomplete"); },
.Err(error) => { @assert(false, "unexpected err"); },
}
}
fn test_multiple_and_leftover() {
var wire = ByteBuffer.new();
defer { ByteBuffer.drop(&wire); }
expect_ok(write_frame(&wire, "abcd"));
expect_ok(write_frame(&wire, "ef"));
var bytes = ByteBuffer.as_slice(wire);
var body = ByteBuffer.new();
defer { ByteBuffer.drop(&body); }
match parse_frame(ByteView.from_slice(bytes), &body) {
.Ok(used) => {
expect_body(&body, "abcd");
var rest = bytes[used..bytes.len];
match parse_frame(ByteView.from_slice(rest), &body) {
.Ok(used2) => { expect_body(&body, "ef"); @assert(used2 == rest.len, "second"); },
_ => { @assert(false, "second frame"); },
}
},
_ => { @assert(false, "first frame"); },
}
}
fn test_incomplete_and_errors() {
var body = ByteBuffer.new();
defer { ByteBuffer.drop(&body); }
// 头未结束
var h1 = "Content-Length: 3\r\n";
match parse_frame(ByteView.from_slice(h1), &body) {
.Incomplete => {},
_ => { @assert(false, "h1"); },
}
// 正文不足
var h2 = "Content-Length: 3\r\n\r\nab";
match parse_frame(ByteView.from_slice(h2), &body) {
.Incomplete => {},
_ => { @assert(false, "h2"); },
}
// 缺 Content-Length
var h3 = "X: 1\r\n\r\n";
match parse_frame(ByteView.from_slice(h3), &body) {
.Ok(used) => { @assert(false, "h3 ok"); },
.Incomplete => { @assert(false, "h3 incomplete"); },
.Err(error) => {},
}
// 大小写不敏感 + 额外头
var h4 = "X-Test: yes\r\ncontent-length: 2\r\n\r\nhi";
match parse_frame(ByteView.from_slice(h4), &body) {
.Ok(used) => { expect_body(&body, "hi"); },
_ => { @assert(false, "h4"); },
}
}
fn main() {
test_roundtrip();
test_multiple_and_leftover();
test_incomplete_and_errors();
}
+502
View File
@@ -0,0 +1,502 @@
// Expect retcode = 0
// 开放寻址 + tombstone 哈希表。键和值都按字节复制到表自己的存储。
// 键类型由 hash_fn / eq_fn 解释:回调收到指向键字节的指针(如 *usize / *ByteView)。
// 普通赋值只复制句柄(与 Vec 一样),所有权转移必须使用 take。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .Vec } = @import("vec.spl");
type .{ .ByteView } = @import("byte_view.spl");
type .{ .hash_usize, .eq_usize, .hash_view, .eq_view } = @import("hash.spl");
type .{ .checked_add, .checked_mul, .grow_capacity } = @import("memory.spl");
type .{ .copy } = @import("../sys/mem.spl");
// 槽位状态:Empty/Occupied/Deleted(墓碑,仅在扩容重哈希时清除)。
// 负载因子 70/128。
type SlotState = enum {
Empty,
Occupied,
Deleted,
}
fn state_code(state: SlotState): u8 {
var s: SlotState = state;
ret @enum2int(s) as u8;
}
// 查找/删除结果:显式区分命中与缺失,替代 bool 哨兵。
type LookupResult = enum {
Found,
NotFound,
}
type Map = @self;
keys: Vec,
vals: Vec,
states: Vec,
size: usize,
key_size: usize,
val_size: usize,
hash_fn: fn(*u8): usize,
eq_fn: fn(*u8, *u8): bool,
fn blank(key_size: usize, key_align: usize, val_size: usize, val_align: usize,
hash_fn: fn(*u8): usize, eq_fn: fn(*u8, *u8): bool): Map {
ret Map {
.keys = Vec.blank(key_size, key_align),
.vals = Vec.blank(val_size, val_align),
.states = Vec.blank(1, 1),
.size = 0,
.key_size = key_size,
.val_size = val_size,
.hash_fn = hash_fn,
.eq_fn = eq_fn,
};
}
fn new(key_size: usize, key_align: usize, val_size: usize, val_align: usize,
hash_fn: fn(*u8): usize, eq_fn: fn(*u8, *u8): bool): Map {
ret blank(key_size, key_align, val_size, val_align, hash_fn, eq_fn);
}
fn valid(self: Map): bool {
if self.key_size == 0 || self.val_size == 0 { ret false; }
if self.states.len != self.keys.len || self.states.len != self.vals.len {
ret false;
}
if self.size > self.states.len { ret false; }
ret true;
}
fn size(self: Map): usize {
ret self.size;
}
fn capacity(self: Map): usize {
ret self.states.cap;
}
// 迭代支持:遍历 [0, slot_count),slot_state 为 1 时 key_at/val_at 有效。
fn slot_count(self: Map): usize {
ret self.states.len;
}
fn slot_state(self: Map, index: usize): SlotState {
var code = self.states.data[index];
var occupied: SlotState = .Occupied;
var deleted_state: SlotState = .Deleted;
if code == state_code(occupied) { ret .Occupied; }
if code == state_code(deleted_state) { ret .Deleted; }
ret .Empty;
}
fn slot_occupied(state: SlotState): bool {
match state {
.Occupied => { ret true; },
.Empty => { ret false; },
.Deleted => { ret false; },
}
ret false;
}
fn key_at(self: *Map, index: usize): *u8 {
ret self.keys.data + index * self.key_size;
}
fn val_at(self: *Map, index: usize): *u8 {
ret self.vals.data + index * self.val_size;
}
// 返回占用键的槽位;未找到返回 ~0。容量为 0 时直接未找到。
fn find_slot(self: *Map, key: *u8): usize {
if self.states.cap == 0 { ret ~(0 as usize); }
var mask = self.states.cap - 1;
var i = self.hash_fn(key) & mask;
var empty: SlotState = .Empty;
var occupied: SlotState = .Occupied;
var probes: usize = 0;
while probes < self.states.cap && self.states.data[i] != state_code(empty) {
if self.states.data[i] == state_code(occupied) &&
self.eq_fn(self.keys.data + i * self.key_size, key) {
ret i;
}
i = (i + 1) & mask;
probes = probes + 1;
}
ret ~(0 as usize);
}
// 要求容量非零且键不存在。优先复用探测链中的第一个墓碑。
fn place(self: *Map, key: *u8, val: *u8) {
var mask = self.states.cap - 1;
var i = self.hash_fn(key) & mask;
var empty: SlotState = .Empty;
var deleted: SlotState = .Deleted;
var occupied: SlotState = .Occupied;
var first_deleted = ~(0 as usize);
var probes: usize = 0;
while probes < self.states.cap && self.states.data[i] != state_code(empty) {
if self.states.data[i] == state_code(deleted) && first_deleted == ~(0 as usize) {
first_deleted = i;
}
i = (i + 1) & mask;
probes = probes + 1;
}
if first_deleted != ~(0 as usize) {
i = first_deleted;
}
copy((self.keys.data + i * self.key_size) as *any, key as *any, self.key_size);
copy((self.vals.data + i * self.val_size) as *any, val as *any, self.val_size);
self.states.data[i] = state_code(occupied);
self.size = self.size + 1;
}
// 保证至少 need 个槽位。所有检查在旧表改动前完成,失败保持原表不变。
fn reserve(self: *Map, need: usize): Status {
if !valid(self.*) { ret .Err(make(.InvalidArgument)); }
if need <= self.states.cap { ret .Ok; }
var new_cap = grow_capacity(self.states.cap, 8, need);
var fresh = self.*;
fresh.keys = Vec.blank(self.key_size, self.keys.elem_align);
fresh.vals = Vec.blank(self.val_size, self.vals.elem_align);
fresh.states = Vec.blank(1, 1);
fresh.size = 0;
match Vec.reserve(&fresh.keys, new_cap) {
.Ok => {},
.Err(error) => { drop(&fresh); ret .Err(error); },
}
match Vec.reserve(&fresh.vals, new_cap) {
.Ok => {},
.Err(error) => { drop(&fresh); ret .Err(error); },
}
match Vec.reserve(&fresh.states, new_cap) {
.Ok => {},
.Err(error) => { drop(&fresh); ret .Err(error); },
}
fresh.keys.len = new_cap;
fresh.vals.len = new_cap;
fresh.states.len = new_cap;
var i: usize = 0;
var empty: SlotState = .Empty;
var occupied: SlotState = .Occupied;
while i < new_cap {
fresh.states.data[i] = state_code(empty);
i = i + 1;
}
i = 0;
while i < self.states.len {
if self.states.data[i] == state_code(occupied) {
place(&fresh, self.keys.data + i * self.key_size,
self.vals.data + i * self.val_size);
}
i = i + 1;
}
var old_keys = self.keys;
var old_vals = self.vals;
var old_states = self.states;
self.* = fresh;
Vec.drop(&old_keys);
Vec.drop(&old_vals);
Vec.drop(&old_states);
ret .Ok;
}
// 覆盖已存在的键;否则插入并可能扩容。
fn put(self: *Map, key: *u8, val: *u8): Status {
if !valid(self.*) || key == null || val == null {
ret .Err(make(.InvalidArgument));
}
var existing = find_slot(self, key);
if existing != ~(0 as usize) {
copy((self.vals.data + existing * self.val_size) as *any, val as *any, self.val_size);
ret .Ok;
}
if self.states.cap == 0 {
match reserve(self, 8) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
} else {
var next_size: usize = 0;
match checked_add(self.size, 1) {
.Ok(value) => { next_size = value; },
.Err(error) => { ret .Err(error); },
}
var scaled: usize = 0;
match checked_mul(next_size, 128) {
.Ok(value) => { scaled = value; },
.Err(error) => { ret .Err(error); },
}
if scaled / self.states.cap >= 70 {
var need: usize = 0;
match checked_mul(self.states.cap, 2) {
.Ok(value) => { need = value; },
.Err(error) => { ret .Err(error); },
}
match reserve(self, need) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
}
}
place(self, key, val);
ret .Ok;
}
// 找到键则把值复制到 out 并返回 Found;否则 out 不变并返回 NotFound。
fn get(self: *Map, key: *u8, out: *u8): LookupResult {
if !valid(self.*) || key == null || out == null { ret .NotFound; }
var i = find_slot(self, key);
if i == ~(0 as usize) { ret .NotFound; }
copy(out as *any, (self.vals.data + i * self.val_size) as *any, self.val_size);
ret .Found;
}
fn del(self: *Map, key: *u8): LookupResult {
if !valid(self.*) || key == null { ret .NotFound; }
var i = find_slot(self, key);
if i == ~(0 as usize) { ret .NotFound; }
var deleted_state: SlotState = .Deleted;
self.states.data[i] = state_code(deleted_state);
self.size = self.size - 1;
ret .Found;
}
// 清空内容但保留容量。墓碑与负载计数一并复位。
fn clear(self: *Map) {
var i: usize = 0;
var empty: SlotState = .Empty;
while i < self.states.len {
self.states.data[i] = state_code(empty);
i = i + 1;
}
self.size = 0;
}
fn drop(self: *Map) {
Vec.drop(&self.keys);
Vec.drop(&self.vals);
Vec.drop(&self.states);
self.size = 0;
}
fn take(source: *Map): Map {
var result = source.*;
source.keys = Vec.blank(source.key_size, source.keys.elem_align);
source.vals = Vec.blank(source.val_size, source.vals.elem_align);
source.states = Vec.blank(1, 1);
source.size = 0;
ret result;
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected Map error"); },
}
}
fn expect_invalid(result: Status) {
match result {
.Ok => { @assert(false, "expected Map error"); },
.Err(error) => {
match error.kind {
.InvalidArgument => {},
_ => { @assert(false, "unexpected Map error kind"); },
}
},
}
}
fn count_occupied(m: *Map): usize {
var n: usize = 0;
var i: usize = 0;
while i < slot_count(m.*) {
if slot_occupied(slot_state(m.*, i)) { n = n + 1; }
i = i + 1;
}
ret n;
}
fn found(m: *Map, key: *u8, out: *u8): bool {
match get(m, key, out) {
.Found => { ret true; },
.NotFound => { ret false; },
}
ret false;
}
fn deleted(m: *Map, key: *u8): bool {
match del(m, key) {
.Found => { ret true; },
.NotFound => { ret false; },
}
ret false;
}
fn make_int_map(): Map {
ret new(@sizeof(usize), @alignof(usize), @sizeof(i32), @alignof(i32), hash_usize, eq_usize);
}
fn test_put_get_update() {
var m = make_int_map();
@assert(size(m) == 0 && capacity(m) == 0, "empty map");
@assert(valid(m));
var key: usize = 0;
var value: i32 = 0;
var out: i32 = 0;
expect_invalid(put(&m, null, &value as *u8));
expect_invalid(put(&m, &key as *u8, null));
@assert(size(m) == 0, "failed put preserves map");
key = 7;
value = 70;
expect_ok(put(&m, &key as *u8, &value as *u8));
@assert(size(m) == 1 && valid(m));
out = -1;
@assert(found(&m, &key as *u8, &out as *u8) && out == 70, "insert then get");
value = 71;
expect_ok(put(&m, &key as *u8, &value as *u8));
@assert(size(m) == 1, "update does not grow size");
out = -1;
@assert(found(&m, &key as *u8, &out as *u8) && out == 71, "update overwrites");
key = 8;
out = 123;
@assert(!found(&m, &key as *u8, &out as *u8) && out == 123, "missing key preserves out");
// drop 后还有断言,故保持手动释放,不改为 defer。
drop(&m);
@assert(size(m) == 0 && capacity(m) == 0, "drop resets map");
}
fn test_growth_and_delete() {
var m = make_int_map();
defer { drop(&m); }
var i: i32 = 0;
while i < 1000 {
var key: usize = i as usize;
var value: i32 = i * 3 - 7;
expect_ok(put(&m, &key as *u8, &value as *u8));
i = i + 1;
}
@assert(size(m) == 1000);
@assert(count_occupied(&m) == 1000, "all slots accounted");
i = 0;
while i < 1000 {
var key: usize = i as usize;
var out: i32 = 0;
@assert(found(&m, &key as *u8, &out as *u8), "get after growth");
@assert(out == i * 3 - 7, "value after growth");
i = i + 1;
}
i = 0;
while i < 500 {
var key: usize = i as usize;
@assert(deleted(&m, &key as *u8));
i = i + 1;
}
@assert(size(m) == 500 && count_occupied(&m) == 500, "deleted slots not occupied");
i = 0;
while i < 500 {
var key: usize = i as usize;
var out: i32 = 0;
@assert(!found(&m, &key as *u8, &out as *u8), "deleted key missing");
i = i + 1;
}
// 墓碑槽位可被再次插入复用,且不会重复计数。
var key: usize = 12345;
var value: i32 = 99;
expect_ok(put(&m, &key as *u8, &value as *u8));
@assert(size(m) == 501);
var out: i32 = 0;
@assert(found(&m, &key as *u8, &out as *u8) && out == 99, "reuse tombstone");
@assert(deleted(&m, &key as *u8), "delete key");
@assert(size(m) == 500);
@assert(!found(&m, &key as *u8, &out as *u8));
clear(&m);
@assert(size(m) == 0 && count_occupied(&m) == 0, "clear empties");
}
fn test_take_and_self_put() {
var m = make_int_map();
defer { drop(&m); }
var key: usize = 5;
var value: i32 = 55;
expect_ok(put(&m, &key as *u8, &value as *u8));
var moved = take(&m);
defer { drop(&moved); }
@assert(size(m) == 0 && capacity(m) == 0, "take leaves source empty");
var out: i32 = 0;
@assert(found(&moved, &key as *u8, &out as *u8) && out == 55, "moved keeps content");
// 值指针可以指向表内已有的值(按字节移动,允许重叠)。
var alias: i32 = 0;
@assert(found(&moved, &key as *u8, &alias as *u8));
expect_ok(put(&moved, &key as *u8, &alias as *u8));
@assert(found(&moved, &key as *u8, &out as *u8) && out == 55, "self value put");
}
fn test_byte_view_keys() {
var m = new(@sizeof(ByteView), @alignof(ByteView), @sizeof(i32), @alignof(i32),
hash_view, eq_view);
defer { drop(&m); }
var alpha = ByteView.from_slice("alpha");
var beta = ByteView.from_slice("beta");
var gamma = ByteView.from_slice("gamma");
var one: i32 = 1;
var two: i32 = 2;
var three: i32 = 3;
expect_ok(put(&m, &alpha as *u8, &one as *u8));
expect_ok(put(&m, &beta as *u8, &two as *u8));
expect_ok(put(&m, &gamma as *u8, &three as *u8));
@assert(size(m) == 3);
var out: i32 = 0;
@assert(found(&m, &alpha as *u8, &out as *u8) && out == 1, "alpha");
@assert(found(&m, &beta as *u8, &out as *u8) && out == 2, "beta");
@assert(found(&m, &gamma as *u8, &out as *u8) && out == 3, "gamma");
// 内容相同的不同 ByteView 视为同一个键。
var alpha2 = ByteView.from_slice("alpha");
out = 0;
@assert(found(&m, &alpha2 as *u8, &out as *u8) && out == 1, "equal content key");
@assert(size(m) == 3, "equal content does not insert");
@assert(deleted(&m, &beta as *u8), "delete beta");
@assert(size(m) == 2);
@assert(!found(&m, &beta as *u8, &out as *u8));
}
fn main() {
test_put_get_update();
test_growth_and_delete();
test_take_and_self_put();
test_byte_view_keys();
}
+260
View File
@@ -0,0 +1,260 @@
// Expect retcode = 0
// 尺寸计算和字节移动;不分配、不释放内存,不改变任何资源的所有权。
type .{ .Error, .Status, .make } = @import("error.spl");
type SizeResult = enum {
Ok: usize,
Err: Error,
}
fn checked_add(a: usize, b: usize): SizeResult {
var limit: usize = ~(0 as usize);
if b > limit - a { ret .Err(make(.Overflow)); }
ret .Ok(a + b);
}
fn checked_mul(a: usize, b: usize): SizeResult {
if a == 0 { ret .Ok(0); }
var limit: usize = ~(0 as usize);
if b > limit / a { ret .Err(make(.Overflow)); }
ret .Ok(a * b);
}
// alignment 必须是非零的二次幂。已对齐的值保持不变。
fn align_up(size: usize, alignment: usize): SizeResult {
if alignment == 0 { ret .Err(make(.InvalidAlignment)); }
var mask = alignment - 1;
if (alignment & mask) != 0 { ret .Err(make(.InvalidAlignment)); }
var limit: usize = ~(0 as usize);
if size > limit - mask { ret .Err(make(.Overflow)); }
ret .Ok((size + mask) & ~mask);
}
// 计算至少 need 的容量:从 current 起(不低于 min_cap)按倍增增长;
// 无法再倍增(会溢出)时直接取 need。need 可表示时不溢出。
fn grow_capacity(current: usize, min_cap: usize, need: usize): usize {
var cap = current;
if cap < min_cap { cap = min_cap; }
var limit: usize = ~(0 as usize);
while cap < need {
if cap > limit / 2 {
cap = need;
break;
}
cap = cap * 2;
}
ret cap;
}
// 将 src.len 个字节复制到 dst 的开头,允许两个切片任意重叠。
// 零长度源不访问内存,允许空指针。所有可恢复错误均在首次写入前返回。
// 非空源要求可读,目标前 src.len 字节要求可写,生命周期由调用方保证。
// 长度和地址计算检查不能证明底层分配大小,也不能识别悬空指针。
fn move(dst: []u8, src: []u8): Status {
var count = src.len;
if count == 0 { ret .Ok; }
if dst.len < count { ret .Err(make(.OutOfRange)); }
if dst.ptr == null || src.ptr == null {
ret .Err(make(.InvalidArgument));
}
var dst_addr = dst.ptr as usize;
var src_addr = src.ptr as usize;
var limit: usize = ~(0 as usize);
var last_offset = count - 1;
if last_offset > limit - dst_addr || last_offset > limit - src_addr {
ret .Err(make(.Overflow));
}
if dst_addr == src_addr { ret .Ok; }
if dst_addr < src_addr {
var i: usize = 0;
while i < count {
dst.ptr[i] = src.ptr[i];
i = i + 1;
}
} else {
var i = count;
while i > 0 {
i = i - 1;
dst.ptr[i] = src.ptr[i];
}
}
ret .Ok;
}
fn expect_size(result: SizeResult, expected: usize) {
match result {
.Ok(value) => { @assert(value == expected, "checked size result"); },
.Err(error) => { @assert(false, "unexpected size error"); },
}
}
fn expect_overflow(result: SizeResult) {
match result {
.Ok(value) => { @assert(false, "expected overflow"); },
.Err(error) => {
match error.kind {
.Overflow => {},
_ => { @assert(false, "expected overflow kind"); },
}
},
}
}
fn expect_alignment_error(result: SizeResult) {
match result {
.Ok(value) => { @assert(false, "expected invalid alignment"); },
.Err(error) => {
match error.kind {
.InvalidAlignment => {},
_ => { @assert(false, "expected invalid alignment kind"); },
}
},
}
}
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected move error"); },
}
}
fn expect_invalid_move(result: Status) {
match result {
.Ok => { @assert(false, "expected invalid pointer"); },
.Err(error) => {
match error.kind {
.InvalidArgument => {},
_ => { @assert(false, "expected invalid argument kind"); },
}
},
}
}
fn expect_move_overflow(result: Status) {
match result {
.Ok => { @assert(false, "expected address overflow"); },
.Err(error) => {
match error.kind {
.Overflow => {},
_ => { @assert(false, "expected address overflow kind"); },
}
},
}
}
fn test_sizes() {
var limit: usize = ~(0 as usize);
expect_size(checked_add(0, 0), 0);
expect_size(checked_add(17, 25), 42);
expect_size(checked_add(limit, 0), limit);
expect_size(checked_add(limit - 1, 1), limit);
expect_overflow(checked_add(limit, 1));
expect_overflow(checked_add(1, limit));
expect_size(checked_mul(6, 7), 42);
expect_size(checked_mul(0, limit), 0);
expect_size(checked_mul(limit, 0), 0);
expect_size(checked_mul(limit, 1), limit);
expect_size(checked_mul(limit / 2, 2), limit - 1);
expect_overflow(checked_mul(limit / 2 + 1, 2));
expect_overflow(checked_mul(limit, limit));
expect_size(align_up(0, 8), 0);
expect_size(align_up(1, 8), 8);
expect_size(align_up(8, 8), 8);
expect_size(align_up(9, 8), 16);
expect_size(align_up(limit, 1), limit);
expect_size(align_up(limit - 7, 8), limit - 7);
expect_overflow(align_up(limit - 6, 8));
expect_overflow(align_up(limit, 2));
expect_alignment_error(align_up(0, 0));
expect_alignment_error(align_up(0, 3));
expect_alignment_error(align_up(7, 6));
var highest_power = limit / 2 + 1;
expect_size(align_up(0, highest_power), 0);
expect_size(align_up(1, highest_power), highest_power);
expect_size(align_up(highest_power, highest_power), highest_power);
expect_overflow(align_up(highest_power + 1, highest_power));
@assert(grow_capacity(0, 8, 0) == 8, "grow respects minimum");
@assert(grow_capacity(0, 8, 5) == 8, "grow minimum covers need");
@assert(grow_capacity(8, 8, 9) == 16, "grow doubles");
@assert(grow_capacity(8, 8, 100) == 128, "grow repeats");
@assert(grow_capacity(limit / 2, 8, limit) == limit, "grow exact to limit");
@assert(grow_capacity(limit / 2 + 1, 8, limit) == limit, "grow clamps to need");
}
// 穷举同一 8 字节数组内的所有合法源、目标和长度组合。
// expected 从原始字节值建立快照,不使用被测 move 构造期望值。
fn test_overlap() {
var src_start: usize = 0;
while src_start <= 8 {
var dst_start: usize = 0;
while dst_start <= 8 {
var count: usize = 0;
while count <= 8 - src_start && count <= 8 - dst_start {
var data: [8]u8 = .[0, 1, 2, 3, 4, 5, 6, 7];
var expected: [8]u8 = .[0, 1, 2, 3, 4, 5, 6, 7];
var i: usize = 0;
while i < count {
expected[dst_start + i] = (src_start + i) as u8;
i = i + 1;
}
expect_ok(move(data[dst_start..8], data[src_start..src_start + count]));
i = 0;
while i < 8 {
@assert(data[i] == expected[i], "overlap and surrounding bytes");
i = i + 1;
}
count = count + 1;
}
dst_start = dst_start + 1;
}
src_start = src_start + 1;
}
}
fn test_move_errors() {
var data: [4]u8 = .[10, 20, 30, 40];
var empty: []u8 = .{ .ptr = null, .len = 0 };
expect_ok(move(empty, empty));
expect_ok(move(data[0..4], empty));
match move(data[0..1], data[2..4]) {
.Ok => { @assert(false, "expected short destination"); },
.Err(error) => {
match error.kind {
.OutOfRange => {},
_ => { @assert(false, "expected out of range kind"); },
}
},
}
var invalid: []u8 = .{ .ptr = null, .len = 2 };
expect_invalid_move(move(data[0..4], invalid));
expect_invalid_move(move(invalid, data[0..2]));
// 伪造仅用于验证拒绝路径的地址,必须在任何解引用之前报告错误。
var limit: usize = ~(0 as usize);
var overflowing: []u8 = .{ .ptr = limit as *u8, .len = 2 };
expect_move_overflow(move(data[0..4], overflowing));
expect_move_overflow(move(overflowing, data[0..2]));
expect_move_overflow(move(overflowing, overflowing));
@assert(data[0] == 10, "failure preserves destination byte 0");
@assert(data[1] == 20, "failure preserves destination byte 1");
@assert(data[2] == 30, "failure preserves destination byte 2");
@assert(data[3] == 40, "failure preserves destination byte 3");
}
fn main() {
test_sizes();
test_overlap();
test_move_errors();
}
+1643
View File
File diff suppressed because it is too large. Load diff
+400
View File
@@ -0,0 +1,400 @@
// Expect retcode = 0
// 纯词法路径工具,不访问文件系统。调用方必须显式选择 POSIX 或 Windows 规则;
// 输入视图均为借用,拥有型结果写入 ByteBuffer,失败保持原输出不变。
type .{ .Status, .make } = @import("error.spl");
type .{ .ByteView } = @import("byte_view.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
type .{ .Vec } = @import("vec.spl");
type .{ .is_alpha } = @import("ascii.spl");
type PathStyle = enum { Posix, Windows }
fn is_windows(style: PathStyle): bool {
match style { .Posix => { ret false; }, .Windows => { ret true; }, }
ret false;
}
fn separator(style: PathStyle): u8 {
if is_windows(style) { ret '\\'; }
ret '/';
}
fn is_sep(style: PathStyle, byte: u8): bool {
if is_windows(style) { ret byte == '/' || byte == '\\'; }
ret byte == '/';
}
fn is_drive_prefix(path: ByteView): bool {
ret path.len >= 2 && is_alpha(path.ptr[0]) && path.ptr[1] == ':';
}
fn is_unc(path: ByteView, style: PathStyle): bool {
ret is_windows(style) && path.len >= 2 &&
is_sep(style, path.ptr[0]) && is_sep(style, path.ptr[1]);
}
fn is_absolute(path: ByteView, style: PathStyle): bool {
if path.len == 0 { ret false; }
if !is_windows(style) { ret path.ptr[0] == '/'; }
if is_unc(path, style) { ret true; }
if is_drive_prefix(path) {
ret path.len >= 3 && is_sep(style, path.ptr[2]);
}
// 根相对路径以当前盘符为根,本模块将其视为绝对。
ret is_sep(style, path.ptr[0]);
}
// UNC 根长度不含共享名后的分隔符;不完整时返回 0。
fn unc_root_len(path: ByteView, style: PathStyle): usize {
if !is_unc(path, style) { ret 0; }
var i: usize = 2;
while i < path.len && is_sep(style, path.ptr[i]) { i = i + 1; }
var server = i;
while i < path.len && !is_sep(style, path.ptr[i]) { i = i + 1; }
if i == server { ret 0; }
while i < path.len && is_sep(style, path.ptr[i]) { i = i + 1; }
var share = i;
while i < path.len && !is_sep(style, path.ptr[i]) { i = i + 1; }
if i == share { ret 0; }
ret i;
}
fn root_len(path: ByteView, style: PathStyle): usize {
if path.len == 0 { ret 0; }
if !is_windows(style) {
if path.ptr[0] == '/' { ret 1; }
ret 0;
}
var unc = unc_root_len(path, style);
if unc != 0 { ret unc; }
if is_drive_prefix(path) {
if path.len >= 3 && is_sep(style, path.ptr[2]) { ret 3; }
ret 2;
}
if is_sep(style, path.ptr[0]) { ret 1; }
ret 0;
}
fn last_sep(path: ByteView, style: PathStyle): usize {
var i = path.len;
while i > 0 {
i = i - 1;
if is_sep(style, path.ptr[i]) { ret i; }
}
ret ~(0 as usize);
}
fn slice_or_empty(path: ByteView, start: usize, end: usize): ByteView {
match ByteView.slice(path, start, end) {
.Ok(value) => { ret value; },
.Err(error) => { ret ByteView.empty(); },
}
ret ByteView.empty();
}
fn dirname(path: ByteView, style: PathStyle): ByteView {
var root = root_len(path, style);
if root != 0 && path.len == root { ret path; }
var index = last_sep(path, style);
if index == ~(0 as usize) {
if is_windows(style) && is_drive_prefix(path) {
ret slice_or_empty(path, 0, 2);
}
ret ByteView.empty();
}
if root != 0 && index <= root { ret slice_or_empty(path, 0, root); }
if index == 0 { ret slice_or_empty(path, 0, 1); }
ret slice_or_empty(path, 0, index);
}
fn basename(path: ByteView, style: PathStyle): ByteView {
var root = root_len(path, style);
if root != 0 && path.len == root { ret ByteView.empty(); }
var index = last_sep(path, style);
if index == ~(0 as usize) {
if is_windows(style) && is_drive_prefix(path) {
ret slice_or_empty(path, 2, path.len);
}
ret path;
}
ret slice_or_empty(path, index + 1, path.len);
}
fn extension(path: ByteView, style: PathStyle): ByteView {
var base = basename(path, style);
var i = base.len;
while i > 0 {
i = i - 1;
if base.ptr[i] == '.' {
if i == 0 { ret ByteView.empty(); }
ret slice_or_empty(base, i + 1, base.len);
}
}
ret ByteView.empty();
}
// Windows 盘符相对路径依赖进程的盘符工作目录,join 明确拒绝该歧义。
fn join_into(out: *ByteBuffer, dir: ByteView,
rel: ByteView, style: PathStyle): Status {
if out == null { ret .Err(make(.InvalidArgument)); }
var fresh = ByteBuffer.new();
if is_absolute(rel, style) {
match ByteBuffer.append(&fresh, ByteView.as_slice(rel)) {
.Ok => {}, .Err(error) => { ByteBuffer.drop(&fresh); ret .Err(error); },
}
ByteBuffer.drop(out);
out.* = ByteBuffer.take(&fresh);
ret .Ok;
}
if is_windows(style) && is_drive_prefix(rel) {
ByteBuffer.drop(&fresh);
ret .Err(make(.InvalidArgument));
}
match ByteBuffer.append(&fresh, ByteView.as_slice(dir)) {
.Ok => {}, .Err(error) => { ByteBuffer.drop(&fresh); ret .Err(error); },
}
var drive_relative_base = is_windows(style) && dir.len == 2 && is_drive_prefix(dir);
if dir.len != 0 && !is_sep(style, dir.ptr[dir.len - 1]) && rel.len != 0 &&
!drive_relative_base {
match ByteBuffer.append_byte(&fresh, separator(style)) {
.Ok => {}, .Err(error) => { ByteBuffer.drop(&fresh); ret .Err(error); },
}
}
match ByteBuffer.append(&fresh, ByteView.as_slice(rel)) {
.Ok => {}, .Err(error) => { ByteBuffer.drop(&fresh); ret .Err(error); },
}
ByteBuffer.drop(out);
out.* = ByteBuffer.take(&fresh);
ret .Ok;
}
fn segment_is_parent(buffer: ByteBuffer, rollback: usize, style: PathStyle): bool {
var start = rollback;
if start < buffer.storage.len && is_sep(style, buffer.storage.data[start]) {
start = start + 1;
}
ret buffer.storage.len - start == 2 &&
buffer.storage.data[start] == '.' && buffer.storage.data[start + 1] == '.';
}
fn append_segment(out: *ByteBuffer, starts: *Vec,
segment: ByteView, style: PathStyle): Status {
var rollback = out.storage.len;
if rollback != 0 && !is_sep(style, out.storage.data[rollback - 1]) &&
!(is_windows(style) && out.storage.data[rollback - 1] == ':') {
match ByteBuffer.append_byte(out, separator(style)) {
.Ok => {}, .Err(error) => { ret .Err(error); },
}
}
match Vec.push(starts, &rollback as *u8) {
.Ok => {},
.Err(error) => { out.storage.len = rollback; ret .Err(error); },
}
match ByteBuffer.append(out, ByteView.as_slice(segment)) {
.Ok => {},
.Err(error) => {
starts.len = starts.len - 1;
out.storage.len = rollback;
ret .Err(error);
},
}
ret .Ok;
}
// 规范化分隔符并折叠 '.'/'..'。相对路径无法消去的前导 '..' 会被保留;
// 绝对路径的 '..' 不会越过根,UNC 的 server/share 也不可被消去。
fn normalize_into(out: *ByteBuffer, path: ByteView, style: PathStyle): Status {
if out == null { ret .Err(make(.InvalidArgument)); }
var fresh = ByteBuffer.new();
var starts = Vec.blank(@sizeof(usize), @alignof(usize));
var i: usize = 0;
var absolute = false;
var protected: usize = 0;
if path.len != 0 {
if !is_windows(style) && path.ptr[0] == '/' {
absolute = true;
match ByteBuffer.append_byte(&fresh, '/') {
.Ok => {}, .Err(error) => { Vec.drop(&starts); ByteBuffer.drop(&fresh); ret .Err(error); },
}
while i < path.len && is_sep(style, path.ptr[i]) { i = i + 1; }
} else if is_unc(path, style) {
absolute = true;
protected = 2;
match ByteBuffer.append(&fresh, "\\\\") {
.Ok => {}, .Err(error) => { Vec.drop(&starts); ByteBuffer.drop(&fresh); ret .Err(error); },
}
i = 2;
while i < path.len && is_sep(style, path.ptr[i]) { i = i + 1; }
} else if is_windows(style) && is_drive_prefix(path) {
match ByteBuffer.append(&fresh, path.ptr[0..2]) {
.Ok => {}, .Err(error) => { Vec.drop(&starts); ByteBuffer.drop(&fresh); ret .Err(error); },
}
i = 2;
if i < path.len && is_sep(style, path.ptr[i]) {
absolute = true;
match ByteBuffer.append_byte(&fresh, '\\') {
.Ok => {}, .Err(error) => { Vec.drop(&starts); ByteBuffer.drop(&fresh); ret .Err(error); },
}
while i < path.len && is_sep(style, path.ptr[i]) { i = i + 1; }
}
} else if is_windows(style) && is_sep(style, path.ptr[0]) {
absolute = true;
match ByteBuffer.append_byte(&fresh, '\\') {
.Ok => {}, .Err(error) => { Vec.drop(&starts); ByteBuffer.drop(&fresh); ret .Err(error); },
}
while i < path.len && is_sep(style, path.ptr[i]) { i = i + 1; }
}
}
while i < path.len {
while i < path.len && is_sep(style, path.ptr[i]) { i = i + 1; }
if i >= path.len { break; }
var begin = i;
while i < path.len && !is_sep(style, path.ptr[i]) { i = i + 1; }
var segment = slice_or_empty(path, begin, i);
if ByteView.eq(segment, ByteView.from_slice(".")) {
if protected != 0 && starts.len < protected {
Vec.drop(&starts); ByteBuffer.drop(&fresh);
ret .Err(make(.InvalidArgument));
}
continue;
}
if ByteView.eq(segment, ByteView.from_slice("..")) {
if protected != 0 && starts.len < protected {
Vec.drop(&starts); ByteBuffer.drop(&fresh);
ret .Err(make(.InvalidArgument));
}
if starts.len > protected {
var last: usize = 0;
match Vec.get(&starts, starts.len - 1) {
.Ok(ptr) => { last = (ptr as *usize).*; },
.Err(error) => { Vec.drop(&starts); ByteBuffer.drop(&fresh); ret .Err(error); },
}
if !segment_is_parent(fresh, last, style) {
fresh.storage.len = last;
starts.len = starts.len - 1;
continue;
}
}
if absolute { continue; }
}
match append_segment(&fresh, &starts, segment, style) {
.Ok => {}, .Err(error) => { Vec.drop(&starts); ByteBuffer.drop(&fresh); ret .Err(error); },
}
}
if protected != 0 && starts.len < protected {
Vec.drop(&starts); ByteBuffer.drop(&fresh);
ret .Err(make(.InvalidArgument));
}
Vec.drop(&starts);
ByteBuffer.drop(out);
out.* = ByteBuffer.take(&fresh);
ret .Ok;
}
// ---- 测试 ----
fn expect_ok(result: Status) {
match result { .Ok => {}, .Err(error) => { @assert(false, "unexpected path error"); }, }
}
fn expect_invalid(result: Status) {
match result {
.Ok => { @assert(false, "expected invalid path"); },
.Err(error) => {
match error.kind { .InvalidArgument => {}, _ => { @assert(false); }, }
},
}
}
fn view(text: []u8): ByteView { ret ByteView.from_slice(text); }
fn expect_view(got: ByteView, expected: []u8) {
@assert(ByteView.eq(got, view(expected)), "path view");
}
fn expect_out(out: *ByteBuffer, expected: []u8) {
var actual = ByteBuffer.as_slice(out.*);
@assert(actual.len == expected.len, "path output length");
var i: usize = 0;
while i < expected.len {
@assert(actual.ptr[i] == expected.ptr[i], "path output byte");
i = i + 1;
}
}
fn test_style_and_parts() {
@assert(is_absolute(view("/a"), .Posix));
@assert(!is_absolute(view("\\a"), .Posix));
@assert(is_absolute(view("C:\\a"), .Windows));
@assert(!is_absolute(view("C:a"), .Windows));
@assert(is_absolute(view("\\\\server\\share\\a"), .Windows));
@assert(!is_absolute(view("C:/a"), .Posix));
expect_view(dirname(view("/a/b"), .Posix), "/a");
expect_view(dirname(view("/a"), .Posix), "/");
expect_view(basename(view("/a/b"), .Posix), "b");
expect_view(extension(view("a/b.spl"), .Posix), "spl");
expect_view(extension(view("a/.hidden"), .Posix), "");
expect_view(dirname(view("C:\\a"), .Windows), "C:\\");
expect_view(basename(view("C:\\a"), .Windows), "a");
expect_view(dirname(view("C:relative"), .Windows), "C:");
expect_view(basename(view("C:relative"), .Windows), "relative");
expect_view(dirname(view("\\\\server\\share\\file"), .Windows),
"\\\\server\\share");
}
fn test_join() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
expect_ok(join_into(&out, view("stage2/utils"), view("vec.spl"), .Posix));
expect_out(&out, "stage2/utils/vec.spl");
expect_ok(join_into(&out, view("C:\\base"), view("child\\x"), .Windows));
expect_out(&out, "C:\\base\\child\\x");
expect_ok(join_into(&out, view("C:"), view("child"), .Windows));
expect_out(&out, "C:child");
expect_ok(join_into(&out, view("ignored"), view("D:/abs"), .Windows));
expect_out(&out, "D:/abs");
expect_invalid(join_into(&out, view("C:\\base"), view("D:relative"), .Windows));
expect_out(&out, "D:/abs");
}
fn test_normalize_posix() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
expect_ok(normalize_into(&out, view("a/b/../c"), .Posix));
expect_out(&out, "a/c");
expect_ok(normalize_into(&out, view("../../a/./b"), .Posix));
expect_out(&out, "../../a/b");
expect_ok(normalize_into(&out, view("/../../a//b"), .Posix));
expect_out(&out, "/a/b");
expect_ok(normalize_into(&out, view("a\\b/../c"), .Posix));
expect_out(&out, "c");
}
fn test_normalize_windows() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
expect_ok(normalize_into(&out, view("C:/a\\b/../c"), .Windows));
expect_out(&out, "C:\\a\\c");
expect_ok(normalize_into(&out, view("C:foo\\..\\bar"), .Windows));
expect_out(&out, "C:bar");
expect_ok(normalize_into(&out, view("\\root\\..\\file"), .Windows));
expect_out(&out, "\\file");
expect_ok(normalize_into(&out,
view("\\\\server\\share\\a\\..\\file"), .Windows));
expect_out(&out, "\\\\server\\share\\file");
expect_ok(ByteBuffer.assign(&out, "preserved"));
expect_invalid(normalize_into(&out, view("\\\\server\\..\\file"), .Windows));
expect_out(&out, "preserved");
}
fn main() {
test_style_and_parts();
test_join();
test_normalize_posix();
test_normalize_windows();
}
+235
View File
@@ -0,0 +1,235 @@
// Expect retcode = 0
// 开放寻址集合。键按字节复制到集合自己的存储中;集合只释放自身存储,
// 不释放键值内部引用的资源。哈希与相等回调的约定和 Map 一致。
type .{ .Status } = @import("error.spl");
type .{ .Map, .LookupResult } = @import("map.spl");
type .{ .ByteView } = @import("byte_view.spl");
type .{ .hash_usize, .eq_usize, .hash_view, .eq_view } = @import("hash.spl");
type Set = @self;
map: Map,
fn new(key_size: usize, key_align: usize,
hash_fn: fn(*u8): usize, eq_fn: fn(*u8, *u8): bool): Set {
ret Set {
.map = Map.new(key_size, key_align, 1, 1, hash_fn, eq_fn),
};
}
fn valid(self: Set): bool {
ret Map.valid(self.map) && self.map.val_size == 1;
}
fn size(self: Set): usize {
ret self.map.size;
}
fn capacity(self: Set): usize {
ret self.map.states.cap;
}
fn reserve(self: *Set, need: usize): Status {
ret Map.reserve(&self.map, need);
}
// 重复插入保持集合大小不变。
fn insert(self: *Set, key: *u8): Status {
var marker: u8 = 1;
ret Map.put(&self.map, key, &marker);
}
fn find(self: *Set, key: *u8): LookupResult {
var marker: u8 = 0;
ret Map.get(&self.map, key, &marker);
}
fn remove(self: *Set, key: *u8): LookupResult {
ret Map.del(&self.map, key);
}
// 遍历 [0, slot_count);仅 slot_occupied 为真时 key_at 有效。
fn slot_count(self: Set): usize {
ret Map.slot_count(self.map);
}
fn slot_occupied(self: Set, index: usize): bool {
ret Map.slot_occupied(Map.slot_state(self.map, index));
}
fn key_at(self: *Set, index: usize): *u8 {
ret Map.key_at(&self.map, index);
}
fn clear(self: *Set) {
Map.clear(&self.map);
}
fn take(source: *Set): Set {
ret Set { .map = Map.take(&source.map) };
}
fn drop(self: *Set) {
Map.drop(&self.map);
}
// ---- 测试 ----
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected Set error"); },
}
}
fn found(set: *Set, key: *u8): bool {
match find(set, key) {
.Found => { ret true; },
.NotFound => { ret false; },
}
ret false;
}
fn removed(set: *Set, key: *u8): bool {
match remove(set, key) {
.Found => { ret true; },
.NotFound => { ret false; },
}
ret false;
}
fn constant_hash(key: *u8): usize {
ret 3;
}
fn test_insert_find_remove() {
var set = new(@sizeof(usize), @alignof(usize), hash_usize, eq_usize);
defer { drop(&set); }
@assert(valid(set));
@assert(size(set) == 0 && capacity(set) == 0);
var i: usize = 0;
while i < 1000 {
expect_ok(insert(&set, &i as *u8));
i = i + 1;
}
@assert(size(set) == 1000, "all unique keys inserted");
i = 0;
while i < 1000 {
@assert(found(&set, &i as *u8), "key survives growth");
i = i + 1;
}
// 重复键不增加 size。
i = 0;
while i < 1000 {
expect_ok(insert(&set, &i as *u8));
i = i + 1;
}
@assert(size(set) == 1000, "duplicate insertion is idempotent");
i = 0;
while i < 1000 {
if i % 2 == 0 { @assert(removed(&set, &i as *u8)); }
i = i + 1;
}
@assert(size(set) == 500);
i = 0;
while i < 1000 {
@assert(found(&set, &i as *u8) == (i % 2 != 0), "removed membership");
i = i + 1;
}
i = 0;
while i < 1000 {
if i % 2 == 0 { expect_ok(insert(&set, &i as *u8)); }
i = i + 1;
}
@assert(size(set) == 1000, "removed keys can be reinserted");
var occupied: usize = 0;
i = 0;
while i < slot_count(set) {
if slot_occupied(set, i) {
var key = (key_at(&set, i) as *usize).*;
@assert(key < 1000, "iteration yields stored key");
occupied = occupied + 1;
}
i = i + 1;
}
@assert(occupied == size(set), "iteration visits each member once");
var missing: usize = 2000;
@assert(!removed(&set, &missing as *u8));
clear(&set);
@assert(size(set) == 0 && capacity(set) != 0, "clear retains allocation");
}
fn test_collisions_and_take() {
var set = new(@sizeof(usize), @alignof(usize), constant_hash, eq_usize);
defer { drop(&set); }
var i: usize = 0;
while i < 64 {
expect_ok(insert(&set, &i as *u8));
i = i + 1;
}
i = 0;
while i < 64 {
@assert(found(&set, &i as *u8), "collision chain lookup");
i = i + 1;
}
// 删除整条碰撞链后重新插入,验证墓碑会被复用且探测会终止。
i = 0;
while i < 64 {
@assert(removed(&set, &i as *u8));
i = i + 1;
}
@assert(size(set) == 0);
i = 64;
while i < 128 {
expect_ok(insert(&set, &i as *u8));
i = i + 1;
}
i = 64;
while i < 128 {
@assert(found(&set, &i as *u8), "tombstone collision chain reuse");
i = i + 1;
}
var moved = take(&set);
defer { drop(&moved); }
@assert(size(set) == 0 && capacity(set) == 0, "take clears source");
@assert(size(moved) == 64, "take preserves members");
i = 64;
while i < 128 {
@assert(found(&moved, &i as *u8));
i = i + 1;
}
}
fn test_byte_view_keys() {
var set = new(@sizeof(ByteView), @alignof(ByteView), hash_view, eq_view);
defer { drop(&set); }
var alpha = ByteView.from_slice("alpha");
var alpha_copy = ByteView.from_slice("alpha");
var beta = ByteView.from_slice("beta");
expect_ok(insert(&set, &alpha as *u8));
expect_ok(insert(&set, &alpha_copy as *u8));
expect_ok(insert(&set, &beta as *u8));
@assert(size(set) == 2, "ByteView keys compare by content");
@assert(found(&set, &alpha_copy as *u8));
@assert(removed(&set, &alpha_copy as *u8));
@assert(!found(&set, &alpha as *u8));
}
fn main() {
test_insert_find_remove();
test_collisions_and_take();
test_byte_view_keys();
}
+261
View File
@@ -0,0 +1,261 @@
// Expect retcode = 0
// 源文件与位置映射:fname + text 借用调用方存储;行起始表由 Source 拥有。
// 提供字节偏移 <-> (行,列)(行列均为 1-based、按字节计),以及取整行文本。
// Sources 是按 fname 索引的多文件集合。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .ByteView, .FindResult } = @import("byte_view.spl");
type .{ .Vec } = @import("vec.spl");
type .{ .Map } = @import("map.spl");
type .{ .hash_view, .eq_view } = @import("hash.spl");
type Position = struct {
line: usize, // 1-based
col: usize, // 1-based,按字节
}
type Source = @self;
fname: ByteView, // 借用
text: ByteView, // 借用
line_starts: Vec, // usize:每行起始字节偏移(含首行 0)
type SourceResult = enum {
Ok: Source,
Err: Error,
}
type AddResult = enum {
Ok: usize,
Err: Error,
}
fn blank(): Source {
ret Source {
.fname = ByteView.empty(),
.text = ByteView.empty(),
.line_starts = Vec.blank(@sizeof(usize), 8),
};
}
fn new(fname: ByteView, text: ByteView): SourceResult {
var starts = Vec.blank(@sizeof(usize), 8);
var zero: usize = 0;
match Vec.push(&starts, &zero as *u8) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
var i: usize = 0;
while i < text.len {
if text.ptr[i] == '\n' {
var next = i + 1;
match Vec.push(&starts, &next as *u8) {
.Ok => {},
.Err(error) => { Vec.drop(&starts); ret .Err(error); },
}
}
i = i + 1;
}
ret .Ok(Source { .fname = fname, .text = text, .line_starts = starts });
}
fn line_count(self: Source): usize {
ret self.line_starts.len;
}
fn line_start_offset(self: Source, line: usize): usize {
if line == 0 || line > self.line_starts.len { ret ~(0 as usize); }
match Vec.get(&self.line_starts, line - 1) {
.Ok(ptr) => { ret (ptr as *usize).*; },
.Err(error) => { ret ~(0 as usize); },
}
ret ~(0 as usize);
}
// offset 所在行(0-based);超出范围夹到末行。
fn line_index_at(self: Source, offset: usize): usize {
var off = offset;
if off > self.text.len { off = self.text.len; }
var lo: usize = 0;
var hi: usize = self.line_starts.len;
while lo + 1 < hi {
var mid = (lo + hi) / 2;
var start = line_start_offset(self, mid + 1); // 1-based -> 内部
if start != ~(0 as usize) && start <= off { lo = mid; } else { hi = mid; }
}
ret lo;
}
fn line_col(self: Source, offset: usize): Position {
var off = offset;
if off > self.text.len { off = self.text.len; }
var line0 = line_index_at(self, off);
var start = line_start_offset(self, line0 + 1); // 1-based
if start == ~(0 as usize) { start = 0; }
ret Position { .line = line0 + 1, .col = off - start + 1 };
}
// line 为 1-based;返回整行(去掉行尾 '\n' 与 '\r')。
fn line_text(self: Source, line: usize): ByteView {
var n = self.line_starts.len;
if line == 0 || line > n { ret ByteView.empty(); }
var start = line_start_offset(self, line);
if start == ~(0 as usize) { ret ByteView.empty(); }
var end = self.text.len;
if line < n {
var next = line_start_offset(self, line + 1);
if next != ~(0 as usize) { end = next; }
}
while end > start && (self.text.ptr[end - 1] == '\n' || self.text.ptr[end - 1] == '\r') {
end = end - 1;
}
var r = ByteView.slice(self.text, start, end);
match r {
.Ok(v) => { ret v; },
.Err(error) => { ret ByteView.empty(); },
}
ret ByteView.empty();
}
fn drop(self: *Source) {
Vec.drop(&self.line_starts);
}
// ---- 多文件集合 ----
type Sources = struct {
items: Vec, // Source
by_name: Map, // ByteView(fname) -> usize
}
fn set_new(): Sources {
ret Sources {
.items = Vec.blank(@sizeof(Source), 8),
.by_name = Map.blank(@sizeof(ByteView), @alignof(ByteView), @sizeof(usize),
@alignof(usize), hash_view, eq_view),
};
}
fn set_add(set: *Sources, fname: ByteView, text: ByteView): AddResult {
var src = new(fname, text);
var s = blank();
match src {
.Ok(v) => { s = v; },
.Err(error) => { ret .Err(error); },
}
var index = set.items.len;
match Vec.push(&set.items, &s as *u8) {
.Ok => {},
.Err(error) => { drop(&s); ret .Err(error); },
}
match Map.put(&set.by_name, &fname as *u8, &index as *u8) {
.Ok => {},
.Err(error) => {
// 回滚最后一项
set.items.len = index;
drop(&s);
ret .Err(error);
},
}
ret .Ok(index);
}
fn set_at(set: *Sources, index: usize): *Source {
match Vec.get(&set.items, index) {
.Ok(ptr) => { ret ptr as *Source; },
.Err(error) => { ret null; },
}
ret null;
}
fn set_find(set: *Sources, fname: ByteView): FindResult {
var out: usize = 0;
match Map.get(&set.by_name, &fname as *u8, &out as *u8) {
.Found => { ret .Found(out); },
.NotFound => {},
}
ret .NotFound;
}
fn set_drop(set: *Sources) {
var i: usize = 0;
while i < set.items.len {
var s = set_at(set, i);
if s != null { drop(s); }
i = i + 1;
}
Vec.drop(&set.items);
Map.drop(&set.by_name);
}
// ---- 测试辅助 ----
fn view(text: []u8): ByteView {
ret ByteView.from_slice(text);
}
fn test_single() {
var text = "line1\nline2\n\nline4";
var r = new(view("a.spl"), view(text));
var src = blank();
match r {
.Ok(v) => { src = v; },
.Err(error) => { @assert(false, "source new"); },
}
@assert(line_count(src) == 4, "line count");
var p0 = line_col(src, 0);
@assert(p0.line == 1 && p0.col == 1, "start");
var p6 = line_col(src, 6);
@assert(p6.line == 2 && p6.col == 1, "line2 start");
var p8 = line_col(src, 8);
@assert(p8.line == 2 && p8.col == 3, "line2 col3");
var p12 = line_col(src, 12);
@assert(p12.line == 3 && p12.col == 1, "empty line3");
var p13 = line_col(src, 13);
@assert(p13.line == 4 && p13.col == 1, "line4 start");
var p18 = line_col(src, 18);
@assert(p18.line == 4 && p18.col == 6, "past end clamps");
var l1 = line_text(src, 1);
var l3 = line_text(src, 3);
var l4 = line_text(src, 4);
@assert(ByteView.eq(l1, view("line1")), "line1");
@assert(ByteView.eq(l3, view("")), "line3 empty");
@assert(ByteView.eq(l4, view("line4")), "line4");
drop(&src);
}
fn test_sources() {
var set = set_new();
var r1 = set_add(&set, view("a.spl"), view("x\ny"));
var r2 = set_add(&set, view("b.spl"), view("z"));
var a: usize = 0;
var b: usize = 0;
match r1 { .Ok(v) => { a = v; }, .Err(e) => { @assert(false, "add a"); } }
match r2 { .Ok(v) => { b = v; }, .Err(e) => { @assert(false, "add b"); } }
@assert(a == 0 && b == 1, "indices");
match set_find(&set, view("b.spl")) {
.Found(i) => { @assert(i == 1, "find b"); },
.NotFound => { @assert(false, "b missing"); },
}
match set_find(&set, view("c.spl")) {
.Found(i) => { @assert(false, "c unexpected"); },
.NotFound => {},
}
var sb = set_at(&set, b);
@assert(sb != null && line_count(sb.*) == 1, "at b");
set_drop(&set);
}
fn main() {
test_single();
test_sources();
}
+236
View File
@@ -0,0 +1,236 @@
// Expect retcode = 0
// 拥有型字节字符串:在 ByteBuffer 之上提供字符串常用操作。
// 普通赋值复制句柄(共享存储),所有权转移用 take;失败不产生部分状态。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .ByteView, .FindResult } = @import("byte_view.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
type Str = @self;
storage: ByteBuffer,
type StrResult = enum {
Ok: Str,
Err: Error,
}
fn new(): Str {
ret Str { .storage = ByteBuffer.new() };
}
// 复制 view 指向的字节。
fn from_view(view: ByteView): StrResult {
var s = new();
match append_view(&s, view) {
.Ok => {},
.Err(error) => { drop(&s); ret .Err(error); },
}
ret .Ok(s);
}
fn from_slice(bytes: []u8): StrResult {
ret from_view(ByteView.from_slice(bytes));
}
fn size(self: Str): usize {
ret ByteBuffer.size(self.storage);
}
fn is_empty(self: Str): bool {
ret ByteBuffer.is_empty(self.storage);
}
fn as_view(self: *Str): ByteView {
ret ByteView.from_slice(ByteBuffer.as_slice(self.storage));
}
fn as_slice(self: *Str): []u8 {
ret ByteBuffer.as_slice(self.storage);
}
fn reserve(self: *Str, capacity: usize): Status {
ret ByteBuffer.reserve(&self.storage, capacity);
}
fn append_view(self: *Str, view: ByteView): Status {
ret ByteBuffer.append(&self.storage, ByteView.as_slice(view));
}
fn append(self: *Str, bytes: []u8): Status {
ret ByteBuffer.append(&self.storage, bytes);
}
fn append_str(self: *Str, other: Str): Status {
var o = other;
ret append_view(self, as_view(&o));
}
fn append_byte(self: *Str, byte: u8): Status {
ret ByteBuffer.append_byte(&self.storage, byte);
}
fn clear(self: *Str) {
ByteBuffer.clear(&self.storage);
}
fn eq(a: Str, b: Str): bool {
var x = a;
var y = b;
ret ByteView.eq(as_view(&x), as_view(&y));
}
fn eq_slice(a: Str, bytes: []u8): bool {
var x = a;
ret ByteView.eq(as_view(&x), ByteView.from_slice(bytes));
}
fn cmp(a: Str, b: Str): i32 {
var x = a;
var y = b;
ret ByteView.cmp(as_view(&x), as_view(&y));
}
fn starts_with(self: Str, prefix: Str): bool {
var x = self;
var p = prefix;
ret ByteView.starts_with(as_view(&x), as_view(&p));
}
fn ends_with(self: Str, suffix: Str): bool {
var x = self;
var s = suffix;
ret ByteView.ends_with(as_view(&x), as_view(&s));
}
fn find(self: Str, needle: Str): FindResult {
var x = self;
var n = needle;
ret ByteView.find(as_view(&x), as_view(&n));
}
// 深复制;允许 out 与 source 为同一对象。
fn clone(out: *Str, source: Str): Status {
ret ByteBuffer.clone(&out.storage, source.storage);
}
fn take(source: *Str): Str {
ret Str { .storage = ByteBuffer.take(&source.storage) };
}
fn drop(self: *Str) {
ByteBuffer.drop(&self.storage);
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected str error"); },
}
}
fn expect_text(s: *Str, expected: []u8) {
var view = as_view(s);
@assert(ByteView.eq(view, ByteView.from_slice(expected)), "str text");
}
fn test_construction() {
var s = new();
defer { drop(&s); }
@assert(is_empty(s) && size(s) == 0, "empty new");
expect_ok(append(&s, "hello"));
expect_ok(append_byte(&s, ' '));
expect_ok(append(&s, "world"));
expect_text(&s, "hello world");
@assert(size(s) == 11, "size");
var r = from_slice("copy");
match r {
.Ok(copy) => {
expect_text(&copy, "copy");
@assert(eq(copy, copy), "self eq");
drop(&copy);
},
.Err(error) => { @assert(false, "from_slice"); },
}
}
fn test_compare_and_search() {
var hello_r = from_slice("hello");
var hello: Str = new();
defer { drop(&hello); }
match hello_r {
.Ok(v) => { hello = v; },
.Err(error) => { @assert(false, "hello"); },
}
var help_r = from_slice("help");
var help: Str = new();
defer { drop(&help); }
match help_r {
.Ok(v) => { help = v; },
.Err(error) => { @assert(false, "help"); },
}
@assert(eq(hello, hello), "eq");
@assert(!eq(hello, help), "ne");
@assert(eq_slice(hello, "hello"), "eq_slice");
@assert(cmp(hello, help) < 0, "cmp lt");
@assert(cmp(help, hello) > 0, "cmp gt");
@assert(starts_with(hello, hello), "starts_with");
@assert(ends_with(hello, hello), "ends_with");
var pre_r = from_slice("he");
var pre: Str = new();
defer { drop(&pre); }
match pre_r { .Ok(v) => { pre = v; }, .Err(e) => { @assert(false, "pre"); } }
@assert(starts_with(hello, pre), "starts he");
@assert(!ends_with(hello, pre), "!ends he");
var needle_r = from_slice("ll");
var needle: Str = new();
defer { drop(&needle); }
match needle_r { .Ok(v) => { needle = v; }, .Err(e) => { @assert(false, "needle"); } }
match find(hello, needle) {
.Found(index) => { @assert(index == 2, "find ll"); },
.NotFound => { @assert(false, "ll not found"); },
}
match find(hello, pre) {
.Found(index) => { @assert(index == 0, "find he"); },
.NotFound => { @assert(false, "he not found"); },
}
}
fn test_clone_take_and_failures() {
var source = new();
defer { drop(&source); }
expect_ok(append(&source, "owned"));
var copy = new();
defer { drop(&copy); }
expect_ok(clone(&copy, source));
expect_text(&copy, "owned");
expect_ok(append_byte(&source, '!')); // '!'
expect_text(&copy, "owned"); // 独立
var before = ByteBuffer.as_slice(copy.storage).ptr;
expect_ok(clone(&copy, copy));
@assert(ByteBuffer.as_slice(copy.storage).ptr != before, "self clone replaces allocation");
expect_text(&copy, "owned");
var moved = take(&copy);
defer { drop(&moved); }
@assert(ByteBuffer.size(copy.storage) == 0 && ByteBuffer.capacity(copy.storage) == 0,
"take empties source");
expect_text(&moved, "owned");
clear(&moved);
@assert(is_empty(moved) && ByteBuffer.capacity(moved.storage) != 0, "clear keeps capacity");
}
fn main() {
test_construction();
test_compare_and_search();
test_clone_take_and_failures();
}
+290
View File
@@ -0,0 +1,290 @@
// Expect retcode = 0
// UTF-8 工具:解码/编码、校验、码点数、以及 UTF-8 字节偏移 <-> UTF-16 code unit 偏移
// (LSP 位置基于 UTF-16)。严格校验过长编码与代理区。
type .{ .Error, .Status, .make } = @import("error.spl");
type .{ .ByteBuffer } = @import("byte_buffer.spl");
// 解码结果:Ok 携带消耗字节数;明确区分越界/截断/非法,避免 0 哨兵歧义。
type DecodeResult = enum {
Ok: usize,
Eof, // index 已越过输入
Truncated, // 序列尾部字节不足
Invalid, // 续字节/过长编码/代理区/超出码点范围
}
// 从 index 解码一个码点到 out_cp;返回 DecodeResult。
fn decode(data: *u8, len: usize, index: usize, out_cp: *u32): DecodeResult {
if index >= len { ret .Eof; }
var b0 = data[index];
if b0 < 0x80 {
out_cp.* = b0 as u32;
ret .Ok(1);
}
if b0 < 0xC2 { ret .Invalid; } // 续字节或过长编码的前导
if b0 < 0xE0 {
if index + 1 >= len { ret .Truncated; }
var b1 = data[index + 1];
if (b1 & 0xC0) != 0x80 { ret .Invalid; }
out_cp.* = (((b0 & 0x1F) as u32) << 6) | ((b1 & 0x3F) as u32);
ret .Ok(2);
}
if b0 < 0xF0 {
if index + 2 >= len { ret .Truncated; }
var b1 = data[index + 1];
var b2 = data[index + 2];
if (b1 & 0xC0) != 0x80 || (b2 & 0xC0) != 0x80 { ret .Invalid; }
var cp = (((b0 & 0x0F) as u32) << 12) | (((b1 & 0x3F) as u32) << 6) | ((b2 & 0x3F) as u32);
if cp < 0x800 { ret .Invalid; } // 过长
if cp >= 0xD800 && cp <= 0xDFFF { ret .Invalid; } // 代理区
out_cp.* = cp;
ret .Ok(3);
}
if b0 < 0xF5 {
if index + 3 >= len { ret .Truncated; }
var b1 = data[index + 1];
var b2 = data[index + 2];
var b3 = data[index + 3];
if (b1 & 0xC0) != 0x80 || (b2 & 0xC0) != 0x80 || (b3 & 0xC0) != 0x80 { ret .Invalid; }
var cp = (((b0 & 0x07) as u32) << 18) | (((b1 & 0x3F) as u32) << 12) |
(((b2 & 0x3F) as u32) << 6) | ((b3 & 0x3F) as u32);
if cp < 0x10000 || cp > 0x10FFFF { ret .Invalid; }
out_cp.* = cp;
ret .Ok(4);
}
ret .Invalid;
}
// 测试辅助:把 DecodeResult 归约为“消耗字节数”,非 Ok 视为 0。
fn decode_used(data: *u8, len: usize, index: usize, out_cp: *u32): usize {
match decode(data, len, index, out_cp) {
.Ok(used) => { ret used; },
.Eof => { ret 0; },
.Truncated => { ret 0; },
.Invalid => { ret 0; },
}
ret 0;
}
fn valid(data: *u8, len: usize): bool {
var i: usize = 0;
var cp: u32 = 0;
while i < len {
match decode(data, len, i, &cp) {
.Ok(used) => { i = i + used; },
_ => { ret false; },
}
}
ret true;
}
fn encode_into(out: *ByteBuffer, cp: u32): Status {
if cp < 0x80 {
ret ByteBuffer.append_byte(out, cp as u8);
}
if cp < 0x800 {
var b0 = (0xC0 | ((cp >> 6) as u8));
var b1 = (0x80 | ((cp & 0x3F) as u8));
match ByteBuffer.append_byte(out, b0) { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append_byte(out, b1);
}
if cp >= 0xD800 && cp <= 0xDFFF { ret .Err(make(.InvalidArgument)); }
if cp < 0x10000 {
var b0 = (0xE0 | ((cp >> 12) as u8));
var b1 = (0x80 | (((cp >> 6) & 0x3F) as u8));
var b2 = (0x80 | ((cp & 0x3F) as u8));
match ByteBuffer.append_byte(out, b0) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, b1) { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append_byte(out, b2);
}
if cp <= 0x10FFFF {
var b0 = (0xF0 | ((cp >> 18) as u8));
var b1 = (0x80 | (((cp >> 12) & 0x3F) as u8));
var b2 = (0x80 | (((cp >> 6) & 0x3F) as u8));
var b3 = (0x80 | ((cp & 0x3F) as u8));
match ByteBuffer.append_byte(out, b0) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, b1) { .Ok => {}, .Err(e) => { ret .Err(e); } }
match ByteBuffer.append_byte(out, b2) { .Ok => {}, .Err(e) => { ret .Err(e); } }
ret ByteBuffer.append_byte(out, b3);
}
ret .Err(make(.InvalidArgument));
}
fn count_codepoints(data: *u8, len: usize): usize {
var i: usize = 0;
var n: usize = 0;
var cp: u32 = 0;
while i < len {
match decode(data, len, i, &cp) {
.Ok(used) => { i = i + used; n = n + 1; },
_ => { ret n; },
}
}
ret n;
}
// 码点占用的 UTF-16 code unit 数:BMP 为 1,补充平面为 2。
fn utf16_units(data: *u8, len: usize): usize {
var i: usize = 0;
var n: usize = 0;
var cp: u32 = 0;
while i < len {
match decode(data, len, i, &cp) {
.Ok(used) => {
if cp >= 0x10000 { n = n + 2; } else { n = n + 1; }
i = i + used;
},
_ => { ret n; },
}
}
ret n;
}
// 字节偏移 -> UTF-16 偏移(夹取到 [0, utf16_units])。
fn byte_to_utf16(data: *u8, len: usize, byte_off: usize): usize {
var i: usize = 0;
var n: usize = 0;
var cp: u32 = 0;
while i < len && i < byte_off {
match decode(data, len, i, &cp) {
.Ok(used) => {
if cp >= 0x10000 { n = n + 2; } else { n = n + 1; }
i = i + used;
},
_ => { ret n; },
}
}
ret n;
}
// UTF-16 偏移 -> 字节偏移(夹取;落在码点内部时返回该码点起始字节)。
fn utf16_to_byte(data: *u8, len: usize, utf16_off: usize): usize {
var i: usize = 0;
var n: usize = 0;
var cp: u32 = 0;
while i < len {
if n >= utf16_off { ret i; }
var used: usize = 0;
match decode(data, len, i, &cp) {
.Ok(value) => { used = value; },
_ => { ret i; },
}
var units: usize = 1;
if cp >= 0x10000 { units = 2; }
if n + units > utf16_off { ret i; }
n = n + units;
i = i + used;
}
ret i;
}
// ---- 测试辅助 ----
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected utf8 error"); },
}
}
fn test_decode_encode_roundtrip() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
expect_ok(encode_into(&out, 0x41)); // 'A'
expect_ok(encode_into(&out, 0xE9)); // é
expect_ok(encode_into(&out, 0x20AC)); // €
expect_ok(encode_into(&out, 0x1F600)); // 😀
var bytes = ByteBuffer.as_slice(out);
@assert(bytes.len == 1 + 2 + 3 + 4, "encoded length");
@assert(bytes.ptr[0] == 0x41, "A");
@assert(bytes.ptr[1] == 0xC3 && bytes.ptr[2] == 0xA9, "e-acute");
@assert(bytes.ptr[3] == 0xE2 && bytes.ptr[4] == 0x82 && bytes.ptr[5] == 0xAC, "euro");
@assert(bytes.ptr[6] == 0xF0 && bytes.ptr[9] == 0x80, "emoji head/tail");
@assert(valid(bytes.ptr, bytes.len), "valid");
@assert(count_codepoints(bytes.ptr, bytes.len) == 4, "codepoints");
@assert(utf16_units(bytes.ptr, bytes.len) == 1 + 1 + 1 + 2, "utf16 units");
var cp: u32 = 0;
@assert(decode_used(bytes.ptr, bytes.len, 0, &cp) == 1 && cp == 0x41, "dec A");
@assert(decode_used(bytes.ptr, bytes.len, 1, &cp) == 2 && cp == 0xE9, "dec e");
@assert(decode_used(bytes.ptr, bytes.len, 3, &cp) == 3 && cp == 0x20AC, "dec euro");
@assert(decode_used(bytes.ptr, bytes.len, 6, &cp) == 4 && cp == 0x1F600, "dec emoji");
}
fn test_invalid() {
var bad1: [2]u8 = .[0xC0, 0x80]; // 过长
var bad2: [3]u8 = .[0xED, 0xA0, 0x80]; // 代理区
var bad3: [2]u8 = .[0xC3, 0x28]; // 坏续字节
var bad4: [1]u8 = .[0x80]; // 孤立续字节
var bad5: [3]u8 = .[0xE2, 0x82]; // 截断
var s1 = bad1[0..2];
var s2 = bad2[0..3];
var s3 = bad3[0..2];
var s4 = bad4[0..1];
var s5 = bad5[0..2];
@assert(!valid(s1.ptr, s1.len), "overlong");
@assert(!valid(s2.ptr, s2.len), "surrogate");
@assert(!valid(s3.ptr, s3.len), "bad cont");
@assert(!valid(s4.ptr, s4.len), "lone cont");
@assert(!valid(s5.ptr, s5.len), "truncated");
// 新 ADT:越界/截断/非法可区分。
var cp: u32 = 0;
match decode(s5.ptr, s5.len, 0, &cp) {
.Truncated => {},
_ => { @assert(false, "truncated sequence should be Truncated"); },
}
match decode(s5.ptr, s5.len, s5.len, &cp) {
.Eof => {},
_ => { @assert(false, "past end should be Eof"); },
}
match decode(s1.ptr, s1.len, 0, &cp) {
.Invalid => {},
_ => { @assert(false, "overlong should be Invalid"); },
}
match decode(s4.ptr, s4.len, 0, &cp) {
.Invalid => {},
_ => { @assert(false, "lone continuation should be Invalid"); },
}
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
match encode_into(&out, 0xD800) {
.Ok => { @assert(false, "surrogate encode"); },
.Err(error) => {},
}
match encode_into(&out, 0x110000) {
.Ok => { @assert(false, "out of range encode"); },
.Err(error) => {},
}
}
fn test_offsets() {
var out = ByteBuffer.new();
defer { ByteBuffer.drop(&out); }
expect_ok(encode_into(&out, 0x41)); // byte 0, utf16 0
expect_ok(encode_into(&out, 0x1F600)); // bytes 1..4, utf16 1..2
expect_ok(encode_into(&out, 0x42)); // byte 5, utf16 3
var b = ByteBuffer.as_slice(out);
@assert(byte_to_utf16(b.ptr, b.len, 0) == 0, "b0");
@assert(byte_to_utf16(b.ptr, b.len, 1) == 1, "b1");
@assert(byte_to_utf16(b.ptr, b.len, 5) == 3, "b5");
@assert(byte_to_utf16(b.ptr, b.len, 6) == 4, "clamp");
@assert(utf16_to_byte(b.ptr, b.len, 0) == 0, "u0");
@assert(utf16_to_byte(b.ptr, b.len, 1) == 1, "u1");
@assert(utf16_to_byte(b.ptr, b.len, 2) == 1, "u2 stays in emoji");
@assert(utf16_to_byte(b.ptr, b.len, 3) == 5, "u3");
@assert(utf16_to_byte(b.ptr, b.len, 99) == 6, "clamp");
}
fn main() {
test_decode_encode_roundtrip();
test_invalid();
test_offsets();
}
+100
View File
@@ -0,0 +1,100 @@
// Expect retcode = 0
// 显式装箱值:运行期格式化用的最小 ADT。调用方显式构造(如 Value.int(x)),
// 库内用 match 分派。不做隐式装箱、不带运行期类型系统。
// Str 借用 ByteView,不拥有存储;Ptr 是类型擦除指针。
type .{ .ByteView } = @import("byte_view.spl");
type Value = enum {
Int: i64,
Uint: u64,
Bool: bool,
Char: u8,
Str: ByteView,
Ptr: *any,
}
fn int(value: i64): Value {
ret .Int(value);
}
fn uint(value: u64): Value {
ret .Uint(value);
}
fn boolean(value: bool): Value {
ret .Bool(value);
}
fn char(value: u8): Value {
ret .Char(value);
}
fn str(bytes: []u8): Value {
ret .Str(ByteView.from_slice(bytes));
}
fn str_view(view: ByteView): Value {
ret .Str(view);
}
fn addr(value: *any): Value {
ret .Ptr(value);
}
// ---- 测试 ----
fn test_int_and_uint() {
match int(-5) {
.Int(v) => { @assert(v == -5, "int payload"); },
_ => { @assert(false, "expected int"); },
}
match uint(5) {
.Uint(v) => { @assert(v == 5, "uint payload"); },
_ => { @assert(false, "expected uint"); },
}
}
fn test_scalars() {
match boolean(true) {
.Bool(v) => { @assert(v, "bool payload"); },
_ => { @assert(false, "expected bool"); },
}
match char('A') {
.Char(v) => { @assert(v == 'A', "char payload"); },
_ => { @assert(false, "expected char"); },
}
}
fn test_borrowed_str() {
var text: [3]u8 = .[104, 105, 0];
var s = str(text[0..2]);
match s {
.Str(view) => {
@assert(view.len == 2 && view.ptr[0] == 104 && view.ptr[1] == 105,
"str payload borrows");
},
_ => { @assert(false, "expected str"); },
}
@assert(text[0] == 104, "source untouched");
}
fn test_ptr() {
var x: i32 = 7;
match addr(&x as *any) {
.Ptr(p) => { @assert((p as *i32).* == 7, "ptr payload"); },
_ => { @assert(false, "expected ptr"); },
}
match addr(null) {
.Ptr(p) => { @assert(p == null, "null ptr payload"); },
_ => { @assert(false, "expected ptr"); },
}
}
fn main() {
test_int_and_uint();
test_scalars();
test_borrowed_str();
test_ptr();
}
+439
View File
@@ -0,0 +1,439 @@
// Expect retcode = 0
// 类型擦除的动态数组。元素按值复制,数组只释放自身存储,不释放元素内部资源。
// Vec 拥有 raw 指向的分配;普通赋值会复制所有权,所有权转移必须使用 take。
type .{ .Error, .Kind, .Status } = @import("error.spl");
type .{ .SizeResult, .checked_add, .checked_mul, .grow_capacity, .move } = @import("memory.spl");
type .{ .alloc, .copy, .free } = @import("../sys/mem.spl");
type Vec = @self;
raw: *u8,
data: *u8,
len: usize,
cap: usize,
elem_size: usize,
elem_align: usize,
type VecResult = enum {
Ok: Vec,
Err: Error,
}
type PtrResult = enum {
Ok: *u8,
Err: Error,
}
fn blank(elem_size: usize, elem_align: usize): Vec {
ret Vec {
.raw = null,
.data = null,
.len = 0,
.cap = 0,
.elem_size = elem_size,
.elem_align = elem_align,
};
}
fn valid_alignment(alignment: usize): bool {
ret alignment != 0 && (alignment & (alignment - 1)) == 0;
}
fn new(elem_size: usize, elem_align: usize): VecResult {
if elem_size == 0 { ret .Err(Error.make(.InvalidArgument)); }
if !valid_alignment(elem_align) {
ret .Err(Error.make(.InvalidAlignment));
}
ret .Ok(blank(elem_size, elem_align));
}
fn valid(self: Vec): bool {
if self.elem_size == 0 || !valid_alignment(self.elem_align) { ret false; }
if self.len > self.cap { ret false; }
if self.cap == 0 {
ret self.raw == null && self.data == null && self.len == 0;
}
if self.raw == null || self.data == null { ret false; }
ret (self.data as usize & (self.elem_align - 1)) == 0;
}
fn status_error(kind: Kind): Status {
ret .Err(Error.make(kind));
}
// 计算元素区字节数。错误时不修改任何 Vec。
fn byte_count(count: usize, elem_size: usize): SizeResult {
ret checked_mul(count, elem_size);
}
fn allocate(capacity: usize, elem_size: usize, elem_align: usize): VecResult {
if elem_size == 0 { ret .Err(Error.make(.InvalidArgument)); }
if !valid_alignment(elem_align) {
ret .Err(Error.make(.InvalidAlignment));
}
if capacity == 0 { ret .Ok(blank(elem_size, elem_align)); }
var bytes: usize = 0;
match byte_count(capacity, elem_size) {
.Ok(value) => { bytes = value; },
.Err(error) => { ret .Err(error); },
}
var total: usize = 0;
match checked_add(bytes, elem_align - 1) {
.Ok(value) => { total = value; },
.Err(error) => { ret .Err(error); },
}
var raw = alloc(total) as *u8;
if raw == null {
ret .Err(Error.make(.Overflow));
}
var address = raw as usize;
var mask = elem_align - 1;
if address > (~(0 as usize)) - mask {
free(raw as *any);
ret .Err(Error.make(.Overflow));
}
var aligned = (address + mask) & ~mask;
ret .Ok(Vec {
.raw = raw,
.data = aligned as *u8,
.len = 0,
.cap = capacity,
.elem_size = elem_size,
.elem_align = elem_align,
});
}
// 保证至少可容纳 need 个元素。所有检查在原对象改变前完成。
fn reserve(self: *Vec, need: usize): Status {
if !valid(self.*) { ret status_error(.InvalidArgument); }
if need <= self.cap { ret .Ok; }
var new_cap = grow_capacity(self.cap, 8, need);
var fresh: Vec = undefined;
match allocate(new_cap, self.elem_size, self.elem_align) {
.Ok(value) => { fresh = value; },
.Err(error) => { ret .Err(error); },
}
var used_bytes: usize = 0;
match byte_count(self.len, self.elem_size) {
.Ok(value) => { used_bytes = value; },
.Err(error) => {
drop(&fresh);
ret .Err(error);
},
}
if used_bytes != 0 {
copy(fresh.data as *any, self.data as *any, used_bytes);
}
fresh.len = self.len;
var old_raw = self.raw;
self.* = fresh;
free(old_raw as *any);
ret .Ok;
}
fn get(self: *Vec, index: usize): PtrResult {
if !valid(self.*) { ret .Err(Error.make(.InvalidArgument)); }
if index >= self.len { ret .Err(Error.make(.OutOfRange)); }
ret .Ok(self.data + index * self.elem_size);
}
fn set(self: *Vec, index: usize, elem: *u8): Status {
if !valid(self.*) || elem == null { ret status_error(.InvalidArgument); }
if index >= self.len { ret status_error(.OutOfRange); }
var dst = self.data + index * self.elem_size;
ret move(dst[0..self.elem_size], elem[0..self.elem_size]);
}
// 追加 count 个连续元素。elems 可以指向 self 当前已初始化的元素区。
fn append(self: *Vec, elems: *u8, count: usize): Status {
if !valid(self.*) { ret status_error(.InvalidArgument); }
if count == 0 { ret .Ok; }
if elems == null { ret status_error(.InvalidArgument); }
var copy_bytes: usize = 0;
match byte_count(count, self.elem_size) {
.Ok(value) => { copy_bytes = value; },
.Err(error) => { ret .Err(error); },
}
var new_len: usize = 0;
match checked_add(self.len, count) {
.Ok(value) => { new_len = value; },
.Err(error) => { ret .Err(error); },
}
var used_bytes: usize = 0;
match byte_count(self.len, self.elem_size) {
.Ok(value) => { used_bytes = value; },
.Err(error) => { ret .Err(error); },
}
var source_inside = false;
var source_offset: usize = 0;
if used_bytes != 0 {
var base = self.data as usize;
var source = elems as usize;
if source >= base && source - base < used_bytes {
source_offset = source - base;
if copy_bytes > used_bytes - source_offset {
ret status_error(.OutOfRange);
}
source_inside = true;
}
}
match reserve(self, new_len) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
if source_inside { elems = self.data + source_offset; }
var dst = self.data + used_bytes;
match move(dst[0..copy_bytes], elems[0..copy_bytes]) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
self.len = new_len;
ret .Ok;
}
fn push(self: *Vec, elem: *u8): Status {
ret append(self, elem, 1);
}
// 将末元素复制到 out,然后缩短数组。out 可以与元素区重叠。
fn pop(self: *Vec, out: *u8): Status {
if !valid(self.*) || out == null { ret status_error(.InvalidArgument); }
if self.len == 0 { ret status_error(.OutOfRange); }
var source = self.data + (self.len - 1) * self.elem_size;
match move(out[0..self.elem_size], source[0..self.elem_size]) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
self.len = self.len - 1;
ret .Ok;
}
fn clear(self: *Vec) {
self.len = 0;
}
// 成功时先释放 out 原有存储再提交副本;失败保持 out 不变。
// out 与 src 指向同一个 Vec 也允许。
fn clone(out: *Vec, src: Vec): Status {
if !valid(out.*) || !valid(src) { ret status_error(.InvalidArgument); }
if out.elem_size != src.elem_size || out.elem_align != src.elem_align {
ret status_error(.InvalidArgument);
}
var fresh = blank(src.elem_size, src.elem_align);
match reserve(&fresh, src.len) {
.Ok => {},
.Err(error) => { ret .Err(error); },
}
var bytes: usize = 0;
match byte_count(src.len, src.elem_size) {
.Ok(value) => { bytes = value; },
.Err(error) => {
drop(&fresh);
ret .Err(error);
},
}
if bytes != 0 {
copy(fresh.data as *any, src.data as *any, bytes);
}
fresh.len = src.len;
drop(out);
out.* = fresh;
ret .Ok;
}
// 显式转移所有权,返回值必须由接收方最终 drop。
fn take(source: *Vec): Vec {
var result = source.*;
source.* = blank(result.elem_size, result.elem_align);
ret result;
}
fn drop(self: *Vec) {
var elem_size = self.elem_size;
var elem_align = self.elem_align;
free(self.raw as *any);
self.* = blank(elem_size, elem_align);
}
fn expect_ok(result: Status) {
match result {
.Ok => {},
.Err(error) => { @assert(false, "unexpected Vec error"); },
}
}
fn expect_error(result: Status, overflow: bool) {
match result {
.Ok => { @assert(false, "expected Vec error"); },
.Err(error) => {
match error.kind {
.Overflow => { @assert(overflow, "unexpected overflow"); },
.OutOfRange => { @assert(!overflow, "unexpected range error"); },
_ => { @assert(false, "unexpected Vec error kind"); },
}
},
}
}
fn make_vec(elem_size: usize, elem_align: usize): Vec {
match new(elem_size, elem_align) {
.Ok(value) => { ret value; },
.Err(error) => { @assert(false, "Vec construction"); },
}
ret blank(1, 1);
}
fn expect_i32(self: *Vec, index: usize, expected: i32) {
match get(self, index) {
.Ok(ptr) => { @assert((ptr as *i32).* == expected, "Vec element value"); },
.Err(error) => { @assert(false, "Vec element access"); },
}
}
fn test_construction_and_alignment() {
match new(0, 1) {
.Ok(value) => { @assert(false, "zero element size"); },
.Err(error) => {
match error.kind { .InvalidArgument => {}, _ => { @assert(false); }, }
},
}
match new(1, 3) {
.Ok(value) => { @assert(false, "invalid element alignment"); },
.Err(error) => {
match error.kind { .InvalidAlignment => {}, _ => { @assert(false); }, }
},
}
var alignment: usize = 1;
while alignment <= 64 {
var v = make_vec(3, alignment);
expect_ok(reserve(&v, 9));
@assert((v.data as usize & (alignment - 1)) == 0, "requested alignment");
@assert(v.cap >= 9 && v.len == 0);
drop(&v);
@assert(v.raw == null && v.data == null && v.cap == 0);
alignment = alignment * 2;
}
}
fn test_growth_and_access() {
var v = make_vec(@sizeof(i32), @alignof(i32));
defer { drop(&v); }
var i: i32 = 0;
while i < 1000 {
var value = i * 3 - 7;
expect_ok(push(&v, &value as *u8));
i = i + 1;
}
@assert(v.len == 1000 && v.cap >= v.len);
i = 0;
while i < 1000 {
expect_i32(&v, i as usize, i * 3 - 7);
i = i + 1;
}
var replacement: i32 = 123456;
expect_ok(set(&v, 500, &replacement as *u8));
expect_i32(&v, 500, replacement);
expect_error(set(&v, 1000, &replacement as *u8), false);
var popped: i32 = 0;
expect_ok(pop(&v, &popped as *u8));
@assert(popped == 2990 && v.len == 999, "pop copies then removes");
}
fn test_self_reference() {
var v = make_vec(@sizeof(i32), @alignof(i32));
defer { drop(&v); }
var i: i32 = 0;
while i < 8 {
expect_ok(push(&v, &i as *u8));
i = i + 1;
}
@assert(v.len == 8 && v.cap == 8, "prepare growth boundary");
// 源指向旧分配,append 必须在扩容后重新定位它。
expect_ok(append(&v, v.data, v.len));
@assert(v.len == 16);
i = 0;
while i < 16 {
expect_i32(&v, i as usize, i % 8);
i = i + 1;
}
var preserved_len = v.len;
expect_error(append(&v, v.data + (v.len - 1) * v.elem_size, 2), false);
@assert(v.len == preserved_len, "invalid self range preserves Vec");
expect_i32(&v, 15, 7);
var last_ptr: *u8 = null;
match get(&v, 15) {
.Ok(ptr) => { last_ptr = ptr; },
.Err(error) => { @assert(false); },
}
expect_ok(set(&v, 0, last_ptr));
expect_i32(&v, 0, 7);
}
fn test_clone_take_and_failures() {
var source = make_vec(@sizeof(i32), @alignof(i32));
defer { drop(&source); }
var one: i32 = 1;
var two: i32 = 2;
expect_ok(push(&source, &one as *u8));
expect_ok(push(&source, &two as *u8));
var copy = make_vec(@sizeof(i32), @alignof(i32));
defer { drop(&copy); }
expect_ok(clone(&copy, source));
expect_i32(&copy, 0, 1);
one = 99;
expect_ok(set(&source, 0, &one as *u8));
expect_i32(&copy, 0, 1);
// out 与 src 为同一对象仍产生内容相同的新分配。
var old_data = copy.data;
expect_ok(clone(&copy, copy));
@assert(copy.data != old_data, "self clone replaces allocation");
expect_i32(&copy, 1, 2);
var moved = take(&copy);
defer { drop(&moved); }
@assert(copy.raw == null && copy.data == null && copy.len == 0 && copy.cap == 0);
expect_i32(&moved, 0, 1);
var old_raw = moved.raw;
var old_len = moved.len;
var old_cap = moved.cap;
expect_error(reserve(&moved, (~(0 as usize)) / moved.elem_size + 1), true);
@assert(moved.raw == old_raw && moved.len == old_len && moved.cap == old_cap,
"reserve failure preserves Vec");
clear(&moved);
@assert(moved.len == 0 && moved.cap == old_cap, "clear retains capacity");
var output: i32 = 55;
expect_error(pop(&moved, &output as *u8), false);
@assert(output == 55, "failed pop preserves output");
}
fn main() {
test_construction_and_alignment();
test_growth_and_access();
test_self_reference();
test_clone_take_and_failures();
}