bashrs 1.0.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
# Rash - Bidirectional Shell Safety Tool

[![Crates.io](https://img.shields.io/crates/v/bashrs.svg)](https://crates.io/crates/bashrs)
[![Documentation](https://docs.rs/bashrs/badge.svg)](https://docs.rs/bashrs)
[![License](https://img.shields.io/crates/l/bashrs.svg)](LICENSE)
[![CI](https://github.com/paiml/bashrs/workflows/CI/badge.svg)](https://github.com/paiml/bashrs/actions)
[![Tests](https://img.shields.io/badge/tests-756%20passing-brightgreen)](https://github.com/paiml/bashrs/actions)
[![PropertyTests](https://img.shields.io/badge/property_tests-52%20passing-blue)](https://github.com/paiml/bashrs/blob/main/rash/src/testing/)
[![Coverage](https://img.shields.io/badge/coverage-85.36%25-green)](https://github.com/paiml/bashrs/actions)
[![Mutation](https://img.shields.io/badge/mutation-83%25%20baseline-yellow)](https://github.com/paiml/bashrs)

**Rash** is a bidirectional shell safety tool that lets you write shell scripts in REAL Rust and automatically purify legacy bash scripts.

## Why Rash?

- ๐Ÿ›ก๏ธ **Safety First**: Automatic protection against shell injection attacks
- ๐Ÿ” **Compile-Time Verification**: Catch errors before deployment
- ๐Ÿ“ฆ **Zero Runtime Dependencies**: Generated scripts work on any POSIX shell
- ๐ŸŽฏ **Deterministic Output**: Same input always produces identical scripts
- โœ… **ShellCheck Compliant**: All output passes strict linting

## How Rash Works: Two Workflows

Rash operates in **two directions** to maximize shell script safety:

### ๐Ÿš€ PRIMARY: Rust โ†’ Safe Shell (Production-Ready)

**Write new scripts in REAL Rust, transpile to provably safe shell.**

```
Rust Code (.rs) โ†’ cargo test โ†’ Transpile โ†’ Safe POSIX Shell
                   โ†‘ Test FIRST with Rust tooling
```

**Use cases**:
- Bootstrap installers (Node.js, Rust toolchain, etc.)
- CI/CD deployment scripts
- System configuration tools
- Any new shell automation

**Benefits**:
- Full Rust std library support
- Test with `cargo test`, lint with `cargo clippy`
- Property-based testing with proptest
- 100% deterministic, idempotent output

### ๐Ÿ”„ SECONDARY: Bash โ†’ Rust โ†’ Purified Bash (Legacy Cleanup)

**Ingest messy bash, convert to Rust with tests, output purified shell.**

```
Messy Bash โ†’ Parser โ†’ Rust + Tests โ†’ Transpile โ†’ Purified Bash
                       โ†‘ Tests auto-generated
```

**Use cases**:
- Clean up legacy bash scripts
- Remove non-deterministic constructs ($RANDOM, timestamps, $$)
- Enforce idempotency (mkdir -p, rm -f)
- Generate comprehensive test suites

**Benefits**:
- Automatic test generation
- Remove unsafe patterns
- Maintain shell compatibility
- Preserve functionality while improving safety

See [`examples/PURIFICATION_WORKFLOW.md`](examples/PURIFICATION_WORKFLOW.md) for detailed purification examples.

---

## Quick Start (PRIMARY Workflow)

Write Rust:

```rust
// install.rs
#[rash::main]
fn main() {
    let version = env_var_or("VERSION", "1.0.0");
    let prefix = env_var_or("PREFIX", "/usr/local");
    
    echo("Installing MyApp {version} to {prefix}");
    
    // Create installation directories
    mkdir_p("{prefix}/bin");
    mkdir_p("{prefix}/share/myapp");
    
    // Copy files (with automatic quoting)
    if exec("cp myapp {prefix}/bin/") {
        echo("โœ“ Binary installed");
    } else {
        echo("โœ— Failed to install binary");
        exit(1);
    }
}
```

Get POSIX shell:

```bash
$ bashrs build install.rs -o install.sh
$ cat install.sh
#!/bin/sh
# Generated by Rash v0.4.0
# POSIX-compliant shell script

set -euf
IFS=' 	
'
export LC_ALL=C

# Rash runtime functions
rash_require() {
    if ! "$@"; then
        echo "FATAL: Requirement failed: $*" >&2
        exit 1
    fi
}

# Main script begins
main() {
    VERSION="${VERSION:-1.0.0}"
    PREFIX="${PREFIX:-/usr/local}"
    
    echo "Installing MyApp $VERSION to $PREFIX"
    
    mkdir -p "$PREFIX/bin"
    mkdir -p "$PREFIX/share/myapp"
    
    if cp myapp "$PREFIX/bin/"; then
        echo "โœ“ Binary installed"
    else
        echo "โœ— Failed to install binary"
        exit 1
    fi
}

# Execute main function
main "$@"
```

## Installation

### From crates.io (Recommended)

```bash
# Install latest release candidate
cargo install bashrs --version 1.0.0-rc1

# Or install latest stable
cargo install bashrs
```

### Binary Releases

Pre-built binaries are available for Linux and macOS:

```bash
# Linux x86_64
curl -L https://github.com/paiml/bashrs/releases/latest/download/bashrs-x86_64-unknown-linux-musl.tar.gz | tar xz

# macOS x86_64
curl -L https://github.com/paiml/bashrs/releases/latest/download/bashrs-x86_64-apple-darwin.tar.gz | tar xz

# macOS ARM64
curl -L https://github.com/paiml/bashrs/releases/latest/download/bashrs-aarch64-apple-darwin.tar.gz | tar xz
```

### Using cargo-binstall

```bash
cargo binstall bashrs
```

### From Source

```bash
# Full build with all features
cargo install --git https://github.com/paiml/bashrs

# Minimal build (smaller binary, ~2MB)
cargo install --git https://github.com/paiml/bashrs --no-default-features --features minimal
```

## Usage

### Basic Commands

```bash
# Transpile a Rust file to shell
bashrs build input.rs -o output.sh

# Check if a file is valid Rash
bashrs check input.rs

# Initialize a new Rash project
bashrs init my-project

# Verify safety properties
bashrs verify input.rs output.sh

# Inspect AST and safety properties
bashrs inspect input.rs

# Compile to self-extracting script (BETA)
bashrs compile input.rs -o install --self-extracting
```

### CLI Options

```bash
USAGE:
    bashrs [OPTIONS] <COMMAND>

COMMANDS:
    build       Transpile Rust to shell script
    check       Validate Rust source without transpiling
    init        Initialize a new Rash project
    verify      Verify shell script matches source
    inspect     Analyze AST and safety properties
    compile     Compile to standalone binary (BETA - experimental)

OPTIONS:
    -v, --verbose            Enable verbose output
    -V, --version            Print version information
    -h, --help               Print help information
    --target <SHELL>         Target shell: posix, bash, ash (default: posix)
    --verify <LEVEL>         Verification level: none, basic, strict, paranoid
    --validation <LEVEL>     Validation level: none, minimal, strict, paranoid

BUILD OPTIONS:
    -o, --output <FILE>      Output file (default: stdout)
    --optimize               Enable optimization passes
    --strict                 Enable strict mode checks
    --emit-proof             Emit verification proof alongside output
```

## Language Features

### Supported Rust Subset

Rash supports a carefully chosen subset of Rust that maps cleanly to shell:

#### Variables and Types
```rust
let name = "Alice";              // String literals
let count = 42;                  // Integers (including negatives: -42)
let flag = true;                 // Booleans
let user = env("USER");          // Environment variables
let result = capture("date");    // Command output
```

#### Arithmetic Operations
```rust
let x = 1 + 2;                   // Addition โ†’ $((1 + 2))
let y = 10 - 3;                  // Subtraction โ†’ $((10 - 3))
let z = 4 * 5;                   // Multiplication โ†’ $((4 * 5))
let w = 20 / 4;                  // Division โ†’ $((20 / 4))
```

#### Comparison Operators
```rust
if x > 0 {                       // Greater than โ†’ [ "$x" -gt 0 ]
    println!("Positive");        // println! macro supported
}
if y == 5 { ... }                // Equal โ†’ [ "$y" -eq 5 ]
if z < 10 { ... }                // Less than โ†’ [ "$z" -lt 10 ]
```

#### User-Defined Functions
```rust
fn add(a: i32, b: i32) -> i32 {
    a + b                        // Return value via echo
}

fn main() {
    let sum = add(1, 2);         // Captured with $(add 1 2)
    println!("Sum: {}", sum);
}
```

#### Built-in Functions
```rust
// I/O operations
echo("Hello, World!");           // Print to stdout
println!("Hello, World!");       // println! macro (Sprint 10)
eprint("Error!");                // Print to stderr

// File system
mkdir_p("/tmp/myapp");           // Create directory recursively
write_file("config.txt", data);  // Write file
let content = read_file("config.txt");  // Read file
if path_exists("/etc/config") { ... }   // Check path

// Process management  
exec("ls -la");                  // Run command
let output = capture("date");    // Capture command output
exit(0);                         // Exit with code

// Environment
set_env("KEY", "value");         // Set environment variable
let val = env("KEY");            // Get environment variable
let val = env_var_or("KEY", "default"); // With default
```

#### Control Flow
```rust
// Conditionals
if condition {
    // ...
} else if other {
    // ...
} else {
    // ...
}

// โœ… Pattern matching - SUPPORTED (experimental in v1.0.0-rc1)
match value {
    "linux" => echo("Linux detected"),
    "darwin" => echo("macOS detected"),
    _ => echo("Unknown OS"),
}
```

#### Loops โœ… (Supported in v1.0.0-rc1)
```rust
// โœ… For loops - FULLY SUPPORTED
for i in 0..10 {
    echo("Iteration: {i}");
}

// โœ… While loops - FULLY SUPPORTED
let mut count = 0;
while count < 10 {
    count = count + 1;
    echo("Count: {count}");
}
```

### Safety Features

All generated scripts are protected against:

- **Command Injection**: All variables are properly quoted
- **Path Traversal**: Paths are validated and escaped  
- **Glob Expansion**: Glob patterns are quoted when needed
- **Word Splitting**: IFS is set to safe value
- **Undefined Variables**: `set -u` catches undefined vars

Example of automatic safety:

```rust
let user_input = env("UNTRUSTED");
exec("echo {user_input}");  // Safe: becomes echo "$user_input"
```

## Beta Features โš—๏ธ

The following features are available but marked as **experimental** in v1.0:

### Binary Compilation (BETA)

Compile Rust to self-extracting shell scripts or container images:

```bash
# Self-extracting script (includes runtime)
bashrs compile install.rs -o install --self-extracting

# Container image (OCI format)
bashrs compile app.rs -o app --container --format oci
```

**Status**:
- โœ… Self-extracting scripts work and are tested
- โš ๏ธ Container packaging is experimental
- โš ๏ธ Binary optimization is in progress

**Limitations**:
- Container formats are not fully implemented
- Advanced runtime optimizations pending
- Limited to dash/bash/busybox runtimes

**Recommendation**: Use `bashrs build` for production deployments. Use `compile` for quick testing or when you need a single-file installer.

### Proof Generation (BETA)

Generate formal verification proofs alongside transpiled scripts:

```bash
bashrs build input.rs -o output.sh --emit-proof
```

This creates `output.proof` with formal correctness guarantees.

**Status**: โš ๏ธ Proof format is experimental and may change

## Examples

See the [`examples/`](examples/) directory for complete examples:

- **Basic**
  - [Hello World]examples/hello.rs - Simplest example
  - [Variables]examples/basic/variables.rs - Variable usage and escaping
  - [Functions]examples/basic/functions.rs - Built-in functions
  - [Standard Library]examples/stdlib_demo.rs - Stdlib functions demo

- **Control Flow**
  - [Conditionals]examples/control_flow/conditionals.rs - If/else statements
  - [Loops]examples/control_flow/loops.rs - Bounded iteration

- **Safety**
  - [Injection Prevention]examples/safety/injection_prevention.rs - Security examples
  - [String Escaping]examples/safety/escaping.rs - Special character handling

- **Real-World**
  - [Node Installer]examples/node-installer.rs - Node.js bootstrap script
  - [Rust Installer]examples/rust-installer.rs - Rust toolchain installer

## Shell Compatibility

Generated scripts are tested on:

| Shell | Version | Status |
|-------|---------|--------|
| POSIX sh | - | โœ… Full support |
| dash | 0.5.11+ | โœ… Full support |
| bash | 3.2+ | โœ… Full support |
| ash (BusyBox) | 1.30+ | โœ… Full support |
| zsh | 5.0+ | โœ… Full support |
| mksh | R59+ | โœ… Full support |

## Performance

Rash is designed for fast transpilation:

- **21.1ยตs** transpile time for simple scripts (100x better than target!)
- Memory usage <10MB for most scripts
- Generated scripts add minimal overhead (~20 lines boilerplate)

## Quality Metrics (v1.0.0)

| Metric | Status | Notes |
|--------|--------|-------|
| **Tests** | 756/756 โœ… | 100% pass rate (752 unit + 4 integration) |
| **Property Tests** | 52 properties โœ… | ~26,000+ test cases, 0 failures |
| **Core Coverage** | 85.36% โœ… | Parser, IR, Emitter, Verifier |
| **Total Coverage** | 82.18% โœ… | All modules including CLI |
| **Mutation Kill Rate** | ~83% (baseline) ๐ŸŸก | Target: โ‰ฅ90% (Sprint 26 in progress) |
| **Multi-Shell** | 100% pass โœ… | sh, dash, bash, ash, zsh, mksh |
| **ShellCheck** | 24/24 pass โœ… | All generated scripts POSIX-compliant |
| **Performance** | 19.1ยตs โœ… | Simple transpile (523x better than target!) |
| **Complexity** | Median 1.0 โœ… | All core functions <10 |
| **Edge Cases** | 11/11 fixed โœ… | 100% completion |

**v1.0.0 Status**: โœ… **STABLE** - Production-ready with A+ quality grade

## Troubleshooting

Having issues? Check our **[Error Guide](docs/ERROR_GUIDE.md)** for common errors and solutions.

## MCP Server

Rash provides a Model Context Protocol (MCP) server for AI-assisted shell script generation:

```bash
# Install from crates.io
cargo install rash-mcp

# Run MCP server
rash-mcp
```

The MCP server is available in the official registry as `io.github.paiml/rash`.

**For developers**: See [MCP Registry Publishing Guide](docs/mcp-registry-publish.md) for details on the automated publishing process.

## Contributing

We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.

### Development Setup

```bash
# Clone the repository
git clone https://github.com/paiml/rash.git
cd rash

# Run tests
make test

# Run with all checks
make validate

# Build release binary
make release
```

### Publishing to MCP Registry

For maintainers publishing new MCP server versions, see the [MCP Registry Publishing Guide](docs/mcp-registry-publish.md).

## License

Rash is licensed under the MIT License. See [LICENSE](LICENSE) for details.

## Acknowledgments

Rash is built with safety principles inspired by:
- [ShellCheck]https://www.shellcheck.net/ for shell script analysis
- [Oil Shell]https://www.oilshell.org/ for shell language design
- The Rust community for memory safety practices

## Roadmap

### v1.0.0-rc1 (Current Release) ๐Ÿงช

**Status**: Release Candidate - Ready for Testing
**Released**: 2025-10-04
**Quality Metrics**:
- 667 tests passing (100% pass rate)
- 97.7% mutation kill rate (42/43 mutants caught)
- 83.07% code coverage (88.74% core transpiler)
- 0 shellcheck warnings
- 37/37 book examples passing

**Core Features** (Complete):
- [x] Rust-to-Shell transpilation (POSIX, Bash, Dash, Ash)
- [x] Full AST parsing and validation (98.92% coverage)
- [x] IR generation and optimization (87-99% coverage)
- [x] Safety verification and escape handling (95.45% coverage)
- [x] Multi-shell compatibility testing (100% pass rate)
- [x] Property-based testing (114k executions, 0 failures)
- [x] Fuzzing infrastructure (0 failures)
- [x] ShellCheck compliance (24/24 tests pass)
- [x] Arithmetic expressions and comparisons
- [x] User-defined functions
- [x] `println!` macro support
- [x] MCP server (rash-mcp)

**CLI Tools** (Complete):
- [x] `bashrs build` - Transpile Rust to shell
- [x] `bashrs check` - Validate Rust compatibility
- [x] `bashrs init` - Project scaffolding
- [x] `bashrs verify` - Script verification
- [x] `bashrs inspect` - Formal verification reports

**Shipped in v1.0.0-rc1**:
- [x] Control flow (if/else if/else) - STABLE
- [x] For loops (0..n, 0..=n) - STABLE
- [x] While loops (with max_iterations safety) - STABLE
- [x] Match expressions (basic pattern matching) - EXPERIMENTAL
- [x] Logical operators (&&, ||, !) - STABLE
- [x] String and integer comparisons - STABLE
- [x] Self-extracting scripts - STABLE
- [ ] Container packaging (in progress)
- [ ] Proof generation (experimental format)

### v1.1 (Planned)

**Interactive Features**:
- [ ] Playground/REPL (separate `rash-playground` crate)
- [ ] Web-based transpiler
- [ ] Live syntax highlighting

**Language Features**:
- [x] For loops (`for i in 0..10`) - SHIPPED in v1.0.0-rc1
- [x] Match expressions (pattern matching) - SHIPPED in v1.0.0-rc1
- [x] While loops - SHIPPED in v1.0.0-rc1
- [ ] Arrays and collections (advanced operations)
- [ ] Enhanced pattern matching guards

**Tooling**:
- [ ] Language server protocol (LSP)
- [ ] IDE integration examples
- [ ] Better error diagnostics

### v1.2+ (Future)

**Advanced Features**:
- [ ] Incremental compilation
- [ ] More shell targets (fish, PowerShell, nushell)
- [ ] Package manager integration
- [ ] Advanced optimizations (constant folding, DCE)
- [ ] Formal verification with SMT solvers

**Documentation**:
- [ ] Video tutorials
- [ ] Interactive examples
- [ ] Best practices guide

See [v1.0-feature-scope.md](.quality/v1.0-feature-scope.md) for detailed feature decisions.