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
472
473
474
475
476
477
478
479
480
481
482
483
484
impl MakefileConverter {
    fn new() -> Self {
        Self {
            line: 1,
            vars: std::collections::HashMap::new(),
        }
    }

    fn next_span(&mut self) -> Span {
        let span = Span {
            start: self.line,
            end: self.line,
            line: self.line,
        };
        self.line += 1;
        span
    }

    /// Emit raw makefile lines from exec()/println!() calls.
    ///
    /// First pass: collect variable bindings for format resolution.
    /// Second pass: resolve and emit each exec/println line.
    fn emit_raw_lines(&mut self, entry_fn: &Function) -> Result<String> {
        // First pass: collect variable bindings
        self.collect_variable_bindings(entry_fn);

        // Second pass: collect output lines
        let mut output = String::new();
        for stmt in &entry_fn.body {
            self.emit_raw_output_stmt(stmt, &mut output);
        }

        Ok(output)
    }

    /// Collect variable bindings from let statements
    fn collect_variable_bindings(&mut self, entry_fn: &Function) {
        for stmt in &entry_fn.body {
            if let Stmt::Let {
                name,
                value: Expr::Literal(Literal::Str(s)),
                ..
            } = stmt
            {
                self.vars.insert(name.clone(), s.clone());
            }
        }
    }

    /// Emit a single raw output statement (exec/println/print) into the output buffer
    fn emit_raw_output_stmt(&self, stmt: &Stmt, output: &mut String) {
        if let Stmt::Expr(Expr::FunctionCall { name, args }) = stmt {
            let is_output = matches!(
                name.as_str(),
                "exec" | "rash_println" | "println" | "rash_print" | "print"
            );
            if is_output {
                if let Some(first_arg) = args.first() {
                    let resolved = self.resolve_concat_expr(first_arg);
                    if !resolved.is_empty() {
                        output.push_str(&resolved);
                        if name != "rash_print" && name != "print" {
                            output.push('\n');
                        }
                    }
                }
            }
        }
    }

    fn convert(&self, ast: &RestrictedAst) -> Result<MakeAst> {
        let mut converter = MakefileConverter::new();
        let mut items = Vec::new();

        // Find the entry point function
        let entry_fn = ast
            .functions
            .iter()
            .find(|f| f.name == ast.entry_point)
            .ok_or_else(|| Error::IrGeneration("Entry point not found".to_string()))?;

        // Convert each statement in the entry function
        for stmt in &entry_fn.body {
            if let Some(item) = converter.convert_stmt(stmt)? {
                items.push(item);
            }
        }

        // Convert non-main functions as potential helper targets
        for function in &ast.functions {
            if function.name != ast.entry_point {
                if let Some(target) = Self::convert_helper_function(function, &mut converter) {
                    items.push(target);
                }
            }
        }

        Ok(MakeAst {
            items,
            metadata: MakeMetadata::new(),
        })
    }

    /// Convert a non-main function into a Makefile target, if it has echo/println statements
    fn convert_helper_function(
        function: &Function,
        converter: &mut MakefileConverter,
    ) -> Option<MakeItem> {
        let mut recipes = Vec::new();
        for stmt in &function.body {
            if let Stmt::Expr(Expr::FunctionCall { name, args }) = stmt {
                if name == "echo" || name == "println" {
                    if let Some(Expr::Literal(Literal::Str(s))) = args.first() {
                        recipes.push(format!("@echo '{}'", s));
                    }
                }
            }
        }

        if recipes.is_empty() {
            return None;
        }

        let params: Vec<String> = function.params.iter().map(|p| p.name.clone()).collect();
        Some(MakeItem::Target {
            name: function.name.clone(),
            prerequisites: params,
            recipe: recipes,
            phony: true,
            recipe_metadata: None,
            span: converter.next_span(),
        })
    }

    fn convert_stmt(&mut self, stmt: &Stmt) -> Result<Option<MakeItem>> {
        match stmt {
            Stmt::Let { name, value, .. } => self.convert_let(name, value),
            Stmt::Expr(expr) => self.convert_expr(expr),
            _ => Ok(None),
        }
    }

