Debian Codegraph @

src/ast/makefile.rs

raw symbols SCIP
1 use crate::lossless::{
2 parse, Conditional, Error, ErrorInfo, Include, Makefile, ParseError, Rule, SyntaxNode,
3 VariableDefinition, VariableReference, Vpath,
4 };
5 use crate::pattern::matches_pattern;
6 use crate::SyntaxKind::*;
7 use rowan::ast::AstNode;
8 use rowan::GreenNodeBuilder;
9 use std::collections::VecDeque;
10
11 /// Represents different types of items that can appear in a Makefile
12 #[derive(Clone)]
13 pub enum MakefileItem {
14 /// A rule definition (e.g., "target: prerequisites")
15 Rule(Rule),
16 /// A variable definition (e.g., "VAR = value")
17 Variable(VariableDefinition),
18 /// An include directive (e.g., "include foo.mk")
19 Include(Include),
20 /// A conditional block (e.g., "ifdef DEBUG ... endif")
21 Conditional(Conditional),
22 /// A `vpath` directive (e.g., `vpath %.c src`)
23 Vpath(Vpath),
24 }
25
26 impl MakefileItem {
27 /// Try to cast a syntax node to a MakefileItem
28 pub(crate) fn cast(node: SyntaxNode) -> Option<Self> {
29 if let Some(rule) = Rule::cast(node.clone()) {
30 Some(MakefileItem::Rule(rule))
31 } else if let Some(var) = VariableDefinition::cast(node.clone()) {
32 Some(MakefileItem::Variable(var))
33 } else if let Some(inc) = Include::cast(node.clone()) {
34 Some(MakefileItem::Include(inc))
35 } else if let Some(vp) = Vpath::cast(node.clone()) {
36 Some(MakefileItem::Vpath(vp))
37 } else {
38 Conditional::cast(node).map(MakefileItem::Conditional)
39 }
40 }
41
42 /// Get the underlying syntax node
43 pub fn syntax(&self) -> &SyntaxNode {
44 match self {
45 MakefileItem::Rule(r) => r.syntax(),
46 MakefileItem::Variable(v) => v.syntax(),
47 MakefileItem::Include(i) => i.syntax(),
48 MakefileItem::Conditional(c) => c.syntax(),
49 MakefileItem::Vpath(v) => v.syntax(),
50 }
51 }
52
53 /// Helper to get parent node or return an appropriate error
54 fn get_parent_or_error(&self, action: &str, method: &str) -> Result<SyntaxNode, Error> {
55 self.syntax().parent().ok_or_else(|| {
56 Error::Parse(ParseError {
57 errors: vec![ErrorInfo {
58 message: format!("Cannot {} item without parent", action),
59 line: 1,
60 context: format!("MakefileItem::{}", method),
61 }],
62 })
63 })
64 }
65
66 /// Check if a token is a regular comment (not a shebang)
67 fn is_regular_comment(token: &rowan::SyntaxToken<crate::lossless::Lang>) -> bool {
68 token.kind() == COMMENT && !token.text().starts_with("#!")
69 }
70
71 /// Extract comment text from a comment token, removing '#' prefix
72 fn extract_comment_text(token: &rowan::SyntaxToken<crate::lossless::Lang>) -> String {
73 let text = token.text();
74 text.strip_prefix("# ")
75 .or_else(|| text.strip_prefix('#'))
76 .unwrap_or(text)
77 .to_string()
78 }
79
80 /// Helper to find all preceding comment-related elements up to the first non-comment element
81 ///
82 /// Returns elements in reverse order (from closest to furthest from the item)
83 fn collect_preceding_comment_elements(
84 &self,
85 ) -> Vec<rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<crate::lossless::Lang>>> {
86 let mut elements = Vec::new();
87 let mut current = self.syntax().prev_sibling_or_token();
88
89 while let Some(element) = current {
90 match &element {
91 rowan::NodeOrToken::Token(token) if Self::is_regular_comment(token) => {
92 elements.push(element.clone());
93 }
94 rowan::NodeOrToken::Token(token)
95 if token.kind() == NEWLINE || token.kind() == WHITESPACE =>
96 {
97 elements.push(element.clone());
98 }
99 rowan::NodeOrToken::Node(n) if n.kind() == BLANK_LINE => {
100 elements.push(element.clone());
101 }
102 rowan::NodeOrToken::Token(token) if token.kind() == COMMENT => {
103 // Hit a shebang, stop here
104 break;
105 }
106 _ => break,
107 }
108 current = element.prev_sibling_or_token();
109 }
110
111 elements
112 }
113
114 /// Helper to parse comment text and extract properly formatted comment tokens
115 fn parse_comment_tokens(
116 comment_text: &str,
117 ) -> (
118 rowan::SyntaxToken<crate::lossless::Lang>,
119 Option<rowan::SyntaxToken<crate::lossless::Lang>>,
120 ) {
121 let comment_line = format!("# {}\n", comment_text);
122 let temp_makefile = crate::lossless::parse(&comment_line, None);
123 let root = temp_makefile.root();
124
125 let mut comment_token = None;
126 let mut newline_token = None;
127 let mut found_comment = false;
128
129 for element in root.syntax().children_with_tokens() {
130 if let rowan::NodeOrToken::Token(token) = element {
131 if token.kind() == COMMENT {
132 comment_token = Some(token);
133 found_comment = true;
134 } else if token.kind() == NEWLINE && found_comment && newline_token.is_none() {
135 newline_token = Some(token);
136 break;
137 }
138 }
139 }
140
141 (
142 comment_token.expect("Failed to extract comment token"),
143 newline_token,
144 )
145 }
146
147 /// Replace this MakefileItem with another MakefileItem
148 ///
149 /// This preserves the position of the original item but replaces its content
150 /// with the new item. Preceding comments are preserved.
151 ///
152 /// # Example
153 /// ```
154 /// use makefile_lossless::{Makefile, MakefileItem};
155 /// let mut makefile: Makefile = "VAR1 = old\nrule:\n\tcommand\n".parse().unwrap();
156 /// let temp: Makefile = "VAR2 = new\n".parse().unwrap();
157 /// let new_var = temp.variable_definitions().next().unwrap();
158 /// let mut first_item = makefile.items().next().unwrap();
159 /// first_item.replace(MakefileItem::Variable(new_var)).unwrap();
160 /// assert!(makefile.to_string().contains("VAR2 = new"));
161 /// assert!(!makefile.to_string().contains("VAR1"));
162 /// ```
163 pub fn replace(&mut self, new_item: MakefileItem) -> Result<(), Error> {
164 let parent = self.get_parent_or_error("replace", "replace")?;
165 let current_index = self.syntax().index();
166
167 // Replace the current node with the new item's syntax
168 parent.splice_children(
169 current_index..current_index + 1,
170 vec![new_item.syntax().clone().into()],
171 );
172
173 // Update self to point to the new item
174 *self = new_item;
175
176 Ok(())
177 }
178
179 /// Add a comment before this MakefileItem
180 ///
181 /// The comment text should not include the leading '#' character.
182 /// Multiple comment lines can be added by calling this method multiple times.
183 ///
184 /// # Example
185 /// ```
186 /// use makefile_lossless::Makefile;
187 /// let mut makefile: Makefile = "VAR = value\n".parse().unwrap();
188 /// let mut item = makefile.items().next().unwrap();
189 /// item.add_comment("This is a variable").unwrap();
190 /// assert!(makefile.to_string().contains("# This is a variable"));
191 /// ```
192 pub fn add_comment(&mut self, comment_text: &str) -> Result<(), Error> {
193 let parent = self.get_parent_or_error("add comment to", "add_comment")?;
194 let current_index = self.syntax().index();
195
196 // Get properly formatted comment tokens
197 let (comment_token, newline_token) = Self::parse_comment_tokens(comment_text);
198
199 let mut elements = vec![rowan::NodeOrToken::Token(comment_token)];
200 if let Some(newline) = newline_token {
201 elements.push(rowan::NodeOrToken::Token(newline));
202 }
203
204 // Insert comment and newline before the current item
205 parent.splice_children(current_index..current_index, elements);
206
207 Ok(())
208 }
209
210 /// Get all preceding comments for this MakefileItem
211 ///
212 /// Returns an iterator of comment strings (without the leading '#' and whitespace).
213 ///
214 /// # Example
215 /// ```
216 /// use makefile_lossless::Makefile;
217 /// let makefile: Makefile = "# Comment 1\n# Comment 2\nVAR = value\n".parse().unwrap();
218 /// let item = makefile.items().next().unwrap();
219 /// let comments: Vec<_> = item.preceding_comments().collect();
220 /// assert_eq!(comments.len(), 2);
221 /// assert_eq!(comments[0], "Comment 1");
222 /// assert_eq!(comments[1], "Comment 2");
223 /// ```
224 pub fn preceding_comments(&self) -> impl Iterator<Item = String> {
225 let elements = self.collect_preceding_comment_elements();
226 let mut comments = Vec::new();
227
228 // Process elements in reverse order (furthest to closest)
229 for element in elements.iter().rev() {
230 if let rowan::NodeOrToken::Token(token) = element {
231 if token.kind() == COMMENT {
232 comments.push(Self::extract_comment_text(token));
233 }
234 }
235 }
236
237 comments.into_iter()
238 }
239
240 /// Remove all preceding comments for this MakefileItem
241 ///
242 /// Returns the number of comments removed.
243 ///
244 /// # Example
245 /// ```
246 /// use makefile_lossless::Makefile;
247 /// let mut makefile: Makefile = "# Comment 1\n# Comment 2\nVAR = value\n".parse().unwrap();
248 /// let mut item = makefile.items().next().unwrap();
249 /// let count = item.remove_comments().unwrap();
250 /// assert_eq!(count, 2);
251 /// assert!(!makefile.to_string().contains("# Comment"));
252 /// ```
253 pub fn remove_comments(&mut self) -> Result<usize, Error> {
254 let parent = self.get_parent_or_error("remove comments from", "remove_comments")?;
255 let collected_elements = self.collect_preceding_comment_elements();
256
257 // Count the comments
258 let mut comment_count = 0;
259 for element in collected_elements.iter() {
260 if let rowan::NodeOrToken::Token(token) = element {
261 if token.kind() == COMMENT {
262 comment_count += 1;
263 }
264 }
265 }
266
267 // Determine which elements to remove - similar to remove_with_preceding_comments
268 // We remove comments and up to 1 blank line worth of newlines
269 let mut elements_to_remove = Vec::new();
270 let mut consecutive_newlines = 0;
271 for element in collected_elements.iter().rev() {
272 let should_remove = match element {
273 rowan::NodeOrToken::Token(token) if token.kind() == COMMENT => {
274 consecutive_newlines = 0;
275 true // Remove comments
276 }
277 rowan::NodeOrToken::Token(token) if token.kind() == NEWLINE => {
278 consecutive_newlines += 1;
279 comment_count > 0 && consecutive_newlines <= 1
280 }
281 rowan::NodeOrToken::Token(token) if token.kind() == WHITESPACE => comment_count > 0,
282 rowan::NodeOrToken::Node(n) if n.kind() == BLANK_LINE => {
283 consecutive_newlines += 1;
284 comment_count > 0 && consecutive_newlines <= 1
285 }
286 _ => false,
287 };
288
289 if should_remove {
290 elements_to_remove.push(element.clone());
291 }
292 }
293
294 // Remove elements in reverse order (from highest index to lowest)
295 elements_to_remove.sort_by_key(|el| std::cmp::Reverse(el.index()));
296 for element in elements_to_remove {
297 let idx = element.index();
298 parent.splice_children(idx..idx + 1, vec![]);
299 }
300
301 Ok(comment_count)
302 }
303
304 /// Modify the first preceding comment for this MakefileItem
305 ///
306 /// Returns `true` if a comment was found and modified, `false` if no comment exists.
307 /// The comment text should not include the leading '#' character.
308 ///
309 /// # Example
310 /// ```
311 /// use makefile_lossless::Makefile;
312 /// let mut makefile: Makefile = "# Old comment\nVAR = value\n".parse().unwrap();
313 /// let mut item = makefile.items().next().unwrap();
314 /// let modified = item.modify_comment("New comment").unwrap();
315 /// assert!(modified);
316 /// assert!(makefile.to_string().contains("# New comment"));
317 /// assert!(!makefile.to_string().contains("# Old comment"));
318 /// ```
319 pub fn modify_comment(&mut self, new_comment_text: &str) -> Result<bool, Error> {
320 let parent = self.get_parent_or_error("modify comment for", "modify_comment")?;
321
322 // Find the first preceding comment (closest to the item)
323 let collected_elements = self.collect_preceding_comment_elements();
324 let comment_element = collected_elements.iter().find(|element| {
325 if let rowan::NodeOrToken::Token(token) = element {
326 token.kind() == COMMENT
327 } else {
328 false
329 }
330 });
331
332 if let Some(element) = comment_element {
333 let idx = element.index();
334 let (new_comment_token, _) = Self::parse_comment_tokens(new_comment_text);
335 parent.splice_children(
336 idx..idx + 1,
337 vec![rowan::NodeOrToken::Token(new_comment_token)],
338 );
339 Ok(true)
340 } else {
341 Ok(false)
342 }
343 }
344
345 /// Insert a new MakefileItem before this item
346 ///
347 /// This inserts the new item immediately before the current item in the makefile.
348 /// The new item is inserted at the same level as the current item.
349 ///
350 /// # Example
351 /// ```
352 /// use makefile_lossless::{Makefile, MakefileItem};
353 /// let mut makefile: Makefile = "VAR1 = first\nVAR2 = second\n".parse().unwrap();
354 /// let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
355 /// let new_var = temp.variable_definitions().next().unwrap();
356 /// let mut second_item = makefile.items().nth(1).unwrap();
357 /// second_item.insert_before(MakefileItem::Variable(new_var)).unwrap();
358 /// let result = makefile.to_string();
359 /// assert!(result.contains("VAR1 = first\nVAR_NEW = inserted\nVAR2 = second"));
360 /// ```
361 pub fn insert_before(&mut self, new_item: MakefileItem) -> Result<(), Error> {
362 let parent = self.get_parent_or_error("insert before", "insert_before")?;
363 let current_index = self.syntax().index();
364
365 // Insert the new item before the current item
366 parent.splice_children(
367 current_index..current_index,
368 vec![new_item.syntax().clone().into()],
369 );
370
371 Ok(())
372 }
373
374 /// Insert a new MakefileItem after this item
375 ///
376 /// This inserts the new item immediately after the current item in the makefile.
377 /// The new item is inserted at the same level as the current item.
378 ///
379 /// # Example
380 /// ```
381 /// use makefile_lossless::{Makefile, MakefileItem};
382 /// let mut makefile: Makefile = "VAR1 = first\nVAR2 = second\n".parse().unwrap();
383 /// let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
384 /// let new_var = temp.variable_definitions().next().unwrap();
385 /// let mut first_item = makefile.items().next().unwrap();
386 /// first_item.insert_after(MakefileItem::Variable(new_var)).unwrap();
387 /// let result = makefile.to_string();
388 /// assert!(result.contains("VAR1 = first\nVAR_NEW = inserted\nVAR2 = second"));
389 /// ```
390 pub fn insert_after(&mut self, new_item: MakefileItem) -> Result<(), Error> {
391 let parent = self.get_parent_or_error("insert after", "insert_after")?;
392 let current_index = self.syntax().index();
393
394 // Insert the new item after the current item
395 parent.splice_children(
396 current_index + 1..current_index + 1,
397 vec![new_item.syntax().clone().into()],
398 );
399
400 Ok(())
401 }
402 }
403
404 // Internal trait for extracting specific item types from MakefileItem
405 trait ExtractFromItem: Sized {
406 fn extract(item: MakefileItem) -> Option<Self>;
407 }
408
409 impl ExtractFromItem for Rule {
410 fn extract(item: MakefileItem) -> Option<Self> {
411 match item {
412 MakefileItem::Rule(r) => Some(r),
413 _ => None,
414 }
415 }
416 }
417
418 impl ExtractFromItem for VariableDefinition {
419 fn extract(item: MakefileItem) -> Option<Self> {
420 match item {
421 MakefileItem::Variable(v) => Some(v),
422 _ => None,
423 }
424 }
425 }
426
427 // Internal stack-based iterator for recursively collecting items from conditionals
428 struct RecursiveItemsIter<T> {
429 stack: VecDeque<MakefileItem>,
430 _phantom: std::marker::PhantomData<T>,
431 }
432
433 impl<T> RecursiveItemsIter<T> {
434 fn new(items: impl Iterator<Item = MakefileItem>) -> Self {
435 Self {
436 stack: items.collect(),
437 _phantom: std::marker::PhantomData,
438 }
439 }
440 }
441
442 impl<T: ExtractFromItem> Iterator for RecursiveItemsIter<T> {
443 type Item = T;
444
445 fn next(&mut self) -> Option<Self::Item> {
446 while let Some(item) = self.stack.pop_front() {
447 if let MakefileItem::Conditional(ref cond) = item {
448 // Push in natural order since we pop from front
449 self.stack.extend(cond.if_items());
450 self.stack.extend(cond.else_items());
451 }
452 if let Some(extracted) = T::extract(item) {
453 return Some(extracted);
454 }
455 }
456 None
457 }
458 }
459
460 /// Iterator over blocks of consecutive comment lines in a makefile.
461 struct CommentBlockIter {
462 elements: Vec<rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<crate::lossless::Lang>>>,
463 pos: usize,
464 }
465
466 impl CommentBlockIter {
467 fn new(root: &SyntaxNode) -> Self {
468 Self {
469 elements: root.children_with_tokens().collect(),
470 pos: 0,
471 }
472 }
473 }
474
475 impl Iterator for CommentBlockIter {
476 type Item = rowan::TextRange;
477
478 fn next(&mut self) -> Option<Self::Item> {
479 // Find the start of the next comment
480 while self.pos < self.elements.len() {
481 if let Some(token) = self.elements[self.pos].as_token() {
482 if token.kind() == COMMENT {
483 break;
484 }
485 }
486 self.pos += 1;
487 }
488
489 if self.pos >= self.elements.len() {
490 return None;
491 }
492
493 let block_start = self.elements[self.pos]
494 .as_token()
495 .unwrap()
496 .text_range()
497 .start();
498 let mut block_end = self.elements[self.pos]
499 .as_token()
500 .unwrap()
501 .text_range()
502 .end();
503 let mut comment_count = 1;
504 self.pos += 1;
505
506 // Extend the block through consecutive comments (with whitespace/newlines/blank lines between)
507 while self.pos < self.elements.len() {
508 match &self.elements[self.pos] {
509 rowan::NodeOrToken::Token(token)
510 if token.kind() == NEWLINE || token.kind() == WHITESPACE =>
511 {
512 self.pos += 1;
513 }
514 rowan::NodeOrToken::Node(node) if node.kind() == BLANK_LINE => {
515 self.pos += 1;
516 }
517 rowan::NodeOrToken::Token(token) if token.kind() == COMMENT => {
518 block_end = token.text_range().end();
519 comment_count += 1;
520 self.pos += 1;
521 }
522 _ => break,
523 }
524 }
525
526 // Only return blocks with 2+ comment lines
527 if comment_count >= 2 {
528 Some(rowan::TextRange::new(block_start, block_end))
529 } else {
530 // Single comment line — skip it and try next
531 self.next()
532 }
533 }
534 }
535
536 impl Makefile {
537 /// Create a new empty makefile
538 pub fn new() -> Makefile {
539 let mut builder = GreenNodeBuilder::new();
540
541 builder.start_node(ROOT.into());
542 builder.finish_node();
543
544 let syntax = SyntaxNode::new_root_mut(builder.finish());
545 Makefile::cast(syntax).unwrap()
546 }
547
548 /// Parse makefile text, returning a Parse result
549 pub fn parse(text: &str) -> crate::Parse<Makefile> {
550 crate::Parse::<Makefile>::parse_makefile(text)
551 }
552
553 /// Get the text content of the makefile
554 pub fn code(&self) -> String {
555 self.syntax().text().to_string()
556 }
557
558 /// Check if this node is the root of a makefile
559 pub fn is_root(&self) -> bool {
560 self.syntax().kind() == ROOT
561 }
562
563 /// Read a makefile from a reader
564 pub fn read<R: std::io::Read>(mut r: R) -> Result<Makefile, Error> {
565 let mut buf = String::new();
566 r.read_to_string(&mut buf)?;
567 buf.parse()
568 }
569
570 /// Read makefile from a reader, but allow syntax errors
571 pub fn read_relaxed<R: std::io::Read>(mut r: R) -> Result<Makefile, Error> {
572 let mut buf = String::new();
573 r.read_to_string(&mut buf)?;
574
575 let parsed = parse(&buf, None);
576 Ok(parsed.root())
577 }
578
579 /// Parse a makefile from a string, allowing syntax errors.
580 ///
581 /// Returns the parsed makefile and a list of errors. The makefile tree is
582 /// always returned, even if there are parse errors, enabling error-resilient
583 /// tooling that can work with partial or invalid input.
584 pub fn from_str_relaxed(s: &str) -> (Self, Vec<ErrorInfo>) {
585 let parsed = parse(s, None);
586 (parsed.root(), parsed.errors)
587 }
588
589 /// Read a makefile from a file path, allowing syntax errors.
590 ///
591 /// Returns the parsed makefile and a list of errors.
592 pub fn from_file_relaxed(
593 path: impl AsRef<std::path::Path>,
594 ) -> Result<(Self, Vec<ErrorInfo>), std::io::Error> {
595 let text = std::fs::read_to_string(path)?;
596 Ok(Self::from_str_relaxed(&text))
597 }
598
599 /// Retrieve the rules in the makefile
600 ///
601 /// # Example
602 /// ```
603 /// use makefile_lossless::Makefile;
604 /// let makefile: Makefile = "rule: dependency\n\tcommand\n".parse().unwrap();
605 /// assert_eq!(makefile.rules().count(), 1);
606 /// ```
607 pub fn rules(&self) -> impl Iterator<Item = Rule> + '_ {
608 RecursiveItemsIter::new(self.items())
609 }
610
611 /// Get all rules that have a specific target
612 pub fn rules_by_target<'a>(&'a self, target: &'a str) -> impl Iterator<Item = Rule> + 'a {
613 self.rules()
614 .filter(move |rule| rule.targets().any(|t| t == target))
615 }
616
617 /// Get all variable definitions in the makefile
618 pub fn variable_definitions(&self) -> impl Iterator<Item = VariableDefinition> + '_ {
619 RecursiveItemsIter::new(self.items())
620 }
621
622 /// Get all conditionals in the makefile (top-level only)
623 pub fn conditionals(&self) -> impl Iterator<Item = Conditional> + '_ {
624 self.items().filter_map(|item| match item {
625 MakefileItem::Conditional(c) => Some(c),
626 _ => None,
627 })
628 }
629
630 /// Get all top-level items (rules, variables, includes, conditionals) in the makefile
631 ///
632 /// # Example
633 /// ```
634 /// use makefile_lossless::{Makefile, MakefileItem};
635 /// let makefile: Makefile = r#"VAR = value
636 /// ifdef DEBUG
637 /// CFLAGS = -g
638 /// endif
639 /// rule:
640 /// command
641 /// "#.parse().unwrap();
642 /// let items: Vec<_> = makefile.items().collect();
643 /// assert_eq!(items.len(), 3); // VAR, conditional, rule
644 /// ```
645 pub fn items(&self) -> impl Iterator<Item = MakefileItem> + '_ {
646 self.syntax().children().filter_map(MakefileItem::cast)
647 }
648
649 /// Find all variables by name
650 ///
651 /// Returns an iterator over all variable definitions with the given name.
652 /// Makefiles can have multiple definitions of the same variable.
653 ///
654 /// # Example
655 /// ```
656 /// use makefile_lossless::Makefile;
657 /// let makefile: Makefile = "VAR1 = value1\nVAR2 = value2\nVAR1 = value3\n".parse().unwrap();
658 /// let vars: Vec<_> = makefile.find_variable("VAR1").collect();
659 /// assert_eq!(vars.len(), 2);
660 /// assert_eq!(vars[0].raw_value(), Some("value1".to_string()));
661 /// assert_eq!(vars[1].raw_value(), Some("value3".to_string()));
662 /// ```
663 pub fn find_variable<'a>(
664 &'a self,
665 name: &'a str,
666 ) -> impl Iterator<Item = VariableDefinition> + 'a {
667 self.variable_definitions()
668 .filter(move |var| var.name().as_deref() == Some(name))
669 }
670
671 /// Get all variable references in the makefile.
672 ///
673 /// Walks the entire syntax tree to find all `$(VAR)` and `${VAR}` references
674 /// in variable values, prerequisites, and targets.
675 ///
676 /// Note: Variable references inside recipes are not included, since recipes
677 /// are stored as raw text in the syntax tree.
678 ///
679 /// # Example
680 /// ```
681 /// use makefile_lossless::Makefile;
682 /// let makefile: Makefile = "CFLAGS = $(BASE_FLAGS) -Wall\nall: $(TARGETS)\n".parse().unwrap();
683 /// let refs: Vec<_> = makefile.variable_references().collect();
684 /// let names: Vec<_> = refs.iter().filter_map(|r| r.name()).collect();
685 /// assert!(names.contains(&"BASE_FLAGS".to_string()));
686 /// assert!(names.contains(&"TARGETS".to_string()));
687 /// ```
688 pub fn variable_references(&self) -> impl Iterator<Item = VariableReference> + '_ {
689 self.syntax()
690 .descendants()
691 .filter_map(VariableReference::cast)
692 }
693
694 /// Get all top-level items that overlap with the given text range.
695 ///
696 /// Since items are stored in document order, this skips items entirely
697 /// before the range and stops once past it.
698 ///
699 /// # Example
700 /// ```
701 /// use makefile_lossless::{Makefile, TextRange};
702 /// let makefile: Makefile = "CC = gcc\nall: build\n\techo done\n".parse().unwrap();
703 /// let range = TextRange::new(0.into(), 8.into());
704 /// let items: Vec<_> = makefile.items_in_range(range).collect();
705 /// assert_eq!(items.len(), 1);
706 /// ```
707 pub fn items_in_range(
708 &self,
709 range: rowan::TextRange,
710 ) -> impl Iterator<Item = MakefileItem> + '_ {
711 self.items()
712 .skip_while(move |item| item.syntax().text_range().end() <= range.start())
713 .take_while(move |item| item.syntax().text_range().start() < range.end())
714 }
715
716 /// Get all variable references that overlap with the given text range.
717 ///
718 /// Only walks descendants of top-level items that overlap the range,
719 /// rather than scanning the entire tree.
720 pub fn variable_references_in_range(
721 &self,
722 range: rowan::TextRange,
723 ) -> impl Iterator<Item = VariableReference> + '_ {
724 self.items_in_range(range).flat_map(|item| {
725 item.syntax()
726 .descendants()
727 .filter_map(VariableReference::cast)
728 .collect::<Vec<_>>()
729 })
730 }
731
732 /// Get all rules that overlap with the given text range.
733 pub fn rules_in_range(&self, range: rowan::TextRange) -> impl Iterator<Item = Rule> + '_ {
734 self.items_in_range(range).filter_map(|item| match item {
735 MakefileItem::Rule(r) => Some(r),
736 _ => None,
737 })
738 }
739
740 /// Get all variable definitions that overlap with the given text range.
741 pub fn variable_definitions_in_range(
742 &self,
743 range: rowan::TextRange,
744 ) -> impl Iterator<Item = VariableDefinition> + '_ {
745 self.items_in_range(range).filter_map(|item| match item {
746 MakefileItem::Variable(v) => Some(v),
747 _ => None,
748 })
749 }
750
751 /// Get all blocks of consecutive comment lines in the makefile.
752 ///
753 /// Returns the text range of each block. A comment block is two or more
754 /// consecutive comment lines (separated only by whitespace or blank lines).
755 ///
756 /// # Example
757 /// ```
758 /// use makefile_lossless::Makefile;
759 /// let makefile: Makefile = "# line 1\n# line 2\n# line 3\nall:\n\techo done\n".parse().unwrap();
760 /// let blocks: Vec<_> = makefile.comment_blocks().collect();
761 /// assert_eq!(blocks.len(), 1);
762 /// ```
763 pub fn comment_blocks(&self) -> impl Iterator<Item = rowan::TextRange> + '_ {
764 CommentBlockIter::new(self.syntax())
765 }
766
767 /// Add a new rule to the makefile
768 ///
769 /// # Example
770 /// ```
771 /// use makefile_lossless::Makefile;
772 /// let mut makefile = Makefile::new();
773 /// makefile.add_rule("rule");
774 /// assert_eq!(makefile.to_string(), "rule:\n");
775 /// ```
776 pub fn add_rule(&mut self, target: &str) -> Rule {
777 let mut builder = GreenNodeBuilder::new();
778 builder.start_node(RULE.into());
779 builder.token(IDENTIFIER.into(), target);
780 builder.token(OPERATOR.into(), ":");
781 builder.token(NEWLINE.into(), "\n");
782 builder.finish_node();
783
784 let syntax = SyntaxNode::new_root_mut(builder.finish());
785 let pos = self.syntax().children_with_tokens().count();
786
787 // Add a blank line before the new rule if there are existing rules
788 // This maintains standard makefile formatting
789 let needs_blank_line = self.syntax().children().any(|c| c.kind() == RULE);
790
791 if needs_blank_line {
792 // Create a BLANK_LINE node
793 let mut bl_builder = GreenNodeBuilder::new();
794 bl_builder.start_node(BLANK_LINE.into());
795 bl_builder.token(NEWLINE.into(), "\n");
796 bl_builder.finish_node();
797 let blank_line = SyntaxNode::new_root_mut(bl_builder.finish());
798
799 self.syntax()
800 .splice_children(pos..pos, vec![blank_line.into(), syntax.into()]);
801 } else {
802 self.syntax().splice_children(pos..pos, vec![syntax.into()]);
803 }
804
805 // Use children().count() - 1 to get the last added child node
806 // (not children_with_tokens().count() which includes tokens)
807 Rule::cast(self.syntax().children().last().unwrap()).unwrap()
808 }
809
810 /// Add a new conditional to the makefile
811 ///
812 /// # Arguments
813 /// * `conditional_type` - The type of conditional: "ifdef", "ifndef", "ifeq", or "ifneq"
814 /// * `condition` - The condition expression (e.g., "DEBUG" for ifdef/ifndef, or "(a,b)" for ifeq/ifneq)
815 /// * `if_body` - The content of the if branch
816 /// * `else_body` - Optional content for the else branch
817 ///
818 /// # Example
819 /// ```
820 /// use makefile_lossless::Makefile;
821 /// let mut makefile = Makefile::new();
822 /// makefile.add_conditional("ifdef", "DEBUG", "VAR = debug\n", None);
823 /// assert!(makefile.to_string().contains("ifdef DEBUG"));
824 /// ```
825 pub fn add_conditional(
826 &mut self,
827 conditional_type: &str,
828 condition: &str,
829 if_body: &str,
830 else_body: Option<&str>,
831 ) -> Result<Conditional, Error> {
832 // Validate conditional type
833 if !["ifdef", "ifndef", "ifeq", "ifneq"].contains(&conditional_type) {
834 return Err(Error::Parse(ParseError {
835 errors: vec![ErrorInfo {
836 message: format!(
837 "Invalid conditional type: {}. Must be one of: ifdef, ifndef, ifeq, ifneq",
838 conditional_type
839 ),
840 line: 1,
841 context: "add_conditional".to_string(),
842 }],
843 }));
844 }
845
846 let mut builder = GreenNodeBuilder::new();
847 builder.start_node(CONDITIONAL.into());
848
849 // Build CONDITIONAL_IF
850 builder.start_node(CONDITIONAL_IF.into());
851 builder.token(IDENTIFIER.into(), conditional_type);
852 builder.token(WHITESPACE.into(), " ");
853
854 // Wrap condition in EXPR node
855 builder.start_node(EXPR.into());
856 builder.token(IDENTIFIER.into(), condition);
857 builder.finish_node();
858
859 builder.token(NEWLINE.into(), "\n");
860 builder.finish_node();
861
862 // Add if body content
863 if !if_body.is_empty() {
864 for line in if_body.lines() {
865 if !line.is_empty() {
866 builder.token(IDENTIFIER.into(), line);
867 }
868 builder.token(NEWLINE.into(), "\n");
869 }
870 // Add final newline if if_body doesn't end with one
871 if !if_body.ends_with('\n') && !if_body.is_empty() {
872 builder.token(NEWLINE.into(), "\n");
873 }
874 }
875
876 // Add else clause if provided
877 if let Some(else_content) = else_body {
878 builder.start_node(CONDITIONAL_ELSE.into());
879 builder.token(IDENTIFIER.into(), "else");
880 builder.token(NEWLINE.into(), "\n");
881 builder.finish_node();
882
883 // Add else body content
884 if !else_content.is_empty() {
885 for line in else_content.lines() {
886 if !line.is_empty() {
887 builder.token(IDENTIFIER.into(), line);
888 }
889 builder.token(NEWLINE.into(), "\n");
890 }
891 // Add final newline if else_content doesn't end with one
892 if !else_content.ends_with('\n') && !else_content.is_empty() {
893 builder.token(NEWLINE.into(), "\n");
894 }
895 }
896 }
897
898 // Build CONDITIONAL_ENDIF
899 builder.start_node(CONDITIONAL_ENDIF.into());
900 builder.token(IDENTIFIER.into(), "endif");
901 builder.token(NEWLINE.into(), "\n");
902 builder.finish_node();
903
904 builder.finish_node();
905
906 let syntax = SyntaxNode::new_root_mut(builder.finish());
907 let pos = self.syntax().children_with_tokens().count();
908
909 // Add a blank line before the new conditional if there are existing elements
910 let needs_blank_line = self
911 .syntax()
912 .children()
913 .any(|c| c.kind() == RULE || c.kind() == VARIABLE || c.kind() == CONDITIONAL);
914
915 if needs_blank_line {
916 // Create a BLANK_LINE node
917 let mut bl_builder = GreenNodeBuilder::new();
918 bl_builder.start_node(BLANK_LINE.into());
919 bl_builder.token(NEWLINE.into(), "\n");
920 bl_builder.finish_node();
921 let blank_line = SyntaxNode::new_root_mut(bl_builder.finish());
922
923 self.syntax()
924 .splice_children(pos..pos, vec![blank_line.into(), syntax.into()]);
925 } else {
926 self.syntax().splice_children(pos..pos, vec![syntax.into()]);
927 }
928
929 // Return the newly added conditional
930 Ok(Conditional::cast(self.syntax().children().last().unwrap()).unwrap())
931 }
932
933 /// Add a new conditional to the makefile with typed items
934 ///
935 /// This is a more type-safe alternative to `add_conditional` that accepts iterators of
936 /// `MakefileItem` instead of raw strings.
937 ///
938 /// # Arguments
939 /// * `conditional_type` - The type of conditional: "ifdef", "ifndef", "ifeq", or "ifneq"
940 /// * `condition` - The condition expression (e.g., "DEBUG" for ifdef/ifndef, or "(a,b)" for ifeq/ifneq)
941 /// * `if_items` - Items for the if branch
942 /// * `else_items` - Optional items for the else branch
943 ///
944 /// # Example
945 /// ```
946 /// use makefile_lossless::{Makefile, MakefileItem};
947 /// let mut makefile = Makefile::new();
948 /// let temp1: Makefile = "CFLAGS = -g\n".parse().unwrap();
949 /// let var1 = temp1.variable_definitions().next().unwrap();
950 /// let temp2: Makefile = "CFLAGS = -O2\n".parse().unwrap();
951 /// let var2 = temp2.variable_definitions().next().unwrap();
952 /// makefile.add_conditional_with_items(
953 /// "ifdef",
954 /// "DEBUG",
955 /// vec![MakefileItem::Variable(var1)],
956 /// Some(vec![MakefileItem::Variable(var2)])
957 /// ).unwrap();
958 /// assert!(makefile.to_string().contains("ifdef DEBUG"));
959 /// assert!(makefile.to_string().contains("CFLAGS = -g"));
960 /// assert!(makefile.to_string().contains("CFLAGS = -O2"));
961 /// ```
962 pub fn add_conditional_with_items<I1, I2>(
963 &mut self,
964 conditional_type: &str,
965 condition: &str,
966 if_items: I1,
967 else_items: Option<I2>,
968 ) -> Result<Conditional, Error>
969 where
970 I1: IntoIterator<Item = MakefileItem>,
971 I2: IntoIterator<Item = MakefileItem>,
972 {
973 // Validate conditional type
974 if !["ifdef", "ifndef", "ifeq", "ifneq"].contains(&conditional_type) {
975 return Err(Error::Parse(ParseError {
976 errors: vec![ErrorInfo {
977 message: format!(
978 "Invalid conditional type: {}. Must be one of: ifdef, ifndef, ifeq, ifneq",
979 conditional_type
980 ),
981 line: 1,
982 context: "add_conditional_with_items".to_string(),
983 }],
984 }));
985 }
986
987 let mut builder = GreenNodeBuilder::new();
988 builder.start_node(CONDITIONAL.into());
989
990 // Build CONDITIONAL_IF
991 builder.start_node(CONDITIONAL_IF.into());
992 builder.token(IDENTIFIER.into(), conditional_type);
993 builder.token(WHITESPACE.into(), " ");
994
995 // Wrap condition in EXPR node
996 builder.start_node(EXPR.into());
997 builder.token(IDENTIFIER.into(), condition);
998 builder.finish_node();
999
1000 builder.token(NEWLINE.into(), "\n");
1001 builder.finish_node();
1002
1003 // Add if branch items
1004 for item in if_items {
1005 // Clone the item's syntax tree into our builder
1006 let item_text = item.syntax().to_string();
1007 // Parse it again to get green nodes
1008 builder.token(IDENTIFIER.into(), item_text.trim());
1009 builder.token(NEWLINE.into(), "\n");
1010 }
1011
1012 // Add else clause if provided
1013 if let Some(else_iter) = else_items {
1014 builder.start_node(CONDITIONAL_ELSE.into());
1015 builder.token(IDENTIFIER.into(), "else");
1016 builder.token(NEWLINE.into(), "\n");
1017 builder.finish_node();
1018
1019 // Add else branch items
1020 for item in else_iter {
1021 let item_text = item.syntax().to_string();
1022 builder.token(IDENTIFIER.into(), item_text.trim());
1023 builder.token(NEWLINE.into(), "\n");
1024 }
1025 }
1026
1027 // Build CONDITIONAL_ENDIF
1028 builder.start_node(CONDITIONAL_ENDIF.into());
1029 builder.token(IDENTIFIER.into(), "endif");
1030 builder.token(NEWLINE.into(), "\n");
1031 builder.finish_node();
1032
1033 builder.finish_node();
1034
1035 let syntax = SyntaxNode::new_root_mut(builder.finish());
1036 let pos = self.syntax().children_with_tokens().count();
1037
1038 // Add a blank line before the new conditional if there are existing elements
1039 let needs_blank_line = self
1040 .syntax()
1041 .children()
1042 .any(|c| c.kind() == RULE || c.kind() == VARIABLE || c.kind() == CONDITIONAL);
1043
1044 if needs_blank_line {
1045 // Create a BLANK_LINE node
1046 let mut bl_builder = GreenNodeBuilder::new();
1047 bl_builder.start_node(BLANK_LINE.into());
1048 bl_builder.token(NEWLINE.into(), "\n");
1049 bl_builder.finish_node();
1050 let blank_line = SyntaxNode::new_root_mut(bl_builder.finish());
1051
1052 self.syntax()
1053 .splice_children(pos..pos, vec![blank_line.into(), syntax.into()]);
1054 } else {
1055 self.syntax().splice_children(pos..pos, vec![syntax.into()]);
1056 }
1057
1058 // Return the newly added conditional
1059 Ok(Conditional::cast(self.syntax().children().last().unwrap()).unwrap())
1060 }
1061
1062 /// Read the makefile
1063 pub fn from_reader<R: std::io::Read>(mut r: R) -> Result<Makefile, Error> {
1064 let mut buf = String::new();
1065 r.read_to_string(&mut buf)?;
1066
1067 let parsed = parse(&buf, None);
1068 if !parsed.errors.is_empty() {
1069 Err(Error::Parse(ParseError {
1070 errors: parsed.errors,
1071 }))
1072 } else {
1073 Ok(parsed.root())
1074 }
1075 }
1076
1077 /// Replace rule at given index with a new rule
1078 ///
1079 /// # Example
1080 /// ```
1081 /// use makefile_lossless::Makefile;
1082 /// let mut makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap();
1083 /// let new_rule: makefile_lossless::Rule = "new_rule:\n\tnew_command\n".parse().unwrap();
1084 /// makefile.replace_rule(0, new_rule).unwrap();
1085 /// assert!(makefile.rules().any(|r| r.targets().any(|t| t == "new_rule")));
1086 /// ```
1087 pub fn replace_rule(&mut self, index: usize, new_rule: Rule) -> Result<(), Error> {
1088 let rules: Vec<_> = self
1089 .syntax()
1090 .children()
1091 .filter(|n| n.kind() == RULE)
1092 .collect();
1093
1094 if rules.is_empty() {
1095 return Err(Error::Parse(ParseError {
1096 errors: vec![ErrorInfo {
1097 message: "Cannot replace rule in empty makefile".to_string(),
1098 line: 1,
1099 context: "replace_rule".to_string(),
1100 }],
1101 }));
1102 }
1103
1104 if index >= rules.len() {
1105 return Err(Error::Parse(ParseError {
1106 errors: vec![ErrorInfo {
1107 message: format!(
1108 "Rule index {} out of bounds (max {})",
1109 index,
1110 rules.len() - 1
1111 ),
1112 line: 1,
1113 context: "replace_rule".to_string(),
1114 }],
1115 }));
1116 }
1117
1118 let target_node = &rules[index];
1119 let target_index = target_node.index();
1120
1121 // Replace the rule at the target index
1122 self.syntax().splice_children(
1123 target_index..target_index + 1,
1124 vec![new_rule.syntax().clone().into()],
1125 );
1126 Ok(())
1127 }
1128
1129 /// Remove rule at given index
1130 ///
1131 /// # Example
1132 /// ```
1133 /// use makefile_lossless::Makefile;
1134 /// let mut makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap();
1135 /// let removed = makefile.remove_rule(0).unwrap();
1136 /// assert_eq!(removed.targets().collect::<Vec<_>>(), vec!["rule1"]);
1137 /// assert_eq!(makefile.rules().count(), 1);
1138 /// ```
1139 pub fn remove_rule(&mut self, index: usize) -> Result<Rule, Error> {
1140 let rules: Vec<_> = self
1141 .syntax()
1142 .children()
1143 .filter(|n| n.kind() == RULE)
1144 .collect();
1145
1146 if rules.is_empty() {
1147 return Err(Error::Parse(ParseError {
1148 errors: vec![ErrorInfo {
1149 message: "Cannot remove rule from empty makefile".to_string(),
1150 line: 1,
1151 context: "remove_rule".to_string(),
1152 }],
1153 }));
1154 }
1155
1156 if index >= rules.len() {
1157 return Err(Error::Parse(ParseError {
1158 errors: vec![ErrorInfo {
1159 message: format!(
1160 "Rule index {} out of bounds (max {})",
1161 index,
1162 rules.len() - 1
1163 ),
1164 line: 1,
1165 context: "remove_rule".to_string(),
1166 }],
1167 }));
1168 }
1169
1170 let target_node = rules[index].clone();
1171 let target_index = target_node.index();
1172
1173 // Remove the rule at the target index
1174 self.syntax()
1175 .splice_children(target_index..target_index + 1, vec![]);
1176 Ok(Rule::cast(target_node).unwrap())
1177 }
1178
1179 /// Insert rule at given position
1180 ///
1181 /// # Example
1182 /// ```
1183 /// use makefile_lossless::Makefile;
1184 /// let mut makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap();
1185 /// let new_rule: makefile_lossless::Rule = "inserted_rule:\n\tinserted_command\n".parse().unwrap();
1186 /// makefile.insert_rule(1, new_rule).unwrap();
1187 /// let targets: Vec<_> = makefile.rules().flat_map(|r| r.targets().collect::<Vec<_>>()).collect();
1188 /// assert_eq!(targets, vec!["rule1", "inserted_rule", "rule2"]);
1189 /// ```
1190 pub fn insert_rule(&mut self, index: usize, new_rule: Rule) -> Result<(), Error> {
1191 let rules: Vec<_> = self
1192 .syntax()
1193 .children()
1194 .filter(|n| n.kind() == RULE)
1195 .collect();
1196
1197 if index > rules.len() {
1198 return Err(Error::Parse(ParseError {
1199 errors: vec![ErrorInfo {
1200 message: format!("Rule index {} out of bounds (max {})", index, rules.len()),
1201 line: 1,
1202 context: "insert_rule".to_string(),
1203 }],
1204 }));
1205 }
1206
1207 let target_index = if index == rules.len() {
1208 // Insert at the end
1209 self.syntax().children_with_tokens().count()
1210 } else {
1211 // Insert before the rule at the given index
1212 rules[index].index()
1213 };
1214
1215 // Build the nodes to insert
1216 let mut nodes_to_insert = Vec::new();
1217
1218 // Determine if we need to add blank lines to maintain formatting consistency
1219 if index == 0 && !rules.is_empty() {
1220 // Inserting before the first rule - check if first rule has a blank line before it
1221 // If so, we should add one after our new rule instead
1222 // For now, just add the rule without a blank line before it
1223 nodes_to_insert.push(new_rule.syntax().clone().into());
1224
1225 // Add a blank line after the new rule
1226 let mut bl_builder = GreenNodeBuilder::new();
1227 bl_builder.start_node(BLANK_LINE.into());
1228 bl_builder.token(NEWLINE.into(), "\n");
1229 bl_builder.finish_node();
1230 let blank_line = SyntaxNode::new_root_mut(bl_builder.finish());
1231 nodes_to_insert.push(blank_line.into());
1232 } else if index < rules.len() {
1233 // Inserting in the middle (before an existing rule)
1234 // The syntax tree structure is: ... [maybe BLANK_LINE] RULE(target) ...
1235 // We're inserting right before RULE(target)
1236
1237 // If there's a BLANK_LINE immediately before the target rule,
1238 // it will stay there and separate the previous rule from our new rule.
1239 // We don't need to add a BLANK_LINE before our new rule in that case.
1240
1241 // But we DO need to add a BLANK_LINE after our new rule to separate it
1242 // from the target rule (which we're inserting before).
1243
1244 // Check if there's a blank line immediately before target_index
1245 let has_blank_before = if target_index > 0 {
1246 self.syntax()
1247 .children_with_tokens()
1248 .nth(target_index - 1)
1249 .and_then(|n| n.as_node().map(|node| node.kind() == BLANK_LINE))
1250 .unwrap_or(false)
1251 } else {
1252 false
1253 };
1254
1255 // Only add a blank before if there isn't one already and we're not at the start
1256 if !has_blank_before && index > 0 {
1257 let mut bl_builder = GreenNodeBuilder::new();
1258 bl_builder.start_node(BLANK_LINE.into());
1259 bl_builder.token(NEWLINE.into(), "\n");
1260 bl_builder.finish_node();
1261 let blank_line = SyntaxNode::new_root_mut(bl_builder.finish());
1262 nodes_to_insert.push(blank_line.into());
1263 }
1264
1265 // Add the new rule
1266 nodes_to_insert.push(new_rule.syntax().clone().into());
1267
1268 // Always add a blank line after the new rule to separate it from the next rule
1269 let mut bl_builder = GreenNodeBuilder::new();
1270 bl_builder.start_node(BLANK_LINE.into());
1271 bl_builder.token(NEWLINE.into(), "\n");
1272 bl_builder.finish_node();
1273 let blank_line = SyntaxNode::new_root_mut(bl_builder.finish());
1274 nodes_to_insert.push(blank_line.into());
1275 } else {
1276 // Inserting at the end when there are existing rules
1277 // Add a blank line before the new rule
1278 let mut bl_builder = GreenNodeBuilder::new();
1279 bl_builder.start_node(BLANK_LINE.into());
1280 bl_builder.token(NEWLINE.into(), "\n");
1281 bl_builder.finish_node();
1282 let blank_line = SyntaxNode::new_root_mut(bl_builder.finish());
1283 nodes_to_insert.push(blank_line.into());
1284
1285 // Add the new rule
1286 nodes_to_insert.push(new_rule.syntax().clone().into());
1287 }
1288
1289 // Insert all nodes at the target index
1290 self.syntax()
1291 .splice_children(target_index..target_index, nodes_to_insert);
1292 Ok(())
1293 }
1294
1295 /// Get all include directives in the makefile
1296 ///
1297 /// # Example
1298 /// ```
1299 /// use makefile_lossless::Makefile;
1300 /// let makefile: Makefile = "include config.mk\n-include .env\n".parse().unwrap();
1301 /// let includes = makefile.includes().collect::<Vec<_>>();
1302 /// assert_eq!(includes.len(), 2);
1303 /// ```
1304 pub fn includes(&self) -> impl Iterator<Item = Include> {
1305 self.syntax().children().filter_map(Include::cast)
1306 }
1307
1308 /// Get all included file paths
1309 ///
1310 /// # Example
1311 /// ```
1312 /// use makefile_lossless::Makefile;
1313 /// let makefile: Makefile = "include config.mk\n-include .env\n".parse().unwrap();
1314 /// let paths = makefile.included_files().collect::<Vec<_>>();
1315 /// assert_eq!(paths, vec!["config.mk", ".env"]);
1316 /// ```
1317 pub fn included_files(&self) -> impl Iterator<Item = String> + '_ {
1318 // We need to collect all Include nodes from anywhere in the syntax tree,
1319 // not just direct children of the root, to handle includes in conditionals
1320 fn collect_includes(node: &SyntaxNode) -> Vec<Include> {
1321 let mut includes = Vec::new();
1322
1323 // First check if this node itself is an Include
1324 if let Some(include) = Include::cast(node.clone()) {
1325 includes.push(include);
1326 }
1327
1328 // Then recurse into all children
1329 for child in node.children() {
1330 includes.extend(collect_includes(&child));
1331 }
1332
1333 includes
1334 }
1335
1336 // Start collection from the root node
1337 let includes = collect_includes(self.syntax());
1338
1339 // Convert to an iterator of paths
1340 includes.into_iter().map(|include| {
1341 include
1342 .syntax()
1343 .children()
1344 .find(|node| node.kind() == EXPR)
1345 .map(|expr| expr.text().to_string().trim().to_string())
1346 .unwrap_or_default()
1347 })
1348 }
1349
1350 /// Find the first rule with a specific target name
1351 ///
1352 /// # Example
1353 /// ```
1354 /// use makefile_lossless::Makefile;
1355 /// let makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap();
1356 /// let rule = makefile.find_rule_by_target("rule2");
1357 /// assert!(rule.is_some());
1358 /// assert_eq!(rule.unwrap().targets().collect::<Vec<_>>(), vec!["rule2"]);
1359 /// ```
1360 pub fn find_rule_by_target(&self, target: &str) -> Option<Rule> {
1361 self.rules()
1362 .find(|rule| rule.targets().any(|t| t == target))
1363 }
1364
1365 /// Find all rules with a specific target name
1366 ///
1367 /// # Example
1368 /// ```
1369 /// use makefile_lossless::Makefile;
1370 /// let makefile: Makefile = "rule1:\n\tcommand1\nrule1:\n\tcommand2\nrule2:\n\tcommand3\n".parse().unwrap();
1371 /// let rules: Vec<_> = makefile.find_rules_by_target("rule1").collect();
1372 /// assert_eq!(rules.len(), 2);
1373 /// ```
1374 pub fn find_rules_by_target<'a>(&'a self, target: &'a str) -> impl Iterator<Item = Rule> + 'a {
1375 self.rules_by_target(target)
1376 }
1377
1378 /// Find the first rule whose target matches the given pattern
1379 ///
1380 /// Supports make-style pattern matching where `%` in a rule's target acts as a wildcard.
1381 /// For example, a rule with target `%.o` will match `foo.o`, `bar.o`, etc.
1382 ///
1383 /// # Example
1384 /// ```
1385 /// use makefile_lossless::Makefile;
1386 /// let makefile: Makefile = "%.o: %.c\n\t$(CC) -c $<\n".parse().unwrap();
1387 /// let rule = makefile.find_rule_by_target_pattern("foo.o");
1388 /// assert!(rule.is_some());
1389 /// ```
1390 pub fn find_rule_by_target_pattern(&self, target: &str) -> Option<Rule> {
1391 self.rules()
1392 .find(|rule| rule.targets().any(|t| matches_pattern(&t, target)))
1393 }
1394
1395 /// Find all rules whose targets match the given pattern
1396 ///
1397 /// Supports make-style pattern matching where `%` in a rule's target acts as a wildcard.
1398 /// For example, a rule with target `%.o` will match `foo.o`, `bar.o`, etc.
1399 ///
1400 /// # Example
1401 /// ```
1402 /// use makefile_lossless::Makefile;
1403 /// let makefile: Makefile = "%.o: %.c\n\t$(CC) -c $<\n%.o: %.s\n\t$(AS) -o $@ $<\n".parse().unwrap();
1404 /// let rules: Vec<_> = makefile.find_rules_by_target_pattern("foo.o").collect();
1405 /// assert_eq!(rules.len(), 2);
1406 /// ```
1407 pub fn find_rules_by_target_pattern<'a>(
1408 &'a self,
1409 target: &'a str,
1410 ) -> impl Iterator<Item = Rule> + 'a {
1411 self.rules()
1412 .filter(move |rule| rule.targets().any(|t| matches_pattern(&t, target)))
1413 }
1414
1415 /// Add a target to .PHONY (creates .PHONY rule if it doesn't exist)
1416 ///
1417 /// # Example
1418 /// ```
1419 /// use makefile_lossless::Makefile;
1420 /// let mut makefile = Makefile::new();
1421 /// makefile.add_phony_target("clean").unwrap();
1422 /// assert!(makefile.is_phony("clean"));
1423 /// ```
1424 pub fn add_phony_target(&mut self, target: &str) -> Result<(), Error> {
1425 // Find existing .PHONY rule
1426 if let Some(mut phony_rule) = self.find_rule_by_target(".PHONY") {
1427 // Check if target is already in prerequisites
1428 if !phony_rule.prerequisites().any(|p| p == target) {
1429 phony_rule.add_prerequisite(target)?;
1430 }
1431 } else {
1432 // Create new .PHONY rule
1433 let mut phony_rule = self.add_rule(".PHONY");
1434 phony_rule.add_prerequisite(target)?;
1435 }
1436 Ok(())
1437 }
1438
1439 /// Remove a target from .PHONY (removes .PHONY rule if it becomes empty)
1440 ///
1441 /// Returns `true` if the target was found and removed, `false` if it wasn't in .PHONY.
1442 /// If there are multiple .PHONY rules, it removes the target from the first rule that contains it.
1443 ///
1444 /// # Example
1445 /// ```
1446 /// use makefile_lossless::Makefile;
1447 /// let mut makefile: Makefile = ".PHONY: clean test\n".parse().unwrap();
1448 /// assert!(makefile.remove_phony_target("clean").unwrap());
1449 /// assert!(!makefile.is_phony("clean"));
1450 /// assert!(makefile.is_phony("test"));
1451 /// ```
1452 pub fn remove_phony_target(&mut self, target: &str) -> Result<bool, Error> {
1453 // Find the first .PHONY rule that contains the target
1454 let mut phony_rule = None;
1455 for rule in self.rules_by_target(".PHONY") {
1456 if rule.prerequisites().any(|p| p == target) {
1457 phony_rule = Some(rule);
1458 break;
1459 }
1460 }
1461
1462 let mut phony_rule = match phony_rule {
1463 Some(rule) => rule,
1464 None => return Ok(false),
1465 };
1466
1467 // Count prerequisites before removal
1468 let prereq_count = phony_rule.prerequisites().count();
1469
1470 // Remove the prerequisite
1471 phony_rule.remove_prerequisite(target)?;
1472
1473 // Check if .PHONY has no more prerequisites, if so remove the rule
1474 if prereq_count == 1 {
1475 // We just removed the last prerequisite, so remove the entire rule
1476 phony_rule.remove()?;
1477 }
1478
1479 Ok(true)
1480 }
1481
1482 /// Check if a target is marked as phony
1483 ///
1484 /// # Example
1485 /// ```
1486 /// use makefile_lossless::Makefile;
1487 /// let makefile: Makefile = ".PHONY: clean test\n".parse().unwrap();
1488 /// assert!(makefile.is_phony("clean"));
1489 /// assert!(makefile.is_phony("test"));
1490 /// assert!(!makefile.is_phony("build"));
1491 /// ```
1492 pub fn is_phony(&self, target: &str) -> bool {
1493 // Check all .PHONY rules since there can be multiple
1494 self.rules_by_target(".PHONY")
1495 .any(|rule| rule.prerequisites().any(|p| p == target))
1496 }
1497
1498 /// Get all phony targets
1499 ///
1500 /// # Example
1501 /// ```
1502 /// use makefile_lossless::Makefile;
1503 /// let makefile: Makefile = ".PHONY: clean test build\n".parse().unwrap();
1504 /// let phony_targets: Vec<_> = makefile.phony_targets().collect();
1505 /// assert_eq!(phony_targets, vec!["clean", "test", "build"]);
1506 /// ```
1507 pub fn phony_targets(&self) -> impl Iterator<Item = String> + '_ {
1508 // Collect from all .PHONY rules since there can be multiple
1509 self.rules_by_target(".PHONY")
1510 .flat_map(|rule| rule.prerequisites().collect::<Vec<_>>())
1511 }
1512
1513 /// Add a new include directive at the beginning of the makefile
1514 ///
1515 /// # Arguments
1516 /// * `path` - The file path to include (e.g., "config.mk")
1517 ///
1518 /// # Example
1519 /// ```
1520 /// use makefile_lossless::Makefile;
1521 /// let mut makefile = Makefile::new();
1522 /// makefile.add_include("config.mk");
1523 /// assert_eq!(makefile.included_files().collect::<Vec<_>>(), vec!["config.mk"]);
1524 /// ```
1525 pub fn add_include(&mut self, path: &str) -> Include {
1526 let mut builder = GreenNodeBuilder::new();
1527 builder.start_node(INCLUDE.into());
1528 builder.token(IDENTIFIER.into(), "include");
1529 builder.token(WHITESPACE.into(), " ");
1530
1531 // Wrap path in EXPR node
1532 builder.start_node(EXPR.into());
1533 builder.token(IDENTIFIER.into(), path);
1534 builder.finish_node();
1535
1536 builder.token(NEWLINE.into(), "\n");
1537 builder.finish_node();
1538
1539 let syntax = SyntaxNode::new_root_mut(builder.finish());
1540
1541 // Insert at the beginning (position 0)
1542 self.syntax().splice_children(0..0, vec![syntax.into()]);
1543
1544 // Return the newly added include (first child)
1545 Include::cast(self.syntax().children().next().unwrap()).unwrap()
1546 }
1547
1548 /// Insert an include directive at a specific position
1549 ///
1550 /// The position is relative to other top-level items (rules, variables, includes, conditionals).
1551 ///
1552 /// # Arguments
1553 /// * `index` - The position to insert at (0 = beginning, items().count() = end)
1554 /// * `path` - The file path to include (e.g., "config.mk")
1555 ///
1556 /// # Example
1557 /// ```
1558 /// use makefile_lossless::Makefile;
1559 /// let mut makefile: Makefile = "VAR = value\nrule:\n\tcommand\n".parse().unwrap();
1560 /// makefile.insert_include(1, "config.mk").unwrap();
1561 /// let items: Vec<_> = makefile.items().collect();
1562 /// assert_eq!(items.len(), 3); // VAR, include, rule
1563 /// ```
1564 pub fn insert_include(&mut self, index: usize, path: &str) -> Result<Include, Error> {
1565 let items: Vec<_> = self.syntax().children().collect();
1566
1567 if index > items.len() {
1568 return Err(Error::Parse(ParseError {
1569 errors: vec![ErrorInfo {
1570 message: format!("Index {} out of bounds (max {})", index, items.len()),
1571 line: 1,
1572 context: "insert_include".to_string(),
1573 }],
1574 }));
1575 }
1576
1577 let mut builder = GreenNodeBuilder::new();
1578 builder.start_node(INCLUDE.into());
1579 builder.token(IDENTIFIER.into(), "include");
1580 builder.token(WHITESPACE.into(), " ");
1581
1582 // Wrap path in EXPR node
1583 builder.start_node(EXPR.into());
1584 builder.token(IDENTIFIER.into(), path);
1585 builder.finish_node();
1586
1587 builder.token(NEWLINE.into(), "\n");
1588 builder.finish_node();
1589
1590 let syntax = SyntaxNode::new_root_mut(builder.finish());
1591
1592 let target_index = if index == items.len() {
1593 // Insert at the end
1594 self.syntax().children_with_tokens().count()
1595 } else {
1596 // Insert before the item at the given index
1597 items[index].index()
1598 };
1599
1600 // Insert the include node
1601 self.syntax()
1602 .splice_children(target_index..target_index, vec![syntax.into()]);
1603
1604 // Find and return the newly added include
1605 // It should be at the child index we inserted at
1606 Ok(Include::cast(self.syntax().children().nth(index).unwrap()).unwrap())
1607 }
1608
1609 /// Insert an include directive after a specific MakefileItem
1610 ///
1611 /// This is useful when you want to insert an include relative to another item in the makefile.
1612 ///
1613 /// # Arguments
1614 /// * `after` - The MakefileItem to insert after
1615 /// * `path` - The file path to include (e.g., "config.mk")
1616 ///
1617 /// # Example
1618 /// ```
1619 /// use makefile_lossless::Makefile;
1620 /// let mut makefile: Makefile = "VAR1 = value1\nVAR2 = value2\n".parse().unwrap();
1621 /// let first_var = makefile.items().next().unwrap();
1622 /// makefile.insert_include_after(&first_var, "config.mk").unwrap();
1623 /// let paths: Vec<_> = makefile.included_files().collect();
1624 /// assert_eq!(paths, vec!["config.mk"]);
1625 /// ```
1626 pub fn insert_include_after(
1627 &mut self,
1628 after: &MakefileItem,
1629 path: &str,
1630 ) -> Result<Include, Error> {
1631 let mut builder = GreenNodeBuilder::new();
1632 builder.start_node(INCLUDE.into());
1633 builder.token(IDENTIFIER.into(), "include");
1634 builder.token(WHITESPACE.into(), " ");
1635
1636 // Wrap path in EXPR node
1637 builder.start_node(EXPR.into());
1638 builder.token(IDENTIFIER.into(), path);
1639 builder.finish_node();
1640
1641 builder.token(NEWLINE.into(), "\n");
1642 builder.finish_node();
1643
1644 let syntax = SyntaxNode::new_root_mut(builder.finish());
1645
1646 // Find the position of the item to insert after
1647 let after_syntax = after.syntax();
1648 let target_index = after_syntax.index() + 1;
1649
1650 // Insert the include node after the target item
1651 self.syntax()
1652 .splice_children(target_index..target_index, vec![syntax.into()]);
1653
1654 // Find and return the newly added include
1655 // It should be the child immediately after the 'after' item
1656 let after_child_index = self
1657 .syntax()
1658 .children()
1659 .position(|child| child.text_range() == after_syntax.text_range())
1660 .ok_or_else(|| {
1661 Error::Parse(ParseError {
1662 errors: vec![ErrorInfo {
1663 message: "Could not find the reference item".to_string(),
1664 line: 1,
1665 context: "insert_include_after".to_string(),
1666 }],
1667 })
1668 })?;
1669
1670 Ok(Include::cast(self.syntax().children().nth(after_child_index + 1).unwrap()).unwrap())
1671 }
1672 }
1673
1674 #[cfg(test)]
1675 mod tests {
1676 use super::*;
1677
1678 #[test]
1679 fn test_makefile_item_replace_variable_with_variable() {
1680 let makefile: Makefile = "VAR1 = old\nrule:\n\tcommand\n".parse().unwrap();
1681 let temp: Makefile = "VAR2 = new\n".parse().unwrap();
1682 let new_var = temp.variable_definitions().next().unwrap();
1683 let mut first_item = makefile.items().next().unwrap();
1684 first_item.replace(MakefileItem::Variable(new_var)).unwrap();
1685
1686 let result = makefile.to_string();
1687 assert_eq!(result, "VAR2 = new\nrule:\n\tcommand\n");
1688 }
1689
1690 #[test]
1691 fn test_makefile_item_replace_variable_with_rule() {
1692 let makefile: Makefile = "VAR1 = value\nrule1:\n\tcommand1\n".parse().unwrap();
1693 let temp: Makefile = "new_rule:\n\tnew_command\n".parse().unwrap();
1694 let new_rule = temp.rules().next().unwrap();
1695 let mut first_item = makefile.items().next().unwrap();
1696 first_item.replace(MakefileItem::Rule(new_rule)).unwrap();
1697
1698 let result = makefile.to_string();
1699 assert_eq!(result, "new_rule:\n\tnew_command\nrule1:\n\tcommand1\n");
1700 }
1701
1702 #[test]
1703 fn test_makefile_item_replace_preserves_position() {
1704 let makefile: Makefile = "VAR1 = first\nVAR2 = second\nVAR3 = third\n"
1705 .parse()
1706 .unwrap();
1707 let temp: Makefile = "NEW = replacement\n".parse().unwrap();
1708 let new_var = temp.variable_definitions().next().unwrap();
1709
1710 // Replace the second item
1711 let mut second_item = makefile.items().nth(1).unwrap();
1712 second_item
1713 .replace(MakefileItem::Variable(new_var))
1714 .unwrap();
1715
1716 let items: Vec<_> = makefile.variable_definitions().collect();
1717 assert_eq!(items.len(), 3);
1718 assert_eq!(items[0].name(), Some("VAR1".to_string()));
1719 assert_eq!(items[1].name(), Some("NEW".to_string()));
1720 assert_eq!(items[2].name(), Some("VAR3".to_string()));
1721 }
1722
1723 #[test]
1724 fn test_makefile_item_add_comment() {
1725 let makefile: Makefile = "VAR = value\n".parse().unwrap();
1726 let mut item = makefile.items().next().unwrap();
1727 item.add_comment("This is a variable").unwrap();
1728
1729 let result = makefile.to_string();
1730 assert_eq!(result, "# This is a variable\nVAR = value\n");
1731 }
1732
1733 #[test]
1734 fn test_makefile_item_add_multiple_comments() {
1735 let makefile: Makefile = "VAR = value\n".parse().unwrap();
1736 let mut item = makefile.items().next().unwrap();
1737 item.add_comment("Comment 1").unwrap();
1738 // Note: After modifying the tree, we need to get a fresh reference
1739 let mut item = makefile.items().next().unwrap();
1740 item.add_comment("Comment 2").unwrap();
1741
1742 let result = makefile.to_string();
1743 // Comments are added before the item, so adding Comment 2 after Comment 1
1744 // results in Comment 1 appearing first (furthest from item), then Comment 2
1745 assert_eq!(result, "# Comment 1\n# Comment 2\nVAR = value\n");
1746 }
1747
1748 #[test]
1749 fn test_makefile_item_preceding_comments() {
1750 let makefile: Makefile = "# Comment 1\n# Comment 2\nVAR = value\n".parse().unwrap();
1751 let item = makefile.items().next().unwrap();
1752 let comments: Vec<_> = item.preceding_comments().collect();
1753 assert_eq!(comments.len(), 2);
1754 assert_eq!(comments[0], "Comment 1");
1755 assert_eq!(comments[1], "Comment 2");
1756 }
1757
1758 #[test]
1759 fn test_makefile_item_preceding_comments_no_comments() {
1760 let makefile: Makefile = "VAR = value\n".parse().unwrap();
1761 let item = makefile.items().next().unwrap();
1762 let comments: Vec<_> = item.preceding_comments().collect();
1763 assert_eq!(comments.len(), 0);
1764 }
1765
1766 #[test]
1767 fn test_makefile_item_preceding_comments_ignores_shebang() {
1768 let makefile: Makefile = "#!/usr/bin/make\n# Real comment\nVAR = value\n"
1769 .parse()
1770 .unwrap();
1771 let item = makefile.items().next().unwrap();
1772 let comments: Vec<_> = item.preceding_comments().collect();
1773 assert_eq!(comments.len(), 1);
1774 assert_eq!(comments[0], "Real comment");
1775 }
1776
1777 #[test]
1778 fn test_makefile_item_remove_comments() {
1779 let makefile: Makefile = "# Comment 1\n# Comment 2\nVAR = value\n".parse().unwrap();
1780 // Get a fresh reference to the item to ensure we have the current tree state
1781 let mut item = makefile.items().next().unwrap();
1782 let count = item.remove_comments().unwrap();
1783
1784 assert_eq!(count, 2);
1785 let result = makefile.to_string();
1786 assert_eq!(result, "VAR = value\n");
1787 }
1788
1789 #[test]
1790 fn test_makefile_item_remove_comments_no_comments() {
1791 let makefile: Makefile = "VAR = value\n".parse().unwrap();
1792 let mut item = makefile.items().next().unwrap();
1793 let count = item.remove_comments().unwrap();
1794
1795 assert_eq!(count, 0);
1796 assert_eq!(makefile.to_string(), "VAR = value\n");
1797 }
1798
1799 #[test]
1800 fn test_makefile_item_modify_comment() {
1801 let makefile: Makefile = "# Old comment\nVAR = value\n".parse().unwrap();
1802 let mut item = makefile.items().next().unwrap();
1803 let modified = item.modify_comment("New comment").unwrap();
1804
1805 assert!(modified);
1806 let result = makefile.to_string();
1807 assert_eq!(result, "# New comment\nVAR = value\n");
1808 }
1809
1810 #[test]
1811 fn test_makefile_item_modify_comment_no_comment() {
1812 let makefile: Makefile = "VAR = value\n".parse().unwrap();
1813 let mut item = makefile.items().next().unwrap();
1814 let modified = item.modify_comment("New comment").unwrap();
1815
1816 assert!(!modified);
1817 assert_eq!(makefile.to_string(), "VAR = value\n");
1818 }
1819
1820 #[test]
1821 fn test_makefile_item_modify_comment_modifies_closest() {
1822 let makefile: Makefile = "# Comment 1\n# Comment 2\n# Comment 3\nVAR = value\n"
1823 .parse()
1824 .unwrap();
1825 let mut item = makefile.items().next().unwrap();
1826 let modified = item.modify_comment("Modified").unwrap();
1827
1828 assert!(modified);
1829 let result = makefile.to_string();
1830 assert_eq!(
1831 result,
1832 "# Comment 1\n# Comment 2\n# Modified\nVAR = value\n"
1833 );
1834 }
1835
1836 #[test]
1837 fn test_makefile_item_comment_workflow() {
1838 // Test adding, modifying, and removing comments in sequence
1839 let makefile: Makefile = "VAR = value\n".parse().unwrap();
1840 let mut item = makefile.items().next().unwrap();
1841
1842 // Add a comment
1843 item.add_comment("Initial comment").unwrap();
1844 assert_eq!(makefile.to_string(), "# Initial comment\nVAR = value\n");
1845
1846 // Get a fresh reference after modification
1847 let mut item = makefile.items().next().unwrap();
1848 // Modify it
1849 item.modify_comment("Updated comment").unwrap();
1850 assert_eq!(makefile.to_string(), "# Updated comment\nVAR = value\n");
1851
1852 // Get a fresh reference after modification
1853 let mut item = makefile.items().next().unwrap();
1854 // Remove it
1855 let count = item.remove_comments().unwrap();
1856 assert_eq!(count, 1);
1857 assert_eq!(makefile.to_string(), "VAR = value\n");
1858 }
1859
1860 #[test]
1861 fn test_makefile_item_replace_with_comments() {
1862 let makefile: Makefile = "# Comment for VAR1\nVAR1 = old\nrule:\n\tcommand\n"
1863 .parse()
1864 .unwrap();
1865 let temp: Makefile = "VAR2 = new\n".parse().unwrap();
1866 let new_var = temp.variable_definitions().next().unwrap();
1867 let mut first_item = makefile.items().next().unwrap();
1868
1869 // Verify comment exists before replace
1870 let comments: Vec<_> = first_item.preceding_comments().collect();
1871 assert_eq!(comments.len(), 1);
1872 assert_eq!(comments[0], "Comment for VAR1");
1873
1874 // Replace the item
1875 first_item.replace(MakefileItem::Variable(new_var)).unwrap();
1876
1877 let result = makefile.to_string();
1878 // The comment should still be there (replace preserves preceding comments)
1879 assert_eq!(result, "# Comment for VAR1\nVAR2 = new\nrule:\n\tcommand\n");
1880 }
1881
1882 #[test]
1883 fn test_makefile_item_insert_before_variable() {
1884 let makefile: Makefile = "VAR1 = first\nVAR2 = second\n".parse().unwrap();
1885 let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
1886 let new_var = temp.variable_definitions().next().unwrap();
1887 let mut second_item = makefile.items().nth(1).unwrap();
1888 second_item
1889 .insert_before(MakefileItem::Variable(new_var))
1890 .unwrap();
1891
1892 let result = makefile.to_string();
1893 assert_eq!(result, "VAR1 = first\nVAR_NEW = inserted\nVAR2 = second\n");
1894 }
1895
1896 #[test]
1897 fn test_makefile_item_insert_after_variable() {
1898 let makefile: Makefile = "VAR1 = first\nVAR2 = second\n".parse().unwrap();
1899 let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
1900 let new_var = temp.variable_definitions().next().unwrap();
1901 let mut first_item = makefile.items().next().unwrap();
1902 first_item
1903 .insert_after(MakefileItem::Variable(new_var))
1904 .unwrap();
1905
1906 let result = makefile.to_string();
1907 assert_eq!(result, "VAR1 = first\nVAR_NEW = inserted\nVAR2 = second\n");
1908 }
1909
1910 #[test]
1911 fn test_makefile_item_insert_before_first_item() {
1912 let makefile: Makefile = "VAR1 = first\nVAR2 = second\n".parse().unwrap();
1913 let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
1914 let new_var = temp.variable_definitions().next().unwrap();
1915 let mut first_item = makefile.items().next().unwrap();
1916 first_item
1917 .insert_before(MakefileItem::Variable(new_var))
1918 .unwrap();
1919
1920 let result = makefile.to_string();
1921 assert_eq!(result, "VAR_NEW = inserted\nVAR1 = first\nVAR2 = second\n");
1922 }
1923
1924 #[test]
1925 fn test_makefile_item_insert_after_last_item() {
1926 let makefile: Makefile = "VAR1 = first\nVAR2 = second\n".parse().unwrap();
1927 let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
1928 let new_var = temp.variable_definitions().next().unwrap();
1929 let mut last_item = makefile.items().nth(1).unwrap();
1930 last_item
1931 .insert_after(MakefileItem::Variable(new_var))
1932 .unwrap();
1933
1934 let result = makefile.to_string();
1935 assert_eq!(result, "VAR1 = first\nVAR2 = second\nVAR_NEW = inserted\n");
1936 }
1937
1938 #[test]
1939 fn test_makefile_item_insert_before_include() {
1940 let makefile: Makefile = "VAR1 = value\nrule:\n\tcommand\n".parse().unwrap();
1941 let temp: Makefile = "include test.mk\n".parse().unwrap();
1942 let new_include = temp.includes().next().unwrap();
1943 let mut first_item = makefile.items().next().unwrap();
1944 first_item
1945 .insert_before(MakefileItem::Include(new_include))
1946 .unwrap();
1947
1948 let result = makefile.to_string();
1949 assert_eq!(result, "include test.mk\nVAR1 = value\nrule:\n\tcommand\n");
1950 }
1951
1952 #[test]
1953 fn test_makefile_item_insert_after_include() {
1954 let makefile: Makefile = "VAR1 = value\nrule:\n\tcommand\n".parse().unwrap();
1955 let temp: Makefile = "include test.mk\n".parse().unwrap();
1956 let new_include = temp.includes().next().unwrap();
1957 let mut first_item = makefile.items().next().unwrap();
1958 first_item
1959 .insert_after(MakefileItem::Include(new_include))
1960 .unwrap();
1961
1962 let result = makefile.to_string();
1963 assert_eq!(result, "VAR1 = value\ninclude test.mk\nrule:\n\tcommand\n");
1964 }
1965
1966 #[test]
1967 fn test_makefile_item_insert_before_rule() {
1968 let makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap();
1969 let temp: Makefile = "new_rule:\n\tnew_command\n".parse().unwrap();
1970 let new_rule = temp.rules().next().unwrap();
1971 let mut second_item = makefile.items().nth(1).unwrap();
1972 second_item
1973 .insert_before(MakefileItem::Rule(new_rule))
1974 .unwrap();
1975
1976 let result = makefile.to_string();
1977 assert_eq!(
1978 result,
1979 "rule1:\n\tcommand1\nnew_rule:\n\tnew_command\nrule2:\n\tcommand2\n"
1980 );
1981 }
1982
1983 #[test]
1984 fn test_makefile_item_insert_after_rule() {
1985 let makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap();
1986 let temp: Makefile = "new_rule:\n\tnew_command\n".parse().unwrap();
1987 let new_rule = temp.rules().next().unwrap();
1988 let mut first_item = makefile.items().next().unwrap();
1989 first_item
1990 .insert_after(MakefileItem::Rule(new_rule))
1991 .unwrap();
1992
1993 let result = makefile.to_string();
1994 assert_eq!(
1995 result,
1996 "rule1:\n\tcommand1\nnew_rule:\n\tnew_command\nrule2:\n\tcommand2\n"
1997 );
1998 }
1999
2000 #[test]
2001 fn test_makefile_item_insert_before_with_comments() {
2002 let makefile: Makefile = "# Comment 1\nVAR1 = first\n# Comment 2\nVAR2 = second\n"
2003 .parse()
2004 .unwrap();
2005 let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
2006 let new_var = temp.variable_definitions().next().unwrap();
2007 let mut second_item = makefile.items().nth(1).unwrap();
2008 second_item
2009 .insert_before(MakefileItem::Variable(new_var))
2010 .unwrap();
2011
2012 let result = makefile.to_string();
2013 // The new variable should be inserted before Comment 2 (which precedes VAR2)
2014 // This is correct because insert_before inserts before the item and its preceding comments
2015 assert_eq!(
2016 result,
2017 "# Comment 1\nVAR1 = first\n# Comment 2\nVAR_NEW = inserted\nVAR2 = second\n"
2018 );
2019 }
2020
2021 #[test]
2022 fn test_makefile_item_insert_after_with_comments() {
2023 let makefile: Makefile = "# Comment 1\nVAR1 = first\n# Comment 2\nVAR2 = second\n"
2024 .parse()
2025 .unwrap();
2026 let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
2027 let new_var = temp.variable_definitions().next().unwrap();
2028 let mut first_item = makefile.items().next().unwrap();
2029 first_item
2030 .insert_after(MakefileItem::Variable(new_var))
2031 .unwrap();
2032
2033 let result = makefile.to_string();
2034 // The new variable should be inserted between VAR1 and Comment 2/VAR2
2035 assert_eq!(
2036 result,
2037 "# Comment 1\nVAR1 = first\nVAR_NEW = inserted\n# Comment 2\nVAR2 = second\n"
2038 );
2039 }
2040
2041 #[test]
2042 fn test_makefile_item_insert_before_preserves_formatting() {
2043 let makefile: Makefile = "VAR1 = first\nVAR2 = second\n".parse().unwrap();
2044 let temp: Makefile = "VAR_NEW = inserted\n".parse().unwrap();
2045 let new_var = temp.variable_definitions().next().unwrap();
2046 let mut second_item = makefile.items().nth(1).unwrap();
2047 second_item
2048 .insert_before(MakefileItem::Variable(new_var))
2049 .unwrap();
2050
2051 let result = makefile.to_string();
2052 // Formatting of the new item is preserved from its source
2053 assert_eq!(
2054 result,
2055 "VAR1 = first\nVAR_NEW = inserted\nVAR2 = second\n"
2056 );
2057 }
2058
2059 #[test]
2060 fn test_makefile_item_insert_multiple_items() {
2061 let makefile: Makefile = "VAR1 = first\nVAR2 = last\n".parse().unwrap();
2062 let temp: Makefile = "VAR_A = a\nVAR_B = b\n".parse().unwrap();
2063 let mut new_vars: Vec<_> = temp.variable_definitions().collect();
2064
2065 let mut target_item = makefile.items().nth(1).unwrap();
2066 target_item
2067 .insert_before(MakefileItem::Variable(new_vars.pop().unwrap()))
2068 .unwrap();
2069
2070 // Get fresh reference after first insertion
2071 let mut target_item = makefile.items().nth(1).unwrap();
2072 target_item
2073 .insert_before(MakefileItem::Variable(new_vars.pop().unwrap()))
2074 .unwrap();
2075
2076 let result = makefile.to_string();
2077 assert_eq!(result, "VAR1 = first\nVAR_A = a\nVAR_B = b\nVAR2 = last\n");
2078 }
2079
2080 #[test]
2081 fn test_rules_after_nested_conditionals() {
2082 // Test for bug where .rules() returns no rules after nested conditionals
2083 // This was reported in https://bugs.debian.org/1126511
2084 let makefile_content = r#"#!/usr/bin/make -f
2085
2086 ifeq ($(filter nodoc, $(DEB_BUILD_OPTIONS)),)
2087 ifneq ($(shell which valadoc),)
2088 BUILD_DOC:=-Ddocs=true
2089 endif
2090 endif
2091
2092 %:
2093 dh $@
2094
2095 override_dh_auto_configure:
2096 echo test
2097 "#;
2098 let makefile: Makefile = makefile_content.parse().unwrap();
2099
2100 let rules: Vec<_> = makefile.rules().collect();
2101 let targets: Vec<Vec<_>> = rules.iter().map(|r| r.targets().collect()).collect();
2102 assert_eq!(
2103 rules.len(),
2104 2,
2105 "Expected 2 rules (% and override_dh_auto_configure), got {} rules with targets: {:?}",
2106 rules.len(),
2107 targets
2108 );
2109
2110 assert_eq!(targets[0], vec!["%"]);
2111 assert_eq!(targets[1], vec!["override_dh_auto_configure"]);
2112
2113 // Also test that pattern matching works
2114 assert!(makefile.find_rule_by_target_pattern("build-arch").is_some());
2115 assert!(makefile
2116 .find_rule_by_target_pattern("build-indep")
2117 .is_some());
2118 }
2119
2120 #[test]
2121 fn test_items_in_range_single_item() {
2122 let input = "CC = gcc\n\nall: build\n\techo done\n";
2123 let makefile: Makefile = input.parse().unwrap();
2124 // Range covering just the variable definition "CC = gcc\n"
2125 let range = rowan::TextRange::new(0.into(), 8.into());
2126 let items: Vec<_> = makefile.items_in_range(range).collect();
2127 assert_eq!(items.len(), 1);
2128 assert!(matches!(items[0], MakefileItem::Variable(_)));
2129 }
2130
2131 #[test]
2132 fn test_items_in_range_multiple_items() {
2133 let input = "CC = gcc\n\nall: build\n\techo done\n";
2134 let makefile: Makefile = input.parse().unwrap();
2135 // Range covering the whole file
2136 let range = rowan::TextRange::new(0.into(), (input.len() as u32).into());
2137 let items: Vec<_> = makefile.items_in_range(range).collect();
2138 assert_eq!(items.len(), 2);
2139 }
2140
2141 #[test]
2142 fn test_items_in_range_no_overlap() {
2143 let input = "CC = gcc\n\nall: build\n\techo done\n";
2144 let makefile: Makefile = input.parse().unwrap();
2145 // Range in the blank line between items
2146 let range = rowan::TextRange::new(9.into(), 10.into());
2147 let items: Vec<_> = makefile.items_in_range(range).collect();
2148 assert_eq!(items.len(), 0);
2149 }
2150
2151 #[test]
2152 fn test_items_in_range_partial_overlap() {
2153 let input = "CC = gcc\nLD = ld\nall: build\n\techo done\n";
2154 let makefile: Makefile = input.parse().unwrap();
2155 // Range overlapping end of first var and start of second
2156 let range = rowan::TextRange::new(5.into(), 12.into());
2157 let items: Vec<_> = makefile.items_in_range(range).collect();
2158 assert_eq!(items.len(), 2);
2159 }
2160
2161 #[test]
2162 fn test_rules_in_range() {
2163 let input = "CC = gcc\nall: build\n\techo done\nclean:\n\trm -rf build\n";
2164 let makefile: Makefile = input.parse().unwrap();
2165 // Range covering the whole file
2166 let range = rowan::TextRange::new(0.into(), (input.len() as u32).into());
2167 let rules: Vec<_> = makefile.rules_in_range(range).collect();
2168 assert_eq!(rules.len(), 2);
2169
2170 // Range covering only the variable
2171 let range = rowan::TextRange::new(0.into(), 9.into());
2172 let rules: Vec<_> = makefile.rules_in_range(range).collect();
2173 assert_eq!(rules.len(), 0);
2174 }
2175
2176 #[test]
2177 fn test_variable_definitions_in_range() {
2178 let input = "CC = gcc\nLD = ld\nall: build\n\techo done\n";
2179 let makefile: Makefile = input.parse().unwrap();
2180 // Range covering the two variable definitions
2181 let range = rowan::TextRange::new(0.into(), 17.into());
2182 let vars: Vec<_> = makefile.variable_definitions_in_range(range).collect();
2183 assert_eq!(vars.len(), 2);
2184
2185 // Range covering only the rule
2186 let range = rowan::TextRange::new(17.into(), (input.len() as u32).into());
2187 let vars: Vec<_> = makefile.variable_definitions_in_range(range).collect();
2188 assert_eq!(vars.len(), 0);
2189 }
2190
2191 #[test]
2192 fn test_variable_references_in_range() {
2193 let input = "CFLAGS = $(BASE) -Wall\nall: $(TARGETS)\n\techo done\n";
2194 let makefile: Makefile = input.parse().unwrap();
2195
2196 // Full range should find the same refs as variable_references()
2197 let all_refs: Vec<_> = makefile.variable_references().collect();
2198 let range = rowan::TextRange::new(0.into(), (input.len() as u32).into());
2199 let refs: Vec<_> = makefile.variable_references_in_range(range).collect();
2200 assert_eq!(refs.len(), all_refs.len());
2201
2202 // Range covering only the variable definition should find $(BASE)
2203 // Find the actual end of the variable item
2204 let var_item = makefile.items().next().unwrap();
2205 let var_end: u32 = var_item.syntax().text_range().end().into();
2206 let range = rowan::TextRange::new(0.into(), var_end.into());
2207 let refs: Vec<_> = makefile.variable_references_in_range(range).collect();
2208 assert_eq!(refs.len(), 1);
2209 assert_eq!(refs[0].name(), Some("BASE".to_string()));
2210
2211 // Range covering only the rule should find $(TARGETS)
2212 let range = rowan::TextRange::new(var_end.into(), (input.len() as u32).into());
2213 let refs: Vec<_> = makefile.variable_references_in_range(range).collect();
2214 assert_eq!(refs.len(), 1);
2215 assert_eq!(refs[0].name(), Some("TARGETS".to_string()));
2216 }
2217
2218 #[test]
2219 fn test_comment_blocks_single_block() {
2220 let makefile: Makefile = "# line 1\n# line 2\n# line 3\nall:\n\techo done\n"
2221 .parse()
2222 .unwrap();
2223 let blocks: Vec<_> = makefile.comment_blocks().collect();
2224 assert_eq!(blocks.len(), 1);
2225 let text = &makefile.to_string()[std::ops::Range::from(blocks[0])];
2226 assert!(text.contains("# line 1"));
2227 assert!(text.contains("# line 3"));
2228 }
2229
2230 #[test]
2231 fn test_comment_blocks_multiple_blocks() {
2232 let makefile: Makefile =
2233 "# block 1a\n# block 1b\nVAR = value\n# block 2a\n# block 2b\nall:\n\techo done\n"
2234 .parse()
2235 .unwrap();
2236 let blocks: Vec<_> = makefile.comment_blocks().collect();
2237 assert_eq!(blocks.len(), 2);
2238 }
2239
2240 #[test]
2241 fn test_comment_blocks_no_blocks() {
2242 let makefile: Makefile = "VAR = value\nall:\n\techo done\n".parse().unwrap();
2243 let blocks: Vec<_> = makefile.comment_blocks().collect();
2244 assert_eq!(blocks.len(), 0);
2245 }
2246
2247 #[test]
2248 fn test_comment_blocks_single_comment_not_a_block() {
2249 let makefile: Makefile = "# just one line\nVAR = value\n".parse().unwrap();
2250 let blocks: Vec<_> = makefile.comment_blocks().collect();
2251 assert_eq!(blocks.len(), 0);
2252 }
2253
2254 #[test]
2255 fn test_comment_blocks_with_blank_line_between() {
2256 let makefile: Makefile = "# line 1\n\n# line 2\nVAR = value\n".parse().unwrap();
2257 let blocks: Vec<_> = makefile.comment_blocks().collect();
2258 // Blank lines between comments should still form a block
2259 assert_eq!(blocks.len(), 1);
2260 }
2261 }