Debian Codegraph @

src/ast/rule.rs

raw symbols SCIP
1 use super::makefile::MakefileItem;
2 use crate::lossless::{
3 remove_with_preceding_comments, trim_trailing_newlines, Conditional, Error, ErrorInfo,
4 Makefile, ParseError, Recipe, Rule, SyntaxElement, SyntaxNode,
5 };
6 use crate::SyntaxKind::*;
7 use rowan::ast::AstNode;
8 use rowan::GreenNodeBuilder;
9
10 // Helper function to build a PREREQUISITES node containing PREREQUISITE nodes
11 fn build_prerequisites_node(prereqs: &[String], include_leading_space: bool) -> SyntaxNode {
12 let mut builder = GreenNodeBuilder::new();
13 builder.start_node(PREREQUISITES.into());
14
15 for (i, prereq) in prereqs.iter().enumerate() {
16 // Add space: before first prerequisite if requested, and between all prerequisites
17 if (i == 0 && include_leading_space) || i > 0 {
18 builder.token(WHITESPACE.into(), " ");
19 }
20
21 // Build each PREREQUISITE node
22 builder.start_node(PREREQUISITE.into());
23 builder.token(IDENTIFIER.into(), prereq);
24 builder.finish_node();
25 }
26
27 builder.finish_node();
28 SyntaxNode::new_root_mut(builder.finish())
29 }
30
31 // Helper function to build targets section (TARGETS node)
32 fn build_targets_node(targets: &[String]) -> SyntaxNode {
33 let mut builder = GreenNodeBuilder::new();
34 builder.start_node(TARGETS.into());
35
36 for (i, target) in targets.iter().enumerate() {
37 if i > 0 {
38 builder.token(WHITESPACE.into(), " ");
39 }
40 builder.token(IDENTIFIER.into(), target);
41 }
42
43 builder.finish_node();
44 SyntaxNode::new_root_mut(builder.finish())
45 }
46
47 /// Represents different types of items that can appear in a Rule's body
48 #[derive(Clone)]
49 pub enum RuleItem {
50 /// A recipe line (command to execute)
51 Recipe(String),
52 /// A conditional block within the rule
53 Conditional(Conditional),
54 }
55
56 impl std::fmt::Debug for RuleItem {
57 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
58 match self {
59 RuleItem::Recipe(text) => f.debug_tuple("Recipe").field(text).finish(),
60 RuleItem::Conditional(_) => f
61 .debug_tuple("Conditional")
62 .field(&"<Conditional>")
63 .finish(),
64 }
65 }
66 }
67
68 impl RuleItem {
69 /// Try to cast a syntax node to a RuleItem
70 pub(crate) fn cast(node: SyntaxNode) -> Option<Self> {
71 match node.kind() {
72 RECIPE => {
73 // Extract the recipe text from the RECIPE node
74 let text = node.children_with_tokens().find_map(|it| {
75 if let Some(token) = it.as_token() {
76 if token.kind() == TEXT {
77 return Some(token.text().to_string());
78 }
79 }
80 None
81 })?;
82 Some(RuleItem::Recipe(text))
83 }
84 CONDITIONAL => Conditional::cast(node).map(RuleItem::Conditional),
85 _ => None,
86 }
87 }
88 }
89
90 impl Rule {
91 /// Parse rule text, returning a Parse result
92 pub fn parse(text: &str) -> crate::Parse<Rule> {
93 crate::Parse::<Rule>::parse_rule(text)
94 }
95
96 /// Create a new rule with the given targets, prerequisites, and recipes
97 ///
98 /// # Arguments
99 /// * `targets` - A slice of target names
100 /// * `prerequisites` - A slice of prerequisite names (can be empty)
101 /// * `recipes` - A slice of recipe lines (can be empty)
102 ///
103 /// # Example
104 /// ```
105 /// use makefile_lossless::Rule;
106 ///
107 /// let rule = Rule::new(&["all"], &["build", "test"], &["echo Done"]);
108 /// assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["all"]);
109 /// assert_eq!(rule.prerequisites().collect::<Vec<_>>(), vec!["build", "test"]);
110 /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["echo Done"]);
111 /// ```
112 pub fn new(targets: &[&str], prerequisites: &[&str], recipes: &[&str]) -> Rule {
113 let mut builder = GreenNodeBuilder::new();
114 builder.start_node(RULE.into());
115
116 // Build targets
117 for (i, target) in targets.iter().enumerate() {
118 if i > 0 {
119 builder.token(WHITESPACE.into(), " ");
120 }
121 builder.token(IDENTIFIER.into(), target);
122 }
123
124 // Add colon
125 builder.token(OPERATOR.into(), ":");
126
127 // Build prerequisites
128 if !prerequisites.is_empty() {
129 builder.token(WHITESPACE.into(), " ");
130 builder.start_node(PREREQUISITES.into());
131
132 for (i, prereq) in prerequisites.iter().enumerate() {
133 if i > 0 {
134 builder.token(WHITESPACE.into(), " ");
135 }
136 builder.start_node(PREREQUISITE.into());
137 builder.token(IDENTIFIER.into(), prereq);
138 builder.finish_node();
139 }
140
141 builder.finish_node();
142 }
143
144 // Add newline after rule declaration
145 builder.token(NEWLINE.into(), "\n");
146
147 // Build recipes
148 for recipe in recipes {
149 builder.start_node(RECIPE.into());
150 builder.token(INDENT.into(), "\t");
151 builder.token(TEXT.into(), recipe);
152 builder.token(NEWLINE.into(), "\n");
153 builder.finish_node();
154 }
155
156 builder.finish_node();
157
158 let syntax = SyntaxNode::new_root_mut(builder.finish());
159 Rule::cast(syntax).unwrap()
160 }
161
162 /// Get the parent item of this rule, if any
163 ///
164 /// Returns `Some(MakefileItem)` if this rule has a parent that is a MakefileItem
165 /// (e.g., a Conditional), or `None` if the parent is the root Makefile node.
166 ///
167 /// # Example
168 /// ```
169 /// use makefile_lossless::Makefile;
170 ///
171 /// let makefile: Makefile = r#"ifdef DEBUG
172 /// all:
173 /// echo "test"
174 /// endif
175 /// "#.parse().unwrap();
176 ///
177 /// let cond = makefile.conditionals().next().unwrap();
178 /// let rule = cond.if_items().next().unwrap();
179 /// // Rule's parent is the conditional
180 /// assert!(matches!(rule, makefile_lossless::MakefileItem::Rule(_)));
181 /// ```
182 pub fn parent(&self) -> Option<MakefileItem> {
183 self.syntax().parent().and_then(MakefileItem::cast)
184 }
185
186 /// Check if this is a double-colon rule (`target:: prereqs`).
187 ///
188 /// Double-colon rules allow multiple recipe blocks for the same target,
189 /// each executed independently when its prerequisites are newer.
190 ///
191 /// # Example
192 /// ```
193 /// use makefile_lossless::Makefile;
194 /// let makefile: Makefile = "all:: dep1\n\techo first\n".parse().unwrap();
195 /// let rule = makefile.rules().next().unwrap();
196 /// assert!(rule.is_double_colon());
197 /// ```
198 pub fn is_double_colon(&self) -> bool {
199 self.syntax()
200 .children_with_tokens()
201 .filter_map(|it| it.into_token())
202 .any(|t| t.kind() == OPERATOR && t.text() == "::")
203 }
204
205 // Helper method to collect variable references from tokens
206 fn collect_variable_reference(
207 &self,
208 tokens: &mut std::iter::Peekable<impl Iterator<Item = SyntaxElement>>,
209 ) -> Option<String> {
210 let mut var_ref = String::new();
211
212 // Check if we're at a $ token
213 if let Some(token) = tokens.next() {
214 if let Some(t) = token.as_token() {
215 if t.kind() == DOLLAR {
216 var_ref.push_str(t.text());
217
218 // Check if the next token is a (
219 if let Some(next) = tokens.peek() {
220 if let Some(nt) = next.as_token() {
221 if nt.kind() == LPAREN {
222 // Consume the opening parenthesis
223 var_ref.push_str(nt.text());
224 tokens.next();
225
226 // Track parenthesis nesting level
227 let mut paren_count = 1;
228
229 // Keep consuming tokens until we find the matching closing parenthesis
230 for next_token in tokens.by_ref() {
231 if let Some(nt) = next_token.as_token() {
232 var_ref.push_str(nt.text());
233
234 if nt.kind() == LPAREN {
235 paren_count += 1;
236 } else if nt.kind() == RPAREN {
237 paren_count -= 1;
238 if paren_count == 0 {
239 break;
240 }
241 }
242 }
243 }
244
245 return Some(var_ref);
246 }
247 }
248 }
249
250 // Handle simpler variable references (though this branch may be less common)
251 for next_token in tokens.by_ref() {
252 if let Some(nt) = next_token.as_token() {
253 var_ref.push_str(nt.text());
254 if nt.kind() == RPAREN {
255 break;
256 }
257 }
258 }
259 return Some(var_ref);
260 }
261 }
262 }
263
264 None
265 }
266
267 // Helper method to extract targets from a TARGETS node
268 fn extract_targets_from_node(node: &SyntaxNode) -> Vec<String> {
269 let mut result = Vec::new();
270 let mut current_target = String::new();
271 let mut in_parens = 0;
272
273 for child in node.children_with_tokens() {
274 if let Some(token) = child.as_token() {
275 match token.kind() {
276 IDENTIFIER => {
277 current_target.push_str(token.text());
278 }
279 WHITESPACE | INDENT | BACKSLASH | NEWLINE => {
280 // Whitespace and line continuations (backslash-newline
281 // plus the continued line's indent) delimit targets,
282 // unless we're inside parentheses.
283 if in_parens == 0 && !current_target.is_empty() {
284 result.push(current_target.clone());
285 current_target.clear();
286 } else if in_parens > 0 {
287 current_target.push_str(token.text());
288 }
289 }
290 LPAREN => {
291 in_parens += 1;
292 current_target.push_str(token.text());
293 }
294 RPAREN => {
295 in_parens -= 1;
296 current_target.push_str(token.text());
297 }
298 DOLLAR => {
299 current_target.push_str(token.text());
300 }
301 _ => {
302 current_target.push_str(token.text());
303 }
304 }
305 } else if let Some(child_node) = child.as_node() {
306 // Handle nested nodes like ARCHIVE_MEMBERS
307 current_target.push_str(&child_node.text().to_string());
308 }
309 }
310
311 // Push the last target if any
312 if !current_target.is_empty() {
313 result.push(current_target);
314 }
315
316 result
317 }
318
319 /// Targets of this rule
320 ///
321 /// # Example
322 /// ```
323 /// use makefile_lossless::Rule;
324 ///
325 /// let rule: Rule = "rule: dependency\n\tcommand".parse().unwrap();
326 /// assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["rule"]);
327 /// ```
328 pub fn targets(&self) -> impl Iterator<Item = String> + '_ {
329 // First check if there's a TARGETS node
330 for child in self.syntax().children_with_tokens() {
331 if let Some(node) = child.as_node() {
332 if node.kind() == TARGETS {
333 // Extract targets from the TARGETS node
334 return Self::extract_targets_from_node(node).into_iter();
335 }
336 }
337 // Stop at the operator
338 if let Some(token) = child.as_token() {
339 if token.kind() == OPERATOR {
340 break;
341 }
342 }
343 }
344
345 // Fallback to old parsing logic for backward compatibility
346 let mut result = Vec::new();
347 let mut tokens = self
348 .syntax()
349 .children_with_tokens()
350 .take_while(|it| it.as_token().map(|t| t.kind() != OPERATOR).unwrap_or(true))
351 .peekable();
352
353 while let Some(token) = tokens.peek().cloned() {
354 if let Some(node) = token.as_node() {
355 tokens.next(); // Consume the node
356 if node.kind() == EXPR {
357 // Handle when the target is an expression node
358 let mut var_content = String::new();
359 for child in node.children_with_tokens() {
360 if let Some(t) = child.as_token() {
361 var_content.push_str(t.text());
362 }
363 }
364 if !var_content.is_empty() {
365 result.push(var_content);
366 }
367 }
368 } else if let Some(t) = token.as_token() {
369 if t.kind() == DOLLAR {
370 if let Some(var_ref) = self.collect_variable_reference(&mut tokens) {
371 result.push(var_ref);
372 }
373 } else if t.kind() == IDENTIFIER {
374 // Check if this identifier is followed by archive members
375 let ident_text = t.text().to_string();
376 tokens.next(); // Consume the identifier
377
378 // Peek ahead to see if we have archive member syntax
379 if let Some(next) = tokens.peek() {
380 if let Some(next_token) = next.as_token() {
381 if next_token.kind() == LPAREN {
382 // This is an archive member target, collect the whole thing
383 let mut archive_target = ident_text;
384 archive_target.push_str(next_token.text()); // Add '('
385 tokens.next(); // Consume LPAREN
386
387 // Collect everything until RPAREN
388 while let Some(token) = tokens.peek() {
389 if let Some(node) = token.as_node() {
390 if node.kind() == ARCHIVE_MEMBERS {
391 archive_target.push_str(&node.text().to_string());
392 tokens.next();
393 } else {
394 tokens.next();
395 }
396 } else if let Some(t) = token.as_token() {
397 if t.kind() == RPAREN {
398 archive_target.push_str(t.text());
399 tokens.next();
400 break;
401 } else {
402 tokens.next();
403 }
404 } else {
405 break;
406 }
407 }
408 result.push(archive_target);
409 } else {
410 // Regular identifier
411 result.push(ident_text);
412 }
413 } else {
414 // Regular identifier
415 result.push(ident_text);
416 }
417 } else {
418 // Regular identifier
419 result.push(ident_text);
420 }
421 } else {
422 tokens.next(); // Skip other token types
423 }
424 }
425 }
426 result.into_iter()
427 }
428
429 /// Get the prerequisites in the rule
430 ///
431 /// # Example
432 /// ```
433 /// use makefile_lossless::Rule;
434 /// let rule: Rule = "rule: dependency\n\tcommand".parse().unwrap();
435 /// assert_eq!(rule.prerequisites().collect::<Vec<_>>(), vec!["dependency"]);
436 /// ```
437 pub fn prerequisites(&self) -> impl Iterator<Item = String> + '_ {
438 // Find PREREQUISITES node after OPERATOR token
439 let mut found_operator = false;
440 let mut prerequisites_node = None;
441
442 for element in self.syntax().children_with_tokens() {
443 if let Some(token) = element.as_token() {
444 if token.kind() == OPERATOR {
445 found_operator = true;
446 }
447 } else if let Some(node) = element.as_node() {
448 if found_operator && node.kind() == PREREQUISITES {
449 prerequisites_node = Some(node.clone());
450 break;
451 }
452 }
453 }
454
455 let result: Vec<String> = if let Some(prereqs) = prerequisites_node {
456 // Iterate over PREREQUISITE child nodes
457 prereqs
458 .children()
459 .filter(|child| child.kind() == PREREQUISITE)
460 .map(|child| child.text().to_string().trim().to_string())
461 .collect()
462 } else {
463 Vec::new()
464 };
465
466 result.into_iter()
467 }
468
469 /// Get the commands in the rule
470 ///
471 /// # Example
472 /// ```
473 /// use makefile_lossless::Rule;
474 /// let rule: Rule = "rule: dependency\n\tcommand".parse().unwrap();
475 /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command"]);
476 /// ```
477 pub fn recipes(&self) -> impl Iterator<Item = String> {
478 self.recipe_nodes().map(|r| r.text())
479 }
480
481 /// If this rule is actually a target-specific variable assignment
482 /// (`target: VAR [op] value`), return the embedded [`VariableDefinition`].
483 ///
484 /// # Example
485 /// ```
486 /// use makefile_lossless::Rule;
487 /// let rule: Rule = "all: CFLAGS = -O2\n".parse().unwrap();
488 /// let var = rule.scoped_assignment().unwrap();
489 /// assert_eq!(var.name(), Some("CFLAGS".to_string()));
490 /// assert_eq!(var.assignment_operator(), Some("=".to_string()));
491 /// ```
492 pub fn scoped_assignment(&self) -> Option<crate::lossless::VariableDefinition> {
493 self.syntax()
494 .children()
495 .find(|c| c.kind() == VARIABLE)
496 .and_then(crate::lossless::VariableDefinition::cast)
497 }
498
499 /// Get recipe nodes with line/column information
500 ///
501 /// Returns an iterator over `Recipe` AST nodes, which support the `line()`, `column()`,
502 /// and `line_col()` methods to get position information.
503 ///
504 /// # Example
505 /// ```
506 /// use makefile_lossless::Rule;
507 ///
508 /// let rule_text = "test:\n\techo line1\n\techo line2\n";
509 /// let rule: Rule = rule_text.parse().unwrap();
510 ///
511 /// let recipe_nodes: Vec<_> = rule.recipe_nodes().collect();
512 /// assert_eq!(recipe_nodes.len(), 2);
513 /// assert_eq!(recipe_nodes[0].text(), "echo line1");
514 /// assert_eq!(recipe_nodes[0].line(), 1); // 0-indexed
515 /// assert_eq!(recipe_nodes[1].text(), "echo line2");
516 /// assert_eq!(recipe_nodes[1].line(), 2);
517 /// ```
518 pub fn recipe_nodes(&self) -> impl Iterator<Item = Recipe> {
519 self.syntax()
520 .children()
521 .filter(|it| it.kind() == RECIPE)
522 .filter_map(Recipe::cast)
523 }
524
525 /// Get all items (recipe lines and conditionals) in the rule's body
526 ///
527 /// This method iterates through the rule's body and yields both recipe lines
528 /// and any conditionals that appear within the rule.
529 ///
530 /// # Example
531 /// ```
532 /// use makefile_lossless::{Rule, RuleItem};
533 ///
534 /// let rule_text = r#"test:
535 /// echo "before"
536 /// ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))
537 /// ./run-tests
538 /// endif
539 /// echo "after"
540 /// "#;
541 /// let rule: Rule = rule_text.parse().unwrap();
542 ///
543 /// let items: Vec<_> = rule.items().collect();
544 /// assert_eq!(items.len(), 3); // recipe, conditional, recipe
545 ///
546 /// match &items[0] {
547 /// RuleItem::Recipe(r) => assert_eq!(r, "echo \"before\""),
548 /// _ => panic!("Expected recipe"),
549 /// }
550 ///
551 /// match &items[1] {
552 /// RuleItem::Conditional(_) => {},
553 /// _ => panic!("Expected conditional"),
554 /// }
555 ///
556 /// match &items[2] {
557 /// RuleItem::Recipe(r) => assert_eq!(r, "echo \"after\""),
558 /// _ => panic!("Expected recipe"),
559 /// }
560 /// ```
561 pub fn items(&self) -> impl Iterator<Item = RuleItem> + '_ {
562 self.syntax()
563 .children()
564 .filter(|n| n.kind() == RECIPE || n.kind() == CONDITIONAL)
565 .filter_map(RuleItem::cast)
566 }
567
568 /// Replace the command at index i with a new line
569 ///
570 /// # Example
571 /// ```
572 /// use makefile_lossless::Rule;
573 /// let mut rule: Rule = "rule: dependency\n\tcommand".parse().unwrap();
574 /// rule.replace_command(0, "new command");
575 /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["new command"]);
576 /// ```
577 pub fn replace_command(&mut self, i: usize, line: &str) -> bool {
578 // Collect all RECIPE nodes (matching the indexing used by recipe_nodes())
579 let recipes: Vec<_> = self
580 .syntax()
581 .children()
582 .filter(|n| n.kind() == RECIPE)
583 .collect();
584
585 if i >= recipes.len() {
586 return false;
587 }
588
589 // Get the target RECIPE node and its index among all siblings
590 let target_node = &recipes[i];
591 let target_index = target_node.index();
592
593 let mut builder = GreenNodeBuilder::new();
594 builder.start_node(RECIPE.into());
595 builder.token(INDENT.into(), "\t");
596 builder.token(TEXT.into(), line);
597 builder.token(NEWLINE.into(), "\n");
598 builder.finish_node();
599
600 let syntax = SyntaxNode::new_root_mut(builder.finish());
601
602 self.syntax()
603 .splice_children(target_index..target_index + 1, vec![syntax.into()]);
604
605 true
606 }
607
608 /// Add a new command to the rule
609 ///
610 /// # Example
611 /// ```
612 /// use makefile_lossless::Rule;
613 /// let mut rule: Rule = "rule: dependency\n\tcommand".parse().unwrap();
614 /// rule.push_command("command2");
615 /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command", "command2"]);
616 /// ```
617 pub fn push_command(&mut self, line: &str) {
618 // Find the latest RECIPE entry, then append the new line after it.
619 let index = self
620 .syntax()
621 .children_with_tokens()
622 .filter(|it| it.kind() == RECIPE)
623 .last();
624
625 let index = index.map_or_else(
626 || self.syntax().children_with_tokens().count(),
627 |it| it.index() + 1,
628 );
629
630 let mut builder = GreenNodeBuilder::new();
631 builder.start_node(RECIPE.into());
632 builder.token(INDENT.into(), "\t");
633 builder.token(TEXT.into(), line);
634 builder.token(NEWLINE.into(), "\n");
635 builder.finish_node();
636 let syntax = SyntaxNode::new_root_mut(builder.finish());
637
638 self.syntax()
639 .splice_children(index..index, vec![syntax.into()]);
640 }
641
642 /// Remove command at given index
643 ///
644 /// # Example
645 /// ```
646 /// use makefile_lossless::Rule;
647 /// let mut rule: Rule = "rule:\n\tcommand1\n\tcommand2\n".parse().unwrap();
648 /// rule.remove_command(0);
649 /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command2"]);
650 /// ```
651 pub fn remove_command(&mut self, index: usize) -> bool {
652 let recipes: Vec<_> = self
653 .syntax()
654 .children()
655 .filter(|n| n.kind() == RECIPE)
656 .collect();
657
658 if index >= recipes.len() {
659 return false;
660 }
661
662 let target_node = &recipes[index];
663 let target_index = target_node.index();
664
665 self.syntax()
666 .splice_children(target_index..target_index + 1, vec![]);
667 true
668 }
669
670 /// Insert command at given index
671 ///
672 /// # Example
673 /// ```
674 /// use makefile_lossless::Rule;
675 /// let mut rule: Rule = "rule:\n\tcommand1\n\tcommand2\n".parse().unwrap();
676 /// rule.insert_command(1, "inserted_command");
677 /// let recipes: Vec<_> = rule.recipes().collect();
678 /// assert_eq!(recipes, vec!["command1", "inserted_command", "command2"]);
679 /// ```
680 pub fn insert_command(&mut self, index: usize, line: &str) -> bool {
681 let recipes: Vec<_> = self
682 .syntax()
683 .children()
684 .filter(|n| n.kind() == RECIPE)
685 .collect();
686
687 if index > recipes.len() {
688 return false;
689 }
690
691 let target_index = if index == recipes.len() {
692 // Insert at the end - find position after last recipe
693 recipes.last().map(|n| n.index() + 1).unwrap_or_else(|| {
694 // No recipes exist, insert after the rule header
695 self.syntax().children_with_tokens().count()
696 })
697 } else {
698 // Insert before the recipe at the given index
699 recipes[index].index()
700 };
701
702 let mut builder = GreenNodeBuilder::new();
703 builder.start_node(RECIPE.into());
704 builder.token(INDENT.into(), "\t");
705 builder.token(TEXT.into(), line);
706 builder.token(NEWLINE.into(), "\n");
707 builder.finish_node();
708 let syntax = SyntaxNode::new_root_mut(builder.finish());
709
710 self.syntax()
711 .splice_children(target_index..target_index, vec![syntax.into()]);
712 true
713 }
714
715 /// Get the number of commands/recipes in this rule
716 ///
717 /// # Example
718 /// ```
719 /// use makefile_lossless::Rule;
720 /// let rule: Rule = "rule:\n\tcommand1\n\tcommand2\n".parse().unwrap();
721 /// assert_eq!(rule.recipe_count(), 2);
722 /// ```
723 pub fn recipe_count(&self) -> usize {
724 self.syntax()
725 .children()
726 .filter(|n| n.kind() == RECIPE)
727 .count()
728 }
729
730 /// Clear all commands from this rule
731 ///
732 /// # Example
733 /// ```
734 /// use makefile_lossless::Rule;
735 /// let mut rule: Rule = "rule:\n\tcommand1\n\tcommand2\n".parse().unwrap();
736 /// rule.clear_commands();
737 /// assert_eq!(rule.recipe_count(), 0);
738 /// ```
739 pub fn clear_commands(&mut self) {
740 let recipes: Vec<_> = self
741 .syntax()
742 .children()
743 .filter(|n| n.kind() == RECIPE)
744 .collect();
745
746 if recipes.is_empty() {
747 return;
748 }
749
750 // Remove all recipes in reverse order to maintain correct indices
751 for recipe in recipes.iter().rev() {
752 let index = recipe.index();
753 self.syntax().splice_children(index..index + 1, vec![]);
754 }
755 }
756
757 /// Remove a prerequisite from this rule
758 ///
759 /// Returns `true` if the prerequisite was found and removed, `false` if it wasn't found.
760 ///
761 /// # Example
762 /// ```
763 /// use makefile_lossless::Rule;
764 /// let mut rule: Rule = "target: dep1 dep2 dep3\n".parse().unwrap();
765 /// assert!(rule.remove_prerequisite("dep2").unwrap());
766 /// assert_eq!(rule.prerequisites().collect::<Vec<_>>(), vec!["dep1", "dep3"]);
767 /// assert!(!rule.remove_prerequisite("nonexistent").unwrap());
768 /// ```
769 pub fn remove_prerequisite(&mut self, target: &str) -> Result<bool, Error> {
770 // Find the PREREQUISITES node after the OPERATOR
771 let mut found_operator = false;
772 let mut prereqs_node = None;
773
774 for child in self.syntax().children_with_tokens() {
775 if let Some(token) = child.as_token() {
776 if token.kind() == OPERATOR {
777 found_operator = true;
778 }
779 } else if let Some(node) = child.as_node() {
780 if found_operator && node.kind() == PREREQUISITES {
781 prereqs_node = Some(node.clone());
782 break;
783 }
784 }
785 }
786
787 let prereqs_node = match prereqs_node {
788 Some(node) => node,
789 None => return Ok(false), // No prerequisites
790 };
791
792 // Collect current prerequisites
793 let current_prereqs: Vec<String> = self.prerequisites().collect();
794
795 // Check if target exists
796 if !current_prereqs.iter().any(|p| p == target) {
797 return Ok(false);
798 }
799
800 // Filter out the target
801 let new_prereqs: Vec<String> = current_prereqs
802 .into_iter()
803 .filter(|p| p != target)
804 .collect();
805
806 // Check if the existing PREREQUISITES node starts with whitespace
807 let has_leading_whitespace = prereqs_node
808 .children_with_tokens()
809 .next()
810 .map(|e| matches!(e.as_token().map(|t| t.kind()), Some(WHITESPACE)))
811 .unwrap_or(false);
812
813 // Rebuild the PREREQUISITES node with the new prerequisites
814 let prereqs_index = prereqs_node.index();
815 let new_prereqs_node = build_prerequisites_node(&new_prereqs, has_leading_whitespace);
816
817 self.syntax().splice_children(
818 prereqs_index..prereqs_index + 1,
819 vec![new_prereqs_node.into()],
820 );
821
822 Ok(true)
823 }
824
825 /// Add a prerequisite to this rule
826 ///
827 /// # Example
828 /// ```
829 /// use makefile_lossless::Rule;
830 /// let mut rule: Rule = "target: dep1\n".parse().unwrap();
831 /// rule.add_prerequisite("dep2").unwrap();
832 /// assert_eq!(rule.prerequisites().collect::<Vec<_>>(), vec!["dep1", "dep2"]);
833 /// ```
834 pub fn add_prerequisite(&mut self, target: &str) -> Result<(), Error> {
835 let mut current_prereqs: Vec<String> = self.prerequisites().collect();
836 current_prereqs.push(target.to_string());
837 self.set_prerequisites(current_prereqs.iter().map(|s| s.as_str()).collect())
838 }
839
840 /// Set the prerequisites for this rule, replacing any existing ones
841 ///
842 /// # Example
843 /// ```
844 /// use makefile_lossless::Rule;
845 /// let mut rule: Rule = "target: old_dep\n".parse().unwrap();
846 /// rule.set_prerequisites(vec!["new_dep1", "new_dep2"]).unwrap();
847 /// assert_eq!(rule.prerequisites().collect::<Vec<_>>(), vec!["new_dep1", "new_dep2"]);
848 /// ```
849 pub fn set_prerequisites(&mut self, prereqs: Vec<&str>) -> Result<(), Error> {
850 // Find the PREREQUISITES node after the OPERATOR, or the position to insert it
851 let mut prereqs_index = None;
852 let mut operator_found = false;
853
854 for child in self.syntax().children_with_tokens() {
855 if let Some(token) = child.as_token() {
856 if token.kind() == OPERATOR {
857 operator_found = true;
858 }
859 } else if let Some(node) = child.as_node() {
860 if operator_found && node.kind() == PREREQUISITES {
861 prereqs_index = Some((node.index(), true)); // (index, exists)
862 break;
863 }
864 }
865 }
866
867 match prereqs_index {
868 Some((idx, true)) => {
869 // Check if there's whitespace between OPERATOR and PREREQUISITES
870 let has_external_whitespace = self
871 .syntax()
872 .children_with_tokens()
873 .skip_while(|e| !matches!(e.as_token().map(|t| t.kind()), Some(OPERATOR)))
874 .nth(1) // Skip the OPERATOR itself and get next
875 .map(|e| matches!(e.as_token().map(|t| t.kind()), Some(WHITESPACE)))
876 .unwrap_or(false);
877
878 let new_prereqs = build_prerequisites_node(
879 &prereqs.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
880 !has_external_whitespace, // Include leading space only if no external whitespace
881 );
882 self.syntax()
883 .splice_children(idx..idx + 1, vec![new_prereqs.into()]);
884 }
885 _ => {
886 // Insert new PREREQUISITES (need leading space inside node)
887 let new_prereqs = build_prerequisites_node(
888 &prereqs.iter().map(|s| s.to_string()).collect::<Vec<_>>(),
889 true, // Include leading space
890 );
891
892 let insert_pos = self
893 .syntax()
894 .children_with_tokens()
895 .position(|t| t.as_token().map(|t| t.kind() == OPERATOR).unwrap_or(false))
896 .map(|p| p + 1)
897 .ok_or_else(|| {
898 Error::Parse(ParseError {
899 errors: vec![ErrorInfo {
900 message: "No operator found in rule".to_string(),
901 line: 1,
902 context: "set_prerequisites".to_string(),
903 }],
904 })
905 })?;
906
907 self.syntax()
908 .splice_children(insert_pos..insert_pos, vec![new_prereqs.into()]);
909 }
910 }
911
912 Ok(())
913 }
914
915 /// Rename a target in this rule
916 ///
917 /// Returns `Ok(true)` if the target was found and renamed, `Ok(false)` if the target was not found.
918 ///
919 /// # Example
920 /// ```
921 /// use makefile_lossless::Rule;
922 /// let mut rule: Rule = "old_target: dependency\n\tcommand".parse().unwrap();
923 /// rule.rename_target("old_target", "new_target").unwrap();
924 /// assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["new_target"]);
925 /// ```
926 pub fn rename_target(&mut self, old_name: &str, new_name: &str) -> Result<bool, Error> {
927 // Collect current targets
928 let current_targets: Vec<String> = self.targets().collect();
929
930 // Check if the target to rename exists
931 if !current_targets.iter().any(|t| t == old_name) {
932 return Ok(false);
933 }
934
935 // Create new target list with the renamed target
936 let new_targets: Vec<String> = current_targets
937 .into_iter()
938 .map(|t| {
939 if t == old_name {
940 new_name.to_string()
941 } else {
942 t
943 }
944 })
945 .collect();
946
947 // Find the TARGETS node
948 let mut targets_index = None;
949 for (idx, child) in self.syntax().children_with_tokens().enumerate() {
950 if let Some(node) = child.as_node() {
951 if node.kind() == TARGETS {
952 targets_index = Some(idx);
953 break;
954 }
955 }
956 }
957
958 let targets_index = targets_index.ok_or_else(|| {
959 Error::Parse(ParseError {
960 errors: vec![ErrorInfo {
961 message: "No TARGETS node found in rule".to_string(),
962 line: 1,
963 context: "rename_target".to_string(),
964 }],
965 })
966 })?;
967
968 // Build new targets node
969 let new_targets_node = build_targets_node(&new_targets);
970
971 // Replace the TARGETS node
972 self.syntax().splice_children(
973 targets_index..targets_index + 1,
974 vec![new_targets_node.into()],
975 );
976
977 Ok(true)
978 }
979
980 /// Add a target to this rule
981 ///
982 /// # Example
983 /// ```
984 /// use makefile_lossless::Rule;
985 /// let mut rule: Rule = "target1: dependency\n\tcommand".parse().unwrap();
986 /// rule.add_target("target2").unwrap();
987 /// assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["target1", "target2"]);
988 /// ```
989 pub fn add_target(&mut self, target: &str) -> Result<(), Error> {
990 let mut current_targets: Vec<String> = self.targets().collect();
991 current_targets.push(target.to_string());
992 self.set_targets(current_targets.iter().map(|s| s.as_str()).collect())
993 }
994
995 /// Set the targets for this rule, replacing any existing ones
996 ///
997 /// Returns an error if the targets list is empty (rules must have at least one target).
998 ///
999 /// # Example
1000 /// ```
1001 /// use makefile_lossless::Rule;
1002 /// let mut rule: Rule = "old_target: dependency\n\tcommand".parse().unwrap();
1003 /// rule.set_targets(vec!["new_target1", "new_target2"]).unwrap();
1004 /// assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["new_target1", "new_target2"]);
1005 /// ```
1006 pub fn set_targets(&mut self, targets: Vec<&str>) -> Result<(), Error> {
1007 // Ensure targets list is not empty
1008 if targets.is_empty() {
1009 return Err(Error::Parse(ParseError {
1010 errors: vec![ErrorInfo {
1011 message: "Cannot set empty targets list for a rule".to_string(),
1012 line: 1,
1013 context: "set_targets".to_string(),
1014 }],
1015 }));
1016 }
1017
1018 // Find the TARGETS node
1019 let mut targets_index = None;
1020 for (idx, child) in self.syntax().children_with_tokens().enumerate() {
1021 if let Some(node) = child.as_node() {
1022 if node.kind() == TARGETS {
1023 targets_index = Some(idx);
1024 break;
1025 }
1026 }
1027 }
1028
1029 let targets_index = targets_index.ok_or_else(|| {
1030 Error::Parse(ParseError {
1031 errors: vec![ErrorInfo {
1032 message: "No TARGETS node found in rule".to_string(),
1033 line: 1,
1034 context: "set_targets".to_string(),
1035 }],
1036 })
1037 })?;
1038
1039 // Build new targets node
1040 let new_targets_node =
1041 build_targets_node(&targets.iter().map(|s| s.to_string()).collect::<Vec<_>>());
1042
1043 // Replace the TARGETS node
1044 self.syntax().splice_children(
1045 targets_index..targets_index + 1,
1046 vec![new_targets_node.into()],
1047 );
1048
1049 Ok(())
1050 }
1051
1052 /// Check if this rule has a specific target
1053 ///
1054 /// # Example
1055 /// ```
1056 /// use makefile_lossless::Rule;
1057 /// let rule: Rule = "target1 target2: dependency\n\tcommand".parse().unwrap();
1058 /// assert!(rule.has_target("target1"));
1059 /// assert!(rule.has_target("target2"));
1060 /// assert!(!rule.has_target("target3"));
1061 /// ```
1062 pub fn has_target(&self, target: &str) -> bool {
1063 self.targets().any(|t| t == target)
1064 }
1065
1066 /// Remove a target from this rule
1067 ///
1068 /// Returns `Ok(true)` if the target was found and removed, `Ok(false)` if the target was not found.
1069 /// Returns an error if attempting to remove the last target (rules must have at least one target).
1070 ///
1071 /// # Example
1072 /// ```
1073 /// use makefile_lossless::Rule;
1074 /// let mut rule: Rule = "target1 target2: dependency\n\tcommand".parse().unwrap();
1075 /// rule.remove_target("target1").unwrap();
1076 /// assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["target2"]);
1077 /// ```
1078 pub fn remove_target(&mut self, target_name: &str) -> Result<bool, Error> {
1079 // Collect current targets
1080 let current_targets: Vec<String> = self.targets().collect();
1081
1082 // Check if the target exists
1083 if !current_targets.iter().any(|t| t == target_name) {
1084 return Ok(false);
1085 }
1086
1087 // Filter out the target to remove
1088 let new_targets: Vec<String> = current_targets
1089 .into_iter()
1090 .filter(|t| t != target_name)
1091 .collect();
1092
1093 // If no targets remain, return an error
1094 if new_targets.is_empty() {
1095 return Err(Error::Parse(ParseError {
1096 errors: vec![ErrorInfo {
1097 message: "Cannot remove all targets from a rule".to_string(),
1098 line: 1,
1099 context: "remove_target".to_string(),
1100 }],
1101 }));
1102 }
1103
1104 // Find the TARGETS node
1105 let mut targets_index = None;
1106 for (idx, child) in self.syntax().children_with_tokens().enumerate() {
1107 if let Some(node) = child.as_node() {
1108 if node.kind() == TARGETS {
1109 targets_index = Some(idx);
1110 break;
1111 }
1112 }
1113 }
1114
1115 let targets_index = targets_index.ok_or_else(|| {
1116 Error::Parse(ParseError {
1117 errors: vec![ErrorInfo {
1118 message: "No TARGETS node found in rule".to_string(),
1119 line: 1,
1120 context: "remove_target".to_string(),
1121 }],
1122 })
1123 })?;
1124
1125 // Build new targets node
1126 let new_targets_node = build_targets_node(&new_targets);
1127
1128 // Replace the TARGETS node
1129 self.syntax().splice_children(
1130 targets_index..targets_index + 1,
1131 vec![new_targets_node.into()],
1132 );
1133
1134 Ok(true)
1135 }
1136
1137 /// Remove this rule from its parent Makefile
1138 ///
1139 /// # Example
1140 /// ```
1141 /// use makefile_lossless::Makefile;
1142 /// let mut makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap();
1143 /// let rule = makefile.rules().next().unwrap();
1144 /// rule.remove().unwrap();
1145 /// assert_eq!(makefile.rules().count(), 1);
1146 /// ```
1147 ///
1148 /// This will also remove any preceding comments and up to 1 empty line before the rule.
1149 /// When removing the last rule in a makefile, this will also trim any trailing blank lines
1150 /// from the previous rule to avoid leaving extra whitespace at the end of the file.
1151 pub fn remove(self) -> Result<(), Error> {
1152 let parent = self.syntax().parent().ok_or_else(|| {
1153 Error::Parse(ParseError {
1154 errors: vec![ErrorInfo {
1155 message: "Rule has no parent".to_string(),
1156 line: 1,
1157 context: "remove".to_string(),
1158 }],
1159 })
1160 })?;
1161
1162 // Check if this is the last rule by seeing if there's any next sibling that's a RULE
1163 let is_last_rule = self
1164 .syntax()
1165 .siblings(rowan::Direction::Next)
1166 .skip(1) // Skip self
1167 .all(|sibling| sibling.kind() != RULE);
1168
1169 remove_with_preceding_comments(self.syntax(), &parent);
1170
1171 // If we removed the last rule, trim trailing newlines from the last remaining RULE
1172 if is_last_rule {
1173 // Find the last RULE node in the parent
1174 if let Some(last_rule_node) = parent
1175 .children()
1176 .filter(|child| child.kind() == RULE)
1177 .last()
1178 {
1179 trim_trailing_newlines(&last_rule_node);
1180 }
1181 }
1182
1183 Ok(())
1184 }
1185 }
1186
1187 impl Default for Makefile {
1188 fn default() -> Self {
1189 Self::new()
1190 }
1191 }
1192
1193 #[cfg(test)]
1194 mod tests {
1195 use crate::Makefile;
1196
1197 #[test]
1198 fn test_rules_with_pipe_in_shell_continuation() {
1199 let input = "VAR ?= $(shell cmd | \\\n\t\tsed -e 's/foo/bar/')\n\n%:\n\tdh $@\n";
1200 let (makefile, _errors) = Makefile::from_str_relaxed(input);
1201 let rules: Vec<_> = makefile.rules().collect();
1202 assert_eq!(rules.len(), 1, "Expected 1 rule");
1203 }
1204
1205 #[test]
1206 fn test_roundtrip_with_backslash_in_variable_continuation() {
1207 let input = "DEB_UPSTREAM_VERSION ?= $(shell dpkg-parsechangelog | \\\n\
1208 \t\t\t sed -rne 's,^Version: ([^-]+).*,\\1,p')\n\
1209 \n\
1210 %:\n\
1211 \tdh $@ --with autoreconf\n\
1212 \n\
1213 override_dh_strip:\n\
1214 \tdh_strip --dbg-package=f2fs-tools-dbg\n";
1215 let (makefile, errors) = Makefile::from_str_relaxed(input);
1216 assert!(errors.is_empty(), "Unexpected parse errors: {:?}", errors);
1217
1218 let rules: Vec<_> = makefile.rules().collect();
1219 assert_eq!(rules.len(), 2, "Expected 2 rules, got {}", rules.len());
1220
1221 let output = makefile.to_string();
1222 assert_eq!(input, output, "Round-trip failed");
1223 }
1224 }