    fn convert_let(&mut self, name: &str, value: &Expr) -> Result<Option<MakeItem>> {
        // let cc = "gcc"; -> CC := gcc
        let var_value = self.expr_to_string(value)?;
        let var_name = name.to_uppercase();

        // Track binding for println! format resolution
        if let Expr::Literal(Literal::Str(s)) = value {
            self.vars.insert(name.to_string(), s.clone());
        }

        Ok(Some(MakeItem::Variable {
            name: var_name,
            value: var_value,
            flavor: VarFlavor::Simple, // := (immediate assignment)
            span: self.next_span(),
        }))
    }

    fn convert_expr(&mut self, expr: &Expr) -> Result<Option<MakeItem>> {
        match expr {
            Expr::FunctionCall { name, args } => {
                if name == "target" || name == "phony_target" {
                    self.convert_target_call(name, args)
                } else if (name == "println"
                    || name == "rash_println"
                    || name == "rash_print"
                    || name == "rash_eprintln")
                    && !args.is_empty()
                {
                    self.convert_println(args)
                } else if name == "exec" && !args.is_empty() {
                    self.convert_exec(args)
                } else {
                    Ok(None)
                }
            }
            _ => Ok(None),
        }
    }

    /// Convert a println!() call into a MakeItem by resolving its argument.
    ///
    /// The parser converts `println!("fmt", args...)` into:
    ///   `FunctionCall { name: "rash_println", args: [resolved_expr] }`
    /// where resolved_expr is either a literal string or a `__format_concat` call.
    ///
    /// The resolved line is analyzed:
    /// - Contains `:` with no `=` → Target rule (name: deps)
    /// - Contains `:=` or `=` → Variable assignment
    /// - Otherwise → Comment (raw line)
    fn convert_println(&mut self, args: &[Expr]) -> Result<Option<MakeItem>> {
        let resolved = match args.first() {
            Some(expr) => self.resolve_concat_expr(expr),
            None => return Ok(None),
        };
        if resolved.is_empty() {
            return Ok(None);
        }
        self.analyze_makefile_line(&resolved)
    }

    /// Analyze a raw makefile line and convert it to the appropriate MakeItem.
    ///
    /// Detection rules (in priority order):
    /// 1. `.PHONY:` → Target with phony=true
    /// 2. Tab-prefixed → Comment (recipe line, will be associated with preceding target)
    /// 3. `NAME :=` → Variable (Simple flavor)
    /// 4. `name:` with no `=` → Target rule
    /// 5. `NAME =` → Variable (Recursive flavor)
    /// 6. Otherwise → Comment
    fn analyze_makefile_line(&mut self, line: &str) -> Result<Option<MakeItem>> {
        // .PHONY line (check before general colon detection)
        if line.starts_with(".PHONY") {
            if let Some(colon_pos) = line.find(':') {
                let _targets: Vec<String> = line[colon_pos + 1..]
                    .split_whitespace()
                    .map(String::from)
                    .collect();
                // Emit a .PHONY comment — the targets will be marked phony individually
                return Ok(Some(MakeItem::Comment {
                    text: line.to_string(),
                    span: self.next_span(),
                }));
            }
        }

        // Tab-prefixed lines are recipe lines (emit as comment to preserve content)
        if line.starts_with('\t') {
            return Ok(Some(MakeItem::Comment {
                text: line.to_string(),
                span: self.next_span(),
            }));
        }

        // Detect variable assignment: "NAME := value" (Simple)
        if let Some(eq_idx) = line.find(":=") {
            let var_name = line[..eq_idx].trim().to_string();
            let var_val = line[eq_idx + 2..].trim().to_string();
            if !var_name.is_empty() && !var_name.contains(' ') {
                return Ok(Some(MakeItem::Variable {
                    name: var_name,
                    value: var_val,
                    flavor: VarFlavor::Simple,
                    span: self.next_span(),
                }));
            }
        }

        // Detect target rule: "name: deps" (but not after := which was handled above)
        if let Some(colon_idx) = line.find(':') {
            // Make sure this isn't a := (already handled)
            let after_colon = line.get(colon_idx + 1..colon_idx + 2).unwrap_or("");
            if after_colon != "=" {
                let target_name = line[..colon_idx].trim().to_string();
                let deps_str = line[colon_idx + 1..].trim();
                if !target_name.is_empty()
                    && !target_name.contains(' ')
                    && !target_name.starts_with('#')
                {
                    let prerequisites: Vec<String> = if deps_str.is_empty() {
                        vec![]
                    } else {
                        deps_str.split_whitespace().map(String::from).collect()
                    };
                    return Ok(Some(MakeItem::Target {
                        name: target_name,
                        prerequisites,
                        recipe: vec![],
                        phony: false,
                        recipe_metadata: None,
                        span: self.next_span(),
                    }));
                }
            }
        }

        // Detect recursive variable assignment: "NAME = value"
        if let Some(eq_idx) = line.find('=') {
            let before = line[..eq_idx].trim();
            if !before.is_empty()
                && !before.contains(' ')
                && !before.starts_with('\t')
                && !before.starts_with('.')
                && !before.starts_with('#')
            {
                let var_val = line[eq_idx + 1..].trim().to_string();
                return Ok(Some(MakeItem::Variable {
                    name: before.to_string(),
                    value: var_val,
                    flavor: VarFlavor::Recursive,
                    span: self.next_span(),
                }));
            }
        }

        // Default: emit as comment
        Ok(Some(MakeItem::Comment {
            text: line.to_string(),
            span: self.next_span(),
        }))
    }

