<p align="center">
  <img src="assets/logo.png" alt="Redline" width="280">
  <br><br>
  <b>Cross the performance line. Won't compile.</b>
  <p align="center">
    <a href="https://crates.io/crates/redline"><img src="https://img.shields.io/crates/v/redline?color=green" alt="crates.io"></a>
    <a href="https://github.com/TxsharDev/Redline/blob/master/LICENSE"><img src="https://img.shields.io/badge/license-Apache%202.0-green" alt="License"></a>
    <a href="#"><img src="https://img.shields.io/badge/tests-14%20pass-green" alt="Tests"></a>
  </p>
  <p align="center">
    <a href="docs/wiki/Quick-Start.md">Quick Start</a> &nbsp;|&nbsp;
    <a href="docs/wiki/Constraints.md">Constraints</a> &nbsp;|&nbsp;
    <a href="docs/wiki/Cost-Model.md">Cost Model</a> &nbsp;|&nbsp;
    <a href="docs/wiki/Use-Cases.md">Use Cases</a> &nbsp;|&nbsp;
    <a href="docs/wiki/Limitations.md">Limitations</a>
  </p>
</p>

---

Rust proves memory safety at compile time. Redline enforces performance bounds at compile time.

```rust
#[redline(latency = "< 1ms")]
fn process_request(req: &Request) -> Response {
    // compiler checks: estimated worst-case for every visible path < 1ms
}
```

If any code path can exceed the bound, the function does not compile. Not a warning. Not a lint. A hard compiler error.

## Install

```toml
[dependencies]
redline = "0.1"
```

## Usage

```rust
use redline::redline;

// Latency bound: estimated worst-case must be under 1ms
#[redline(latency = "< 1ms")]
fn fast_handler(data: &[u8]) -> u64 {
    let mut sum: u64 = 0;
    for i in 0..100 {
        sum += data.get(i).copied().unwrap_or(0) as u64;
    }
    sum
}

// Zero allocations: no Vec, String, Box, HashMap, clone, collect
#[redline(allocs = 0)]
fn hot_path(a: f64, b: f64) -> f64 {
    a * a + b * b
}

// Zero syscalls: no file I/O, no network, no println
#[redline(syscalls = 0)]
fn pure_compute(x: i32) -> i32 {
    x * x + 2 * x + 1
}

// Combined: all constraints checked together
#[redline(latency = "< 100us", allocs = 0, syscalls = 0)]
fn critical_section(data: &[u8]) -> u64 {
    let mut h: u64 = 0;
    for i in 0..64 {
        h ^= data.get(i).copied().unwrap_or(0) as u64;
    }
    h
}
```

## What Happens When You Break It

```rust
#[redline(allocs = 0)]
fn oops() -> String {
    String::from("hello")  // allocates
}
```

```
error: redline: function `oops` has 1 allocation(s), limit is 0
 --> src/main.rs:3:1
  |
3 | #[redline(allocs = 0)]
  | ^^^^^^^^^^^^^^^^^^^^^^
```

```rust
#[redline(syscalls = 0)]
fn also_oops() {
    println!("this is I/O");  // syscall
}
```

```
error: redline: function `also_oops` has 1 syscall(s), limit is 0
```

```rust
#[redline(latency = "< 1us")]
fn too_slow() -> u64 {
    let mut sum: u64 = 0;
    for i in 0..10000 {
        sum += i;
    }
    sum
}
```

```
error: redline: estimated worst-case latency 10001ns exceeds bound 1000ns in `too_slow`
```

The binary is never produced. The performance violation is caught before any code runs.

## Supported Constraints

| Constraint | Syntax | What It Checks |
|-----------|--------|---------------|
| Latency | `latency = "< 1ms"` | Worst-case estimated execution time |
| Throughput | `throughput = "> 1GB/s"` | Minimum sustained throughput |
| Allocations | `allocs = 0` or `allocs = "< 5"` | Heap allocation count |
| Syscalls | `syscalls = 0` | System call count (I/O, network, print) |
| Stack size | `max_stack = "< 4KB"` | Stack frame size estimate |

### Time Units
`ns`, `us`, `ms`, `s`

### Size Units
`B`, `KB`, `MB`, `GB`, `TB`

## How It Works

