bashrs 1.0.0-rc2

Rust-to-Shell transpiler for deterministic bootstrap scripts
Documentation

Rash - Rust to Shell Transpiler

Crates.io Documentation License CI Tests PropertyTests Coverage Mutation

Rash transpiles a safe subset of Rust to POSIX-compliant shell scripts, enabling you to write maintainable and type-safe shell scripts using familiar Rust syntax.

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

Quick Start

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

$ 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)

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

# 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

cargo binstall bashrs

From Source

# 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

# 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

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

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

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

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

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

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

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

// โœ… 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:

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:

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

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/ directory for complete examples:

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-rc)

Metric Status Notes
Tests 683/683 โœ… 100% pass rate
Core Coverage 88.74% โœ… AST, IR, Emitter, Validation
Total Coverage 83.07% โœ… All modules including CLI
Property Tests 114k executions โœ… 0 failures
Multi-Shell 100% pass โœ… sh, dash, bash, ash
ShellCheck 24/24 pass โœ… All generated scripts
Performance ~21ยตs โœ… Transpile time
Fuzzing 0 failures โœ… Extensive input testing

v1.0 Ready: Publication-quality code with comprehensive testing and formal verification.

Troubleshooting

Having issues? Check our Error Guide for common errors and solutions.

MCP Server

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

# 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 for details on the automated publishing process.

Contributing

We welcome contributions! Please see our Contributing Guide for details.

Development Setup

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

License

Rash is licensed under the MIT License. See LICENSE for details.

Acknowledgments

Rash is built with safety principles inspired by:

  • ShellCheck for shell script analysis
  • Oil Shell 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):

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

CLI Tools (Complete):

  • bashrs build - Transpile Rust to shell
  • bashrs check - Validate Rust compatibility
  • bashrs init - Project scaffolding
  • bashrs verify - Script verification
  • bashrs inspect - Formal verification reports

Shipped in v1.0.0-rc1:

  • Control flow (if/else if/else) - STABLE
  • For loops (0..n, 0..=n) - STABLE
  • While loops (with max_iterations safety) - STABLE
  • Match expressions (basic pattern matching) - EXPERIMENTAL
  • Logical operators (&&, ||, !) - STABLE
  • String and integer comparisons - STABLE
  • 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:

  • For loops (for i in 0..10) - SHIPPED in v1.0.0-rc1
  • Match expressions (pattern matching) - SHIPPED in v1.0.0-rc1
  • 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 for detailed feature decisions.