@freelang/backend-c
v1.0.0
Published
Production-ready C code generator for the FreeLang programming language with comprehensive language features
Maintainers
Readme
FreeLang C Backend
Production-ready C code generator for the FreeLang programming language.
A high-performance compiler backend that transforms FreeLang abstract syntax trees (AST) into optimized C code, combining FreeLang's type safety with C's portability and performance.
🚀 Features
Language Features (Complete)
- ✅ Pattern Matching: if-let patterns, match expressions, Option/Result handling
- ✅ Generic Types: Generic functions and structs with type parameters
- ✅ Error Handling: Result types, try-catch expressions, error propagation
- ✅ Extended Standard Library: 45+ built-in functions
- ✅ Memory Optimization: Automatic allocator inference, ownership analysis, defer statements
- ✅ Performance Optimization: Inline functions, dead code elimination, constant folding, loop optimization
- ✅ Low-Level Control: Direct memory manipulation, pointer operations, manual optimization
Code Quality
- Comprehensive test coverage
- Production-ready example programs
- Complete type-safe code generation
- Memory-safe patterns with allocator strategies
- Comprehensive documentation
📦 Installation
npm install @freelang/backend-c🎯 Quick Start
As a FreeLang Backend
# Install FreeLang and C backend
npm install -g @freelang/freelang @freelang/backend-c
# Compile FreeLang to C
freelang build main.free --backend c
# Compile to native executable
gcc -O2 main.c -o main -lm
# Run
./mainAs a Library
import { compileToC } from '@freelang/backend-c';
import { Parser, TypeChecker } from '@freelang/freelang';
const source = `
fn main() {
println("Hello, C!");
}
`;
// Parse and type-check
const ast = new Parser(source).parse();
const typed = new TypeChecker().check(ast);
// Generate C code
const cCode = compileToC(typed);
console.log(cCode);📚 Documentation
- Getting Started Guide - Complete usage instructions
- C Runtime Library - FreeLang C runtime functions
- Examples - 10 complete example programs
🎓 10 Complete Examples
- hello-world - Basic I/O and functions
- functions - Function definitions and calls
- structs - Struct definitions and usage
- fibonacci - Recursive functions
- pattern-matching - if-let, match expressions, Option/Result
- generics - Generic functions and structs with type parameters
- error-handling - Result types, error propagation
- stdlib - 45+ built-in functions demonstration
- memory-optimization - Allocator strategies, manual optimization
- performance - Inline, constant folding, loop optimization
Run any example:
freelang build examples/pattern-matching/main.free --backend c
gcc -O2 pattern-matching.c -o pattern-matching -lm
./pattern-matching🔧 Configuration
Allocator Strategies
import { CCodeGenerator } from '@freelang/backend-c';
const generator = new CCodeGenerator({
allocatorStrategy: 'arena' // Fast, short-lived allocations
// or 'stack' (stack-based, fastest)
// or 'heap' (malloc/free, flexible)
// or 'pool' (fixed-size pool, predictable)
});Optimization Levels
# Debug build (with assertions and symbols)
gcc main.c -o main -g -DDEBUG
# Optimized build (O2)
gcc -O2 main.c -o main -lm
# Size-optimized build (Os)
gcc -Os main.c -o main -lm
# Fastest build (O3)
gcc -O3 main.c -o main -lm📊 Features Summary
| Feature | Status | Examples | |---------|--------|----------| | Pattern Matching | ✅ Complete | pattern-matching/ | | Generic Types | ✅ Complete | generics/ | | Error Handling | ✅ Complete | error-handling/ | | Standard Library | ✅ Complete | stdlib/ | | Memory Optimization | ✅ Complete | memory-optimization/ | | Performance Optimization | ✅ Complete | performance/ | | Total | ✅ Complete | 10 programs |
🧪 Testing
# Run all tests
npm test
# Run specific test file
npm test -- codegen.test.ts
# Watch mode
npm run test:watch
# Coverage report
npm run test:coverage🏗️ Project Structure
src/
├─ index.ts # Plugin interface
├─ codegen.ts # Main code generator (1,100+ lines)
├─ stdlib.ts # 45+ built-in functions
├─ types.ts # Type mapping
└─ templates/ # C code templates
tests/
├─ codegen.test.ts # Code generation tests
├─ types.test.ts # Type mapping tests
├─ patterns.test.ts # Pattern matching tests
├─ generics.test.ts # Generic type tests
├─ error-handling.test.ts # Error handling tests
├─ stdlib.test.ts # Standard library tests
├─ memory-optimization.test.ts
├─ performance.test.ts
└─ integration.test.ts # Integration tests
examples/
├─ hello-world/
├─ functions/
├─ structs/
├─ fibonacci/
├─ pattern-matching/
├─ generics/
├─ error-handling/
├─ stdlib/
├─ memory-optimization/
└─ performance/📈 Statistics
| Metric | Value | |--------|-------| | Code Lines (src/) | 1,100+ | | Built-in Functions | 45+ | | Example Programs | 10 | | Test Files | 9 | | Documentation | Complete |
🔄 Code Generation Pipeline
FreeLang Source Code
↓
Parser (FreeLang)
↓
Type Checker (FreeLang)
↓
AST
↓
CCodeGenerator ← [This Package]
↓
C Code
↓
C Compiler (gcc/clang)
↓
Native Executable📖 Built-in Functions (45+)
String Functions (8): strlen, strcat, strcmp, strcpy, substring, uppercase, lowercase, trim
Array Functions (10): first, last, take, drop, flatten, unique, compact, count, sum, average
Math Functions (12): min, max, gcd, lcm, clamp, sqrt, pow, floor, ceil, round, abs, exp
Type Functions (4): typeof, sizeof, is_null, is_empty
System Functions (3): sleep, timestamp, now
Memory Functions (4): malloc_c, free_c, calloc_c, realloc_c
Utility Functions (4): panic, unwrap, assert
See stdlib.ts for complete list and mappings.
🤝 Contributing
Contributions are welcome! Please:
- Fork the repository
- Create a feature branch
- Add tests for new functionality
- Ensure all tests pass (
npm test) - Submit a pull request
📝 License
MIT - See LICENSE file
🔗 Related Projects
- FreeLang - The FreeLang programming language
- FreeLang Zig Backend - Zig code generator
- C Standard Library - C reference documentation
📞 Support
Version 1.0.0 - Production Ready ✅
Made with ❤️ for the FreeLang community
