Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

NextC

A system programming language inspired by C, offering modern syntax, stronger type safety, zero-cost abstractions, and full low-level control.


This project is licensed under either of Apache License, Version 2.0 or MIT at your option.

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.

  • Author (English name): Glacyend
  • Author (Chinese name): 周沁彬 (Zhou Qinbin)
  • Author (Chinese art name): 凌雪蓝冰 (Lingxue Lanbing)

This document is licensed under the Creative Commons Attribution‑ShareAlike 4.0 International License.

Warning

NextC is currently in the preliminary design phase; the basic language documentation is still being written. Please keep an eye on changes to this document.

Version

Current version: 0.0.0 + 2026.08

In development: 0.1.0

Core Philosophy

  • Strict Type Safety: Arrays and pointers are seperated; implicit type conversions are not allowed; pointer-to-other-type conversions are prohibited; strict const semantics.
  • Safe Pointer Operations: Pointer arithmetic is disallowed; array-to-pointer decay is not supported; runtime null pointer checks (in Debug mode).
  • Flexible Memory Management: Choose between manual memory management like C, or enable the planned GC (introduced in version 2.0, which will disable the manual delete statement).
  • Runtime Checks for Undefined Behavior: In Debug mode, array bounds checking, union correctness, and other checks are performed to catch undefined behavior.
  • Efficient and Lightweight: Borrowing C’s simplicity and high performance, source code is compiled directly to LLVM IR, with further optimizations performed by LLVM.
  • Modern Syntax: Adopts modern syntax features such as type inference, fixed-width integer types, mandatory braces, and multi-pass compilation.
  • Modular Programming: Supports multi-file programming via modules.
  • C Interoperability: Supports C FFI, allowing the use of external C functions and libraries.
  • Compatibility with Low-Level Unsafe Operations: Use unsafe blocks for unavoidable low-level operations such as pointer arithmetic and array pointer manipulation.

NextC Compiler

The NextC compiler uses Rust for its frontend and LLVM as its backend. The Rust third-party library Inkwell provides Rust bindings for LLVM.

The NextC compiler transforms the source code into an AST through lexical analysis and syntactic parsing. It then performs semantic analysis on the AST to generate an annotated AST, which is subsequently translated into LLVM IR by the code generation module. Finally, the LLVM backend performs further optimization and translation.

More

Grammar

The following grammar rules are given in EBNF.

Warning

NextC is currently in the early design and development phase; syntax rules may be added, removed, or modified at any time. Until NextC 1.0 is released, this document is subject to significant change.

Keywords

All NextC keywords are:

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

Type Identifiers

Tip

Pointer types incorporate * into the type identifier. This means the following declares three pointer variables:

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)? ")" "*"

Code Labels

Warning

NextC has no goto statement. Code labels are only allowed inside loops and are used to break out of nested loops.

CodeTag ::= "@" Identifier;

Expressions

Operator precedence in NextC generally follows that of C.

Tip

In NextC, assignment (=), increment (++), and decrement (--) are statements, not expressions. However, their precedence is the same as in C.

NextC does not have the comma operator.

Parentheses can change precedence; when building the AST, the expression inside parentheses becomes a separate node, so it is not a separate grammar rule.

NextC requires parentheses around the conditional operator, so it has the highest precedence.

Literals

Basically the same as in C.

For integer literals (IntegerLiteral):

  • Default type is int; no automatic conversion; type suffixes must be added manually.
  • Prefixes 0x, 0o, 0b denote hexadecimal, octal, and binary respectively.
  • Suffixes b and sb denote byte and sbyte respectively.
  • Suffixes s and l denote short and long respectively.
  • Suffixes us, u, and ul denote ushort, uint, and ulong respectively.
  • Signs belong to unary expressions, not to the literal.
  • Underscores (_) are allowed anywhere except at the beginning or end, in any number and position.

For floating‑point literals (FloatLiteral):

  • Default type is double; no automatic conversion; type suffixes must be added manually.
  • Syntax is essentially the same as in C.
  • Underscores (_) are allowed anywhere except at the beginning or end, in any number and position.
  • Suffix f denotes float.

