Debian Codegraph @

src/ast/conditional.rs

raw symbols SCIP
1 use super::makefile::MakefileItem;
2 use crate::lossless::{remove_with_preceding_comments, Conditional, Error, ErrorInfo, ParseError};
3 use crate::SyntaxKind::*;
4 use rowan::ast::AstNode;
5 use rowan::{GreenNodeBuilder, SyntaxNode};
6
7 /// Split `s` at the first top-level comma. A comma is "top-level" when it
8 /// is not inside a `$(...)` / `${...}` group. Returns `None` if no such
9 /// comma exists.
10 fn split_top_level_comma(s: &str) -> Option<(&str, &str)> {
11 let bytes = s.as_bytes();
12 let mut paren = 0usize;
13 let mut brace = 0usize;
14 let mut i = 0;
15 while i < bytes.len() {
16 match bytes[i] {
17 b'$' if i + 1 < bytes.len() => {
18 let next = bytes[i + 1];
19 if next == b'(' {
20 paren += 1;
21 i += 2;
22 continue;
23 }
24 if next == b'{' {
25 brace += 1;
26 i += 2;
27 continue;
28 }
29 // $$ or $X — skip both.
30 i += 2;
31 continue;
32 }
33 b'(' => paren += 1,
34 b')' => paren = paren.saturating_sub(1),
35 b'{' => brace += 1,
36 b'}' => brace = brace.saturating_sub(1),
37 b',' if paren == 0 && brace == 0 => {
38 return Some((&s[..i], &s[i + 1..]));
39 }
40 _ => {}
41 }
42 i += 1;
43 }
44 None
45 }
46
47 /// Extract two quoted strings from `s`, in the form `"a" "b"` or `'a' 'b'`.
48 /// Returns `None` if fewer than two quoted strings are present. Surrounding
49 /// quote characters are stripped from each result.
50 fn quoted_pair(s: &str) -> Option<Vec<String>> {
51 let mut out = Vec::new();
52 let mut iter = s.chars().peekable();
53 while iter.peek().is_some() {
54 // Skip leading whitespace between args.
55 while let Some(&c) = iter.peek() {
56 if c.is_ascii_whitespace() {
57 iter.next();
58 } else {
59 break;
60 }
61 }
62 let opener = match iter.next() {
63 Some(c @ ('"' | '\'')) => c,
64 _ => break,
65 };
66 let mut buf = String::new();
67 for c in iter.by_ref() {
68 if c == opener {
69 out.push(buf);
70 buf = String::new();
71 break;
72 }
73 buf.push(c);
74 }
75 }
76 if out.len() >= 2 {
77 Some(out)
78 } else {
79 None
80 }
81 }
82
83 impl Conditional {
84 /// Get the parent item of this conditional, if any
85 ///
86 /// Returns `Some(MakefileItem)` if this conditional has a parent that is a MakefileItem
87 /// (e.g., another Conditional for nested conditionals), or `None` if the parent is the root Makefile node.
88 ///
89 /// # Example
90 /// ```
91 /// use makefile_lossless::Makefile;
92 ///
93 /// let makefile: Makefile = r#"ifdef OUTER
94 /// ifdef INNER
95 /// VAR = value
96 /// endif
97 /// endif
98 /// "#.parse().unwrap();
99 ///
100 /// let outer = makefile.conditionals().next().unwrap();
101 /// let inner = outer.if_items().find_map(|item| {
102 /// if let makefile_lossless::MakefileItem::Conditional(c) = item {
103 /// Some(c)
104 /// } else {
105 /// None
106 /// }
107 /// }).unwrap();
108 /// // Inner conditional's parent is the outer conditional
109 /// assert!(inner.parent().is_some());
110 /// ```
111 pub fn parent(&self) -> Option<MakefileItem> {
112 self.syntax().parent().and_then(MakefileItem::cast)
113 }
114
115 /// Get the type of conditional (ifdef, ifndef, ifeq, ifneq)
116 pub fn conditional_type(&self) -> Option<String> {
117 self.syntax()
118 .children()
119 .find(|it| it.kind() == CONDITIONAL_IF)?
120 .children_with_tokens()
121 .find(|it| it.kind() == IDENTIFIER)
122 .map(|it| it.as_token().unwrap().text().to_string())
123 }
124
125 /// Get the condition expression
126 pub fn condition(&self) -> Option<String> {
127 let if_node = self
128 .syntax()
129 .children()
130 .find(|it| it.kind() == CONDITIONAL_IF)?;
131
132 // Find the EXPR node which contains the condition
133 let expr_node = if_node.children().find(|it| it.kind() == EXPR)?;
134
135 Some(expr_node.text().to_string().trim().to_string())
136 }
137
138 /// For an `ifeq` / `ifneq` conditional, return the two argument
139 /// strings (unexpanded). Supports both the `(a,b)` and `"a" "b"`
140 /// (or `'a' 'b'`) syntaxes.
141 ///
142 /// Returns `None` for `ifdef` / `ifndef` (or if the args can't be
143 /// recovered).
144 ///
145 /// # Example
146 /// ```
147 /// use makefile_lossless::Makefile;
148 /// let mf: Makefile = "ifeq ($(A),$(B))\nX = 1\nendif\n".parse().unwrap();
149 /// let c = mf.conditionals().next().unwrap();
150 /// assert_eq!(c.ifeq_args(), Some(("$(A)".to_string(), "$(B)".to_string())));
151 /// ```
152 pub fn ifeq_args(&self) -> Option<(String, String)> {
153 let if_node = self
154 .syntax()
155 .children()
156 .find(|it| it.kind() == CONDITIONAL_IF)?;
157 // Inside CONDITIONAL_IF there is one EXPR node wrapping the args.
158 let wrapper = if_node.children().find(|it| it.kind() == EXPR)?;
159
160 let text = wrapper.text().to_string();
161 let stripped = text.trim();
162 // Form 1: parenthesised — `(a, b)`. Split at the top-level comma,
163 // ignoring commas inside nested `$(...)` / `${...}`.
164 if let Some(inner) = stripped
165 .strip_prefix('(')
166 .and_then(|s| s.trim_end().strip_suffix(')'))
167 {
168 if let Some((a, b)) = split_top_level_comma(inner) {
169 return Some((a.trim().to_string(), b.trim().to_string()));
170 }
171 }
172
173 // Form 2: quoted — `"a" "b"` or `'a' 'b'`.
174 let mut parts = quoted_pair(&text)?;
175 let b = parts.pop()?;
176 let a = parts.pop()?;
177 Some((a, b))
178 }
179
180 /// Check if this conditional has an else clause
181 pub fn has_else(&self) -> bool {
182 self.syntax()
183 .children()
184 .any(|it| it.kind() == CONDITIONAL_ELSE)
185 }
186
187 /// Get the body content of the if branch
188 pub fn if_body(&self) -> Option<String> {
189 let mut body = String::new();
190 let mut in_if_body = false;
191
192 for child in self.syntax().children_with_tokens() {
193 if child.kind() == CONDITIONAL_IF {
194 in_if_body = true;
195 continue;
196 }
197 if child.kind() == CONDITIONAL_ELSE || child.kind() == CONDITIONAL_ENDIF {
198 break;
199 }
200 if in_if_body {
201 body.push_str(child.to_string().as_str());
202 }
203 }
204
205 if body.is_empty() {
206 None
207 } else {
208 Some(body)
209 }
210 }
211
212 /// Get the body content of the else branch (if it exists)
213 pub fn else_body(&self) -> Option<String> {
214 if !self.has_else() {
215 return None;
216 }
217
218 let mut body = String::new();
219 let mut in_else_body = false;
220
221 for child in self.syntax().children_with_tokens() {
222 if child.kind() == CONDITIONAL_ELSE {
223 in_else_body = true;
224 continue;
225 }
226 if child.kind() == CONDITIONAL_ENDIF {
227 break;
228 }
229 if in_else_body {
230 body.push_str(child.to_string().as_str());
231 }
232 }
233
234 if body.is_empty() {
235 None
236 } else {
237 Some(body)
238 }
239 }
240
241 /// Remove this conditional from the makefile
242 pub fn remove(&mut self) -> Result<(), Error> {
243 let Some(parent) = self.syntax().parent() else {
244 return Err(Error::Parse(ParseError {
245 errors: vec![ErrorInfo {
246 message: "Cannot remove conditional: no parent node".to_string(),
247 line: 1,
248 context: "conditional_remove".to_string(),
249 }],
250 }));
251 };
252
253 remove_with_preceding_comments(self.syntax(), &parent);
254
255 Ok(())
256 }
257
258 /// Remove the conditional directives (ifdef/endif) but keep the body content
259 ///
260 /// This "unwraps" the conditional, keeping only the if branch content.
261 /// Returns an error if the conditional has an else clause.
262 ///
263 /// # Example
264 /// ```
265 /// use makefile_lossless::Makefile;
266 /// let mut makefile: Makefile = r#"ifdef DEBUG
267 /// VAR = debug
268 /// endif
269 /// "#.parse().unwrap();
270 /// let mut cond = makefile.conditionals().next().unwrap();
271 /// cond.unwrap().unwrap();
272 /// // Now makefile contains just "VAR = debug\n"
273 /// assert!(makefile.to_string().contains("VAR = debug"));
274 /// assert!(!makefile.to_string().contains("ifdef"));
275 /// ```
276 pub fn unwrap(&mut self) -> Result<(), Error> {
277 // Check if there's an else clause
278 if self.has_else() {
279 return Err(Error::Parse(ParseError {
280 errors: vec![ErrorInfo {
281 message: "Cannot unwrap conditional with else clause".to_string(),
282 line: 1,
283 context: "conditional_unwrap".to_string(),
284 }],
285 }));
286 }
287
288 let Some(parent) = self.syntax().parent() else {
289 return Err(Error::Parse(ParseError {
290 errors: vec![ErrorInfo {
291 message: "Cannot unwrap conditional: no parent node".to_string(),
292 line: 1,
293 context: "conditional_unwrap".to_string(),
294 }],
295 }));
296 };
297
298 // Collect the body items (everything between CONDITIONAL_IF and CONDITIONAL_ENDIF)
299 let body_nodes: Vec<_> = self
300 .syntax()
301 .children_with_tokens()
302 .skip_while(|n| n.kind() != CONDITIONAL_IF)
303 .skip(1) // Skip CONDITIONAL_IF itself
304 .take_while(|n| n.kind() != CONDITIONAL_ENDIF)
305 .collect();
306
307 // Find the position of this conditional in parent
308 let conditional_index = self.syntax().index();
309
310 // Replace the entire conditional with just its body items
311 parent.splice_children(conditional_index..conditional_index + 1, body_nodes);
312
313 Ok(())
314 }
315
316 /// Get all items (rules, variables, includes, nested conditionals) in the if branch
317 ///
318 /// # Example
319 /// ```
320 /// use makefile_lossless::Makefile;
321 /// let makefile: Makefile = r#"ifdef DEBUG
322 /// VAR = debug
323 /// rule:
324 /// command
325 /// endif
326 /// "#.parse().unwrap();
327 /// let cond = makefile.conditionals().next().unwrap();
328 /// let items: Vec<_> = cond.if_items().collect();
329 /// assert_eq!(items.len(), 2); // One variable, one rule
330 /// ```
331 pub fn if_items(&self) -> impl Iterator<Item = MakefileItem> + '_ {
332 self.syntax()
333 .children()
334 .skip_while(|n| n.kind() != CONDITIONAL_IF)
335 .skip(1) // Skip the CONDITIONAL_IF itself
336 .take_while(|n| n.kind() != CONDITIONAL_ELSE && n.kind() != CONDITIONAL_ENDIF)
337 .filter_map(MakefileItem::cast)
338 }
339
340 /// Get all items (rules, variables, includes, nested conditionals) in the else branch
341 ///
342 /// # Example
343 /// ```
344 /// use makefile_lossless::Makefile;
345 /// let makefile: Makefile = r#"ifdef DEBUG
346 /// VAR = debug
347 /// else
348 /// VAR = release
349 /// endif
350 /// "#.parse().unwrap();
351 /// let cond = makefile.conditionals().next().unwrap();
352 /// let items: Vec<_> = cond.else_items().collect();
353 /// assert_eq!(items.len(), 1); // One variable in else branch
354 /// ```
355 pub fn else_items(&self) -> impl Iterator<Item = MakefileItem> + '_ {
356 self.syntax()
357 .children()
358 .skip_while(|n| n.kind() != CONDITIONAL_ELSE)
359 .skip(1) // Skip the CONDITIONAL_ELSE itself
360 .take_while(|n| n.kind() != CONDITIONAL_ENDIF)
361 .filter_map(MakefileItem::cast)
362 }
363
364 /// Add an item to the if branch of the conditional
365 ///
366 /// # Example
367 /// ```
368 /// use makefile_lossless::{Makefile, MakefileItem};
369 /// let mut makefile: Makefile = "ifdef DEBUG\nendif\n".parse().unwrap();
370 /// let mut cond = makefile.conditionals().next().unwrap();
371 /// let temp: Makefile = "CFLAGS = -g\n".parse().unwrap();
372 /// let var = temp.variable_definitions().next().unwrap();
373 /// cond.add_if_item(MakefileItem::Variable(var));
374 /// assert!(makefile.to_string().contains("CFLAGS = -g"));
375 /// ```
376 pub fn add_if_item(&mut self, item: MakefileItem) {
377 let item_node = item.syntax().clone();
378
379 // Find position after CONDITIONAL_IF
380 let insert_pos = self
381 .syntax()
382 .children_with_tokens()
383 .position(|n| n.kind() == CONDITIONAL_IF)
384 .map(|p| p + 1)
385 .unwrap_or(0);
386
387 self.syntax()
388 .splice_children(insert_pos..insert_pos, vec![item_node.into()]);
389 }
390
391 /// Add an item to the else branch of the conditional
392 ///
393 /// If the conditional doesn't have an else branch, this will create one.
394 ///
395 /// # Example
396 /// ```
397 /// use makefile_lossless::{Makefile, MakefileItem};
398 /// let mut makefile: Makefile = "ifdef DEBUG\nVAR=1\nendif\n".parse().unwrap();
399 /// let mut cond = makefile.conditionals().next().unwrap();
400 /// let temp: Makefile = "CFLAGS = -O2\n".parse().unwrap();
401 /// let var = temp.variable_definitions().next().unwrap();
402 /// cond.add_else_item(MakefileItem::Variable(var));
403 /// assert!(makefile.to_string().contains("else"));
404 /// assert!(makefile.to_string().contains("CFLAGS = -O2"));
405 /// ```
406 pub fn add_else_item(&mut self, item: MakefileItem) {
407 // Ensure there's an else clause
408 if !self.has_else() {
409 self.add_else_clause();
410 }
411
412 let item_node = item.syntax().clone();
413
414 // Find position after CONDITIONAL_ELSE
415 let insert_pos = self
416 .syntax()
417 .children_with_tokens()
418 .position(|n| n.kind() == CONDITIONAL_ELSE)
419 .map(|p| p + 1)
420 .unwrap_or(0);
421
422 self.syntax()
423 .splice_children(insert_pos..insert_pos, vec![item_node.into()]);
424 }
425
426 /// Add a matching `endif` to close this conditional, if it doesn't already
427 /// have one.
428 ///
429 /// Returns `Ok(true)` if a CONDITIONAL_ENDIF was inserted, `Ok(false)` if
430 /// the conditional was already terminated. Returns an error if the
431 /// conditional has no recognized opener (e.g. a bare `else`/`endif` that
432 /// the parser wrapped in a CONDITIONAL node).
433 ///
434 /// If the existing body does not end with a newline, one is inserted
435 /// before the `endif` so it lands on its own line.
436 ///
437 /// # Example
438 /// ```
439 /// use makefile_lossless::Makefile;
440 /// let makefile: Makefile = "ifdef DEBUG\nVAR = 1\n".parse().unwrap();
441 /// let mut cond = makefile.conditionals().next().unwrap();
442 /// assert!(cond.add_endif().unwrap());
443 /// assert_eq!(makefile.code(), "ifdef DEBUG\nVAR = 1\nendif\n");
444 /// ```
445 pub fn add_endif(&mut self) -> Result<bool, Error> {
446 if self.conditional_type().is_none() {
447 return Err(Error::Parse(ParseError {
448 errors: vec![ErrorInfo {
449 message: "Cannot add endif to conditional with no opener".to_string(),
450 line: 1,
451 context: "conditional_add_endif".to_string(),
452 }],
453 }));
454 }
455 if self
456 .syntax()
457 .children_with_tokens()
458 .any(|c| c.kind() == CONDITIONAL_ENDIF)
459 {
460 return Ok(false);
461 }
462
463 // Need a newline before `endif` if the current tail doesn't already end
464 // with one.
465 let needs_newline = self
466 .syntax()
467 .last_token()
468 .is_none_or(|t| t.kind() != NEWLINE);
469
470 let mut builder = GreenNodeBuilder::new();
471 builder.start_node(CONDITIONAL_ENDIF.into());
472 if needs_newline {
473 builder.token(NEWLINE.into(), "\n");
474 }
475 builder.token(IDENTIFIER.into(), "endif");
476 builder.token(NEWLINE.into(), "\n");
477 builder.finish_node();
478
479 let endif = SyntaxNode::new_root_mut(builder.finish());
480 let count = self.syntax().children_with_tokens().count();
481 self.syntax()
482 .splice_children(count..count, vec![endif.into()]);
483
484 Ok(true)
485 }
486
487 /// Add an else clause to the conditional if it doesn't already have one
488 fn add_else_clause(&mut self) {
489 if self.has_else() {
490 return;
491 }
492
493 let mut builder = GreenNodeBuilder::new();
494 builder.start_node(CONDITIONAL_ELSE.into());
495 builder.token(IDENTIFIER.into(), "else");
496 builder.token(NEWLINE.into(), "\n");
497 builder.finish_node();
498
499 let syntax = SyntaxNode::new_root_mut(builder.finish());
500
501 // Find position before CONDITIONAL_ENDIF
502 let insert_pos = self
503 .syntax()
504 .children_with_tokens()
505 .position(|n| n.kind() == CONDITIONAL_ENDIF)
506 .unwrap_or(self.syntax().children_with_tokens().count());
507
508 self.syntax()
509 .splice_children(insert_pos..insert_pos, vec![syntax.into()]);
510 }
511 }
512
513 #[cfg(test)]
514 mod tests {
515
516 use crate::lossless::Makefile;
517
518 #[test]
519 fn test_conditional_parent() {
520 let makefile: Makefile = r#"ifdef DEBUG
521 VAR = debug
522 endif
523 "#
524 .parse()
525 .unwrap();
526
527 let cond = makefile.conditionals().next().unwrap();
528 let parent = cond.parent();
529 // Parent is ROOT node which doesn't cast to MakefileItem
530 assert!(parent.is_none());
531 }
532
533 #[test]
534 fn test_add_endif_to_unterminated() {
535 let makefile: Makefile = "ifdef DEBUG\nVAR = 1\n".parse().unwrap();
536 let mut cond = makefile.conditionals().next().unwrap();
537 assert!(cond.add_endif().unwrap());
538 assert_eq!(makefile.code(), "ifdef DEBUG\nVAR = 1\nendif\n");
539 }
540
541 #[test]
542 fn test_add_endif_already_terminated_noop() {
543 let makefile: Makefile = "ifdef DEBUG\nVAR = 1\nendif\n".parse().unwrap();
544 let mut cond = makefile.conditionals().next().unwrap();
545 assert!(!cond.add_endif().unwrap());
546 assert_eq!(makefile.code(), "ifdef DEBUG\nVAR = 1\nendif\n");
547 }
548
549 #[test]
550 fn test_add_endif_no_trailing_newline() {
551 // Source with no final newline produces a parse error, but the tree
552 // is still usable for mutations.
553 let parsed = Makefile::parse("ifdef DEBUG\nVAR = 1");
554 let makefile = parsed.tree();
555 let mut cond = makefile.conditionals().next().unwrap();
556 assert!(cond.add_endif().unwrap());
557 assert_eq!(makefile.code(), "ifdef DEBUG\nVAR = 1\nendif\n");
558 }
559
560 #[test]
561 fn test_add_endif_with_else() {
562 let makefile: Makefile = "ifdef DEBUG\nA = 1\nelse\nA = 2\n".parse().unwrap();
563 let mut cond = makefile.conditionals().next().unwrap();
564 assert!(cond.add_endif().unwrap());
565 assert_eq!(makefile.code(), "ifdef DEBUG\nA = 1\nelse\nA = 2\nendif\n");
566 }
567
568 #[test]
569 fn test_add_endif_rejects_bare_else() {
570 // A bare `else`/`endif` is wrapped in a Conditional node with no
571 // CONDITIONAL_IF, so conditional_type() is None. We refuse to add
572 // an `endif` to it — the parser already complains.
573 let parsed = Makefile::parse("else\nVAR = 1\n");
574 let makefile = parsed.tree();
575 let mut cond = makefile.conditionals().next().unwrap();
576 assert!(cond.conditional_type().is_none());
577 assert!(cond.add_endif().is_err());
578 }
579
580 #[test]
581 fn test_add_endif_preserves_existing_body() {
582 let makefile: Makefile = "ifeq ($(X),y)\nA = 1\nB = 2\n".parse().unwrap();
583 let mut cond = makefile.conditionals().next().unwrap();
584 assert!(cond.add_endif().unwrap());
585 assert_eq!(makefile.code(), "ifeq ($(X),y)\nA = 1\nB = 2\nendif\n");
586 }
587 }