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
485
486
//! Enhanced error types for Makefile parser
//!
//! Sprint 73 Phase 5: Error Handling Polish
//!
//! Provides structured error types with:
//! - Source location (file, line, column)
//! - Code snippets
//! - Explanatory notes
//! - Recovery hints
//!
//! Target: Error quality score ≥0.8

use std::fmt;
use thiserror::Error;

/// Source location information for error reporting
#[derive(Debug, Clone, PartialEq)]
pub struct SourceLocation {
    pub file: Option<String>,
    pub line: usize,
    pub column: Option<usize>,
    pub source_line: Option<String>,
}

impl SourceLocation {
    pub fn new(line: usize) -> Self {
        Self {
            file: None,
            line,
            column: None,
            source_line: None,
        }
    }

    pub fn with_file(mut self, file: String) -> Self {
        self.file = Some(file);
        self
    }

    pub fn with_column(mut self, column: usize) -> Self {
        self.column = Some(column);
        self
    }

    pub fn with_source_line(mut self, source_line: String) -> Self {
        self.source_line = Some(source_line);
        self
    }
}

impl fmt::Display for SourceLocation {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        if let Some(file) = &self.file {
            write!(f, "{}:{}", file, self.line)?;
        } else {
            write!(f, "line {}", self.line)?;
        }

        if let Some(col) = self.column {
            write!(f, ":{}", col)?;
        }

        Ok(())
    }
}

/// Enhanced error types for Makefile parsing
#[derive(Error, Debug)]
pub enum MakeParseError {
    #[error("Invalid variable assignment at {location}")]
    InvalidVariableAssignment {
        location: SourceLocation,
        found: String,
    },

    #[error("Empty variable name at {location}")]
    EmptyVariableName { location: SourceLocation },

    #[error("No assignment operator found at {location}")]
    NoAssignmentOperator {
        location: SourceLocation,
        found: String,
    },

    #[error("Invalid include syntax at {location}")]
    InvalidIncludeSyntax {
        location: SourceLocation,
        found: String,
    },

    #[error("Invalid conditional syntax at {location}")]
    InvalidConditionalSyntax {
        location: SourceLocation,
        directive: String,
        found: String,
    },

    #[error("Conditional requires arguments at {location}")]
    MissingConditionalArguments {
        location: SourceLocation,
        directive: String,
        expected_args: usize,
        found_args: usize,
    },

    #[error("Missing variable name in {directive} at {location}")]
    MissingVariableName {
        location: SourceLocation,
        directive: String,
    },

    #[error("Unknown conditional directive at {location}")]
    UnknownConditional {
        location: SourceLocation,
        found: String,
    },

    #[error("Invalid target rule syntax at {location}")]
    InvalidTargetRule {
        location: SourceLocation,
        found: String,
    },

    #[error("Empty target name at {location}")]
    EmptyTargetName { location: SourceLocation },

    #[error("Unterminated define block for variable '{var_name}' at {location}")]
    UnterminatedDefine {
        location: SourceLocation,
        var_name: String,
    },

    #[error("Unexpected end of file")]
    UnexpectedEof,
}

impl MakeParseError {
    /// Get the location information for this error
    pub fn location(&self) -> Option<&SourceLocation> {
        match self {
            Self::InvalidVariableAssignment { location, .. } => Some(location),
            Self::EmptyVariableName { location } => Some(location),
            Self::NoAssignmentOperator { location, .. } => Some(location),
            Self::InvalidIncludeSyntax { location, .. } => Some(location),
            Self::InvalidConditionalSyntax { location, .. } => Some(location),
            Self::MissingConditionalArguments { location, .. } => Some(location),
            Self::MissingVariableName { location, .. } => Some(location),
            Self::UnknownConditional { location, .. } => Some(location),
            Self::InvalidTargetRule { location, .. } => Some(location),
            Self::EmptyTargetName { location } => Some(location),
            Self::UnterminatedDefine { location, .. } => Some(location),
            Self::UnexpectedEof => None,
        }
    }

