bashrs 6.66.0

Rust-to-Shell transpiler for deterministic bootstrap scripts
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
use crate::ast::restricted::{
    BinaryOp, Expr, Function, Literal, MatchArm, Parameter, Pattern, RestrictedAst, Stmt, Type,
    UnaryOp,
};
use crate::models::{Error, Result};
use syn::{
    parse::Parser, BinOp, Block, Expr as SynExpr, File, FnArg, Item, ItemFn, Lit, Pat, ReturnType,
    Stmt as SynStmt, Type as SynType, UnOp,
};

/// Parse Rust source code into a RestrictedAst
pub fn parse(input: &str) -> Result<RestrictedAst> {
    let file: File = syn::parse_str(input)?;

    let mut functions = Vec::new();
    let mut entry_point = None;

    for item in file.items {
        process_item(item, &mut functions, &mut entry_point)?;
    }

    let entry_point = entry_point
        .ok_or_else(|| Error::Validation("No #[bashrs::main] function found".to_string()))?;

    Ok(RestrictedAst {
        functions,
        entry_point,
    })
}

fn process_item(
    item: Item,
    functions: &mut Vec<Function>,
    entry_point: &mut Option<String>,
) -> Result<()> {
    let item_fn = match item {
        Item::Fn(f) => f,
        // Gracefully skip non-function items (struct, enum, use, const, static, type, trait)
        // Shell is untyped — these Rust constructs have no shell equivalent
        Item::Struct(_)
        | Item::Enum(_)
        | Item::Use(_)
        | Item::Const(_)
        | Item::Static(_)
        | Item::Type(_)
        | Item::Trait(_) => return Ok(()),
        Item::Impl(item_impl) => {
            // Extract methods from impl blocks as regular functions
            for impl_item in item_impl.items {
                if let syn::ImplItem::Fn(method) = impl_item {
                    let item_fn = ItemFn {
                        attrs: method.attrs,
                        vis: method.vis,
                        sig: method.sig,
                        block: Box::new(method.block),
                    };
                    let function = convert_function(item_fn)?;
                    functions.push(function);
                }
            }
            return Ok(());
        }
        _ => {
            return Err(Error::Validation(
                "Only functions are allowed in Rash code".to_string(),
            ));
        }
    };

    let is_main = has_main_attribute(&item_fn) || item_fn.sig.ident == "main";
    let function = convert_function(item_fn)?;

    if is_main {
        check_single_entry_point(entry_point, &function.name)?;
        *entry_point = Some(function.name.clone());
    }

    functions.push(function);
    Ok(())
}

fn has_main_attribute(item_fn: &ItemFn) -> bool {
    item_fn.attrs.iter().any(is_main_attribute)
}

fn is_main_attribute(attr: &syn::Attribute) -> bool {
    let path = attr.path();
    path.segments.len() == 2
        && path
            .segments
            .get(0)
            .is_some_and(|seg| seg.ident == "bashrs" || seg.ident == "rash")
        && path.segments.get(1).is_some_and(|seg| seg.ident == "main")
}

fn check_single_entry_point(current: &Option<String>, _new_name: &str) -> Result<()> {
    if current.is_some() {
        return Err(Error::Validation(
            "Multiple #[bashrs::main] functions found".to_string(),
        ));
    }
    Ok(())
}

fn convert_function(item_fn: ItemFn) -> Result<Function> {
    let name = item_fn.sig.ident.to_string();

    // Convert parameters
    let mut params = Vec::new();
    for input in item_fn.sig.inputs {
        match input {
            FnArg::Typed(pat_type) => {
                if let Pat::Ident(pat_ident) = &*pat_type.pat {
                    let param_name = pat_ident.ident.to_string();
                    let param_type = convert_type(&pat_type.ty)?;
                    params.push(Parameter {
                        name: param_name,
                        param_type,
                    });
                } else {
                    return Err(Error::Validation(
                        "Complex parameter patterns not supported".to_string(),
                    ));
                }
            }
            FnArg::Receiver(_) => {
                // Skip self parameters (shell functions don't have receivers)
                continue;
            }
        }
    }

    // Convert return type
    let return_type = match &item_fn.sig.output {
        ReturnType::Default => Type::Void, // Default to void/unit type
        ReturnType::Type(_, ty) => convert_type(ty)?,
    };

    // Convert function body
    let body = convert_block(&item_fn.block)?;

    Ok(Function {
        name,
        params,
        return_type,
        body,
    })
}

