Module emitter

Module emitter 

Source
Expand description

§Shell Code Emitter Module

This module is responsible for generating shell scripts from the Intermediate Representation (IR). It ensures that all generated shell code is safe, deterministic, and compliant with the target shell dialect.

§Features

  • POSIX Compliance: Generates portable shell scripts that work across different shells
  • Safety Guarantees: Proper escaping and quoting to prevent injection attacks
  • Deterministic Output: Same input always produces identical output
  • Multiple Dialects: Support for POSIX sh, Bash, and other shell variants

§Safety Note

Emitter uses unwrap() on validated IR operations and string operations after validation.

§Architecture

The emitter consists of:

  • Escape Module: Handles string escaping and shell-safe formatting
  • POSIX Emitter: Generates POSIX-compliant shell code
  • Dialect Support: Extensible architecture for different shell dialects

§Examples

§Basic Usage

use bashrs::emitter::emit;
use bashrs::ir::{ShellIR, ShellValue, Command};
use bashrs::ir::effects::EffectSet;
use bashrs::models::Config;

// Create a simple echo command
let ir = ShellIR::Exec {
    cmd: Command {
        program: "echo".to_string(),
        args: vec![ShellValue::String("Hello, World!".to_string())],
    },
    effects: EffectSet::pure(),
};

// Generate shell code
let config = Config::default();
let shell_code = emit(&ir, &config)?;

assert!(shell_code.contains("echo 'Hello, World!'"));

§Variable Assignment

use bashrs::emitter::emit;
use bashrs::ir::{ShellIR, ShellValue};
use bashrs::ir::effects::EffectSet;
use bashrs::models::Config;

let ir = ShellIR::Let {
    name: "USERNAME".to_string(),
    value: ShellValue::String("alice".to_string()),
    effects: EffectSet::pure(),
};

let config = Config::default();
let shell_code = emit(&ir, &config)?;

assert!(shell_code.contains("USERNAME=") && shell_code.contains("alice"));

§Safe String Escaping

use bashrs::emitter::emit;
use bashrs::ir::{ShellIR, ShellValue, Command};
use bashrs::ir::effects::EffectSet;
use bashrs::models::Config;

// Even with special characters, output is safe
let ir = ShellIR::Exec {
    cmd: Command {
        program: "echo".to_string(),
        args: vec![ShellValue::String("Hello $USER; rm -rf /".to_string())],
    },
    effects: EffectSet::pure(),
};

let config = Config::default();
let shell_code = emit(&ir, &config)?;

// Special characters are safely escaped
assert!(shell_code.contains("'Hello $USER; rm -rf /'"));

Re-exports§

pub use posix::PosixEmitter;

Modules§

escape
posix

Functions§

emit
Emit shell code from IR based on target dialect