    /// Get explanatory note for this error
    pub fn note(&self) -> String {
        match self {
            Self::InvalidVariableAssignment { .. } => {
                "Variable assignments must use one of the assignment operators: =, :=, ?=, +=, !=".to_string()
            }
            Self::EmptyVariableName { .. } => {
                "Variable names cannot be empty. A valid variable name must contain at least one character.".to_string()
            }
            Self::NoAssignmentOperator { .. } => {
                "Variable assignments require an assignment operator (=, :=, ?=, +=, or !=)".to_string()
            }
            Self::InvalidIncludeSyntax { .. } => {
                "Include directives must be: 'include file', '-include file', or 'sinclude file'".to_string()
            }
            Self::InvalidConditionalSyntax { directive, .. } => {
                match directive.as_str() {
                    "ifeq" | "ifneq" => {
                        format!("{} requires arguments in parentheses with a comma separator", directive)
                    }
                    "ifdef" | "ifndef" => {
                        format!("{} requires a variable name argument", directive)
                    }
                    _ => "Conditional directives must follow GNU Make syntax".to_string(),
                }
            }
            Self::MissingConditionalArguments { directive, expected_args, found_args, .. } => {
                format!("{} requires {} argument(s), but found {}", directive, expected_args, found_args)
            }
            Self::MissingVariableName { directive, .. } => {
                format!("{} requires a variable name to test", directive)
            }
            Self::UnknownConditional { .. } => {
                "Supported conditional directives are: ifeq, ifneq, ifdef, ifndef".to_string()
            }
            Self::InvalidTargetRule { .. } => {
                "Target rules must have the format: target: prerequisites".to_string()
            }
            Self::EmptyTargetName { .. } => {
                "Target names cannot be empty. A valid target must have a name before the colon.".to_string()
            }
            Self::UnterminatedDefine { .. } => {
                "define blocks must be terminated with 'endef'".to_string()
            }
            Self::UnexpectedEof => {
                "The Makefile ended unexpectedly. Check for unclosed conditional blocks or incomplete rules.".to_string()
            }
        }
    }

    /// Get recovery hint for this error
    pub fn help(&self) -> String {
        match self {
            Self::InvalidVariableAssignment { .. } => {
                "Example: VAR = value\n       VAR := value\n       VAR ?= value".to_string()
            }
            Self::EmptyVariableName { .. } => {
                "Provide a variable name before the assignment operator.\nExample: MY_VAR = value".to_string()
            }
            Self::NoAssignmentOperator { .. } => {
                "Use one of the following assignment operators:\n  =   (recursive expansion)\n  :=  (simple expansion)\n  ?=  (conditional assignment)\n  +=  (append)\n  !=  (shell assignment)".to_string()
            }
            Self::InvalidIncludeSyntax { .. } => {
                "Use: include filename.mk\nOr for optional includes:\n     -include filename.mk\n     sinclude filename.mk".to_string()
            }
            Self::InvalidConditionalSyntax { directive, .. } => {
                match directive.as_str() {
                    "ifeq" => "Use: ifeq ($(VAR),value)\nOr:  ifeq (arg1,arg2)".to_string(),
                    "ifneq" => "Use: ifneq ($(VAR),value)\nOr:  ifneq (arg1,arg2)".to_string(),
                    "ifdef" => "Use: ifdef VARIABLE_NAME".to_string(),
                    "ifndef" => "Use: ifndef VARIABLE_NAME".to_string(),
                    _ => "Check the GNU Make manual for conditional syntax".to_string(),
                }
            }
            Self::MissingConditionalArguments { directive, .. } => {
                match directive.as_str() {
                    "ifeq" | "ifneq" => format!("Use: {} (arg1,arg2)", directive),
                    "ifdef" | "ifndef" => format!("Use: {} VAR_NAME", directive),
                    _ => "Provide the required arguments for the conditional".to_string(),
                }
            }
            Self::MissingVariableName { directive, .. } => {
                format!("Provide a variable name after {}.\nExample: {} DEBUG", directive, directive)
            }
            Self::UnknownConditional { found, .. } => {
                format!("Did you mean one of: ifeq, ifneq, ifdef, ifndef?\nFound: {}", found)
            }
            Self::InvalidTargetRule { .. } => {
                "Use the format: target: prerequisite1 prerequisite2\nFollowed by tab-indented recipe lines".to_string()
            }
            Self::EmptyTargetName { .. } => {
                "Provide a target name before the colon.\nExample: build: main.c\n\t$(CC) -o build main.c".to_string()
            }
            Self::UnterminatedDefine { .. } => {
                "Ensure all define blocks are closed with 'endef'.\nExample:\ndefine VAR_NAME\ncontent\nendef".to_string()
            }
            Self::UnexpectedEof => {
                "Ensure all conditional blocks (ifeq/ifdef/etc.) are closed with 'endif'.\nCheck that all target rules are complete.".to_string()
            }
        }
    }

