mk-rs-core 0.2.0

mk-rust core: lexer, parser, DAG builder, scheduler
Documentation
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
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
//! Parser for mkfile syntax.
//!
//! Converts lexer tokens into an AST: rules and variable assignments.
//! Phase 1a scope: concrete rules only. No metarules, includes, or variable expansion.

use crate::attr::{parse_attributes, Attributes, ParseAttrError};
use crate::error::ParseError;
use crate::include::IncludeContext;
use crate::lex::Token;
use std::path::{Path, PathBuf};

// ── AST types ──────────────────────────────────────────────────────────────

/// Top-level mkfile statement.
#[derive(Debug, Clone, PartialEq)]
pub enum Stmt {
    Rule(Rule),
    Assign(Assign),
}

/// A single build rule.
#[derive(Debug, Clone, PartialEq)]
pub struct Rule {
    pub targets: Vec<String>,
    pub prereqs: Vec<String>,
    pub attributes: Attributes,
    pub recipe: Option<String>,
    pub is_metarule: bool,
    pub is_regex: bool,
    pub line: usize,
    /// Custom comparison program from P: attribute (e.g., "Pcmp" → Some("cmp")).
    pub prog: Option<String>,
}

/// Variable assignment.
#[derive(Debug, Clone, PartialEq)]
pub struct Assign {
    pub name: String,
    pub value: String,
}

// ── Public API ─────────────────────────────────────────────────────────────

/// Parse tokens into statements.
///
/// Thin wrapper that delegates to [`parse_with_includes`] with a fresh
/// include context and the current working directory as the base.
pub fn parse(tokens: &[Token]) -> Result<Vec<Stmt>, ParseError> {
    parse_with_includes(
        tokens,
        &mut IncludeContext::new(),
        &std::env::current_dir().unwrap_or_else(|_| PathBuf::from(".")),
    )
}

/// Parse tokens with include support.
///
/// Handles `< file` include directives by reading and parsing the
/// referenced mkfile. The `base_dir` is used to resolve relative paths.
fn parse_with_includes(
    tokens: &[Token],
    ctx: &mut IncludeContext,
    base_dir: &Path,
) -> Result<Vec<Stmt>, ParseError> {
    let mut stmts = Vec::new();
    let mut pos: usize = 0;
    let mut line: usize = 1;

    while pos < tokens.len() && tokens[pos] != Token::Eof {
        match &tokens[pos] {
            Token::Include => {
                pos += 1;
                if pos < tokens.len() && tokens[pos] == Token::Pipe {
                    // <| command — pipe include
                    pos += 1;
                    let mut cmd_parts = Vec::new();
                    while pos < tokens.len() && matches!(&tokens[pos], Token::Word(_)) {
                        if let Token::Word(ref w) = tokens[pos] {
                            cmd_parts.push(w.clone());
                        }
                        pos += 1;
                    }
                    let command = cmd_parts.join(" ");
                    match ctx.include_command(&command, base_dir) {
                        Ok(included_stmts) => {
                            stmts.extend(included_stmts);
                        }
                        Err(e) => {
                            return Err(ParseError::UnexpectedToken {
                                expected: "valid command".into(),
                                got: e.to_string(),
                                line,
                            });
                        }
                    }
                } else {
                    // < file — include directive
                    let mut path_parts = Vec::new();
                    while pos < tokens.len() && matches!(&tokens[pos], Token::Word(_)) {
                        if let Token::Word(ref w) = tokens[pos] {
                            path_parts.push(w.clone());
                        }
                        pos += 1;
                    }
                    let path = path_parts.join(" ");
                    match ctx.include_file(&path, base_dir) {
                        Ok(included_stmts) => {
                            stmts.extend(included_stmts);
                        }
                        Err(e) => {
                            return Err(ParseError::UnexpectedToken {
                                expected: "valid include path".into(),
                                got: e.to_string(),
                                line,
                            });
                        }
                    }
                }
                // Consume the trailing newline
                if pos < tokens.len() && tokens[pos] == Token::Newline {
                    pos += 1;
                    line += 1;
                }
            }
            Token::Newline => {
                line += 1;
                pos += 1;
            }
            Token::Indent | Token::Pipe => {
                // Skip unrecognized / not-yet-supported top-level tokens
                pos = skip_logical_line(tokens, pos, &mut line);
            }
            Token::Word(_) => {
                if is_assignment(tokens, pos) {
                    let assign = parse_assign(tokens, &mut pos, &mut line)?;
                    stmts.push(Stmt::Assign(assign));
                } else {
                    let rule = parse_rule(tokens, &mut pos, &mut line)?;
                    stmts.push(Stmt::Rule(rule));
                }
            }
            _ => {
                // Colon at start or other unexpected token — try parse_rule
                // (produces EmptyTarget for bare colon, ExpectedColon otherwise)
                let rule = parse_rule(tokens, &mut pos, &mut line)?;
                stmts.push(Stmt::Rule(rule));
            }
        }
    }

    Ok(stmts)
}