fn convert_type(ty: &SynType) -> Result<Type> {
    match ty {
        SynType::Path(type_path) => convert_path_type(type_path),
        SynType::Reference(type_ref) => convert_reference_type(type_ref),
        SynType::Tuple(_) => Ok(Type::Str),
        SynType::Array(_) => Ok(Type::Str),
        _ => Err(Error::Validation("Complex types not supported".to_string())),
    }
}

/// Convert a path type (e.g. bool, String, Result<T, E>) to our Type enum
fn convert_path_type(type_path: &syn::TypePath) -> Result<Type> {
    let path_str = type_path
        .path
        .segments
        .iter()
        .map(|seg| seg.ident.to_string())
        .collect::<Vec<_>>()
        .join("::");

    match path_str.as_str() {
        "bool" => Ok(Type::Bool),
        "u16" => Ok(Type::U16),
        "u32" | "i32" => Ok(Type::U32),
        "str" | "String" => Ok(Type::Str),
        path if path.starts_with("Result") => Ok(Type::Result {
            ok_type: Box::new(Type::Str),
            err_type: Box::new(Type::Str),
        }),
        path if path.starts_with("Option") => Ok(Type::Option {
            inner_type: Box::new(Type::Str),
        }),
        _ => Ok(Type::Str),
    }
}

/// Convert a reference type (e.g. &str, &[T]) to our Type enum
fn convert_reference_type(type_ref: &syn::TypeReference) -> Result<Type> {
    match &*type_ref.elem {
        SynType::Path(_) | SynType::Slice(_) => Ok(Type::Str),
        _ => Ok(Type::Str),
    }
}

fn convert_block(block: &Block) -> Result<Vec<Stmt>> {
    let mut statements = Vec::new();

    for stmt in &block.stmts {
        statements.push(convert_stmt(stmt)?);
    }

    Ok(statements)
}

fn convert_stmt(stmt: &SynStmt) -> Result<Stmt> {
    match stmt {
        SynStmt::Local(local) => convert_let_stmt(local),
        SynStmt::Expr(expr, _) => convert_expr_stmt(expr),
        SynStmt::Macro(macro_stmt) => convert_macro_stmt(macro_stmt),
        _ => Err(Error::Validation("Unsupported statement type".to_string())),
    }
}

fn convert_let_stmt(local: &syn::Local) -> Result<Stmt> {
    // Handle tuple destructuring: let (a, b) = expr → Block containing multiple lets
    if let Pat::Tuple(pat_tuple) = &local.pat {
        let Some(init) = &local.init else {
            return Err(Error::Validation(
                "Let bindings must have initializers".to_string(),
            ));
        };
        let value = convert_expr(&init.expr)?;
        // Generate: { let __tuple = expr; let a = __tuple[0]; let b = __tuple[1]; }
        let tmp_name = "__tuple_tmp".to_string();
        let mut stmts = vec![Stmt::Let {
            name: tmp_name.clone(),
            value,
            declaration: true,
        }];
        for (i, elem) in pat_tuple.elems.iter().enumerate() {
            if let Pat::Ident(ident) = elem {
                let elem_name = ident.ident.to_string();
                stmts.push(Stmt::Let {
                    name: elem_name,
                    value: Expr::Index {
                        object: Box::new(Expr::Variable(tmp_name.clone())),
                        index: Box::new(Expr::Literal(Literal::I32(i as i32))),
                    },
                    declaration: true,
                });
            }
        }
        return Ok(Stmt::Expr(Expr::Block(stmts)));
    }

    // Extract identifier from pattern (handle both Pat::Ident and Pat::Type)
    // This allows: `let x = 5` and `let x: i32 = 5`
    let pat_ident = match &local.pat {
        Pat::Ident(ident) => ident,
        Pat::Type(pat_type) => {
            // For type-annotated patterns like `let args: Vec<String> = ...`
            match &*pat_type.pat {
                Pat::Ident(ident) => ident,
                _ => {
                    return Err(Error::Validation(
                        "Complex patterns not supported in type annotations".to_string(),
                    ));
                }
            }
        }
        _ => {
            return Err(Error::Validation(
                "Complex patterns not supported".to_string(),
            ));
        }
    };

    let name = pat_ident.ident.to_string();

    let Some(init) = &local.init else {
        return Err(Error::Validation(
            "Let bindings must have initializers".to_string(),
        ));
    };

    let value = convert_expr(&init.expr)?;
    Ok(Stmt::Let {
        name,
        value,
        declaration: true,
    })
}

