NextC
一门受 C 语言启发,兼具现代语法、更强类型安全、极致性能和完全底层控制权的系统编程语言。
本项目采用 Apache License, Version 2.0 或 MIT 许可证,您可选择其中任一。
除非您另有明确声明,否则根据 Apache-2.0 许可证的定义,您有意提交给本项目的任何贡献,均应按上述方式以双许可证授权,不附加任何额外条款或条件。
- 作者(英文名):Glacyend
- 作者(中文名):周沁彬
- 作者(中文艺名):凌雪蓝冰
本文档采用 Creative Commons Attribution-ShareAlike 4.0 International License 进行授权。
Warning
目前 NextC 处于初步设计阶段,还在编写语言的基本文档。请时刻留意此文档中的变动。
版本
当前版本:0.0.0 + 2026.08
正在开发:0.1.0
核心哲学
- 严格的类型安全:数组和指针分离、不允许隐式类型转换、不允许指针与其它类型的转换、严格常量(
const)。 - 安全的指针操作:不允许指针算术、不允许数组指针、运行时空指针检查(Debug 模式)。
- 自由的内存管理:可选择与 C 一样的手动内存管理,或者使用计划在 2.0 版本引入的 GC(将禁用手动释放内存的
delete语句)。 - 运行时检查未定义行为:在 Debug 模式下,可以检查数组越界、
union的正确性等。 - 高效而精简:借鉴 C 的简洁性与高性能,将源代码直接编译为 LLVM IR,并由 LLVM 做更多优化。
- 现代化的语法:使用更现代化的语法,如自动类型推导、固定长度整数类型、强制花括号、多遍编译。
- 模块化编程:可以使用模块进行多文件编程。
- 与 C 语言连接:支持 C FFI,可以使用外部 C 函数等。
- 兼容危险底层操作:使用
unsafe来进行不得不的危险底层操作,如指针运算、数组指针等。
编译器
NextC 编译器使用 Rust 开发前端、LLVM 作为后端。Rust 的第三方库 Inkwell 提供 LLVM 的 Rust 接口。
NextC 编译器将源代码经过词法分析、语法解析转换为 AST;然后在 AST 上进行语义分析,生成修饰后的 AST;随后由代码生成模块将其翻译为 LLVM IR,并交由 LLVM 后端进行进一步的优化和翻译。
更多内容
语法规则
以下语法规则采用 EBNF 表示。
Warning
目前 NextC 处于初期设计和开发阶段,随时可能会加入、删除或修改一些语法规则。直到 NextC 1.0 发布之前,此文档都有很大可能进行改动。
关键字
NextC 所有的关键字如下:
as break byte case char
const constexpr continue default delete
else enum external false float
for foreach if import int
long loop new nullptr return
sbyte short slice string struct
switch true typedef uint ulong
union unsafe ushort void while
类型标识符
Tip
指针类型将
*纳入到了类型标识符中,这意味着这段代码将声明三个指针变量:int* a, b, c;
TypeIdent ::= "(" TypeIdent ")"
| ("const")? TypeName
| PointerType ("const")?
| FunctionType ("const")?
| "void"
TypeName ::= BasicType
| ArrayType
| SliceType
| "string"
| (Identifier "::")* Identifier
BasicType ::= "byte"
| "sbyte"
| "short"
| "ushort"
| "int"
| "uint"
| "long"
| "ulong"
| "ssize"
| "usize"
| "char"
| "bool"
| "float"
| "double"
ArrayType ::= TypeIdent "[" Expression "]"
SliceType ::= "slice" "[" TypeIdent "]"
PointerType ::= TypeIdent "*"
FunctionTypeArgList ::= TypeIdent ("," TypeIdent)* (",")?
FunctionType ::= TypeIdent "(" (FunctionTypeArgList)? ")" "*"
代码标签
Warning
NextC 中没有
goto语句,代码标签也只允许在循环中使用,用于跳出多层循环!
CodeTag ::= "@" Identifier;
表达式
在 NextC 中,运算符的优先级一般与 C 相同。
Tip
在 NextC 中,赋值、自增(
++)和自减(--)都是语句,不是表达式。但是其优先级与 C 相同。NextC 中没有逗号表达式。
括号可以改变优先级,构建 AST 时括号内的表达式单独成一节点,所以不单独成一条语法规则。
NextC 要求条件运算符周围必须打括号,因此优先级最高。
字面量
基本与 C 语言一致。
对于整型字面量(IntegerLiteral):
- 默认
int类型,不会自动转换类型,需要手动加类型后缀。 - 前缀
0x、0o、0b分别表示十六进制、八进制和二进制。 - 后缀
b和sb分别表示byte类型和sbyte类型。 - 后缀
s和l分别表示short和long类型。 - 后缀
us、u和ul分别表示ushort、uint和ulong类型。 - 若有正负号,不属于字面量,而属于一元表达式。
- 除开头和结尾外,允许在整型字面量中使用任意数量和任意位置的下划线(
_)。
对于浮点型字面量(FloatLiteral):
- 默认
double类型,不会自动转换类型,需要手动加类型后缀。 - 语法与 C 基本一致。
- 除开头和结尾外,允许在浮点型字面量中使用任意数量和任意位置的下划线(
_)。 - 后缀
f表示float类型。
对于布尔型字面量(BoolLiteral):
true和false分别表示真值和假值。
对于字符串字面量(StringLiteral):
- 语法与 C 基本一致。
r#"..."表示原始字符串:无转义字符。"""..."""表示多行字符串。除第一行外,剩余行的公共缩进将被忽略。若开头的"""后立即换行,则该换行符忽略,且第一行与剩余行的公共缩进将被忽略。
空指针字面量(NullPtrLiteral):
nullptr关键字表示空指针。- 由于 NextC 在安全状态下不允许使用
void*,所以nullptr不能单独使用,其必须能够被推导出具体指针类型。在变量定义、比较表达式中,都可以确定其具体指针类型。
所有的字面量有:
Literal ::= IntegerLiteral
| FloatLiteral
| BoolLiteral
| StringLiteral
| NullPtrLiteral
最高级表达式
Expression ::= "(" Expression ")"
| Call
| Index
| Get
| PtrGet
| Conditional
| ArrayInitList
| Literal
| New
ArgumentList ::= Expression ("," Expression)* (",")?
Call ::= Expression "(" ArgumentList? ")"
Index ::= Expression "[" Expression "]"
Get ::= Expression "." Identifier
PtrGet ::= Expression "->" Identifier
Conditional ::= "(" Expression "?" Expression ":" Expression ")"
ArrayInitList ::= "{" ArgumentList "}"
New ::= "new" (TypeIdent | (TypeIdent "[" Expression "]"))
算术运算
Factor ::= TypeConv (("*" | "/" | "%") TypeConv)*
Term ::= Factor (("+" | "-") Factor)*
位运算
Shift ::= Term (("<<" | ">>") Term)*
BitAnd ::= Equality ("&" Equality)*
BitXor ::= BitAnd ("^" BitAnd)*
BitOr ::= BitXor ("|" BitXor)*
关系运算
Comparison ::= Shift (("<" | "<=" | ">" | ">=") Shift)*
Equality ::= Comparison (("==" | "!=") Comparison)*
逻辑运算
LogicalNot ::= "!" Expression
LogicalAnd ::= BitOr ("&&" BitOr)*
LogicalOr ::= LogicalAnd ("||" LogicalAnd)*
一元运算
Unary ::= Expression
| "+" Expression
| "-" Expression
| LogicalNot
| Deref
| Pointer
Deref ::= "*" Expression
Pointer ::= "&" Expression
类型转换
TypeConv ::= Unary ("as" (BasicType | PointerType))*
语句
NextC 要求部分语句后必须有分号(;)。
语句语法框架如下:
GlobalStatement ::= External
| ("pub")? FunctionDefine
| ("pub")? VariableDefine
| Import
| ("pub")? Typedef
| ("pub")? ConstantDefine
| ("pub")? Struct
| ("pub")? Enum
| ("pub")? Union
Statement ::= ExprStmt
| Assignment
| Increase
| Decrease
| VariableDefine
| ConstantDefine
| Return
| IfElse
| Loop
| While
| DoWhile
| For
| ForEach
| Break
| Continue
| Switch
| Delete
赋值语句
AssignmentSymbol ::= "="
| "*="
| "/="
| "%="
| "+="
| "-="
| "<<="
| ">>="
| "&="
| "^="
| "|="
AssignmentWithoutSemicolon ::= ((Get | PtrGet | Index | Deref) AssignmentSymbol)+ Expression
Assignment ::= AssignmentWithoutSemicolon ";"
自增/自减语句
Tip
符号用前缀或后缀都可以,语义上是一致的。
IncreaseWithoutSemicolon ::= "++" (Get | PtrGet | Index | Deref)
| (Get | PtrGet | Index | Deref) "++"
Increase ::= IncreaseWithoutSemicolon ";"
DecreaseWithoutSemicolon ::= "--" (Get | PtrGet | Index | Deref)
| (Get | PtrGet | Index | Deref) "--"
Decrease ::= DecreaseWithoutSemicolon ";"
表达式语句
ExprStmt ::= Expression ";"
定义变量
VariableDefine ::= TypeIdent Identifier ("=" Expression)? ("," Identifier ("=" Expression)?)* ";"
定义常量
ConstantDefine ::= "constexpr" TypeIdent Identifier "=" Expression ("," Identifier "=" Expression)* ";"
定义函数
FunctionDelcaration ::= TypeIdent Identifier "(" (FunctionDefineArgList)? ")"
FunctionDefineArgList ::= (TypeIdent Identifier) ("," (TypeIdent Identifier))* (",")?
FunctionDefine ::= FunctionDeclaration "{" (Statement)* "}"
外部 C 接口
External ::= "external" "unsafe" FunctionDeclaration ";"
结构体
Members ::= (TypeIdent Identifier ";")+
Struct ::= "struct" Identifier "{" Members "}"
枚举
Enum ::= "enum" Identifier (":" TypeIdent)
"{" Identifier ("," Identifier)* (",")? "}"
联合体
Union ::= "union" Identifier "{" Members "}"
类型别名
TypeDef ::= "typedef" Identifier "=" TypeIdent ";"
返回语句
Return ::= "return" (Expression)? ";"
条件控制流
IfElse ::= "if" "(" Expression ")"
"{" (Statement)* "}"
(
"else" "if" "(" Expression ")"
"{" (Statement)* "}"
)*
(
"else"
"{" (Statement)* "}"
)?
loop 循环
Loop ::= "loop" (CodeTag)? "{" (Statement)* "}"
while 循环
While ::= "while" (CodeTag)? "(" Expression ")"
"{" (Statement)* "}"
do-while 循环
Tip
由于 NextC 要求分句必须是块(带花括号),所以
do-while后面可以不加分号。若加了分号,则将被视为空语句,编译器将发出警告。
DoWhile ::= "do" (CodeTag)? "{" (Statement)* "}"
"while" "(" Expression ")"
for 循环
Incremental ::= AssignWithoutSemicolon
| IncreaseWithoutSemicolon
| DecreaseWithoutSemicolon
For ::= "for" (CodeTag)? "("
(VariableDefine | ";")
(Expression)? ";"
(Expression | Incremental )? ")"
"{" (Statement)* "}"
foreach 循环
ForEach ::= "foreach" (CodeTag)? "(" TypeIdent Identifier ":" Expression ")"
"{" (Statement)* "}"
break 语句
Break ::= "break" (CodeTag)? ";"
continue 语句
Continue ::= "continue" (CodeTag)? ";"
switch 语句
Tip
为了让语法更简洁和现代化,NextC 中的
switch语句的case和default字句没有冒号,且default字句必须是最后一句。
SwitchCase ::= "case" Expression "{" (Statement)* "}"
SwitchDefault ::= "default" "{" (Statement)* "}"
Switch ::= "switch" "(" Expression ")"
"{" (SwitchCase)* (SwitchDefault)? "}"
delete 语句
Delete ::= "delete" Identifier ("," Identifier)* ";"
注释
与 C 基本一致。
-
//表示单行注释的开头。 -
使用
/* ... */可以表示多行注释或行内注释。但是要注意,与 C 不同的是,这个注释可以嵌套,即你可以写:/* outer /* inner */ outer */ -
使用
///表示文档注释。 -
注释可以在宏中使用。
预编译指令与宏
正在设计中。
初步想法:区分值宏与函数宏。值宏只用于条件编译,不能用于代码中。函数宏与 Rust 的过程宏类似但更精简。
示例程序
Warning
目前 NextC 处于初期设计和开发阶段,随时可能会加入、删除或修改一些语法规则和语义规则。直到 NextC 1.0 发布之前,此文档都有很大可能进行改动。
下面所有程序为设计构想,暂不能编译运行。NextC 1.0 发布之前,下面的程序随时可能进行改动。
Hello, World!
import io;
void main() {
io::println!("Hello, World!");
}
询问名字并问好
import io;
void main() {
io::print!("Please enter your name: ");
string name = "";
io::read_line(&name); // 事实上返回 bool 表示是否正常返回(是否没有错误)。
io::println!("Hello, {}!", name);
delete name; // 记得手动管理内存。
}
分数等级评定
import io;
import strings;
void main() {
io::print!("Please enter your score: ");
uint score = 0;
while (!io::read_uint(&score)) {
io::print!("Invalid score! Try again: ");
}
if (score > 100) {
io::println!("You can't get that score!");
return;
}
char level;
if (score == 100) {
level = 'S';
} else if (score >= 90) {
level = 'A';
} else if (score >= 80) {
level = 'B';
} else if (score >= 60) {
level = 'C';
} else {
level = 'F';
}
// 所有路径均初始化了变量 level,则后面可以正常读取 level。
io::println!("Your level is: {}!", level);
}
整数冒泡排序
import io;
import process;
import slices;
import strings;
import util;
void main() {
io::print!("Enter the length of the array: ");
int length = read_int();
slice[int] arr = slices::new_slice!(int, length);
io::println!("Enter the array below:");
// foreach 语句获取数组或切片的每个元素的指针。
foreach (int* ele : arr) {
*ele = read_int();
}
io::println!("Sorting...");
bubble_sort(arr);
io::println!("Finished!");
io::println!("The sorted array is:");
// const int* 可保证不意外修改切片的元素
foreach (const int* ele : arr) {
io::print!("{} ", *ele);
}
io::println!();
}
// NextC 使用多遍编译器,不需要考虑依赖顺序的问题。
int read_int() {
int result = 0;
if (!io::read_int(&result)) {
io::err_println("Invalid integer.");
process::exit(1);
}
return result;
}
// slice[int] 是胖指针。
// 此处的 const 表示 arr 是不可变变量,但切片内部元素可读可写。
// slice[const int] 的元素就是不可变的。
void bubble_sort(const slice[int] arr) {
usize length = slices::len!(arr);
for (usize i = 0; i < length; i++) {
for (usize j = i + 1; j < length; j++) {
if (arr[j - 1] > arr[j]) {
util::swap!(&arr[j - 1], &arr[j]);
}
}
}
}