    /// Resolve an expression (possibly a `__format_concat` call) to its string value.
    ///
    /// The parser converts `println!("{}: {}", a, b)` to:
    ///   `FunctionCall { name: "__format_concat", args: [Variable("a"), Literal(": "), Variable("b")] }`
    fn resolve_concat_expr(&self, expr: &Expr) -> String {
        match expr {
            Expr::Literal(Literal::Str(s)) => s.clone(),
            Expr::Literal(Literal::I32(n)) => n.to_string(),
            Expr::Literal(Literal::U16(n)) => n.to_string(),
            Expr::Literal(Literal::U32(n)) => n.to_string(),
            Expr::Literal(Literal::Bool(b)) => b.to_string(),
            Expr::Variable(name) => {
                // Try to resolve from tracked bindings, fall back to $(NAME)
                if let Some(val) = self.vars.get(name.as_str()) {
                    val.clone()
                } else {
                    format!("$({})", name.to_uppercase())
                }
            }
            Expr::FunctionCall { name, args } if name == "__format_concat" => {
                // Concatenate all parts
                args.iter().map(|a| self.resolve_concat_expr(a)).collect()
            }
            _ => String::new(),
        }
    }

    /// Convert an exec() call to a MakeItem.
    ///
    /// `exec("CC := gcc")` → Variable { name: "CC", value: "gcc", flavor: Simple }
    /// `exec("build: main.o")` → Target { name: "build", deps: ["main.o"] }
    /// `exec("\tcargo build")` → appended as recipe to previous target
    ///
    /// This reuses the same analysis logic as convert_println.
    fn convert_exec(&mut self, args: &[Expr]) -> Result<Option<MakeItem>> {
        let resolved = match args.first() {
            Some(expr) => self.resolve_concat_expr(expr),
            None => return Ok(None),
        };
        if resolved.is_empty() {
            return Ok(None);
        }
        self.analyze_makefile_line(&resolved)
    }