// ── line-type detection ────────────────────────────────────────────────────

/// Returns true if the logical line starting at `start` is an assignment
/// (contains `=` before `:` or end-of-line).
fn is_assignment(tokens: &[Token], start: usize) -> bool {
    let mut i = start;
    while i < tokens.len() {
        match &tokens[i] {
            Token::Equals => return true,
            Token::Colon => return false,
            Token::Newline | Token::Eof => return false,
            _ => i += 1,
        }
    }
    false
}

/// Skip tokens until the next Newline or Eof, incrementing the line counter.
/// Returns the new position.
fn skip_logical_line(tokens: &[Token], mut pos: usize, line: &mut usize) -> usize {
    while pos < tokens.len() {
        match &tokens[pos] {
            Token::Newline => {
                *line += 1;
                return pos + 1;
            }
            Token::Eof => return pos,
            _ => pos += 1,
        }
    }
    pos
}

// ── assignment parsing ─────────────────────────────────────────────────────

fn parse_assign(
    tokens: &[Token],
    pos: &mut usize,
    line: &mut usize,
) -> Result<Assign, ParseError> {
    // Variable name
    let name = match &tokens[*pos] {
        Token::Word(s) => s.clone(),
        _ => {
            return Err(ParseError::UnexpectedToken {
                expected: "variable name".into(),
                got: token_name(&tokens[*pos]),
                line: *line,
            });
        }
    };
    *pos += 1;

    // Expect `=`
    if !matches!(&tokens[*pos], Token::Equals) {
        return Err(ParseError::UnexpectedToken {
            expected: "=".into(),
            got: token_name(&tokens[*pos]),
            line: *line,
        });
    }
    *pos += 1;

    // Collect value words
    let mut parts: Vec<&str> = Vec::new();
    while *pos < tokens.len() && matches!(&tokens[*pos], Token::Word(_)) {
        if let Token::Word(s) = &tokens[*pos] {
            parts.push(s);
        }
        *pos += 1;
    }
    let value = parts.join(" ");

    // Consume trailing newline
    if *pos < tokens.len() && matches!(&tokens[*pos], Token::Newline) {
        *pos += 1;
        *line += 1;
    }

    Ok(Assign { name, value })
}

// ── rule parsing ───────────────────────────────────────────────────────────