For boolean literals (BoolLiteral):

  • true and false denote truth values.

For string literals (StringLiteral):

  • Syntax is essentially the same as in C.
  • r#"..." denotes a raw string: no escape sequences.
  • """...""" denotes a multi‑line string. Except for the first line, common indentation of the remaining lines is stripped. If the opening """ is immediately followed by a newline, that newline is ignored, and the common indentation of the first line and the remaining lines is stripped.

Null pointer literal (NullPtrLiteral):

  • nullptr denotes a null pointer.
  • Since NextC does not allow void* in safe code, nullptr cannot be used alone; its concrete pointer type must be deducible. In variable definitions and comparison expressions, the concrete pointer type can be determined.

All literals:

Literal ::= IntegerLiteral
          | FloatLiteral
          | BoolLiteral
          | StringLiteral
          | NullPtrLiteral

Primary Expressions

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 "]"))

Arithmetic Operations

Factor ::= TypeConv (("*" | "/" | "%") TypeConv)*
Term ::= Factor (("+" | "-") Factor)*

Bitwise Operations

Shift ::= Term (("<<" | ">>") Term)*
BitAnd ::= Equality ("&" Equality)*
BitXor ::= BitAnd ("^" BitAnd)*
BitOr ::= BitXor ("|" BitXor)*

Relational Operations

Comparison ::= Shift (("<" | "<=" | ">" | ">=") Shift)*
Equality ::= Comparison (("==" | "!=") Comparison)*

Logical Operations

LogicalNot ::= "!" Expression
LogicalAnd ::= BitOr ("&&" BitOr)*
LogicalOr ::= LogicalAnd ("||" LogicalAnd)*

Unary Operations

Unary ::= Expression
        | "+" Expression
        | "-" Expression
        | LogicalNot
        | Deref
        | Pointer

Deref ::= "*" Expression
Pointer ::= "&" Expression

Type Conversions

TypeConv ::= Unary ("as" (BasicType | PointerType))*

Statements

NextC requires that certain statements end with a semicolon (;).

Statement framework:

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

Assignment Statement

AssignmentSymbol ::= "="
                   | "*="
                   | "/="
                   | "%="
                   | "+="
                   | "-="
                   | "<<="
                   | ">>="
                   | "&="
                   | "^="
                   | "|="

AssignmentWithoutSemicolon ::= ((Get | PtrGet | Index | Deref) AssignmentSymbol)+ Expression
Assignment ::= AssignmentWithoutSemicolon ";"

Increment/Decrement Statement

Tip

Prefix and suffix forms are both allowed and have the same semantics.

IncreaseWithoutSemicolon ::= "++" (Get | PtrGet | Index | Deref)
                           | (Get | PtrGet | Index | Deref) "++"
Increase ::= IncreaseWithoutSemicolon ";"

DecreaseWithoutSemicolon ::= "--" (Get | PtrGet | Index | Deref)
                           | (Get | PtrGet | Index | Deref) "--"
Decrease ::= DecreaseWithoutSemicolon ";"

Expression Statement

ExprStmt ::= Expression ";"

Variable Definition

VariableDefine ::= TypeIdent Identifier ("=" Expression)? ("," Identifier ("=" Expression)?)* ";"

Constant Definition

ConstantDefine ::= "constexpr" TypeIdent Identifier "=" Expression ("," Identifier "=" Expression)* ";"

Function Definition

FunctionDeclaration ::= TypeIdent Identifier "(" (FunctionDefineArgList)? ")"

FunctionDefineArgList ::= (TypeIdent Identifier) ("," (TypeIdent Identifier))* (",")?

FunctionDefine ::= FunctionDeclaration "{" (Statement)* "}"

External C Interface

External ::= "external" "unsafe" FunctionDeclaration ";"

Struct

Members ::= (TypeIdent Identifier ";")+

Struct ::= "struct" Identifier "{" Members "}"

Enum

Enum ::= "enum" Identifier (":" TypeIdent)
         "{" Identifier ("," Identifier)* (",")? "}"

Union

Union ::= "union" Identifier "{" Members "}"

Type Alias

TypeDef ::= "typedef" Identifier "=" TypeIdent ";"

Return Statement

Return ::= "return" (Expression)? ";"

Conditional Control Flow

IfElse ::= "if" "(" Expression ")"
           "{" (Statement)* "}"
           (
                "else" "if" "(" Expression ")"
                "{" (Statement)* "}"
           )*
           (
                "else"
                "{" (Statement)* "}"
           )?

loop Loop

Loop ::= "loop" (CodeTag)? "{" (Statement)* "}"

while Loop

While ::= "while" (CodeTag)? "(" Expression ")"
          "{" (Statement)* "}"

do-while Loop

Tip

Because NextC requires that clause bodies must be blocks (with braces), do-while does not require a semicolon. If a semicolon is present, it is treated as an empty statement and the compiler will issue a warning.

DoWhile ::= "do" (CodeTag)? "{" (Statement)* "}"
            "while" "(" Expression ")"

for Loop

Incremental ::= AssignWithoutSemicolon
              | IncreaseWithoutSemicolon
              | DecreaseWithoutSemicolon

For ::= "for" (CodeTag)? "("
        (VariableDefine | ";")
        (Expression)? ";"
        (Expression | Incremental )? ")"
        "{" (Statement)* "}"

foreach Loop

ForEach ::= "foreach" (CodeTag)? "(" TypeIdent Identifier ":" Expression ")"
            "{" (Statement)* "}"

break Statement

Break ::= "break" (CodeTag)? ";"

continue Statement

Continue ::= "continue" (CodeTag)? ";"

switch Statement

Tip

To keep syntax concise and modern, case and default clauses in NextC do not use colons, and the default clause must be the last one.

SwitchCase ::= "case" Expression "{" (Statement)* "}"
SwitchDefault ::= "default" "{" (Statement)* "}"

Switch ::= "switch" "(" Expression ")"
           "{" (SwitchCase)* (SwitchDefault)? "}"

delete Statement

Delete ::= "delete" Identifier ("," Identifier)* ";"

Comments

Basically the same as in C.

  • // starts a single‑line comment.

  • /* ... */ denotes multi‑line or inline comments. Unlike C, these comments can be nested, for example:

    /* outer /* inner */ outer */
    
  • /// denotes a documentation comment.

  • Comments may be used inside macros.

Preprocessor Directives and Macros

Under design.

Initial idea: distinguish value macros from function macros. Value macros are only used for conditional compilation and cannot appear in code. Function macros are similar to Rust procedural macros but simpler.

Examples

Warning

NextC is currently in the early design and development phase; syntax and semantic rules may be added, removed, or modified at any time. Until NextC 1.0 is released, this document is subject to significant change.

All programs below are design prototypes; they cannot be compiled or run yet. Before NextC 1.0, the programs below are likely to change.

Hello, World!

import io;

void main() {
    io::println!("Hello, World!");
}

Ask for Name and Greet

import io;

void main() {
    io::print!("Please enter your name: ");
    string name = "";
    io::read_line(&name);  // returns bool indicating success (no error).
    io::println!("Hello, {}!", name);
    delete name;  // remember to manage memory manually.
}

Score Grading

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';
    }
    // All paths initialise the variable level, so reading level later is safe.

    io::println!("Your level is: {}!", level);
}

Integer Bubble Sort

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 obtains a pointer to each element of the array or slice.
    foreach (int* ele : arr) {
        *ele = read_int();
    }
    io::println!("Sorting...");
    bubble_sort(arr);
    io::println!("Finished!");
    io::println!("The sorted array is:");
    // const int* prevents accidental modification of slice elements.
    foreach (const int* ele : arr) {
        io::print!("{} ", *ele);
    }
    io::println!();
}

// NextC uses a multi‑pass compiler, so dependency order does not matter.
int read_int() {
    int result = 0;
    if (!io::read_int(&result)) {
        io::err_println("Invalid integer.");
        process::exit(1);
    }
    return result;
}

// slice[int] is a fat pointer.
// `const` here means `arr` itself is immutable, but the slice elements are readable and writable.
// A slice[const int] would have immutable elements.
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]);
            }
        }
    }
}