Skip to content

Night-Traders-Dev/SageLang

Repository files navigation

Sage

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.

πŸš€ Features (Implemented)

Core Language

  • 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, for loops, break, continue, match, defer, try/catch/finally
  • Operators: Arithmetic (+, -, *, /), comparison (==, !=, >, <, >=, <=), logical (and, or, not)

Object-Oriented Programming πŸŽ‰ COMPLETE

  • Classes: class ClassName: with full inheritance support
  • Constructors: init(self, ...) method for initialization
  • Methods: Functions with automatic self binding
  • Properties: Dynamic instance variables via self.property
  • Inheritance: class Child(Parent): with method overriding
  • Property Access: obj.property and obj.property = value

Phase 7: Advanced Control Flow πŸŽ‰ NEW

Match Expressions (Pattern Matching)

let status = 200
match status:
    case 200:
        print "OK"
    case 404:
        print "Not Found"
    case 500:
        print "Server Error"
    default:
        print "Unknown Status"

Defer Statements (Scope-Exit Handlers)

proc open_file(filename):
    print "Opening: " + filename
    defer print "Closing: " + filename  # Runs when scope exits
    print "Processing: " + filename
    # Defer executes here automatically

Exception Handling (Try/Catch/Finally)

try:
    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

Advanced Data Structures

  • Arrays: Dynamic lists with push(), pop(), len(), and slicing arr[start:end]
  • Dictionaries: Hash maps with {"key": value} syntax
  • Tuples: Immutable sequences (val1, val2, val3)
  • Array Slicing: Pythonic slice syntax for arrays

Memory Management

  • 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

String Operations

  • Methods: split(), join(), replace(), upper(), lower(), strip()
  • Concatenation: "Hello" + " World"
  • Indexing: Access individual characters

Standard Library (30+ Native Functions)

  • 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()

πŸ›  Building Sage

Sage has zero dependencies and builds with standard GCC/Clang.

Prerequisites

  • A C compiler (gcc or clang)
  • make

Build Steps

  1. Clone the repository:
git clone https://github.com/Night-Traders-Dev/SageLang.git
cd SageLang
  1. Compile:
make clean && make -j$(nproc)

This produces the sage executable.

  1. Run examples:
./sage examples/phase6_classes.sage
./sage examples/exceptions.sage
./sage examples/match_example.sage
./sage examples/defer_example.sage

πŸ“ Example Code

Exception Handling

examples/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

Pattern Matching

# 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"

Defer Statements

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)

Object-Oriented Programming

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

Inheritance

# 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()

Advanced Data Structures

# 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

Memory Management

# 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()

πŸ—Ί Roadmap (Summary)

  • Phase 1: Core Logic (Lexer, Parser, Interpreter, Variables, Loops)
  • Phase 2: Functions (proc definitions, 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

🎯 Vision

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

Future Capabilities

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

πŸ“Š Project Stats

  • 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

πŸ’Ύ Project Structure

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

🀝 Contributing

Sage is an educational project aimed at understanding compiler construction and language design. Contributions are welcome!

Current Focus Areas

  1. Exception Handling: Complete parser/interpreter integration
  2. Generators: Implement yield and lazy evaluation
  3. Module System: Phase 8 implementation (imports, packages)
  4. Testing: Write test cases for Phase 7 features
  5. Documentation: Improving code comments and guides

How to Contribute

  1. Fork the project
  2. Create your feature branch (git checkout -b feature/AmazingFeature)
  3. Commit your changes (git commit -m 'Add some AmazingFeature')
  4. Push to the branch (git push origin feature/AmazingFeature)
  5. Open a Pull Request

Development Guidelines

  • 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

πŸ”— Resources

πŸ“œ License

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)

About

No description, website, or topics provided.

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published