    /// Convert to a displayable error message with note and help
    pub fn to_detailed_string(&self) -> String {
        let mut output = String::new();

        // Error message
        output.push_str("error: ");
        output.push_str(&self.to_string());
        output.push('\n');

        // Source code snippet (if available)
        if let Some(location) = self.location() {
            if let Some(source_line) = &location.source_line {
                output.push('\n');
                output.push_str(&format!("{} | {}\n", location.line, source_line));

                // Add caret indicator if column is known
                if let Some(col) = location.column {
                    let line_num_width = format!("{}", location.line).len();
                    let spaces = " ".repeat(line_num_width + 3 + col.saturating_sub(1));
                    output.push_str(&format!("{}^\n", spaces));
                }
            }
        }

        // Note (explanation)
        output.push('\n');
        output.push_str("note: ");
        output.push_str(&self.note());
        output.push('\n');

        // Help (recovery hint)
        output.push('\n');
        output.push_str("help: ");
        output.push_str(&self.help());
        output.push('\n');

        output
    }

    /// Calculate quality score for this error
    ///
    /// Score components:
    /// - Error message: 1.0 (always present)
    /// - File location: 1.0
    /// - Line number: 0.25
    /// - Column number: 0.25
    /// - Code snippet: 1.0
    /// - Note: 2.5 (always present)
    /// - Help: 2.5 (always present)
    ///
    /// Max: 8.5 → normalized to 1.0
    pub fn quality_score(&self) -> f32 {
        let mut score = 0.0;

        // Error message (always present)
        score += 1.0;

        // Note (always present)
        score += 2.5;

        // Help (always present)
        score += 2.5;

        // Location-based scores
        if let Some(location) = self.location() {
            if location.file.is_some() {
                score += 1.0;
            }
            // Line always present for located errors
            score += 0.25;

            if location.column.is_some() {
                score += 0.25;
            }

            if location.source_line.is_some() {
                score += 1.0;
            }
        }

        score / 8.5 // Normalize to 0-1
    }
}

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

    // ====== SourceLocation Tests ======

    #[test]
    fn test_source_location_new() {
        let loc = SourceLocation::new(42);
        assert_eq!(loc.line, 42);
        assert!(loc.file.is_none());
        assert!(loc.column.is_none());
        assert!(loc.source_line.is_none());
    }

    #[test]
    fn test_source_location_with_file() {
        let loc = SourceLocation::new(10).with_file("Makefile".to_string());
        assert_eq!(loc.file, Some("Makefile".to_string()));
        assert_eq!(loc.line, 10);
    }

    #[test]
    fn test_source_location_with_column() {
        let loc = SourceLocation::new(5).with_column(15);
        assert_eq!(loc.column, Some(15));
    }

    #[test]
    fn test_source_location_with_source_line() {
        let loc = SourceLocation::new(1).with_source_line("CC := gcc".to_string());
        assert_eq!(loc.source_line, Some("CC := gcc".to_string()));
    }

    #[test]
    fn test_source_location_chained_builder() {
        let loc = SourceLocation::new(42)
            .with_file("test.mk".to_string())
            .with_column(8)
            .with_source_line("ifeq ($(X),Y)".to_string());

        assert_eq!(loc.line, 42);
        assert_eq!(loc.file, Some("test.mk".to_string()));
        assert_eq!(loc.column, Some(8));
        assert_eq!(loc.source_line, Some("ifeq ($(X),Y)".to_string()));
    }

    #[test]
    fn test_source_location_display_no_file() {
        let loc = SourceLocation::new(15);
        let display = format!("{}", loc);
        assert_eq!(display, "line 15");
    }

    #[test]
    fn test_source_location_display_with_file() {
        let loc = SourceLocation::new(15).with_file("Makefile".to_string());
        let display = format!("{}", loc);
        assert_eq!(display, "Makefile:15");
    }

    #[test]
    fn test_source_location_display_with_column() {
        let loc = SourceLocation::new(15)
            .with_file("Makefile".to_string())
            .with_column(8);
        let display = format!("{}", loc);
        assert_eq!(display, "Makefile:15:8");
    }

    #[test]
    fn test_source_location_display_no_file_with_column() {
        let loc = SourceLocation::new(15).with_column(8);
        let display = format!("{}", loc);
        assert_eq!(display, "line 15:8");
    }

    #[test]
    fn test_source_location_equality() {
        let loc1 = SourceLocation::new(10).with_file("a.mk".to_string());
        let loc2 = SourceLocation::new(10).with_file("a.mk".to_string());
        let loc3 = SourceLocation::new(20).with_file("a.mk".to_string());

        assert_eq!(loc1, loc2);
        assert_ne!(loc1, loc3);
    }

    // ====== Quality Score Tests ======

    #[test]
    fn test_quality_score_minimum() {
        // UnexpectedEof has no location, so minimal score
        let error = MakeParseError::UnexpectedEof;
        let score = error.quality_score();

        // Score: error(1.0) + note(2.5) + help(2.5) = 6.0 / 8.5 = 0.706
        assert!(score >= 0.7, "Score {} should be ≥0.7", score);
        assert!(score < 0.75, "Score {} should be <0.75", score);
    }

    #[test]
    fn test_quality_score_with_location() {
        let location = SourceLocation::new(15);
        let error = MakeParseError::EmptyVariableName { location };
        let score = error.quality_score();

        // Score: error(1.0) + note(2.5) + help(2.5) + line(0.25) = 6.25 / 8.5 = 0.735
        assert!(score >= 0.73, "Score {} should be ≥0.73", score);
        assert!(score < 0.75, "Score {} should be <0.75", score);
    }

    #[test]
    fn test_quality_score_with_file_and_column() {
        let location = SourceLocation::new(15)
            .with_file("Makefile".to_string())
            .with_column(8);

        let error = MakeParseError::EmptyTargetName { location };
        let score = error.quality_score();

        // Score: error(1.0) + note(2.5) + help(2.5) + file(1.0) + line(0.25) + column(0.25) = 7.5 / 8.5 = 0.882
        assert!(score >= 0.88, "Score {} should be ≥0.88", score);
        assert!(score < 0.89, "Score {} should be <0.89", score);
    }

    #[test]
    fn test_quality_score_with_snippet() {
        let location = SourceLocation::new(15)
            .with_file("Makefile".to_string())
            .with_column(8)
            .with_source_line("ifeq $(VAR) value".to_string());

        let error = MakeParseError::InvalidConditionalSyntax {
            location,
            directive: "ifeq".to_string(),
            found: "$(VAR) value".to_string(),
        };

        let score = error.quality_score();


}
}

        include!("error_part2_incl2.rs");