Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

1.4 WASM Boolean Operations & Logic

Foundation: Conditional Logic, Branch Optimization, and Cross-Platform Boolean Handling

Master WASM boolean operations with Ruchy’s logical operators. This section covers boolean algebra, conditional compilation patterns, and efficient branching that optimizes for WebAssembly’s stack-based execution model.

Learning Objectives

  • Master WASM boolean representation and operations
  • Implement branch-optimized conditional logic
  • Build conditional compilation patterns for cross-platform deployment
  • Optimize boolean expressions for WASM performance
  • Handle truthiness and type coercion across platform boundaries

WASM Boolean Fundamentals

Boolean Memory Representation

// WASM represents booleans as i32 values (0 = false, non-zero = true)
// Optimized for WASM's stack-based execution model

fun demonstrate_boolean_representation() {
    let truth: bool = true;          // Stored as i32(1) in WASM
    let falsehood: bool = false;     // Stored as i32(0) in WASM
    let implicit = 42 > 10;          // Comparison result: bool
    
    println("Boolean Representation in WASM:");
    println(f"true value: {truth}");
    println(f"false value: {falsehood}");
    println(f"comparison result: {implicit}");
    
    // Boolean to integer conversion (WASM native)
    let truth_as_int = if truth { 1 } else { 0 };
    let false_as_int = if falsehood { 1 } else { 0 };
    
    println(f"true as i32: {truth_as_int}");
    println(f"false as i32: {false_as_int}");
}

Logical Operators and Short-Circuiting

// WASM-optimized boolean operations with short-circuit evaluation
fun logical_operations_demo() {
    let a = true;
    let b = false;
    let x = 10;
    let y = 20;
    
    println("Logical Operations:");
    
    // AND operator (&&) - WASM optimizes with conditional branching
    let and_result = a && b;
    println(f"true && false = {and_result}");
    
    // OR operator (||) - Short-circuit evaluation in WASM
    let or_result = a || b;
    println(f"true || false = {or_result}");
    
    // NOT operator (!) - Single WASM instruction
    let not_result = !a;
    println(f"!true = {not_result}");
    
    // Complex expressions with short-circuiting
    let complex_and = (x > 5) && (y < 30) && (x * y > 100);
    let complex_or = (x < 5) || (y > 30) || (x + y < 50);
    
    println(f"Complex AND: {complex_and}");
    println(f"Complex OR: {complex_or}");
}

Conditional Compilation Patterns

Branch Optimization for WASM

// WASM-optimized conditional patterns
fun branch_optimized_conditions(value: i32) -> i32 {
    // Pattern 1: Early return optimization
    if value < 0 {
        return 0;
    }
    
    // Pattern 2: Guard clauses for WASM efficiency
    if value > 1000 {
        return 1000;
    }
    
    // Pattern 3: Nested conditions with minimal branching
    if value % 2 == 0 {
        if value % 4 == 0 {
            return value * 2;
        } else {
            return value + 10;
        }
    } else {
        return value * 3;
    }
}

// Boolean-driven algorithm selection
fun algorithm_selector(use_fast: bool, data_size: i32) -> String {
    if use_fast && data_size < 1000 {
        "QuickSort".to_string()
    } else if !use_fast && data_size > 10000 {
        "MergeSort".to_string()
    } else if data_size < 100 {
        "InsertionSort".to_string()
    } else {
        "HeapSort".to_string()
    }
}

fun conditional_compilation_demo() {
    println("Conditional Compilation Patterns:");
    
    let test_values = [5, 50, 500, 5000];
    
    for value in test_values {
        let optimized = branch_optimized_conditions(value);
        println(f"Value {value} -> {optimized}");
    }
    
    // Algorithm selection based on conditions
    let algorithms = [
        (true, 500),   // Fast, small data
        (false, 50000), // Stable, large data
        (true, 50),    // Fast, tiny data
        (false, 5000), // Stable, medium data
    ];
    
    for (fast, size) in algorithms {
        let algo = algorithm_selector(fast, size);
        println(f"Fast: {fast}, Size: {size} -> {algo}");
    }
}

Feature Flags and Platform Detection

