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
//! Operational semantics for rash AST and POSIX shell
//!
//! This module defines the formal operational semantics for both
//! the tiny rash AST subset and the corresponding POSIX shell commands.

use crate::formal::{AbstractState, TinyAst};
use std::path::{Path, PathBuf};

/// Result of evaluating an AST node or shell command
pub type EvalResult = Result<AbstractState, String>;

/// Operational semantics for the tiny rash AST subset
pub mod rash_semantics {
    use super::*;

    /// Evaluate a rash AST node in a given state
    pub fn eval_rash(ast: &TinyAst, mut state: AbstractState) -> EvalResult {
        match ast {
            TinyAst::ExecuteCommand { command_name, args } => {
                eval_command(&mut state, command_name, args)?;
                Ok(state)
            }

            TinyAst::SetEnvironmentVariable { name, value } => {
                state.set_env(name.clone(), value.clone());
                Ok(state)
            }

            TinyAst::Sequence { commands } => {
                let mut current_state = state;
                for cmd in commands {
                    current_state = eval_rash(cmd, current_state)?;
                }
                Ok(current_state)
            }

            TinyAst::ChangeDirectory { path } => {
                let path_buf = PathBuf::from(path);
                state.change_directory(path_buf)?;
                Ok(state)
            }
        }
    }

    /// Execute a command in the abstract state
    pub fn eval_command(
        state: &mut AbstractState,
        command: &str,
        args: &[String],
    ) -> Result<(), String> {
        match command {
            "echo" => eval_echo_command(state, args),
            "mkdir" => eval_mkdir_command(state, args),
            "test" => eval_test_command(state, args),
            _ => eval_unknown_command(state, command),
        }
    }

    fn eval_echo_command(state: &mut AbstractState, args: &[String]) -> Result<(), String> {
        let output = if args.is_empty() {
            String::new()
        } else {
            args.join(" ")
        };
        state.write_stdout(output);
        Ok(())
    }

    fn eval_mkdir_command(state: &mut AbstractState, args: &[String]) -> Result<(), String> {
        let (parent_flag, paths) = parse_mkdir_args(state, args)?;

        for path_str in paths {
            let path = resolve_path(state, &path_str);
            create_directory_with_options(state, path, parent_flag)?;
        }
        Ok(())
    }

    fn parse_mkdir_args(
        state: &mut AbstractState,
        args: &[String],
    ) -> Result<(bool, Vec<String>), String> {
        let mut parent_flag = false;
        let mut paths = Vec::new();

        for arg in args {
            if arg == "-p" {
                parent_flag = true;
            } else if arg.starts_with('-') {
                state.write_stderr(format!("mkdir: invalid option -- '{arg}'"));
                state.exit_code = 1;
                return Err("Invalid option".to_string());
            } else {
                paths.push(arg.clone());
            }
        }
        Ok((parent_flag, paths))
    }

    fn resolve_path(state: &AbstractState, path_str: &str) -> PathBuf {
        if path_str.starts_with('/') {
            PathBuf::from(path_str)
        } else {
            state.cwd.join(path_str)
        }
    }

    fn create_directory_with_options(
        state: &mut AbstractState,
        path: PathBuf,
        parent_flag: bool,
    ) -> Result<(), String> {
        if parent_flag {
            state.create_directory(path)
        } else {
            validate_parent_exists(state, &path)?;
            state.create_directory(path)
        }
    }

    fn validate_parent_exists(state: &mut AbstractState, path: &Path) -> Result<(), String> {
        if let Some(parent) = path.parent() {
            if !state.filesystem.contains_key(parent) {
                let error_msg = format!(
                    "mkdir: cannot create directory '{}': No such file or directory",
                    path.display()
                );
                state.write_stderr(error_msg);
                state.exit_code = 1;
                return Err("Parent directory does not exist".to_string());
            }
        }
        Ok(())
    }

