A clean, indentation-based systems programming language built in C.
Sage is a new programming language that combines the readability of Python (indentation blocks, clean syntax) with the low-level power of C. It is currently in the advanced development phase, with a fully working interpreter featuring Object-Oriented Programming, Garbage Collection, and Exception Handling.
- Indentation-based syntax: No braces
{}for blocks; just clean, consistent indentation - Type System: Support for Integers, Strings, Booleans, Nil, Arrays, Dictionaries, Tuples, Classes, Instances, and Exceptions
- Functions: Define functions with
proc name(args):with full recursion, closures, and first-class function support - Control Flow:
if/else,while,forloops,break,continue,match,defer,try/catch/finally - Operators: Arithmetic (
+,-,*,/), comparison (==,!=,>,<,>=,<=), logical (and,or,not)
- Classes:
class ClassName:with full inheritance support - Constructors:
init(self, ...)method for initialization - Methods: Functions with automatic
selfbinding - Properties: Dynamic instance variables via
self.property - Inheritance:
class Child(Parent):with method overriding - Property Access:
obj.propertyandobj.property = value
let status = 200
match status:
case 200:
print "OK"
case 404:
print "Not Found"
case 500:
print "Server Error"
default:
print "Unknown Status"proc open_file(filename):
print "Opening: " + filename
defer print "Closing: " + filename # Runs when scope exits
print "Processing: " + filename
# Defer executes here automaticallytry:
let result = divide(10, 0)
catch e:
print "Error: " + e
finally:
print "Cleanup always runs"
proc divide(a, b):
if b == 0:
raise "Division by zero!"
return a / b- Arrays: Dynamic lists with
push(),pop(),len(), and slicingarr[start:end] - Dictionaries: Hash maps with
{"key": value}syntax - Tuples: Immutable sequences
(val1, val2, val3) - Array Slicing: Pythonic slice syntax for arrays
- Garbage Collection: Automatic mark-and-sweep GC
- GC Control:
gc_collect(),gc_enable(),gc_disable() - Statistics:
gc_stats()for memory monitoring - Safe: Prevents use-after-free and memory leaks
- Methods:
split(),join(),replace(),upper(),lower(),strip() - Concatenation:
"Hello" + " World" - Indexing: Access individual characters
- Core:
print(),input(),clock(),tonumber(),len() - Arrays:
push(),pop(),range(),slice() - Strings:
split(),join(),replace(),upper(),lower(),strip() - Dictionaries:
dict_keys(),dict_values(),dict_has(),dict_delete() - GC:
gc_collect(),gc_stats(),gc_enable(),gc_disable()
Sage has zero dependencies and builds with standard GCC/Clang.
- A C compiler (
gccorclang) make
- Clone the repository:
git clone https://github.com/Night-Traders-Dev/SageLang.git
cd SageLang- Compile:
make clean && make -j$(nproc)This produces the sage executable.
- Run examples:
./sage examples/phase6_classes.sage
./sage examples/exceptions.sage
./sage examples/match_example.sage
./sage examples/defer_example.sageexamples/exceptions.sage
# Basic exception handling
try:
print "Trying risky operation..."
raise "Something went wrong!"
print "This won't execute"
catch e:
print "Caught: " + e
finally:
print "Cleanup complete"
# Function with error handling
proc validate_age(age):
if age < 0:
raise "Age cannot be negative"
if age > 150:
raise "Age too high"
return true
try:
validate_age(-5)
catch e:
print "Validation error: " + e# HTTP status code handling
proc handle_status(code):
match code:
case 200:
return "Success"
case 404:
return "Not Found"
case 500:
return "Server Error"
default:
return "Unknown"
let result = handle_status(404)
print result # "Not Found"proc process_file(name):
print "Opening: " + name
defer print "Closing: " + name
defer print "Releasing lock"
defer print "Saving changes"
print "Processing file..."
# Defers execute in reverse order (LIFO)examples/phase6_classes.sage
# Define a class with constructor and methods
class Person:
proc init(self, name, age):
self.name = name
self.age = age
proc greet(self):
print "Hello, my name is"
print self.name
print "I am"
print self.age
print "years old"
proc birthday(self):
self.age = self.age + 1
print "Happy birthday!"
# Create instances
let alice = Person("Alice", 30)
let bob = Person("Bob", 25)
# Call methods
alice.greet()
alice.birthday()
# Access properties
print alice.name
print alice.age# Base class
class Animal:
proc init(self, name):
self.name = name
proc speak(self):
print "Some sound"
# Derived class with method overriding
class Dog(Animal):
proc init(self, name, breed):
self.name = name
self.breed = breed
proc speak(self):
print "Woof! Woof!"
proc info(self):
print self.name
print "is a"
print self.breed
let dog = Dog("Rex", "Golden Retriever")
dog.speak() # Prints "Woof! Woof!"
dog.info()# Arrays with methods
let numbers = [1, 2, 3, 4, 5]
push(numbers, 6)
print numbers[0:3] # [1, 2, 3]
print len(numbers) # 6
# Dictionaries
let person = {"name": "Alice", "age": "30"}
print person["name"]
person["city"] = "NYC"
let keys = dict_keys(person)
print keys # ["name", "age", "city"]
# Tuples
let point = (10, 20, 30)
print point[0] # 10# Get GC statistics
let stats = gc_stats()
print stats["bytes_allocated"]
print stats["num_objects"]
print stats["collections"]
# Manual garbage collection
gc_collect()
# Disable GC for performance-critical section
gc_disable()
# ... intensive computation ...
gc_enable()- Phase 1: Core Logic (Lexer, Parser, Interpreter, Variables, Loops)
- Phase 2: Functions (
procdefinitions, calls, recursion, closures) - Phase 3: Types & Stdlib (Strings, Booleans, Native Functions)
- Phase 4: Memory Management (Mark-and-Sweep Garbage Collection)
- Phase 5: Advanced Data Structures (Arrays, Dictionaries, Tuples, Slicing)
- Phase 6: Object-Oriented Programming (Classes, Inheritance, Methods) β COMPLETE
- Phase 7: Advanced Control Flow π IN PROGRESS (~75% complete)
- Match expressions (pattern matching)
- Defer statements (scope-exit handlers)
- Exception handling (try/catch/finally/raise) - 80% complete
- Generators/yield (lazy evaluation)
- Phase 8: Modules & Packages (Imports, Package Manager) π NEXT
- Phase 9: Low-Level Programming β Planned
- Inline assembly (x86-64, ARM, RISC-V)
- Pointer arithmetic and raw memory access
- FFI (Foreign Function Interface)
- Bit manipulation
- Phase 10: Compiler Development (C/LLVM IR codegen)
- Phase 11: Concurrency (Threads, Async/Await)
- Phase 12: Tooling (LSP, Formatter, Debugger, REPL)
- Phase 13: Self-Hosting (Rewrite compiler in Sage)
π For a detailed breakdown of all planned features, see ROADMAP.md
Sage aims to be a systems programming language that:
- Maintains clean, readable syntax (like Python)
- Provides low-level control (like C/Rust)
- Supports modern OOP with classes and inheritance
- Enables inline assembly for performance-critical code
- Compiles to native code via C or LLVM
- Eventually becomes self-hosted
Module System:
# Import modules
import math
import io from std
# Use imported functions
let result = math.sqrt(16)
io.write_file("output.txt", "Hello")Low-Level Programming:
# Inline assembly
proc fast_multiply(a: i64, b: i64) -> i64:
let result: i64
asm:
"mov rax, {a}"
"imul {b}"
"mov {result}, rax"
: "=r"(result)
: "r"(a), "r"(b)
: "rax", "rdx"
return result
# Pointer operations
proc write_memory(ptr: *mut u8, value: u8):
unsafe:
*ptr = value- Language: C
- Lines of Code: ~8,000+
- Phases Completed: 6.75/13 (~52%)
- Status: Advanced Development (Phase 7 in progress)
- License: MIT
- Current Version: v0.7.0-alpha
sage/
βββ include/ # Header files
β βββ ast.h # AST nodes (match, defer, try/catch)
β βββ lexer.h # Tokenization
β βββ parser.h # Syntax analysis
β βββ env.h # Scope management
β βββ value.h # Type system (exceptions)
β βββ gc.h # Garbage collection
β βββ interpreter.h # Evaluator
βββ src/ # C implementation
β βββ main.c # Entry point
β βββ lexer.c # Tokenizer (match, defer, try, catch, raise)
β βββ parser.c # Parser (exception handling, pattern matching)
β βββ ast.c # AST constructors
β βββ env.c # Environment
β βββ value.c # Values (ExceptionValue)
β βββ gc.c # Mark-and-sweep GC
β βββ interpreter.c # Evaluator (exception propagation)
βββ examples/ # Example programs
β βββ exceptions.sage # Exception handling demos
β βββ match_example.sage # Pattern matching
β βββ defer_example.sage # Defer statements
β βββ phase6_classes.sage # OOP demonstration
β βββ phase5_data.sage # Data structures
β βββ phase4_gc_demo.sage # GC examples
βββ EXCEPTIONS_GUIDE.md # Implementation guide
βββ ROADMAP.md # Detailed development roadmap
βββ Makefile # Build script
βββ README.md # This file
Sage is an educational project aimed at understanding compiler construction and language design. Contributions are welcome!
- Exception Handling: Complete parser/interpreter integration
- Generators: Implement yield and lazy evaluation
- Module System: Phase 8 implementation (imports, packages)
- Testing: Write test cases for Phase 7 features
- Documentation: Improving code comments and guides
- Fork the project
- Create your feature branch (
git checkout -b feature/AmazingFeature) - Commit your changes (
git commit -m 'Add some AmazingFeature') - Push to the branch (
git push origin feature/AmazingFeature) - Open a Pull Request
- Follow the existing code style
- Add comments for complex logic
- Update documentation for new features
- Write example code demonstrating new features
- Check the ROADMAP.md for planned features
- Repository: github.com/Night-Traders-Dev/SageLang
- Detailed Roadmap: ROADMAP.md
- Exception Guide: EXCEPTIONS_GUIDE.md
- Issues: GitHub Issues
- Discussions: GitHub Discussions
Distributed under the MIT License. See LICENSE for more information.
Built with β€οΈ for systems programming enthusiasts
Recent Milestones:
- π November 28, 2025: Phase 7 In Progress - Advanced Control Flow (Match, Defer, Exceptions)
- β November 28, 2025: Phase 6 Complete - Object-Oriented Programming with full OOP support
- β November 27, 2025: Phase 5 Complete - Advanced Data Structures (Arrays, Dicts, Tuples)
- β November 27, 2025: Phase 4 Complete - Garbage Collection (Mark-and-Sweep GC)