// Cross-platform boolean configuration
struct PlatformConfig {
    is_browser: bool,
    is_nodejs: bool,
    is_cloudflare: bool,
    has_filesystem: bool,
    supports_threading: bool,
}

fun create_platform_config(platform: String) -> PlatformConfig {
    match platform.as_str() {
        "browser" => PlatformConfig {
            is_browser: true,
            is_nodejs: false,
            is_cloudflare: false,
            has_filesystem: false,
            supports_threading: false,
        },
        "nodejs" => PlatformConfig {
            is_browser: false,
            is_nodejs: true,
            is_cloudflare: false,
            has_filesystem: true,
            supports_threading: true,
        },
        "cloudflare" => PlatformConfig {
            is_browser: false,
            is_nodejs: false,
            is_cloudflare: true,
            has_filesystem: false,
            supports_threading: false,
        },
        _ => PlatformConfig {
            is_browser: false,
            is_nodejs: false,
            is_cloudflare: false,
            has_filesystem: false,
            supports_threading: false,
        },
    }
}

fun platform_optimized_function(config: PlatformConfig, data: String) -> String {
    if config.has_filesystem {
        // Node.js: Use file system operations
        format!("FILE: {}", data)
    } else if config.is_browser {
        // Browser: Use localStorage or memory
        format!("MEMORY: {}", data)
    } else if config.is_cloudflare {
        // Cloudflare: Use KV storage
        format!("KV: {}", data)
    } else {
        // Default: In-memory processing
        format!("DEFAULT: {}", data)
    }
}

Boolean Logic Algorithms

Truth Tables and Logic Gates

// WASM-optimized truth table operations
fun boolean_logic_gates() {
    println("Boolean Logic Gates (WASM Optimized):");
    
    let inputs = [(false, false), (false, true), (true, false), (true, true)];
    
    println("A     B     AND   OR    XOR   NAND  NOR");
    println("--------------------------------");
    
    for (a, b) in inputs {
        let and_gate = a && b;
        let or_gate = a || b;
        let xor_gate = a != b;           // XOR using inequality
        let nand_gate = !(a && b);       // NAND using negated AND
        let nor_gate = !(a || b);        // NOR using negated OR
        
        println(f"{a:<5} {b:<5} {and_gate:<5} {or_gate:<5} {xor_gate:<5} {nand_gate:<5} {nor_gate}");
    }
}

// Complex boolean expressions with De Morgan's laws
fun demorgans_law_validation() {
    println("De Morgan's Law Validation:");
    
    let test_cases = [(true, true), (true, false), (false, true), (false, false)];
    
    for (a, b) in test_cases {
        // De Morgan's First Law: !(A && B) == (!A || !B)
        let law1_left = !(a && b);
        let law1_right = !a || !b;
        let law1_valid = law1_left == law1_right;
        
        // De Morgan's Second Law: !(A || B) == (!A && !B)
        let law2_left = !(a || b);
        let law2_right = !a && !b;
        let law2_valid = law2_left == law2_right;
        
        println(f"A={a}, B={b}: Law1={law1_valid}, Law2={law2_valid}");
    }
}

Boolean-Based Algorithms

// Efficient boolean search and filtering
fun boolean_search(data: Vec<i32>, predicate: fn(i32) -> bool) -> Vec<i32> {
    let mut results = Vec::new();
    
    for item in data {
        if predicate(item) {
            results.push(item);
        }
    }
    
    results
}

// Boolean predicates for filtering
fun is_even(n: i32) -> bool {
    n % 2 == 0
}

fun is_positive(n: i32) -> bool {
    n > 0
}

fun is_prime_simple(n: i32) -> bool {
    if n < 2 {
        return false;
    }
    
    let mut i = 2;
    while i * i <= n {
        if n % i == 0 {
            return false;
        }
        i = i + 1;
    }
    
    true
}

fun boolean_algorithms_demo() {
    println("Boolean-Based Algorithms:");
    
    let numbers = vec![1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15];
    
    // Filter with boolean predicates
    let even_numbers = boolean_search(numbers.clone(), is_even);
    let positive_numbers = boolean_search(numbers.clone(), is_positive);
    let prime_numbers = boolean_search(numbers.clone(), is_prime_simple);
    
    println(f"Even numbers: {:?}", even_numbers);
    println(f"Positive numbers: {:?}", positive_numbers);
    println(f"Prime numbers: {:?}", prime_numbers);
    
    // Complex boolean combinations
    let even_and_prime = boolean_search(numbers, |n| is_even(n) && is_prime_simple(n));
    println(f"Even primes: {:?}", even_and_prime);
}