    fn convert_target_call(&mut self, func_name: &str, args: &[Expr]) -> Result<Option<MakeItem>> {
        // target("name", &["dep1", "dep2"], &["recipe1", "recipe2"])
        // target("name", &["dep1", "dep2"]) -- deps only, no recipes
        // phony_target("name", &["dep1"], &["recipe1"])
        if args.len() < 2 {
            return Err(Error::Validation(format!(
                "{}() requires at least 2 arguments: name, dependencies (recipes optional)",
                func_name
            )));
        }

        // Extract target name (safe indexing: we verified args.len() >= 2 above)
        let Some(first_arg) = args.first() else {
            return Err(Error::Validation(format!(
                "{}() requires at least 2 arguments",
                func_name
            )));
        };
        let target_name = match first_arg {
            Expr::Literal(Literal::Str(s)) => s.clone(),
            _ => {
                return Err(Error::Validation(format!(
                    "{}() first argument must be a string literal (target name)",
                    func_name
                )))
            }
        };

        // Extract dependencies (from array literal) - safe: verified args.len() >= 2
        let Some(deps_arg) = args.get(1) else {
            return Err(Error::Validation(format!(
                "{}() requires at least 2 arguments",
                func_name
            )));
        };
        let deps = self.extract_string_array(deps_arg)?;

        // Extract recipes (optional third argument)
        let recipes = if let Some(recipes_arg) = args.get(2) {
            self.extract_string_array(recipes_arg)?
        } else {
            Vec::new()
        };

        let is_phony = func_name == "phony_target";

        Ok(Some(MakeItem::Target {
            name: target_name,
            prerequisites: deps,
            recipe: recipes,
            phony: is_phony,
            recipe_metadata: None,
            span: self.next_span(),
        }))
    }

    fn extract_string_array(&self, expr: &Expr) -> Result<Vec<String>> {
        match expr {
            // Handle Array expression: &["dep1", "dep2"]
            Expr::Array(items) => {
                let mut result = Vec::new();
                for item in items {
                    result.push(self.expr_to_string(item)?);
                }
                Ok(result)
            }
            // Handle array/slice literals represented as function calls in our AST
            Expr::FunctionCall { name, args } if name == "__array__" => {
                let mut result = Vec::new();
                for arg in args {
                    result.push(self.expr_to_string(arg)?);
                }
                Ok(result)
            }
            // Handle empty array
            Expr::Literal(Literal::Str(s)) if s.is_empty() => Ok(Vec::new()),
            // Handle single string as array of one
            Expr::Literal(Literal::Str(s)) => Ok(vec![s.clone()]),
            _ => {
                // Try to extract as a string
                Ok(vec![self.expr_to_string(expr)?])
            }
        }
    }

    fn expr_to_string(&self, expr: &Expr) -> Result<String> {
        match expr {
            Expr::Literal(Literal::Str(s)) => Ok(s.clone()),
            Expr::Literal(Literal::U16(n)) => Ok(n.to_string()),
            Expr::Literal(Literal::U32(n)) => Ok(n.to_string()),
            Expr::Literal(Literal::I32(n)) => Ok(n.to_string()),
            Expr::Literal(Literal::Bool(b)) => Ok(b.to_string()),
            Expr::Variable(name) => Ok(format!("$({})", name.to_uppercase())),
            Expr::Array(items) => {
                // Arrays become space-separated lists in Makefiles
                let parts: Vec<String> = items
                    .iter()
                    .map(|item| self.expr_to_string(item))
                    .collect::<Result<_>>()?;
                Ok(parts.join(" "))
            }
            Expr::Binary { left, op, right } => {
                let l = self.expr_to_string(left)?;
                let r = self.expr_to_string(right)?;
                let op_str = match op {
                    BinaryOp::Add => "+",
                    BinaryOp::Sub => "-",
                    BinaryOp::Mul => "*",
                    BinaryOp::Div => "/",
                    _ => return Ok(format!("{} {}", l, r)),
                };
                Ok(format!("$(shell echo $$(({} {} {})))", l, op_str, r))
            }
            Expr::Index { object, index } => {
                let arr_str = self.expr_to_string(object)?;
                let idx_str = self.expr_to_string(index)?;
                Ok(format!("$(word {},{})", idx_str, arr_str))
            }
            _ => Err(Error::Validation(
                "Cannot convert expression to Makefile value".to_string(),
            )),
        }
    }
}










include!("makefile_cont.rs");