fn convert_expr_stmt(expr: &SynExpr) -> Result<Stmt> {
    match expr {
        SynExpr::If(expr_if) => convert_if_stmt(expr_if),
        SynExpr::ForLoop(for_loop) => convert_for_loop(for_loop),
        SynExpr::While(expr_while) => convert_while_loop(expr_while),
        SynExpr::Loop(expr_loop) => {
            // loop { body } → while true { body }
            let body = convert_block(&expr_loop.body)?;
            Ok(Stmt::While {
                condition: Expr::Literal(Literal::Bool(true)),
                body,
                max_iterations: Some(10000),
            })
        }
        SynExpr::Match(expr_match) => convert_match_stmt(expr_match),
        SynExpr::Break(_) => Ok(Stmt::Break),
        SynExpr::Continue(_) => Ok(Stmt::Continue),
        SynExpr::Return(ret_expr) => {
            if let Some(inner) = &ret_expr.expr {
                Ok(Stmt::Return(Some(convert_expr(inner)?)))
            } else {
                Ok(Stmt::Return(None))
            }
        }
        SynExpr::Assign(expr_assign) => convert_assign_stmt(expr_assign),
        // Compound assignment: x += expr, x -= expr, x *= expr, etc.
        SynExpr::Binary(expr_binary) if is_compound_assign(&expr_binary.op) => {
            convert_compound_assign_stmt(expr_binary)
        }
        _ => Ok(Stmt::Expr(convert_expr(expr)?)),
    }
}

fn convert_assign_stmt(expr_assign: &syn::ExprAssign) -> Result<Stmt> {
    // x = expr -> Stmt::Let { name: "x", value: expr }
    // arr[i] = expr -> Stmt::Let { name: "arr_i", value: expr } (flat array convention)
    // In shell, reassignment is the same syntax as initial assignment
    let name = match &*expr_assign.left {
        SynExpr::Path(path) => path
            .path
            .segments
            .iter()
            .map(|seg| seg.ident.to_string())
            .collect::<Vec<_>>()
            .join("::"),
        SynExpr::Index(expr_index) => {
            // Handle both arr[i] and arr[i][j] (nested indices)
            let (array_name, index_suffix) = extract_nested_index_target(expr_index)?;
            format!("{}_{}", array_name, index_suffix)
        }
        SynExpr::Field(expr_field) => {
            // self.value = expr → value = expr (strip receiver, use field name)
            match &expr_field.member {
                syn::Member::Named(ident) => ident.to_string(),
                syn::Member::Unnamed(idx) => format!("field_{}", idx.index),
            }
        }
        SynExpr::Unary(expr_unary) if matches!(expr_unary.op, UnOp::Deref(_)) => {
            // *a = expr → a = expr (shell has no pointers, dereference is identity)
            match &*expr_unary.expr {
                SynExpr::Path(path) => path
                    .path
                    .segments
                    .iter()
                    .map(|seg| seg.ident.to_string())
                    .collect::<Vec<_>>()
                    .join("::"),
                _ => {
                    return Err(Error::Validation(
                        "Complex assignment targets not supported".to_string(),
                    ))
                }
            }
        }
        _ => {
            return Err(Error::Validation(
                "Complex assignment targets not supported".to_string(),
            ))
        }
    };
    let value = convert_expr(&expr_assign.right)?;
    Ok(Stmt::Let {
        name,
        value,
        declaration: false,
    })
}