Redline is a Rust proc-macro. At compile time, it:

1. Parses the performance annotation
2. Walks the function's AST (abstract syntax tree)
3. Counts allocations: `Vec::new`, `Box::new`, `String::from`, `.clone()`, `.collect()`, `.to_string()`, `.to_owned()`, HashMap/BTreeMap/etc.
4. Counts syscalls: `fs::read`, `File::open`, `TcpStream::connect`, `println!`, etc.
5. Estimates loop costs: literal ranges (`0..1000`) give exact iteration count, unknown ranges assume 1000 (pessimistic)
6. Takes worst-case branches: if/else and match analyze both arms, report the slower one
7. Sums the cost model and compares against the annotation
8. Emits a compile error if any constraint is violated

## Cost Model

The cost model uses conservative estimates based on modern x86-64:

| Operation | Estimated Cost |
|-----------|---------------|
| ALU operation | 1 ns |
| Branch | 1 ns |
| Array index | 1 ns |
| Function call | 5 ns |
| HashMap lookup | 25 ns |
| Heap allocation | 50 ns |
| HashMap insert | 50 ns |
| Mutex lock | 100 ns |
| String format | 200 ns |
| Syscall (file I/O) | 1,000 ns |
| println! | 5,000 ns |
| Network syscall | 10,000 ns |

These are intentionally pessimistic. Better to reject a fast function than to accept a slow one.

## What This Does NOT Do

- Does not profile at runtime. All analysis is at compile time.
- Does not guarantee exact nanosecond accuracy. The cost model is an estimate.
- Does not analyze across function boundaries (callee costs are not inlined).
- Does not know runtime values. Loop bounds must be literal for exact analysis; variables assume worst case (1000 iterations).
- Does not replace benchmarks. Use Redline for hard bounds, use criterion for measurement.

## Architecture

```
src/
  lib.rs       Proc-macro entry point (#[redline(...)])
  parse.rs     Attribute parser (latency, throughput, allocs, syscalls, max_stack)
  analyze.rs   AST walker: counts allocs, syscalls, estimates latency per path
  cost.rs      Cost model constants and recognized function signatures
```

## Prior Art

Nothing does this. Tools in the vicinity:

| Tool | What It Does | How Redline Differs |
|------|-------------|-------------------|
| **Clippy** | Linting (style, common mistakes) | Redline enforces performance bounds, not style |
| **Miri** | Runtime UB detection | Redline is compile-time, not runtime |
| **Criterion** | Benchmarking | Redline is a guarantee, not a measurement |
| **perf/flamegraph** | Runtime profiling | Redline prevents slow code from compiling |
| **WCET analyzers** | Worst-case execution time (embedded/real-time) | Those operate on binary/IR. Redline operates on source AST. |
| **#[no_std]** | Removes standard library | Redline lets you use std but bound what you use |

WCET (worst-case execution time) analysis exists in embedded/avionics, but it operates on compiled binaries or LLVM IR, requires hardware-specific timing models, and is not available as a language-level annotation. Redline brings the concept to the source level as a proc-macro.

## Roadmap

**v0.1** (current) - Proc-macro with allocation counting, syscall detection, latency estimation from loop bounds and operation costs. 10 compile-time test cases.

**v0.2** - Cross-function analysis (inline callee costs). Cache-aware cost model. I/O cost modeling. Integration with LLVM cost model for instruction-level estimates.

**v0.3** - Runtime verification mode: instrument the compiled code to validate the static analysis. Feedback loop to calibrate the cost model against real hardware.

## Documentation

- [Wiki: Quick Start](docs/wiki/Quick-Start.md)
- [Wiki: Constraints Reference](docs/wiki/Constraints.md)
- [Wiki: Cost Model](docs/wiki/Cost-Model.md)
- [Wiki: Use Cases](docs/wiki/Use-Cases.md) (6 real-world scenarios)
- [Wiki: Limitations](docs/wiki/Limitations.md) (honest about what it can't catch)
- [Wiki: Architecture](docs/wiki/Architecture.md)
- [Wiki: Troubleshooting](docs/wiki/Troubleshooting.md)

## License

Apache-2.0 | ALIA Labs

Built by [Tushar Sharma](https://github.com/TxsharDev) at ALIA Labs.