fn parse_rule(
    tokens: &[Token],
    pos: &mut usize,
    line: &mut usize,
) -> Result<Rule, ParseError> {
    let start_line = *line;

    // Collect targets (words left of colon)
    let mut targets: Vec<String> = Vec::new();
    while *pos < tokens.len() && matches!(&tokens[*pos], Token::Word(_)) {
        if let Token::Word(s) = &tokens[*pos] {
            targets.push(s.clone());
        }
        *pos += 1;
    }

    if targets.is_empty() {
        return Err(ParseError::EmptyTarget { line: start_line });
    }

    // Expect colon
    if *pos >= tokens.len() || !matches!(&tokens[*pos], Token::Colon) {
        return Err(ParseError::ExpectedColon { line: start_line });
    }
    *pos += 1; // consume `:`

    // Check for attributes between colons: `target:VQ: prereq`
    let mut attrs = Attributes::new();
    let mut prog: Option<String> = None;
    if *pos < tokens.len()
        && matches!(&tokens[*pos], Token::Word(_))
        && *pos + 1 < tokens.len()
        && matches!(&tokens[*pos + 1], Token::Colon)
    {
        if let Token::Word(attr_str) = &tokens[*pos] {
            let (clean_attr_str, extracted_prog) = extract_prog_from_attr(attr_str);
            prog = extracted_prog;
            attrs = parse_attributes(&clean_attr_str).map_err(|e| match e {
                ParseAttrError::UnknownAttr(c) => ParseError::UnknownAttr {
                    attr: c,
                    line: start_line,
                },
            })?;
        }
        *pos += 2; // skip attribute word + closing colon
    }
    // else: single colon, no attributes

    // Collect prerequisites (words right of colon)
    let mut prereqs: Vec<String> = Vec::new();
    while *pos < tokens.len() && matches!(&tokens[*pos], Token::Word(_)) {
        if let Token::Word(s) = &tokens[*pos] {
            prereqs.push(s.clone());
        }
        *pos += 1;
    }

    // Detect GNU Make $(...) syntax in prereqs and reject with clear error.
    // mk has its own glob syntax (*.txt, dir/*.c) — $(wildcard ...) is not needed.
    for prereq in &prereqs {
        if prereq.contains("$(") {
            return Err(ParseError::UnexpectedToken {
                expected: "mk glob pattern (e.g., '*.txt' or 'dir/*.c')".into(),
                got: format!(
                    "GNU Make syntax $(...) in prereq '{}' is not supported",
                    prereq
                ),
                line: start_line,
            });
        }
    }

    // Consume trailing newline after header
    if *pos < tokens.len() && matches!(&tokens[*pos], Token::Newline) {
        *pos += 1;
        *line += 1;
    }

    // Collect recipe (indented lines)
    let recipe = parse_recipe(tokens, pos, line);

    let is_metarule = targets.iter().any(|t| t.contains('%') || t.contains('&'));
    let is_regex = attrs.is_regex();

    Ok(Rule {
        targets,
        prereqs,
        attributes: attrs,
        recipe,
        is_metarule,
        is_regex,
        line: start_line,
        prog,
    })
}

// ── attribute helpers ─────────────────────────────────────────────────────

/// Valid attribute characters (used for extracting P program name).
const VALID_ATTR_CHARS: &[char] = &['V', 'Q', 'N', 'U', 'D', 'E', 'P', 'R', 'n'];

/// Extract the custom comparison program name from a P attribute.
///
/// In Plan 9 mk, `target:Pprog: prereq` attaches the P attribute with a
/// program name directly following the P. E.g., `"Pcmp"` → P attr + program
/// `"cmp"`. The program name is all non-attribute characters after P until
/// the next attribute character or end of string.
///
/// Returns the cleaned attribute string (program chars removed) and the
/// optional program name.
fn extract_prog_from_attr(attr_str: &str) -> (String, Option<String>) {
    if let Some(p_pos) = attr_str.find('P') {
        let before = &attr_str[..p_pos];
        let after = &attr_str[p_pos + 1..];

        // Program name: non-attr chars after P
        let prog_end = after
            .find(|c: char| VALID_ATTR_CHARS.contains(&c))
            .unwrap_or(after.len());
        let prog = &after[..prog_end];

        // Reconstruct attr string: before + 'P' + remaining attrs after prog
        let clean = format!("{}P{}", before, &after[prog_end..]);
        let prog = if prog.is_empty() {
            None
        } else {
            Some(prog.to_string())
        };
        (clean, prog)
    } else {
        (attr_str.to_string(), None)
    }
}

// ── recipe parsing ─────────────────────────────────────────────────────────

/// Collect indented lines after a rule header.
///
/// Reads sequences of `Indent, Word*, Newline` and joins them into
/// a single recipe string. Stops at a blank line, non-indented line, or Eof.
fn parse_recipe(tokens: &[Token], pos: &mut usize, line: &mut usize) -> Option<String> {
    let mut recipe_lines: Vec<String> = Vec::new();

    while *pos < tokens.len() && matches!(&tokens[*pos], Token::Indent) {
        // Skip the Indent token
        *pos += 1;

        // Collect Word tokens until Newline or Eof
        let mut words: Vec<&str> = Vec::new();
        while *pos < tokens.len() && matches!(&tokens[*pos], Token::Word(_)) {
            if let Token::Word(s) = &tokens[*pos] {
                words.push(s);
            }
            *pos += 1;
        }

        if !words.is_empty() {
            recipe_lines.push(words.join(" "));
        }

        // Consume trailing Newline
        if *pos < tokens.len() && matches!(&tokens[*pos], Token::Newline) {
            *pos += 1;
            *line += 1;
        } else {
            // No newline after indented content — stop collecting
            break;
        }
    }

    if recipe_lines.is_empty() {
        None
    } else {
        Some(recipe_lines.join("\n"))
    }
}