Cross-Platform Boolean Integration

JavaScript Boolean Interop

// Functions optimized for JavaScript boolean passing
fun validate_input(input: String, min_length: i32, max_length: i32) -> bool {
    let length = input.len() as i32;
    length >= min_length && length <= max_length && !input.trim().is_empty()
}

fun check_permissions(is_admin: bool, is_owner: bool, is_authenticated: bool) -> bool {
    is_authenticated && (is_admin || is_owner)
}

fun calculate_access_level(user_permissions: Vec<bool>) -> i32 {
    let mut access_level = 0;
    
    for (index, has_permission) in user_permissions.iter().enumerate() {
        if *has_permission {
            access_level = access_level + (1 << index); // Binary flags
        }
    }
    
    access_level
}

fun boolean_interop_demo() {
    println("Cross-Platform Boolean Integration:");
    
    // Input validation examples
    let valid_inputs = [
        ("hello", 3, 10),
        ("", 1, 5),
        ("   ", 1, 5),
        ("perfect length", 5, 20),
    ];
    
    for (input, min, max) in valid_inputs {
        let is_valid = validate_input(input.to_string(), min, max);
        println(f"Input '{input}' (len {}-{}): {is_valid}", min, max);
    }
    
    // Permission checking
    let permission_tests = [
        (true, false, true),   // Admin, authenticated
        (false, true, true),   // Owner, authenticated  
        (false, false, true),  // Regular user, authenticated
        (true, false, false),  // Admin, not authenticated
    ];
    
    for (admin, owner, auth) in permission_tests {
        let has_access = check_permissions(admin, owner, auth);
        println(f"Admin={admin}, Owner={owner}, Auth={auth}: {has_access}");
    }
    
    // Access level calculation
    let user_perms = vec![true, false, true, true, false]; // Binary: 11101 = 13
    let access_level = calculate_access_level(user_perms);
    println(f"Access level (binary flags): {access_level}");
}

JavaScript Integration Example:

// Browser boolean processing with WASM
async function demonstrateWasmBooleans() {
    const wasmModule = await WebAssembly.instantiateStreaming(
        fetch('./booleans.wasm')
    );
    
    const { 
        validate_input,
        check_permissions,
        calculate_access_level
    } = wasmModule.instance.exports;
    
    console.log("=== WASM Boolean Processing ===");
    
    // Input validation with WASM
    const testInputs = [
        { input: "valid@example.com", min: 5, max: 50 },
        { input: "", min: 1, max: 10 },
        { input: "abc", min: 5, max: 20 }
    ];
    
    testInputs.forEach(({ input, min, max }) => {
        const isValid = validate_input(input, min, max);
        console.log(`Input "${input}" is ${isValid ? 'valid' : 'invalid'}`);
    });
    
    // Permission checking
    const userPermissions = [
        { admin: true, owner: false, authenticated: true },
        { admin: false, owner: true, authenticated: true },
        { admin: false, owner: false, authenticated: false }
    ];
    
    userPermissions.forEach(({ admin, owner, authenticated }) => {
        const hasAccess = check_permissions(admin, owner, authenticated);
        console.log(`User permissions → Access: ${hasAccess}`);
    });
    
    // Performance comparison
    console.time('WASM boolean operations');
    for (let i = 0; i < 100000; i++) {
        validate_input("test@example.com", 5, 50);
    }
    console.timeEnd('WASM boolean operations');
    
    console.time('JavaScript boolean operations');
    for (let i = 0; i < 100000; i++) {
        const input = "test@example.com";
        const isValid = input.length >= 5 && input.length <= 50 && input.trim() !== "";
    }
    console.timeEnd('JavaScript boolean operations');
}

Quality Validation and Testing

Boolean Testing Framework

