npm package: @freelang/backend-c
Description: Production-ready C code generator for the FreeLang programming language with comprehensive language features
Author: Kim
Latest version: 1.0.0

# FreeLang C Backend

[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)
[![npm version](https://img.shields.io/badge/npm-v1.0.0-blue)](https://www.npmjs.com/package/@freelang/backend-c)
[![Node.js Version](https://img.shields.io/badge/Node.js-%3E%3D16.0.0-green)](https://nodejs.org/)

**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

```bash
npm install @freelang/backend-c
```

## 🎯 Quick Start

### As a FreeLang Backend

```bash
# 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
./main
```

### As a Library

```typescript
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](./GETTING_STARTED.md) - Complete usage instructions
- [C Runtime Library](./docs/RUNTIME.md) - FreeLang C runtime functions
- [Examples](./examples/) - 10 complete example programs

## 🎓 10 Complete Examples

1. **hello-world** - Basic I/O and functions
2. **functions** - Function definitions and calls
3. **structs** - Struct definitions and usage
4. **fibonacci** - Recursive functions
5. **pattern-matching** - if-let, match expressions, Option/Result
6. **generics** - Generic functions and structs with type parameters
7. **error-handling** - Result types, error propagation
8. **stdlib** - 45+ built-in functions demonstration
9. **memory-optimization** - Allocator strategies, manual optimization
10. **performance** - Inline, constant folding, loop optimization

Run any example:

```bash
freelang build examples/pattern-matching/main.free --backend c
gcc -O2 pattern-matching.c -o pattern-matching -lm
./pattern-matching
```

## 🔧 Configuration

### Allocator Strategies

```typescript
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

```bash
# 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

```bash
# 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](./src/stdlib.ts) for complete list and mappings.

## 🤝 Contributing

Contributions are welcome! Please:

1. Fork the repository
2. Create a feature branch
3. Add tests for new functionality
4. Ensure all tests pass (`npm test`)
5. Submit a pull request

## 📝 License

MIT - See [LICENSE](./LICENSE) file

## 🔗 Related Projects

- [FreeLang](https://gogs.dclub.kr/kim/freelang) - The FreeLang programming language
- [FreeLang Zig Backend](https://gogs.dclub.kr/kim/freelang-zig) - Zig code generator
- [C Standard Library](https://en.cppreference.com/w/c) - C reference documentation

## 📞 Support

- 📖 [Full Documentation](./GETTING_STARTED.md)
- 🐛 [Issue Tracker](https://gogs.dclub.kr/kim/freelang-c/issues)
- 💬 [Discussions](https://gogs.dclub.kr/kim/freelang-c)

---

**Version 1.0.0 - Production Ready** ✅

Made with ❤️ for the FreeLang community