// ── debug helpers ──────────────────────────────────────────────────────────

/// Human-readable name for a token (used in error messages).
fn token_name(tok: &Token) -> String {
    match tok {
        Token::Word(s) => format!("word '{s}'"),
        Token::Colon => "colon".into(),
        Token::Equals => "equals".into(),
        Token::Include => "include".into(),
        Token::Pipe => "pipe".into(),
        Token::Indent => "indent".into(),
        Token::Newline => "newline".into(),
        Token::Eof => "end of file".into(),
    }
}

// ── tests ──────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use crate::lex::{tokenize, ShellMode};

    fn parse_str(input: &str) -> Result<Vec<Stmt>, ParseError> {
        let tokens = tokenize(input, ShellMode::Sh).unwrap();
        parse(&tokens)
    }

    #[test]
    fn simple_rule() {
        let stmts = parse_str("target: prereq\n").unwrap();
        assert_eq!(stmts.len(), 1);
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.targets, vec!["target"]);
                assert_eq!(r.prereqs, vec!["prereq"]);
                assert!(r.recipe.is_none());
                assert!(!r.is_metarule);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_with_recipe() {
        let stmts = parse_str("target: prereq\n\techo hello\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.recipe, Some("echo hello".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_multi_line_recipe() {
        let stmts = parse_str("target: prereq\n\techo one\n\techo two\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.recipe, Some("echo one\necho two".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_without_prereqs() {
        let stmts = parse_str("target:\n\techo hi\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.prereqs, Vec::<String>::new());
                assert_eq!(r.recipe, Some("echo hi".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_with_virtual_attr() {
        let stmts = parse_str("target:V: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.attributes.is_virtual());
                assert!(!r.is_metarule);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_with_multiple_attrs() {
        let stmts = parse_str("target:VQ: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.attributes.is_virtual());
                assert!(r.attributes.is_quiet());
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn assignment() {
        let stmts = parse_str("CC = gcc\n").unwrap();
        match &stmts[0] {
            Stmt::Assign(a) => {
                assert_eq!(a.name, "CC");
                assert_eq!(a.value, "gcc");
            }
            _ => panic!("expected Assign"),
        }
    }

    #[test]
    fn assignment_multi_word_value() {
        let stmts = parse_str("CFLAGS = -Wall -O2\n").unwrap();
        match &stmts[0] {
            Stmt::Assign(a) => {
                assert_eq!(a.name, "CFLAGS");
                assert_eq!(a.value, "-Wall -O2");
            }
            _ => panic!("expected Assign"),
        }
    }

    #[test]
    fn multiple_rules() {
        let stmts = parse_str("a: b\n\techo a\n\nc: d\n\techo c\n").unwrap();
        assert_eq!(stmts.len(), 2);
    }

    #[test]
    fn rule_with_multiple_targets() {
        let stmts = parse_str("a b: c d\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.targets, vec!["a", "b"]);
                assert_eq!(r.prereqs, vec!["c", "d"]);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_with_multiple_prereqs() {
        let stmts = parse_str("prog: a.o b.o c.o\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.prereqs, vec!["a.o", "b.o", "c.o"]);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn missing_colon() {
        let result = parse_str("target prereq\n");
        assert!(result.is_err());
    }

    #[test]
    fn empty_target() {
        let result = parse_str(": prereq\n");
        assert!(result.is_err());
    }

    #[test]
    fn empty_input() {
        let stmts = parse_str("").unwrap();
        assert!(stmts.is_empty());
    }

    #[test]
    fn only_comments() {
        let stmts = parse_str("# just a comment\n").unwrap();
        assert!(stmts.is_empty());
    }

    #[test]
    fn blank_lines_terminate_recipe() {
        let input = "target: prereq\n\techo one\n\necho standalone\n";
        // Blank line terminates recipe. Then "echo standalone" is a bare word — invalid.
        assert!(parse_str(input).is_err());
        // But without the bare word, it parses fine:
        let valid = "target: prereq\n\techo one\n";
        let stmts = parse_str(valid).unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.recipe, Some("echo one".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn metarule_detection() {
        let stmts = parse_str("%.o: %.c\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.is_metarule);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn regex_rule_detection() {
        let stmts = parse_str("foo:R: bar\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.is_regex);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_with_line_number() {
        // Input has a comment on line 1, rule on line 2
        let stmts = parse_str("# comment\ntarget: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.line, 2);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn include_command_parses_stdout() {
        // <| echo "target: prereq" should parse as a rule
        let input = "<| echo \"target: prereq\"\n";
        let tokens = tokenize(input, ShellMode::Sh).unwrap();
        let stmts = parse(&tokens).unwrap();
        assert_eq!(stmts.len(), 1);
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.targets, vec!["target"]);
                assert_eq!(r.prereqs, vec!["prereq"]);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn p_attribute_with_program() {
        // target:Pcmp: prereq → P attr with program "cmp"
        let stmts = parse_str("target:Pcmp: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.attributes.has_comparison());
                assert_eq!(r.prog, Some("cmp".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn p_attribute_no_program() {
        // target:P: prereq → P attr, no program name
        let stmts = parse_str("target:P: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.attributes.has_comparison());
                assert_eq!(r.prog, None);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn p_attribute_with_trailing_attrs() {
        // target:PcmpQ: prereq → P attr, program "cmp", Q attr
        let stmts = parse_str("target:PcmpQ: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.attributes.has_comparison());
                assert!(r.attributes.is_quiet());
                assert_eq!(r.prog, Some("cmp".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn p_attribute_with_leading_attrs() {
        // target:VPcmp: prereq → V attr, P attr, program "cmp"
        let stmts = parse_str("target:VPcmp: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.attributes.is_virtual());
                assert!(r.attributes.has_comparison());
                assert_eq!(r.prog, Some("cmp".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn p_attribute_pv_means_p_and_v_attrs_no_prog() {
        // target:PV: prereq → P attr + V attr, NO program (V is attr char)
        let stmts = parse_str("target:PV: prereq\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert!(r.attributes.has_comparison());
                assert!(r.attributes.is_virtual());
                assert_eq!(r.prog, None);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn rule_no_newline_at_eof() {
        let stmts = parse_str("target: prereq").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.targets, vec!["target"]);
                assert_eq!(r.prereqs, vec!["prereq"]);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn recipe_with_equals_parsed_correctly() {
        // Regression: = inside recipe text was treated as assignment
        let stmts = parse_str("test:V:\n\tconst x=1\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.recipe, Some("const x=1".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn recipe_with_node_equals_parsed_correctly() {
        let stmts = parse_str("test:V:\n\tlet x=1\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.recipe, Some("let x=1".into()));
            }
            _ => panic!("expected Rule"),
        }
    }

    // ── GNU Make syntax rejection tests ────────────────────────────────

    #[test]
    fn rejects_gnu_make_wildcard_syntax() {
        let tokens = tokenize(
            "target: $(wildcard /tmp/test/*.txt)\n\techo x\n",
            ShellMode::Sh,
        )
        .unwrap();
        let result = parse(&tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("$(") || err.contains("$(wildcard"),
            "error should mention $(...) syntax, got: {err}"
        );
    }

    #[test]
    fn rejects_dollar_paren_in_any_prereq() {
        let tokens = tokenize(
            "target: foo $(bar) baz\n\techo x\n",
            ShellMode::Sh,
        )
        .unwrap();
        let result = parse(&tokens);
        assert!(result.is_err());
        let err = result.unwrap_err().to_string();
        assert!(
            err.contains("$("),
            "error should mention $(...) syntax, got: {err}"
        );
    }

    #[test]
    fn allows_dollar_without_paren_in_prereq() {
        // $@ or other single-char $ forms should not trigger the check
        let stmts = parse_str("target: $prereq\n\techo x\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.prereqs, vec!["$prereq"]);
            }
            _ => panic!("expected Rule"),
        }
    }

    #[test]
    fn allows_parentheses_without_dollar_in_prereq() {
        // Archive member syntax like lib.a(foo.o) should still be valid
        let stmts = parse_str("target: lib.a(foo.o)\n\techo x\n").unwrap();
        match &stmts[0] {
            Stmt::Rule(r) => {
                assert_eq!(r.prereqs, vec!["lib.a(foo.o)"]);
            }
            _ => panic!("expected Rule"),
        }
    }
}