    fn eval_test_command(state: &mut AbstractState, args: &[String]) -> Result<(), String> {
        if args.is_empty() {
            state.exit_code = 1;
            return Ok(());
        }

        match args[0].as_str() {
            "-d" => test_directory_exists(state, args),
            "-f" => test_file_exists(state, args),
            _ => {
                state.exit_code = 1;
                Ok(())
            }
        }
    }

    fn test_directory_exists(state: &mut AbstractState, args: &[String]) -> Result<(), String> {
        if args.len() < 2 {
            state.exit_code = 1;
            return Ok(());
        }

        let path = PathBuf::from(&args[1]);
        state.exit_code = match state.filesystem.get(&path) {
            Some(crate::formal::FileSystemEntry::Directory) => 0,
            _ => 1,
        };
        Ok(())
    }

    fn test_file_exists(state: &mut AbstractState, args: &[String]) -> Result<(), String> {
        if args.len() < 2 {
            state.exit_code = 1;
            return Ok(());
        }

        let path = PathBuf::from(&args[1]);
        state.exit_code = match state.filesystem.get(&path) {
            Some(crate::formal::FileSystemEntry::File(_)) => 0,
            _ => 1,
        };
        Ok(())
    }

    fn eval_unknown_command(state: &mut AbstractState, command: &str) -> Result<(), String> {
        state.write_stderr(format!("{command}: command not fully modeled"));
        state.exit_code = 0;
        Ok(())
    }
}

/// Operational semantics for POSIX shell commands
pub mod posix_semantics {
    use super::*;

    /// Evaluate a POSIX shell command string in a given state
    pub fn eval_posix(command: &str, mut state: AbstractState) -> EvalResult {
        // Parse the command string into components
        let parsed = parse_posix_command(command)?;

        for cmd in parsed {
            state = eval_single_posix_command(cmd, state)?;
        }

        Ok(state)
    }

    /// Simple POSIX command representation
    #[derive(Debug, Clone)]
    enum PosixCommand {
        SimpleCommand { name: String, args: Vec<String> },
        Assignment { name: String, value: String },
        ChangeDir { path: String },
    }

    /// Parse a POSIX command string (simplified for our tiny subset)
    fn parse_posix_command(command: &str) -> Result<Vec<PosixCommand>, String> {
        let mut commands = Vec::new();

        // Split by semicolons for sequential commands
        for cmd_str in command.split(';') {
            let cmd_str = cmd_str.trim();
            if cmd_str.is_empty() {
                continue;
            }

            // Check for variable assignment (VAR=value)
            if let Some(eq_pos) = cmd_str.find('=') {
                let (name, value) = cmd_str.split_at(eq_pos);
                let name = name.trim();
                let value = value[1..].trim(); // Skip the '='

                // Check if this is a valid assignment (no spaces in name)
                if !name.contains(' ') && crate::formal::TinyAst::validate_variable_name(name) {
                    // Remove quotes if present
                    let value = value.trim_matches('"').to_string();
                    commands.push(PosixCommand::Assignment {
                        name: name.to_string(),
                        value,
                    });
                    continue;
                }
            }

            // Check for cd command
            if let Some(path_part) = cmd_str.strip_prefix("cd ") {
                let path = path_part.trim().trim_matches('"');
                commands.push(PosixCommand::ChangeDir {
                    path: path.to_string(),
                });
                continue;
            }

            // Parse as simple command
            let parts = parse_command_line(cmd_str)?;
            if !parts.is_empty() {
                commands.push(PosixCommand::SimpleCommand {
                    name: parts[0].clone(),
                    args: parts[1..].to_vec(),
                });
            }
        }

        Ok(commands)
    }

