A modern programming language that compiles to C
Features • Quick Start • Documentation • Examples • Contributing • Testing
Cnext is a high-level, statically-typed language with a familiar syntax that transpiles to C. It combines modern language features like generics, closures, pattern matching, and async/await with the performance and portability of C.
- Checked Memory Allocations — All compiler memory allocations now use safe wrappers that exit cleanly on OOM
- HTTPS Enforcement — Package registry connections require HTTPS, preventing MITM attacks
- Full Test Suite — 66 tests covering all language features, up from 44
- CI Performance Benchmarks — Automated build time tracking in CI
- VS Code Extension v3.1 — New commands: format, lint, new project, doctor, REPL
- Improved Project Scaffolding —
cnext newcreates projects with VS Code config and getting-started guide
- Modern Syntax — Clean, readable code with type inference (
var), string interpolation, and optional semicolons - Rich Type System —
int,long,float,double,str,bool,char,byte,uint,ulong,ushort,ubyte - Type Aliases —
type MyInt = intfor clearer code - Nullable Types —
str?,int?for optional values - Generics — Write reusable code with parameterized types
- Closures — First-class functions with captured variables
- Pattern Matching — Expressive
matchexpressions with wildcards - Classes & Traits — OOP with inheritance, interfaces, and composable traits
- Error Handling —
try/catch/finallywiththrowstatements - Generators & Coroutines — Lazy iteration with
yieldand cooperative multitasking - Async/Await — Asynchronous programming with
async funcandawait - Multithreading — Thread-safe programming with
MutexandChannel - Standard Library — Modules for I/O, math, JSON, networking, crypto, and more
- String Utilities —
contains,starts_with,ends_with,to_upper,to_lower,trim,find,replace, and more - Package Manager — Built-in dependency management with
cnext.toml - Code Formatter —
cnext fmtfor consistent code style - Linter —
cnext lintwith rules for unreachable code, comparisons, and more - REPL —
cnext replfor interactive experimentation - Optimizer — 9 passes: constant propagation, copy propagation, peephole, identity elimination, constant folding, dead code elimination, branch simplification, tail-call detection, loop optimizations
- Package Registry —
cnext search/install/publish/login/logout/update/remove - Language Server — LSP for VS Code, Neovim, Helix, Sublime, Emacs
- Cross-Platform — Windows, Linux, macOS support with conditional compilation
- Developer Tools —
cnext doctor,cnext init,cnext upgrade,cnext cache,cnext config
One-liner (Linux/macOS):
curl -fsSL https://raw.githubusercontent.com/Melton122/cnext/main/install.sh | bashWindows (PowerShell):
iwr -useb https://raw.githubusercontent.com/Melton122/Cnext/main/install.ps1 | iexOr download install.bat from the Releases page and run it.
From Source:
git clone https://github.com/Melton122/cnext.git
cd cnext
make
sudo make installSee docs/installation.md for all platforms and options.
Install the Cnext extension for syntax highlighting, snippets, and build tasks:
# Package and install from source
cd vscode-extension
npm install -g @vscode/vsce
vsce package
code --install-extension cnext-3.1.0.vsixOr search for "Cnext" in the VS Code Extensions panel.
Features:
- Syntax highlighting for all Cnext features
- 25+ code snippets
- Run, build, format, and lint with keyboard shortcuts
- Auto-run and auto-format on save
- New project creator
- Interactive REPL
See vscode-extension/README.md for details.
cnext new my_app
cd my_app
cnext run src/main.cnThis creates a project with sample files demonstrating variables, functions, classes, and modules.
Create a file hello.cn:
main {
printin("Hello, World!")
}
Run it:
cnext run hello.cncnext build file.cn --release # Optimized build
cnext build file.cn --debug # Debug build with symbols
cnext build file.cn --verbose # Show generated C code
cnext build file.cn --clean # Remove build artifactsint x = 42
long big = 9999999999
float pi = 3.14
double precise = 2.718281828
str name = "Cnext"
bool flag = true
char letter = 'A'
byte small = 255
uint unsigned_val = 4294967295
// Type inference
var auto_detected = 100 // int
var greeting = "Hi" // str
// Type aliases
type MyInt = int
type Name = str
MyInt my_num = 100
// Nullable types
str? optional_str = null
int? optional_int = 42
func add(int a, int b) -> int {
return a + b
}
// Arrow syntax for simple functions
func multiply(int a, int b) -> int => a * b
// Default and named arguments
func greet(str name, str greeting = "Hello") {
printin(greeting + ", " + name + "!")
}
greet("World") // Hello, World!
greet("Alice", greeting = "Hi") // Hi, Alice!
class Animal {
str name
func new(str n) {
self.name = n
}
func speak() -> str {
return "..."
}
}
class Dog extends Animal {
func new(str n) {
super.new(n)
}
override func speak() -> str {
return "Woof!"
}
}
func first<T>(T[] arr) -> T {
return arr[0]
}
class Box<T> {
T value
func new(T v) {
self.value = v
}
}
var x = 10
var add_x = (int a) => a + x
printin(add_x(5)) // 15
// Captures by reference
var counter = 0
var increment = () => {
counter = counter + 1
return counter
}
increment() // 1
increment() // 2
enum Color { RED, GREEN, BLUE }
func color_name(Color c) -> str {
match c {
RED => "red"
GREEN => "green"
BLUE => "blue"
_ => "unknown"
}
}
enum HttpStatus {
OK = 200,
NOT_FOUND = 404,
ERROR = 500
}
func describe(HttpStatus code) -> str {
match code {
200 => "OK"
404 => "Not Found"
_ => "Error"
}
}
import string_utils
str s = "Hello, World!"
printin(len(s)) // 13
printin(string_utils.to_upper(s)) // HELLO, WORLD!
printin(string_utils.contains(s, "World")) // true
printin(string_utils.replace(s, "World", "Cnext")) // Hello, Cnext!
| Module | Description |
|---|---|
io |
File I/O operations |
math |
Mathematical functions |
json |
JSON parsing and generation |
net |
HTTP and TCP networking |
os |
System operations |
file |
File system operations |
string_utils |
String manipulation |
time |
Date and time functions |
regex |
Regular expressions |
collections |
Lists, maps, and sets |
crypto |
Cryptographic functions |
path |
Path manipulation |
encoding |
Base64, hex, URL encoding |
process |
Process management |
random |
Random number generation |
thread |
Threading and synchronization |
Create a cnext.toml in your project root:
[package]
name = "my-project"
version = "0.1.0"
[dependencies]
mylib = "https://github.com/user/mylib/raw/main/mylib.cn"Install dependencies:
cnext install# Build the compiler
make
# Build with debug symbols
make DEBUG=1
# Run tests
make test
# Run full test suite (compiler + Python tests)
make check
# Install to /usr/local/bin (Linux/macOS)
make install
# Install to %LOCALAPPDATA%\Cnext\bin (Windows)
mingw32-make install
# Clean build artifacts
make clean
# Format source code
make format
# Show build benchmarks
make benchcnext/
├── src/ # Compiler source code
│ ├── main.c # CLI entry point
│ ├── lexer.c # Tokenizer
│ ├── parser*.c # Parser (6 files)
│ ├── ast.c # AST nodes
│ ├── codegen*.c # Code generation (8 files)
│ ├── semantics*.c # Semantic analysis (5 files)
│ ├── optimizer.c # Optimizer
│ ├── formatter.c # Code formatter
│ ├── linter.c # Linter
│ ├── repl.c # REPL
│ ├── registry.c # Package registry
│ └── semver.c # Semantic versioning
├── include/ # Header files and runtime
│ ├── runtime.h # Runtime library (all functions)
│ ├── collections.h # Data structures
│ ├── string_utils.h # String utilities
│ └── diagnostics.h # Error diagnostics
├── tests/ # Test files (50+ tests)
├── examples/ # Example programs
├── docs/ # Documentation
├── lsp/ # Language Server Protocol
├── website/ # Registry website and playground
└── Makefile # Build system
We welcome contributions! Here's how to get started:
- Fork the repository
- Clone your fork:
git clone https://github.com/YOUR_USERNAME/cnext.git cd cnext - Build the compiler:
make
- Run tests:
make test
- Language: C (GNU C11 standard)
- Indentation: 4 spaces (no tabs)
- Braces: Allman style (opening brace on new line)
- Naming:
snake_casefor functions/variables,UPPER_CASEfor macros - Header guards:
#ifndef CNEXT_NAME_H/#define CNEXT_NAME_H - No comments unless the intent is non-obvious
- Use
checked_alloc.hfor all allocations
- Create a feature branch:
git checkout -b feature/my-feature
- Make your changes
- Run tests:
make test make check # Full test suite
- Commit with a clear message:
git commit -m "Add feature: description of change" - Push and create a pull request
Found a bug? Please report it:
- Check if the issue already exists in GitHub Issues
- If not, create a new issue with:
- Title: Clear, concise description
- Environment: OS, compiler version (
cnext version) - Steps to reproduce: Minimal code example
- Expected behavior: What should happen
- Actual behavior: What actually happens
Good first issues:
- Fix typos in documentation
- Add test cases for edge cases
- Improve error messages
- Add examples
Larger contributions:
- New standard library modules
- Optimizer improvements
- Cross-platform enhancements
- Language features
# Run compiler built-in tests
make test
# Run full test suite
make check
# Run specific test
cnext build tests/test_v9.cn
./out.exeCreate a test file in tests/:
// EXPECT: expected output line 1
// EXPECT: expected output line 2
main {
// Your test code
printin("Hello, World!")
}
- Lexer tests: Token recognition
- Parser tests: Syntax parsing
- Semantic tests: Type checking
- Codegen tests: Code generation
- Runtime tests: Runtime behavior
- Optimizer tests: Optimization passes
- Integration tests: Full program tests
See the examples/ directory for complete programs:
hello.cn- Basic hello worldclasses.cn- OOP with classesclosures.cn- Closure examplesgenerators.cn- Generator functionshttp_server.cn- HTTP servercalculator.cn- Calculatortodo_cli.cn- CLI todo app
MIT License - see LICENSE for details.
Inspired by modern languages like Rust, Go, Swift, and TypeScript, while maintaining compatibility with C through transpilation.
