1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
use super::makefile::MakefileItem;
use crate::lossless::{remove_with_preceding_comments, Conditional, Error, ErrorInfo, ParseError};
use crate::SyntaxKind::*;
use rowan::ast::AstNode;
use rowan::{GreenNodeBuilder, SyntaxNode};
impl Conditional {
/// Get the parent item of this conditional, if any
///
/// Returns `Some(MakefileItem)` if this conditional has a parent that is a MakefileItem
/// (e.g., another Conditional for nested conditionals), or `None` if the parent is the root Makefile node.
///
/// # Example
/// ```
/// use makefile_lossless::Makefile;
///
/// let makefile: Makefile = r#"ifdef OUTER
/// ifdef INNER
/// VAR = value
/// endif
/// endif
/// "#.parse().unwrap();
///
/// let outer = makefile.conditionals().next().unwrap();
/// let inner = outer.if_items().find_map(|item| {
/// if let makefile_lossless::MakefileItem::Conditional(c) = item {
/// Some(c)
/// } else {
/// None
/// }
/// }).unwrap();
/// // Inner conditional's parent is the outer conditional
/// assert!(inner.parent().is_some());
/// ```
pub fn parent(&self) -> Option<MakefileItem> {
self.syntax().parent().and_then(MakefileItem::cast)
}
/// Get the type of conditional (ifdef, ifndef, ifeq, ifneq)
pub fn conditional_type(&self) -> Option<String> {
self.syntax()
.children()
.find(|it| it.kind() == CONDITIONAL_IF)?
.children_with_tokens()
.find(|it| it.kind() == IDENTIFIER)
.map(|it| it.as_token().unwrap().text().to_string())
}
/// Get the condition expression
pub fn condition(&self) -> Option<String> {
let if_node = self
.syntax()
.children()
.find(|it| it.kind() == CONDITIONAL_IF)?;
// Find the EXPR node which contains the condition
let expr_node = if_node.children().find(|it| it.kind() == EXPR)?;
Some(expr_node.text().to_string().trim().to_string())
}
/// Check if this conditional has an else clause
pub fn has_else(&self) -> bool {
self.syntax()
.children()
.any(|it| it.kind() == CONDITIONAL_ELSE)
}
/// Get the body content of the if branch
pub fn if_body(&self) -> Option<String> {
let mut body = String::new();
let mut in_if_body = false;
for child in self.syntax().children_with_tokens() {
if child.kind() == CONDITIONAL_IF {
in_if_body = true;
continue;
}
if child.kind() == CONDITIONAL_ELSE || child.kind() == CONDITIONAL_ENDIF {
break;
}
if in_if_body {
body.push_str(child.to_string().as_str());
}
}
if body.is_empty() {
None
} else {
Some(body)
}
}
/// Get the body content of the else branch (if it exists)
pub fn else_body(&self) -> Option<String> {
if !self.has_else() {
return None;
}
let mut body = String::new();
let mut in_else_body = false;
for child in self.syntax().children_with_tokens() {
if child.kind() == CONDITIONAL_ELSE {
in_else_body = true;
continue;
}
if child.kind() == CONDITIONAL_ENDIF {
break;
}
if in_else_body {
body.push_str(child.to_string().as_str());
}
}
if body.is_empty() {
None
} else {
Some(body)
}
}
/// Remove this conditional from the makefile
pub fn remove(&mut self) -> Result<(), Error> {
let Some(parent) = self.syntax().parent() else {
return Err(Error::Parse(ParseError {
errors: vec![ErrorInfo {
message: "Cannot remove conditional: no parent node".to_string(),
line: 1,
context: "conditional_remove".to_string(),
}],
}));
};
remove_with_preceding_comments(self.syntax(), &parent);
Ok(())
}
/// Remove the conditional directives (ifdef/endif) but keep the body content
///
/// This "unwraps" the conditional, keeping only the if branch content.
/// Returns an error if the conditional has an else clause.
///
/// # Example
/// ```
/// use makefile_lossless::Makefile;
/// let mut makefile: Makefile = r#"ifdef DEBUG
/// VAR = debug
/// endif
/// "#.parse().unwrap();
/// let mut cond = makefile.conditionals().next().unwrap();
/// cond.unwrap().unwrap();
/// // Now makefile contains just "VAR = debug\n"
/// assert!(makefile.to_string().contains("VAR = debug"));
/// assert!(!makefile.to_string().contains("ifdef"));
/// ```
pub fn unwrap(&mut self) -> Result<(), Error> {
// Check if there's an else clause
if self.has_else() {
return Err(Error::Parse(ParseError {
errors: vec![ErrorInfo {
message: "Cannot unwrap conditional with else clause".to_string(),
line: 1,
context: "conditional_unwrap".to_string(),
}],
}));
}
let Some(parent) = self.syntax().parent() else {
return Err(Error::Parse(ParseError {
errors: vec![ErrorInfo {
message: "Cannot unwrap conditional: no parent node".to_string(),
line: 1,
context: "conditional_unwrap".to_string(),
}],
}));
};
// Collect the body items (everything between CONDITIONAL_IF and CONDITIONAL_ENDIF)
let body_nodes: Vec<_> = self
.syntax()
.children_with_tokens()
.skip_while(|n| n.kind() != CONDITIONAL_IF)
.skip(1) // Skip CONDITIONAL_IF itself
.take_while(|n| n.kind() != CONDITIONAL_ENDIF)
.collect();
// Find the position of this conditional in parent
let conditional_index = self.syntax().index();
// Replace the entire conditional with just its body items
parent.splice_children(conditional_index..conditional_index + 1, body_nodes);
Ok(())
}
/// Get all items (rules, variables, includes, nested conditionals) in the if branch
///
/// # Example
/// ```
/// use makefile_lossless::Makefile;
/// let makefile: Makefile = r#"ifdef DEBUG
/// VAR = debug
/// rule:
/// command
/// endif
/// "#.parse().unwrap();
/// let cond = makefile.conditionals().next().unwrap();
/// let items: Vec<_> = cond.if_items().collect();
/// assert_eq!(items.len(), 2); // One variable, one rule
/// ```
pub fn if_items(&self) -> impl Iterator<Item = MakefileItem> + '_ {
self.syntax()
.children()
.skip_while(|n| n.kind() != CONDITIONAL_IF)
.skip(1) // Skip the CONDITIONAL_IF itself
.take_while(|n| n.kind() != CONDITIONAL_ELSE && n.kind() != CONDITIONAL_ENDIF)
.filter_map(MakefileItem::cast)
}
/// Get all items (rules, variables, includes, nested conditionals) in the else branch
///
/// # Example
/// ```
/// use makefile_lossless::Makefile;
/// let makefile: Makefile = r#"ifdef DEBUG
/// VAR = debug
/// else
/// VAR = release
/// endif
/// "#.parse().unwrap();
/// let cond = makefile.conditionals().next().unwrap();
/// let items: Vec<_> = cond.else_items().collect();
/// assert_eq!(items.len(), 1); // One variable in else branch
/// ```
pub fn else_items(&self) -> impl Iterator<Item = MakefileItem> + '_ {
self.syntax()
.children()
.skip_while(|n| n.kind() != CONDITIONAL_ELSE)
.skip(1) // Skip the CONDITIONAL_ELSE itself
.take_while(|n| n.kind() != CONDITIONAL_ENDIF)
.filter_map(MakefileItem::cast)
}
/// Add an item to the if branch of the conditional
///
/// # Example
/// ```
/// use makefile_lossless::{Makefile, MakefileItem};
/// let mut makefile: Makefile = "ifdef DEBUG\nendif\n".parse().unwrap();
/// let mut cond = makefile.conditionals().next().unwrap();
/// let temp: Makefile = "CFLAGS = -g\n".parse().unwrap();
/// let var = temp.variable_definitions().next().unwrap();
/// cond.add_if_item(MakefileItem::Variable(var));
/// assert!(makefile.to_string().contains("CFLAGS = -g"));
/// ```
pub fn add_if_item(&mut self, item: MakefileItem) {
let item_node = item.syntax().clone();
// Find position after CONDITIONAL_IF
let insert_pos = self
.syntax()
.children_with_tokens()
.position(|n| n.kind() == CONDITIONAL_IF)
.map(|p| p + 1)
.unwrap_or(0);
self.syntax()
.splice_children(insert_pos..insert_pos, vec![item_node.into()]);
}
/// Add an item to the else branch of the conditional
///
/// If the conditional doesn't have an else branch, this will create one.
///
/// # Example
/// ```
/// use makefile_lossless::{Makefile, MakefileItem};
/// let mut makefile: Makefile = "ifdef DEBUG\nVAR=1\nendif\n".parse().unwrap();
/// let mut cond = makefile.conditionals().next().unwrap();
/// let temp: Makefile = "CFLAGS = -O2\n".parse().unwrap();
/// let var = temp.variable_definitions().next().unwrap();
/// cond.add_else_item(MakefileItem::Variable(var));
/// assert!(makefile.to_string().contains("else"));
/// assert!(makefile.to_string().contains("CFLAGS = -O2"));
/// ```
pub fn add_else_item(&mut self, item: MakefileItem) {
// Ensure there's an else clause
if !self.has_else() {
self.add_else_clause();
}
let item_node = item.syntax().clone();
// Find position after CONDITIONAL_ELSE
let insert_pos = self
.syntax()
.children_with_tokens()
.position(|n| n.kind() == CONDITIONAL_ELSE)
.map(|p| p + 1)
.unwrap_or(0);
self.syntax()
.splice_children(insert_pos..insert_pos, vec![item_node.into()]);
}
/// Add an else clause to the conditional if it doesn't already have one
fn add_else_clause(&mut self) {
if self.has_else() {
return;
}
let mut builder = GreenNodeBuilder::new();
builder.start_node(CONDITIONAL_ELSE.into());
builder.token(IDENTIFIER.into(), "else");
builder.token(NEWLINE.into(), "\n");
builder.finish_node();
let syntax = SyntaxNode::new_root_mut(builder.finish());
// Find position before CONDITIONAL_ENDIF
let insert_pos = self
.syntax()
.children_with_tokens()
.position(|n| n.kind() == CONDITIONAL_ENDIF)
.unwrap_or(self.syntax().children_with_tokens().count());
self.syntax()
.splice_children(insert_pos..insert_pos, vec![syntax.into()]);
}
}
#[cfg(test)]
mod tests {
use crate::lossless::Makefile;
#[test]
fn test_conditional_parent() {
let makefile: Makefile = r#"ifdef DEBUG
VAR = debug
endif
"#
.parse()
.unwrap();
let cond = makefile.conditionals().next().unwrap();
let parent = cond.parent();
// Parent is ROOT node which doesn't cast to MakefileItem
assert!(parent.is_none());
}
}