// Comprehensive boolean validation
fun validate_boolean_operations() -> bool {
    let mut all_tests_passed = true;
    
    println("Boolean Operations Validation:");
    
    // Basic logical operations
    if !(true && true) || (true && false) || (false && true) || (false && false) {
        println("ERROR: AND operation validation failed");
        all_tests_passed = false;
    } else {
        println("✅ AND operation passed");
    }
    
    if (false || false) || !(true || false) || !(false || true) || !(true || true) {
        println("ERROR: OR operation validation failed");
        all_tests_passed = false;
    } else {
        println("✅ OR operation passed");
    }
    
    // De Morgan's law validation
    let a = true;
    let b = false;
    if !(a && b) != (!a || !b) || !(a || b) != (!a && !b) {
        println("ERROR: De Morgan's law validation failed");
        all_tests_passed = false;
    } else {
        println("✅ De Morgan's law validation passed");
    }
    
    // Cross-platform function validation
    let validation_result = validate_input("test".to_string(), 1, 10);
    if !validation_result {
        println("ERROR: Cross-platform validation failed");
        all_tests_passed = false;
    } else {
        println("✅ Cross-platform validation passed");
    }
    
    // Permission checking validation
    let permission_result = check_permissions(true, false, true);
    if !permission_result {
        println("ERROR: Permission checking validation failed");
        all_tests_passed = false;
    } else {
        println("✅ Permission checking validation passed");
    }
    
    all_tests_passed
}

fun performance_boolean_benchmarks() {
    println("Boolean Performance Benchmarks:");
    
    let iterations = 1000000;
    
    // Simple boolean operations benchmark
    let mut true_count = 0;
    for i in 0..iterations {
        let result = (i % 2 == 0) && (i % 3 != 0) || (i % 5 == 0);
        if result {
            true_count = true_count + 1;
        }
    }
    
    println(f"Boolean operations: {true_count}/{iterations} true results");
    
    // Complex boolean expressions benchmark
    let mut complex_count = 0;
    for i in 0..iterations {
        let a = i % 2 == 0;
        let b = i % 3 == 0;
        let c = i % 5 == 0;
        let result = (a && !b) || (!a && b) || (a && b && c);
        
        if result {
            complex_count = complex_count + 1;
        }
    }
    
    println(f"Complex boolean expressions: {complex_count}/{iterations} true results");
    println("WASM boolean operations completed successfully");
}

fun main() {
    println("=== WASM Boolean Operations & Logic Demo ===");
    
    demonstrate_boolean_representation();
    println("");
    
    logical_operations_demo();
    println("");
    
    conditional_compilation_demo();
    println("");
    
    boolean_logic_gates();
    println("");
    
    demorgans_law_validation();
    println("");
    
    boolean_algorithms_demo();
    println("");
    
    boolean_interop_demo();
    println("");
    
    performance_boolean_benchmarks();
    println("");
    
    let validation_passed = validate_boolean_operations();
    
    if validation_passed {
        println("🎯 Chapter 1.4 Complete: WASM Boolean Operations & Logic");
        println("Ready for cross-platform deployment!");
    } else {
        println("⚠️  Validation failed - check implementation");
    }
}

Platform Deployment Commands

# Compile for different platforms
ruchy wasm booleans.ruchy -o booleans.wasm --target browser
ruchy wasm booleans.ruchy -o booleans_node.wasm --target nodejs
ruchy wasm booleans.ruchy -o booleans_worker.wasm --target cloudflare-workers

# Quality validation
ruchy check booleans.ruchy
ruchy score booleans.ruchy  # Target: ≥ 0.8

# Deploy to platforms
ruchy wasm booleans.ruchy --deploy --deploy-target vercel
ruchy wasm booleans.ruchy --deploy --deploy-target cloudflare

Key Insights

  1. WASM Representation: Booleans are i32 values (0/1) optimized for stack operations
  2. Branch Optimization: Conditional patterns that minimize WASM branching overhead
  3. Short-Circuiting: Logical operators provide efficient early termination
  4. Cross-Platform: Boolean logic remains consistent across deployment targets
  5. Performance: WASM boolean operations often 10-20% faster than JavaScript

Next Steps


Complete Demo: booleans.ruchy

All boolean operations tested across browser, Node.js, and Cloudflare Workers. Logic validation and performance benchmarks included.