    /// Parse a command line into words (simplified shell parsing)
    fn parse_command_line(line: &str) -> Result<Vec<String>, String> {
        let mut words = Vec::new();
        let mut current_word = String::new();
        let mut in_quotes = false;
        let mut escape_next = false;

        for ch in line.chars() {
            if escape_next {
                current_word.push(ch);
                escape_next = false;
                continue;
            }

            match ch {
                '\\' => {
                    escape_next = true;
                }
                '"' => {
                    if in_quotes {
                        // Closing quote - push the word even if empty
                        words.push(current_word.clone());
                        current_word.clear();
                    }
                    in_quotes = !in_quotes;
                }
                ' ' | '\t' => {
                    if in_quotes {
                        current_word.push(ch);
                    } else if !current_word.is_empty() {
                        words.push(current_word.clone());
                        current_word.clear();
                    }
                }
                _ => {
                    current_word.push(ch);
                }
            }
        }

        if in_quotes {
            return Err("Unterminated quote".to_string());
        }

        if !current_word.is_empty() {
            words.push(current_word);
        }

        Ok(words)
    }

    /// Evaluate a single POSIX command
    fn eval_single_posix_command(cmd: PosixCommand, mut state: AbstractState) -> EvalResult {
        match cmd {
            PosixCommand::SimpleCommand { name, args } => {
                // Delegate to rash semantics for consistency
                rash_semantics::eval_command(&mut state, &name, &args)?;
                Ok(state)
            }

            PosixCommand::Assignment { name, value } => {
                state.set_env(name, value);
                Ok(state)
            }

            PosixCommand::ChangeDir { path } => {
                state.change_directory(PathBuf::from(path))?;
                Ok(state)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_rash_echo() {
        let ast = TinyAst::ExecuteCommand {
            command_name: "echo".to_string(),
            args: vec!["Hello".to_string(), "World".to_string()],
        };

        let initial_state = AbstractState::new();
        let result = rash_semantics::eval_rash(&ast, initial_state).unwrap();

        assert_eq!(result.stdout, vec!["Hello World"]);
        assert_eq!(result.exit_code, 0);
    }

    #[test]
    fn test_rash_set_env() {
        let ast = TinyAst::SetEnvironmentVariable {
            name: "RASH_TEST".to_string(),
            value: "test_value".to_string(),
        };

        let initial_state = AbstractState::new();
        let result = rash_semantics::eval_rash(&ast, initial_state).unwrap();

        assert_eq!(result.get_env("RASH_TEST"), Some(&"test_value".to_string()));
    }

    #[test]
    fn test_rash_sequence() {
        let ast = TinyAst::Sequence {
            commands: vec![
                TinyAst::SetEnvironmentVariable {
                    name: "DIR".to_string(),
                    value: "/tmp/test".to_string(),
                },
                TinyAst::ExecuteCommand {
                    command_name: "mkdir".to_string(),
                    args: vec!["-p".to_string(), "/tmp/test".to_string()],
                },
            ],
        };

        let initial_state = AbstractState::new();
        let result = rash_semantics::eval_rash(&ast, initial_state).unwrap();

        assert_eq!(result.get_env("DIR"), Some(&"/tmp/test".to_string()));
        assert!(result.filesystem.contains_key(&PathBuf::from("/tmp/test")));
    }

    #[test]
    fn test_posix_echo() {
        let command = r#"echo "Hello World""#;
        let initial_state = AbstractState::new();
        let result = posix_semantics::eval_posix(command, initial_state).unwrap();

        assert_eq!(result.stdout, vec!["Hello World"]);
        assert_eq!(result.exit_code, 0);
    }

    #[test]
    fn test_posix_assignment() {
        let command = "RASH_TEST=\"test_value\"";
        let initial_state = AbstractState::new();
        let result = posix_semantics::eval_posix(command, initial_state).unwrap();

        assert_eq!(result.get_env("RASH_TEST"), Some(&"test_value".to_string()));
    }

    #[test]
    fn test_posix_sequence() {
        let command = "DIR=\"/tmp/test\"; mkdir -p /tmp/test";
        let initial_state = AbstractState::new();
        let result = posix_semantics::eval_posix(command, initial_state).unwrap();

        assert_eq!(result.get_env("DIR"), Some(&"/tmp/test".to_string()));
        assert!(result.filesystem.contains_key(&PathBuf::from("/tmp/test")));
    }
}