/// Extract array name and combined index suffix for nested index targets like arr[i][j].
fn extract_nested_index_target(expr_index: &syn::ExprIndex) -> Result<(String, String)> {
    let index_suffix = extract_index_suffix(&expr_index.index)?;
    match &*expr_index.expr {
        SynExpr::Path(path) => {
            let name = path
                .path
                .segments
                .iter()
                .map(|seg| seg.ident.to_string())
                .collect::<Vec<_>>()
                .join("::");
            Ok((name, index_suffix))
        }
        SynExpr::Index(inner_index) => {
            // Nested: arr[i][j] → (arr, i_j)
            let (name, inner_suffix) = extract_nested_index_target(inner_index)?;
            Ok((name, format!("{}_{}", inner_suffix, index_suffix)))
        }
        _ => Err(Error::Validation(
            "Complex array index target not supported".to_string(),
        )),
    }
}

/// Extract a naming suffix from an array index expression.
/// Handles literal integers, variables, and simple binary expressions.
/// Extract a suffix string from a function call index expression: arr[hash(val)] → "hash_val"
fn extract_call_index_suffix(call: &syn::ExprCall) -> Result<String> {
    let func_name = if let SynExpr::Path(path) = &*call.func {
        path.path
            .segments
            .iter()
            .map(|seg| seg.ident.to_string())
            .collect::<Vec<_>>()
            .join("_")
    } else {
        "call".to_string()
    };
    let args: Vec<String> = call
        .args
        .iter()
        .filter_map(|arg| extract_index_suffix(arg).ok())
        .collect();
    if args.is_empty() {
        Ok(func_name)
    } else {
        Ok(format!("{}_{}", func_name, args.join("_")))
    }
}

/// Convert a syn path to an underscore-joined string (e.g., `std::io` → `std_io`).
fn path_to_suffix(path: &syn::ExprPath) -> String {
    path.path
        .segments
        .iter()
        .map(|seg| seg.ident.to_string())
        .collect::<Vec<_>>()
        .join("_")
}

/// Extract an integer literal as a suffix string, or error if not an integer.
fn lit_to_index_suffix(lit: &syn::ExprLit) -> Result<String> {
    if let syn::Lit::Int(lit_int) = &lit.lit {
        Ok(lit_int.base10_digits().to_string())
    } else {
        Err(Error::Validation(
            "Array index must be integer or variable".to_string(),
        ))
    }
}

fn extract_index_suffix(expr: &SynExpr) -> Result<String> {
    match expr {
        SynExpr::Lit(lit) => lit_to_index_suffix(lit),
        SynExpr::Path(path) => Ok(path_to_suffix(path)),
        SynExpr::Binary(bin) => {
            let left = extract_index_suffix(&bin.left)?;
            let right = extract_index_suffix(&bin.right)?;
            Ok(format!("{}_{}", left, right))
        }
        SynExpr::Paren(paren) => extract_index_suffix(&paren.expr),
        SynExpr::Index(idx) => {
            let obj = extract_index_suffix(&idx.expr)?;
            let inner = extract_index_suffix(&idx.index)?;
            Ok(format!("{}_{}", obj, inner))
        }
        SynExpr::MethodCall(mc) => {
            let recv = extract_index_suffix(&mc.receiver)?;
            Ok(format!("{}_{}", recv, mc.method))
        }
        SynExpr::Unary(unary) => extract_index_suffix(&unary.expr),
        SynExpr::Call(call) => extract_call_index_suffix(call),
        _ => Err(Error::Validation(
            "Unsupported array index expression".to_string(),
        )),
    }
}


include!("parser_part2_incl2.rs");