| 1 | use crate::lex::lex; |
| 2 | use crate::MakefileVariant; |
| 3 | use crate::SyntaxKind; |
| 4 | use crate::SyntaxKind::*; |
| 5 | use rowan::ast::AstNode; |
| 6 | use std::str::FromStr; |
| 7 | |
| 8 | #[derive(Debug)] |
| 9 | /// An error that can occur when parsing a makefile |
| 10 | pub enum Error { |
| 11 | /// An I/O error occurred |
| 12 | Io(std::io::Error), |
| 13 | |
| 14 | /// A parse error occurred |
| 15 | Parse(ParseError), |
| 16 | } |
| 17 | |
| 18 | impl std::fmt::Display for Error { |
| 19 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 20 | match &self { |
| 21 | Error::Io(e) => write!(f, "IO error: {}", e), |
| 22 | Error::Parse(e) => write!(f, "Parse error: {}", e), |
| 23 | } |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | impl From<std::io::Error> for Error { |
| 28 | fn from(e: std::io::Error) -> Self { |
| 29 | Error::Io(e) |
| 30 | } |
| 31 | } |
| 32 | |
| 33 | impl std::error::Error for Error {} |
| 34 | |
| 35 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 36 | /// An error that occurred while parsing a makefile |
| 37 | pub struct ParseError { |
| 38 | /// The list of individual parsing errors |
| 39 | pub errors: Vec<ErrorInfo>, |
| 40 | } |
| 41 | |
| 42 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 43 | /// Information about a specific parsing error |
| 44 | pub struct ErrorInfo { |
| 45 | /// The error message |
| 46 | pub message: String, |
| 47 | /// The line number where the error occurred |
| 48 | pub line: usize, |
| 49 | /// The context around the error |
| 50 | pub context: String, |
| 51 | } |
| 52 | |
| 53 | impl std::fmt::Display for ParseError { |
| 54 | fn fmt(&self, f: &mut std::fmt::Formatter) -> std::fmt::Result { |
| 55 | for err in &self.errors { |
| 56 | writeln!(f, "Error at line {}: {}", err.line, err.message)?; |
| 57 | writeln!(f, "{}| {}", err.line, err.context)?; |
| 58 | } |
| 59 | Ok(()) |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl std::error::Error for ParseError {} |
| 64 | |
| 65 | impl From<ParseError> for Error { |
| 66 | fn from(e: ParseError) -> Self { |
| 67 | Error::Parse(e) |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | /// A positioned parse error containing location information. |
| 72 | #[derive(Debug, Clone, PartialEq, Eq, Hash)] |
| 73 | pub struct PositionedParseError { |
| 74 | /// The error message |
| 75 | pub message: String, |
| 76 | /// The text range where the error occurred |
| 77 | pub range: rowan::TextRange, |
| 78 | /// Optional error code for categorization |
| 79 | pub code: Option<String>, |
| 80 | } |
| 81 | |
| 82 | impl std::fmt::Display for PositionedParseError { |
| 83 | fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { |
| 84 | write!(f, "{}", self.message) |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | impl std::error::Error for PositionedParseError {} |
| 89 | |
| 90 | /// these two SyntaxKind types, allowing for a nicer SyntaxNode API where |
| 91 | /// "kinds" are values from our `enum SyntaxKind`, instead of plain u16 values. |
| 92 | #[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)] |
| 93 | pub enum Lang {} |
| 94 | impl rowan::Language for Lang { |
| 95 | type Kind = SyntaxKind; |
| 96 | fn kind_from_raw(raw: rowan::SyntaxKind) -> Self::Kind { |
| 97 | unsafe { std::mem::transmute::<u16, SyntaxKind>(raw.0) } |
| 98 | } |
| 99 | fn kind_to_raw(kind: Self::Kind) -> rowan::SyntaxKind { |
| 100 | kind.into() |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | /// GreenNode is an immutable tree, which is cheap to change, |
| 105 | /// but doesn't contain offsets and parent pointers. |
| 106 | use rowan::GreenNode; |
| 107 | |
| 108 | /// You can construct GreenNodes by hand, but a builder |
| 109 | /// is helpful for top-down parsers: it maintains a stack |
| 110 | /// of currently in-progress nodes |
| 111 | use rowan::GreenNodeBuilder; |
| 112 | |
| 113 | /// The parse results are stored as a "green tree". |
| 114 | /// We'll discuss working with the results later |
| 115 | #[derive(Debug)] |
| 116 | pub(crate) struct Parse { |
| 117 | pub(crate) green_node: GreenNode, |
| 118 | pub(crate) errors: Vec<ErrorInfo>, |
| 119 | pub(crate) positioned_errors: Vec<PositionedParseError>, |
| 120 | } |
| 121 | |
| 122 | pub(crate) fn parse(text: &str, variant: Option<MakefileVariant>) -> Parse { |
| 123 | struct Parser { |
| 124 | /// input tokens, including whitespace, |
| 125 | /// in *reverse* order. |
| 126 | tokens: Vec<(SyntaxKind, String)>, |
| 127 | /// the in-progress tree. |
| 128 | builder: GreenNodeBuilder<'static>, |
| 129 | /// the list of syntax errors we've accumulated |
| 130 | /// so far. |
| 131 | errors: Vec<ErrorInfo>, |
| 132 | /// positioned errors with location information |
| 133 | positioned_errors: Vec<PositionedParseError>, |
| 134 | /// Token positions (start, end) in forward order, indexed by forward token index |
| 135 | token_positions: Vec<(rowan::TextSize, rowan::TextSize)>, |
| 136 | /// current token index into token_positions (counting from the end since tokens are in reverse) |
| 137 | current_token_index: usize, |
| 138 | /// The original text |
| 139 | original_text: String, |
| 140 | /// The makefile variant |
| 141 | variant: Option<MakefileVariant>, |
| 142 | /// Parity of the current run of bumped BACKSLASH tokens: true once an |
| 143 | /// odd number have been seen, meaning the next backslash is escaped |
| 144 | /// (`\\`) and a following newline is a literal backslash, not a line |
| 145 | /// continuation. Reset to false by any other token. Mirrors the lexer's |
| 146 | /// `prev_was_backslash`, which makes the same decision for tokenizing |
| 147 | /// the continued line's indent. |
| 148 | pending_backslash_escape: bool, |
| 149 | } |
| 150 | |
| 151 | impl Parser { |
| 152 | fn error(&mut self, msg: String) { |
| 153 | self.builder.start_node(ERROR.into()); |
| 154 | |
| 155 | let (line, context) = if self.current() == Some(INDENT) { |
| 156 | // For indented lines, report the error on the next line |
| 157 | let lines: Vec<&str> = self.original_text.lines().collect(); |
| 158 | let tab_line = lines |
| 159 | .iter() |
| 160 | .enumerate() |
| 161 | .find(|(_, line)| line.starts_with('\t')) |
| 162 | .map(|(i, _)| i + 1) |
| 163 | .unwrap_or(1); |
| 164 | |
| 165 | // Use the next line as context if available |
| 166 | let next_line = tab_line + 1; |
| 167 | if next_line <= lines.len() { |
| 168 | (next_line, lines[next_line - 1].to_string()) |
| 169 | } else { |
| 170 | (tab_line, lines[tab_line - 1].to_string()) |
| 171 | } |
| 172 | } else { |
| 173 | let line = self.get_line_number_for_position(self.tokens.len()); |
| 174 | (line, self.get_context_for_line(line)) |
| 175 | }; |
| 176 | |
| 177 | let message = if self.current() == Some(INDENT) && !msg.contains("indented") { |
| 178 | if !self.tokens.is_empty() && self.tokens[self.tokens.len() - 1].0 == IDENTIFIER { |
| 179 | "expected ':'".to_string() |
| 180 | } else { |
| 181 | "indented line not part of a rule".to_string() |
| 182 | } |
| 183 | } else { |
| 184 | msg |
| 185 | }; |
| 186 | |
| 187 | self.errors.push(ErrorInfo { |
| 188 | message: message.clone(), |
| 189 | line, |
| 190 | context, |
| 191 | }); |
| 192 | |
| 193 | self.add_positioned_error(message, None); |
| 194 | |
| 195 | if self.current().is_some() { |
| 196 | self.bump(); |
| 197 | } |
| 198 | self.builder.finish_node(); |
| 199 | } |
| 200 | |
| 201 | /// Add a positioned error at the current token position |
| 202 | fn add_positioned_error(&mut self, message: String, code: Option<String>) { |
| 203 | let range = if self.current_token_index < self.token_positions.len() { |
| 204 | let (start, end) = self.token_positions[self.current_token_index]; |
| 205 | rowan::TextRange::new(start, end) |
| 206 | } else { |
| 207 | // Default to end of text if no current token |
| 208 | let end = self |
| 209 | .token_positions |
| 210 | .last() |
| 211 | .map(|(_, end)| *end) |
| 212 | .unwrap_or_else(|| rowan::TextSize::from(0)); |
| 213 | rowan::TextRange::new(end, end) |
| 214 | }; |
| 215 | |
| 216 | self.positioned_errors.push(PositionedParseError { |
| 217 | message, |
| 218 | range, |
| 219 | code, |
| 220 | }); |
| 221 | } |
| 222 | |
| 223 | fn get_line_number_for_position(&self, position: usize) -> usize { |
| 224 | if position >= self.tokens.len() { |
| 225 | return self.original_text.matches('\n').count() + 1; |
| 226 | } |
| 227 | |
| 228 | // Count newlines in the processed text up to this position |
| 229 | self.tokens[0..position] |
| 230 | .iter() |
| 231 | .filter(|(kind, _)| *kind == NEWLINE) |
| 232 | .count() |
| 233 | + 1 |
| 234 | } |
| 235 | |
| 236 | fn get_context_for_line(&self, line_number: usize) -> String { |
| 237 | self.original_text |
| 238 | .lines() |
| 239 | .nth(line_number - 1) |
| 240 | .unwrap_or("") |
| 241 | .to_string() |
| 242 | } |
| 243 | |
| 244 | fn parse_recipe_line(&mut self) { |
| 245 | self.builder.start_node(RECIPE.into()); |
| 246 | |
| 247 | // Check for and consume the indent |
| 248 | if self.current() != Some(INDENT) { |
| 249 | self.error("recipe line must start with a tab".to_string()); |
| 250 | self.builder.finish_node(); |
| 251 | return; |
| 252 | } |
| 253 | self.bump(); |
| 254 | |
| 255 | // Parse the recipe content, handling line continuations (backslash at end of line) |
| 256 | loop { |
| 257 | let mut last_text_content: Option<String> = None; |
| 258 | |
| 259 | // Consume all tokens until newline, tracking the last TEXT token's content |
| 260 | while self.current().is_some() && self.current() != Some(NEWLINE) { |
| 261 | // Save the text content if this is a TEXT token |
| 262 | if self.current() == Some(TEXT) { |
| 263 | if let Some((_kind, text)) = self.tokens.last() { |
| 264 | last_text_content = Some(text.clone()); |
| 265 | } |
| 266 | } |
| 267 | self.bump(); |
| 268 | } |
| 269 | |
| 270 | // Consume the newline |
| 271 | if self.current() == Some(NEWLINE) { |
| 272 | self.bump(); |
| 273 | } |
| 274 | |
| 275 | // Check if the last TEXT token ended with a backslash (continuation) |
| 276 | let is_continuation = last_text_content |
| 277 | .as_ref() |
| 278 | .map(|text| text.trim_end().ends_with('\\')) |
| 279 | .unwrap_or(false); |
| 280 | |
| 281 | if is_continuation { |
| 282 | // This is a continuation line - consume the indent of the next line and continue |
| 283 | if self.current() == Some(INDENT) { |
| 284 | self.bump(); |
| 285 | // Continue parsing the next line |
| 286 | continue; |
| 287 | } else { |
| 288 | // If there's no indent after a backslash, that's unusual but we'll stop here |
| 289 | break; |
| 290 | } |
| 291 | } else { |
| 292 | // No continuation - we're done |
| 293 | break; |
| 294 | } |
| 295 | } |
| 296 | |
| 297 | self.builder.finish_node(); |
| 298 | } |
| 299 | |
| 300 | fn parse_rule_target(&mut self) -> bool { |
| 301 | match self.current() { |
| 302 | Some(IDENTIFIER) => { |
| 303 | // Check if this is an archive member (e.g., libfoo.a(bar.o)) |
| 304 | if self.is_archive_member() { |
| 305 | self.parse_archive_member(); |
| 306 | } else { |
| 307 | self.bump(); |
| 308 | } |
| 309 | true |
| 310 | } |
| 311 | Some(DOLLAR) => { |
| 312 | self.parse_variable_reference(); |
| 313 | true |
| 314 | } |
| 315 | _ => { |
| 316 | self.error("expected rule target".to_string()); |
| 317 | false |
| 318 | } |
| 319 | } |
| 320 | } |
| 321 | |
| 322 | fn is_archive_member(&self) -> bool { |
| 323 | // Check if the current identifier is followed by a parenthesis |
| 324 | // Pattern: archive.a(member.o) |
| 325 | if self.tokens.len() < 2 { |
| 326 | return false; |
| 327 | } |
| 328 | |
| 329 | // Look for pattern: IDENTIFIER LPAREN |
| 330 | let current_is_identifier = self.current() == Some(IDENTIFIER); |
| 331 | let next_is_lparen = |
| 332 | self.tokens.len() > 1 && self.tokens[self.tokens.len() - 2].0 == LPAREN; |
| 333 | |
| 334 | current_is_identifier && next_is_lparen |
| 335 | } |
| 336 | |
| 337 | fn parse_archive_member(&mut self) { |
| 338 | // We're parsing something like: libfoo.a(bar.o baz.o) |
| 339 | // Structure will be: |
| 340 | // - IDENTIFIER: libfoo.a |
| 341 | // - LPAREN |
| 342 | // - ARCHIVE_MEMBERS |
| 343 | // - ARCHIVE_MEMBER: bar.o |
| 344 | // - ARCHIVE_MEMBER: baz.o |
| 345 | // - RPAREN |
| 346 | |
| 347 | // Parse archive name |
| 348 | if self.current() == Some(IDENTIFIER) { |
| 349 | self.bump(); |
| 350 | } |
| 351 | |
| 352 | // Parse opening parenthesis |
| 353 | if self.current() == Some(LPAREN) { |
| 354 | self.bump(); |
| 355 | |
| 356 | // Start the ARCHIVE_MEMBERS container for just the members |
| 357 | self.builder.start_node(ARCHIVE_MEMBERS.into()); |
| 358 | |
| 359 | // Parse member name(s) - each as an ARCHIVE_MEMBER node |
| 360 | while self.current().is_some() && self.current() != Some(RPAREN) { |
| 361 | match self.current() { |
| 362 | Some(IDENTIFIER) | Some(TEXT) => { |
| 363 | // Start an individual member node |
| 364 | self.builder.start_node(ARCHIVE_MEMBER.into()); |
| 365 | self.bump(); |
| 366 | self.builder.finish_node(); |
| 367 | } |
| 368 | Some(WHITESPACE) => self.bump(), |
| 369 | Some(DOLLAR) => { |
| 370 | // Variable reference can also be a member |
| 371 | self.builder.start_node(ARCHIVE_MEMBER.into()); |
| 372 | self.parse_variable_reference(); |
| 373 | self.builder.finish_node(); |
| 374 | } |
| 375 | _ => break, |
| 376 | } |
| 377 | } |
| 378 | |
| 379 | // Finish the ARCHIVE_MEMBERS container |
| 380 | self.builder.finish_node(); |
| 381 | |
| 382 | // Parse closing parenthesis |
| 383 | if self.current() == Some(RPAREN) { |
| 384 | self.bump(); |
| 385 | } else { |
| 386 | self.error("expected ')' to close archive member".to_string()); |
| 387 | } |
| 388 | } |
| 389 | } |
| 390 | |
| 391 | fn parse_rule_dependencies(&mut self) { |
| 392 | self.builder.start_node(PREREQUISITES.into()); |
| 393 | |
| 394 | while self.current().is_some() && self.current() != Some(NEWLINE) { |
| 395 | // The prerequisite list may continue on the next physical line. |
| 396 | if self.consume_line_continuation() { |
| 397 | continue; |
| 398 | } |
| 399 | match self.current() { |
| 400 | Some(WHITESPACE) => { |
| 401 | self.bump(); // Consume whitespace between prerequisites |
| 402 | } |
| 403 | Some(COMMENT) => { |
| 404 | // Trailing comment ends the prerequisite list. |
| 405 | self.bump(); |
| 406 | } |
| 407 | Some(_) => { |
| 408 | // Collect contiguous non-whitespace tokens into one |
| 409 | // PREREQUISITE node, preserving structures like |
| 410 | // `$$(@:.out=.src)` or `lib(member.o)` as a single |
| 411 | // word. |
| 412 | self.parse_prerequisite_word(); |
| 413 | } |
| 414 | None => break, |
| 415 | } |
| 416 | } |
| 417 | |
| 418 | self.builder.finish_node(); // End PREREQUISITES |
| 419 | } |
| 420 | |
| 421 | /// Parse a single prerequisite word: consume tokens up to the next |
| 422 | /// whitespace/newline/comment, descending into variable references |
| 423 | /// (`$(...)`, `${...}`, `$X`, `$$`) and archive-member parentheses |
| 424 | /// without treating them as word boundaries. |
| 425 | fn parse_prerequisite_word(&mut self) { |
| 426 | self.builder.start_node(PREREQUISITE.into()); |
| 427 | |
| 428 | // Archive member syntax: `lib(member.o)` — keep as a unit. |
| 429 | if self.current() == Some(IDENTIFIER) && self.is_archive_member() { |
| 430 | self.parse_archive_member(); |
| 431 | self.builder.finish_node(); |
| 432 | return; |
| 433 | } |
| 434 | |
| 435 | // Otherwise, consume tokens until a separator. A line continuation |
| 436 | // ends the word; the outer loop consumes it and resumes on the |
| 437 | // next physical line. |
| 438 | while let Some(kind) = self.current() { |
| 439 | match kind { |
| 440 | WHITESPACE | NEWLINE | COMMENT => break, |
| 441 | BACKSLASH if self.is_line_continuation() => break, |
| 442 | DOLLAR => self.parse_variable_reference(), |
| 443 | _ => self.bump(), |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | self.builder.finish_node(); // End PREREQUISITE |
| 448 | } |
| 449 | |
| 450 | fn parse_rule_recipes(&mut self) { |
| 451 | // Track how many levels deep we are in conditionals that started in this rule |
| 452 | let mut conditional_depth = 0; |
| 453 | // Also track consecutive newlines to detect blank lines |
| 454 | let mut newline_count = 0; |
| 455 | |
| 456 | loop { |
| 457 | match self.current() { |
| 458 | Some(INDENT) => { |
| 459 | newline_count = 0; |
| 460 | self.parse_recipe_line(); |
| 461 | } |
| 462 | Some(NEWLINE) => { |
| 463 | newline_count += 1; |
| 464 | self.bump(); |
| 465 | } |
| 466 | Some(COMMENT) => { |
| 467 | // Comments after blank lines should not be part of the rule |
| 468 | if conditional_depth == 0 && newline_count >= 1 { |
| 469 | break; |
| 470 | } |
| 471 | newline_count = 0; |
| 472 | self.parse_comment(); |
| 473 | } |
| 474 | Some(IDENTIFIER) => { |
| 475 | let token = &self.tokens.last().unwrap().1.clone(); |
| 476 | // Check if this is a starting conditional directive |
| 477 | if Self::is_conditional_start(token) |
| 478 | && matches!(self.variant, None | Some(MakefileVariant::GNUMake)) |
| 479 | { |
| 480 | // If we're not inside a conditional (depth == 0) and there's a blank line, |
| 481 | // this is a top-level conditional, not part of the rule |
| 482 | if conditional_depth == 0 && newline_count >= 1 { |
| 483 | break; |
| 484 | } |
| 485 | newline_count = 0; |
| 486 | conditional_depth += 1; |
| 487 | self.parse_conditional(); |
| 488 | // parse_conditional() handles the entire conditional including endif, |
| 489 | // so we need to decrement after it returns |
| 490 | conditional_depth -= 1; |
| 491 | } else if token == "include" || token == "-include" || token == "sinclude" { |
| 492 | // Includes can appear in rules, with same blank line logic |
| 493 | if conditional_depth == 0 && newline_count >= 1 { |
| 494 | break; |
| 495 | } |
| 496 | newline_count = 0; |
| 497 | self.parse_include(); |
| 498 | } else if token == "else" || token == "endif" { |
| 499 | // These should only appear if we're inside a conditional |
| 500 | // If we see them at depth 0, something is wrong, so break |
| 501 | break; |
| 502 | } else { |
| 503 | // Any other identifier at depth 0 means the rule is over |
| 504 | if conditional_depth == 0 { |
| 505 | break; |
| 506 | } |
| 507 | // Otherwise, it's content inside a conditional (variable assignment, etc.) |
| 508 | // Let it be handled by parse_normal_content |
| 509 | break; |
| 510 | } |
| 511 | } |
| 512 | _ => break, |
| 513 | } |
| 514 | } |
| 515 | } |
| 516 | |
| 517 | fn find_and_consume_colon(&mut self) -> bool { |
| 518 | // Skip whitespace before colon |
| 519 | self.skip_ws(); |
| 520 | |
| 521 | // Check if we're at a colon or double-colon |
| 522 | if self.current() == Some(OPERATOR) |
| 523 | && matches!(self.tokens.last().unwrap().1.as_str(), ":" | "::") |
| 524 | { |
| 525 | self.bump(); |
| 526 | return true; |
| 527 | } |
| 528 | |
| 529 | // Look ahead for a colon on the same line |
| 530 | let has_colon = self |
| 531 | .tokens |
| 532 | .iter() |
| 533 | .rev() |
| 534 | .take_while(|(kind, _)| *kind != NEWLINE) |
| 535 | .any(|(kind, text)| *kind == OPERATOR && (text == ":" || text == "::")); |
| 536 | |
| 537 | if has_colon { |
| 538 | // Consume tokens until we find the colon (staying on same line) |
| 539 | while self.current().is_some() && self.current() != Some(NEWLINE) { |
| 540 | if self.current() == Some(OPERATOR) |
| 541 | && matches!( |
| 542 | self.tokens.last().map(|(_, text)| text.as_str()), |
| 543 | Some(":" | "::") |
| 544 | ) |
| 545 | { |
| 546 | self.bump(); |
| 547 | return true; |
| 548 | } |
| 549 | self.bump(); |
| 550 | } |
| 551 | } |
| 552 | |
| 553 | self.error("expected ':'".to_string()); |
| 554 | false |
| 555 | } |
| 556 | |
| 557 | fn parse_rule(&mut self) { |
| 558 | self.builder.start_node(RULE.into()); |
| 559 | |
| 560 | // Parse targets in a TARGETS node |
| 561 | self.skip_ws(); |
| 562 | self.builder.start_node(TARGETS.into()); |
| 563 | let has_target = self.parse_rule_targets(); |
| 564 | self.builder.finish_node(); |
| 565 | |
| 566 | // Find and consume the colon |
| 567 | let has_colon = if has_target { |
| 568 | self.find_and_consume_colon() |
| 569 | } else { |
| 570 | false |
| 571 | }; |
| 572 | |
| 573 | // Parse dependencies if we found both target and colon |
| 574 | if has_target && has_colon { |
| 575 | self.skip_ws(); |
| 576 | |
| 577 | // Detect a target-specific variable assignment: |
| 578 | // target: VAR [op] value |
| 579 | // by peeking IDENTIFIER (WS)? OPERATOR. If matched, treat |
| 580 | // the line as a scoped assignment (no prerequisites, no |
| 581 | // recipe) and produce a child VARIABLE node so callers can |
| 582 | // use the existing VariableDefinition accessors. |
| 583 | if self.looks_like_target_specific_assignment() { |
| 584 | self.parse_target_specific_assignment(); |
| 585 | } else { |
| 586 | self.parse_rule_dependencies(); |
| 587 | self.expect_eol(); |
| 588 | |
| 589 | // Parse recipe lines |
| 590 | self.parse_rule_recipes(); |
| 591 | } |
| 592 | } |
| 593 | |
| 594 | self.builder.finish_node(); |
| 595 | } |
| 596 | |
| 597 | /// Look ahead (without consuming) for the `IDENTIFIER (WS)? OPERATOR` |
| 598 | /// pattern that marks a target-specific variable assignment such as |
| 599 | /// `all: CFLAGS = -O2`. |
| 600 | fn looks_like_target_specific_assignment(&self) -> bool { |
| 601 | // tokens is reversed (last = current). We look from the end. |
| 602 | let n = self.tokens.len(); |
| 603 | if n < 2 { |
| 604 | return false; |
| 605 | } |
| 606 | // Current token must be an IDENTIFIER (the variable name). |
| 607 | if self.tokens[n - 1].0 != IDENTIFIER { |
| 608 | return false; |
| 609 | } |
| 610 | let mut i = n - 2; |
| 611 | // Optional whitespace. |
| 612 | if self.tokens[i].0 == WHITESPACE { |
| 613 | if i == 0 { |
| 614 | return false; |
| 615 | } |
| 616 | i -= 1; |
| 617 | } |
| 618 | // Next token must be an assignment OPERATOR. |
| 619 | self.tokens[i].0 == OPERATOR |
| 620 | && matches!( |
| 621 | self.tokens[i].1.as_str(), |
| 622 | "=" | ":=" | "::=" | ":::=" | "+=" | "?=" | "!=" |
| 623 | ) |
| 624 | } |
| 625 | |
| 626 | /// Parse `VAR [op] value` after the rule's `:` colon, wrapped in a |
| 627 | /// child `VARIABLE` node. Consumes through the end-of-line. |
| 628 | fn parse_target_specific_assignment(&mut self) { |
| 629 | self.builder.start_node(VARIABLE.into()); |
| 630 | // Variable name (IDENTIFIER). |
| 631 | self.bump(); |
| 632 | self.skip_ws(); |
| 633 | // Assignment operator. |
| 634 | if self.current() == Some(OPERATOR) { |
| 635 | self.bump(); |
| 636 | } |
| 637 | // Optional whitespace before the value. |
| 638 | self.skip_ws(); |
| 639 | // Value lives in an EXPR node, like normal assignments. |
| 640 | self.builder.start_node(EXPR.into()); |
| 641 | while self.current().is_some() && self.current() != Some(NEWLINE) { |
| 642 | self.bump(); |
| 643 | } |
| 644 | self.builder.finish_node(); // EXPR |
| 645 | if self.current() == Some(NEWLINE) { |
| 646 | self.bump(); |
| 647 | } |
| 648 | self.builder.finish_node(); // VARIABLE |
| 649 | } |
| 650 | |
| 651 | fn parse_rule_targets(&mut self) -> bool { |
| 652 | // Parse first target |
| 653 | let has_first_target = self.parse_rule_target(); |
| 654 | |
| 655 | if !has_first_target { |
| 656 | return false; |
| 657 | } |
| 658 | |
| 659 | // Parse additional targets until we hit the colon |
| 660 | loop { |
| 661 | self.skip_ws(); |
| 662 | |
| 663 | // Check if we're at a colon |
| 664 | if self.current() == Some(OPERATOR) && self.tokens.last().unwrap().1 == ":" { |
| 665 | break; |
| 666 | } |
| 667 | |
| 668 | // The target list may continue on the next physical line. |
| 669 | if self.consume_line_continuation() { |
| 670 | continue; |
| 671 | } |
| 672 | |
| 673 | // Try to parse another target |
| 674 | match self.current() { |
| 675 | Some(IDENTIFIER) | Some(DOLLAR) => { |
| 676 | if !self.parse_rule_target() { |
| 677 | break; |
| 678 | } |
| 679 | } |
| 680 | _ => break, |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | true |
| 685 | } |
| 686 | |
| 687 | /// Returns true if the current token is an unescaped BACKSLASH |
| 688 | /// immediately followed by a NEWLINE (a line continuation). A backslash |
| 689 | /// preceded by an odd run of backslashes is itself escaped (`\\`) and |
| 690 | /// does not continue the line. |
| 691 | fn is_line_continuation(&self) -> bool { |
| 692 | !self.pending_backslash_escape |
| 693 | && self.current() == Some(BACKSLASH) |
| 694 | && self.tokens.len() >= 2 |
| 695 | && self.tokens[self.tokens.len() - 2].0 == NEWLINE |
| 696 | } |
| 697 | |
| 698 | /// Consume a backslash-newline line continuation and any indentation on |
| 699 | /// the continued line, so the caller keeps reading the logical line. |
| 700 | /// Returns false if the current position is not a line continuation. |
| 701 | fn consume_line_continuation(&mut self) -> bool { |
| 702 | if !self.is_line_continuation() { |
| 703 | return false; |
| 704 | } |
| 705 | self.bump(); // backslash |
| 706 | self.bump(); // newline |
| 707 | if self.current() == Some(INDENT) { |
| 708 | self.bump(); |
| 709 | } |
| 710 | true |
| 711 | } |
| 712 | |
| 713 | fn parse_comment(&mut self) { |
| 714 | if self.current() == Some(COMMENT) { |
| 715 | self.bump(); // Consume the comment token |
| 716 | |
| 717 | // Handle end of line or file after comment |
| 718 | if self.current() == Some(NEWLINE) { |
| 719 | self.bump(); // Consume the newline |
| 720 | } else if self.current() == Some(WHITESPACE) { |
| 721 | // For whitespace after a comment, just consume it |
| 722 | self.skip_ws(); |
| 723 | if self.current() == Some(NEWLINE) { |
| 724 | self.bump(); |
| 725 | } |
| 726 | } |
| 727 | // If we're at EOF after a comment, that's fine |
| 728 | } else { |
| 729 | self.error("expected comment".to_string()); |
| 730 | } |
| 731 | } |
| 732 | |
| 733 | fn parse_assignment(&mut self) { |
| 734 | self.builder.start_node(VARIABLE.into()); |
| 735 | |
| 736 | // Handle `override` and `export` prefixes (in either order). Both |
| 737 | // are independent modifiers on a variable assignment. |
| 738 | self.skip_ws(); |
| 739 | for _ in 0..2 { |
| 740 | if self.current() == Some(IDENTIFIER) |
| 741 | && matches!( |
| 742 | self.tokens.last().unwrap().1.as_str(), |
| 743 | "export" | "override" |
| 744 | ) |
| 745 | { |
| 746 | self.bump(); |
| 747 | self.skip_ws(); |
| 748 | } else { |
| 749 | break; |
| 750 | } |
| 751 | } |
| 752 | |
| 753 | // Parse variable name |
| 754 | match self.current() { |
| 755 | Some(IDENTIFIER) => self.bump(), |
| 756 | Some(DOLLAR) => self.parse_variable_reference(), |
| 757 | _ => { |
| 758 | self.error("expected variable name".to_string()); |
| 759 | self.builder.finish_node(); |
| 760 | return; |
| 761 | } |
| 762 | } |
| 763 | |
| 764 | // Skip whitespace and parse operator |
| 765 | self.skip_ws(); |
| 766 | match self.current() { |
| 767 | Some(OPERATOR) => { |
| 768 | let op = &self.tokens.last().unwrap().1; |
| 769 | if ["=", ":=", "::=", ":::=", "+=", "?=", "!="].contains(&op.as_str()) { |
| 770 | self.bump(); |
| 771 | self.skip_ws(); |
| 772 | |
| 773 | // Parse value, creating nested EXPR nodes for |
| 774 | // variable references. A trailing `# comment` is |
| 775 | // left as a sibling COMMENT token, not bundled |
| 776 | // into the EXPR. |
| 777 | self.builder.start_node(EXPR.into()); |
| 778 | while self.current().is_some() |
| 779 | && self.current() != Some(NEWLINE) |
| 780 | && self.current() != Some(COMMENT) |
| 781 | { |
| 782 | // The value may continue on the next physical line. |
| 783 | if self.consume_line_continuation() { |
| 784 | continue; |
| 785 | } |
| 786 | if self.current() == Some(DOLLAR) { |
| 787 | self.parse_variable_reference(); |
| 788 | } else { |
| 789 | self.bump(); |
| 790 | } |
| 791 | } |
| 792 | self.builder.finish_node(); |
| 793 | |
| 794 | // Optional trailing comment. |
| 795 | if self.current() == Some(COMMENT) { |
| 796 | self.bump(); |
| 797 | } |
| 798 | |
| 799 | // Expect newline |
| 800 | if self.current() == Some(NEWLINE) { |
| 801 | self.bump(); |
| 802 | } else if !self.is_at_eof() { |
| 803 | self.error("expected newline after variable value".to_string()); |
| 804 | } |
| 805 | } else { |
| 806 | self.error(format!("invalid assignment operator: {}", op)); |
| 807 | } |
| 808 | } |
| 809 | // Bare "export VARNAME" without assignment operator is valid GNU Make |
| 810 | Some(NEWLINE) => { |
| 811 | self.bump(); |
| 812 | } |
| 813 | None => { |
| 814 | // EOF after export VARNAME is fine |
| 815 | } |
| 816 | _ => self.error("expected assignment operator".to_string()), |
| 817 | } |
| 818 | |
| 819 | self.builder.finish_node(); |
| 820 | } |
| 821 | |
| 822 | fn parse_variable_reference(&mut self) { |
| 823 | self.builder.start_node(EXPR.into()); |
| 824 | self.bump(); // Consume $ |
| 825 | |
| 826 | if self.current() == Some(LPAREN) || self.current() == Some(LBRACE) { |
| 827 | let is_brace = self.current() == Some(LBRACE); |
| 828 | self.bump(); // Consume ( or { |
| 829 | |
| 830 | if is_brace { |
| 831 | // For ${...}, consume until matching } |
| 832 | while self.current().is_some() && self.current() != Some(RBRACE) { |
| 833 | if self.current() == Some(DOLLAR) { |
| 834 | self.parse_variable_reference(); |
| 835 | } else { |
| 836 | self.bump(); |
| 837 | } |
| 838 | } |
| 839 | if self.current() == Some(RBRACE) { |
| 840 | self.bump(); // Consume } |
| 841 | } |
| 842 | } else { |
| 843 | // Start by checking if this is a function like $(shell ...) |
| 844 | let mut is_function = false; |
| 845 | |
| 846 | if self.current() == Some(IDENTIFIER) { |
| 847 | let function_name = &self.tokens.last().unwrap().1; |
| 848 | // Common makefile functions |
| 849 | let known_functions = [ |
| 850 | "shell", "wildcard", "call", "eval", "file", "abspath", "dir", |
| 851 | ]; |
| 852 | if known_functions.contains(&function_name.as_str()) { |
| 853 | is_function = true; |
| 854 | } |
| 855 | } |
| 856 | |
| 857 | if is_function { |
| 858 | // Preserve the function name |
| 859 | self.bump(); |
| 860 | |
| 861 | // Parse the rest of the function call, handling nested variable references |
| 862 | self.consume_balanced_parens(1); |
| 863 | } else { |
| 864 | // Handle regular variable references |
| 865 | self.parse_parenthesized_expr_internal(true); |
| 866 | } |
| 867 | } |
| 868 | } else if self.current().is_some() && self.current() != Some(NEWLINE) { |
| 869 | // Single character variable like $X or $$ |
| 870 | self.bump(); |
| 871 | } else { |
| 872 | self.error("expected variable name after $".to_string()); |
| 873 | } |
| 874 | |
| 875 | self.builder.finish_node(); |
| 876 | } |
| 877 | |
| 878 | // Helper method to parse a conditional comparison (ifeq/ifneq) |
| 879 | // Supports both syntaxes: (arg1,arg2) and "arg1" "arg2" |
| 880 | fn parse_parenthesized_expr(&mut self) { |
| 881 | self.builder.start_node(EXPR.into()); |
| 882 | |
| 883 | // Check if we have parenthesized or quoted syntax |
| 884 | if self.current() == Some(LPAREN) { |
| 885 | // Parenthesized syntax: ifeq (arg1,arg2) |
| 886 | self.bump(); // Consume opening paren |
| 887 | self.parse_parenthesized_expr_internal(false); |
| 888 | } else if self.current() == Some(QUOTE) { |
| 889 | // Quoted syntax: ifeq "arg1" "arg2" or ifeq 'arg1' 'arg2' |
| 890 | self.parse_quoted_comparison(); |
| 891 | } else { |
| 892 | self.error("expected opening parenthesis or quote".to_string()); |
| 893 | } |
| 894 | |
| 895 | self.builder.finish_node(); |
| 896 | } |
| 897 | |
| 898 | // Internal helper to parse parenthesized expressions |
| 899 | fn parse_parenthesized_expr_internal(&mut self, is_variable_ref: bool) { |
| 900 | let mut paren_count = 1; |
| 901 | // Each nested LPAREN opens an EXPR node that the matching RPAREN |
| 902 | // closes. If EOF arrives before those RPARENs do, we must still |
| 903 | // close them or the green tree ends up unbalanced (rowan panics |
| 904 | // in GreenNodeBuilder::finish). |
| 905 | let mut open_nested = 0u32; |
| 906 | |
| 907 | while paren_count > 0 && self.current().is_some() { |
| 908 | match self.current() { |
| 909 | Some(LPAREN) => { |
| 910 | paren_count += 1; |
| 911 | self.bump(); |
| 912 | // Start a new expression node for nested parentheses |
| 913 | self.builder.start_node(EXPR.into()); |
| 914 | open_nested += 1; |
| 915 | } |
| 916 | Some(RPAREN) => { |
| 917 | paren_count -= 1; |
| 918 | self.bump(); |
| 919 | if paren_count > 0 { |
| 920 | self.builder.finish_node(); |
| 921 | open_nested -= 1; |
| 922 | } |
| 923 | } |
| 924 | Some(QUOTE) => { |
| 925 | // Handle quoted strings |
| 926 | self.parse_quoted_string(); |
| 927 | } |
| 928 | Some(DOLLAR) => { |
| 929 | // Handle variable references |
| 930 | self.parse_variable_reference(); |
| 931 | } |
| 932 | Some(_) => self.bump(), |
| 933 | None => { |
| 934 | self.error(if is_variable_ref { |
| 935 | "unclosed variable reference".to_string() |
| 936 | } else { |
| 937 | "unclosed parenthesis".to_string() |
| 938 | }); |
| 939 | break; |
| 940 | } |
| 941 | } |
| 942 | } |
| 943 | |
| 944 | for _ in 0..open_nested { |
| 945 | self.builder.finish_node(); |
| 946 | } |
| 947 | |
| 948 | if !is_variable_ref { |
| 949 | self.skip_ws(); |
| 950 | self.expect_eol(); |
| 951 | } |
| 952 | } |
| 953 | |
| 954 | // Helper method to parse quoted comparison for ifeq/ifneq |
| 955 | // Handles: "arg1" "arg2" or 'arg1' 'arg2' |
| 956 | fn parse_quoted_comparison(&mut self) { |
| 957 | // First quoted string - lexer already tokenized the entire string |
| 958 | if self.current() == Some(QUOTE) { |
| 959 | self.bump(); // Consume the entire first quoted string token |
| 960 | } else { |
| 961 | self.error("expected first quoted argument".to_string()); |
| 962 | } |
| 963 | |
| 964 | // Skip whitespace between the two arguments |
| 965 | self.skip_ws(); |
| 966 | |
| 967 | // Second quoted string - lexer already tokenized the entire string |
| 968 | if self.current() == Some(QUOTE) { |
| 969 | self.bump(); // Consume the entire second quoted string token |
| 970 | } else { |
| 971 | self.error("expected second quoted argument".to_string()); |
| 972 | } |
| 973 | |
| 974 | // Skip trailing whitespace and expect end of line |
| 975 | self.skip_ws(); |
| 976 | self.expect_eol(); |
| 977 | } |
| 978 | |
| 979 | // Handle parsing a quoted string. The lexer emits the entire quoted |
| 980 | // string (including both delimiters) as a single QUOTE token, so we |
| 981 | // just consume that one token. |
| 982 | fn parse_quoted_string(&mut self) { |
| 983 | if self.current() == Some(QUOTE) { |
| 984 | self.bump(); |
| 985 | } |
| 986 | } |
| 987 | |
| 988 | fn parse_conditional_keyword(&mut self) -> Option<String> { |
| 989 | if self.current() != Some(IDENTIFIER) { |
| 990 | self.error( |
| 991 | "expected conditional keyword (ifdef, ifndef, ifeq, or ifneq)".to_string(), |
| 992 | ); |
| 993 | return None; |
| 994 | } |
| 995 | |
| 996 | let token = self.tokens.last().unwrap().1.clone(); |
| 997 | if !Self::is_conditional_start(&token) { |
| 998 | self.error(format!("unknown conditional directive: {}", token)); |
| 999 | return None; |
| 1000 | } |
| 1001 | |
| 1002 | self.bump(); |
| 1003 | Some(token) |
| 1004 | } |
| 1005 | |
| 1006 | fn parse_simple_condition(&mut self) { |
| 1007 | self.builder.start_node(EXPR.into()); |
| 1008 | |
| 1009 | // Skip any leading whitespace |
| 1010 | self.skip_ws(); |
| 1011 | |
| 1012 | // Collect variable names |
| 1013 | let mut found_var = false; |
| 1014 | |
| 1015 | while !self.is_at_eof() && self.current() != Some(NEWLINE) { |
| 1016 | match self.current() { |
| 1017 | Some(WHITESPACE) => self.skip_ws(), |
| 1018 | Some(DOLLAR) => { |
| 1019 | found_var = true; |
| 1020 | self.parse_variable_reference(); |
| 1021 | } |
| 1022 | Some(_) => { |
| 1023 | // Accept any token as part of condition |
| 1024 | found_var = true; |
| 1025 | self.bump(); |
| 1026 | } |
| 1027 | None => break, |
| 1028 | } |
| 1029 | } |
| 1030 | |
| 1031 | if !found_var { |
| 1032 | // Empty condition is an error in GNU Make |
| 1033 | self.error("expected condition after conditional directive".to_string()); |
| 1034 | } |
| 1035 | |
| 1036 | self.builder.finish_node(); |
| 1037 | |
| 1038 | // Expect end of line |
| 1039 | if self.current() == Some(NEWLINE) { |
| 1040 | self.bump(); |
| 1041 | } else if !self.is_at_eof() { |
| 1042 | self.skip_until_newline(); |
| 1043 | } |
| 1044 | } |
| 1045 | |
| 1046 | // Helper to check if a token starts a conditional block. |
| 1047 | // Note this requires an exact match: a variable named e.g. `ifpkg` |
| 1048 | // merely starts with "if" and is not a conditional directive. |
| 1049 | fn is_conditional_start(token: &str) -> bool { |
| 1050 | matches!(token, "ifdef" | "ifndef" | "ifeq" | "ifneq") |
| 1051 | } |
| 1052 | |
| 1053 | // Helper to check if a token is a conditional directive |
| 1054 | fn is_conditional_directive(&self, token: &str) -> bool { |
| 1055 | Self::is_conditional_start(token) || token == "else" || token == "endif" |
| 1056 | } |
| 1057 | |
| 1058 | // Helper method to handle conditional token |
| 1059 | fn handle_conditional_token(&mut self, token: &str, depth: &mut usize) -> bool { |
| 1060 | match token { |
| 1061 | "ifdef" | "ifndef" | "ifeq" | "ifneq" |
| 1062 | if matches!(self.variant, None | Some(MakefileVariant::GNUMake)) => |
| 1063 | { |
| 1064 | // Don't increment depth here - parse_conditional manages its own depth internally |
| 1065 | // Incrementing here causes the outer conditional to never exit its loop |
| 1066 | self.parse_conditional(); |
| 1067 | true |
| 1068 | } |
| 1069 | "else" => { |
| 1070 | // Not valid outside of a conditional |
| 1071 | if *depth == 0 { |
| 1072 | self.error("else without matching if".to_string()); |
| 1073 | // Always consume a token to guarantee progress |
| 1074 | self.bump(); |
| 1075 | false |
| 1076 | } else { |
| 1077 | // Start CONDITIONAL_ELSE node |
| 1078 | self.builder.start_node(CONDITIONAL_ELSE.into()); |
| 1079 | |
| 1080 | // Consume the 'else' token |
| 1081 | self.bump(); |
| 1082 | self.skip_ws(); |
| 1083 | |
| 1084 | // Check if this is "else <conditional>" (else ifdef, else ifeq, etc.) |
| 1085 | if self.current() == Some(IDENTIFIER) { |
| 1086 | let next_token = &self.tokens.last().unwrap().1; |
| 1087 | if Self::is_conditional_start(next_token) { |
| 1088 | // This is "else ifdef", "else ifeq", etc. |
| 1089 | // Parse the conditional part |
| 1090 | match next_token.as_str() { |
| 1091 | "ifdef" | "ifndef" => { |
| 1092 | self.bump(); // Consume the directive token |
| 1093 | self.skip_ws(); |
| 1094 | self.parse_simple_condition(); |
| 1095 | } |
| 1096 | "ifeq" | "ifneq" => { |
| 1097 | self.bump(); // Consume the directive token |
| 1098 | self.skip_ws(); |
| 1099 | self.parse_parenthesized_expr(); |
| 1100 | } |
| 1101 | _ => unreachable!(), |
| 1102 | } |
| 1103 | // The newline will be consumed by the conditional body loop |
| 1104 | } else { |
| 1105 | // Plain 'else' with something else after it (not a conditional keyword) |
| 1106 | // The newline will be consumed by the conditional body loop |
| 1107 | } |
| 1108 | } else { |
| 1109 | // Plain 'else' - the newline will be consumed by the conditional body loop |
| 1110 | } |
| 1111 | |
| 1112 | self.builder.finish_node(); // finish CONDITIONAL_ELSE |
| 1113 | true |
| 1114 | } |
| 1115 | } |
| 1116 | "endif" => { |
| 1117 | // Not valid outside of a conditional |
| 1118 | if *depth == 0 { |
| 1119 | self.error("endif without matching if".to_string()); |
| 1120 | // Always consume a token to guarantee progress |
| 1121 | self.bump(); |
| 1122 | false |
| 1123 | } else { |
| 1124 | *depth -= 1; |
| 1125 | |
| 1126 | // Start CONDITIONAL_ENDIF node |
| 1127 | self.builder.start_node(CONDITIONAL_ENDIF.into()); |
| 1128 | |
| 1129 | // Consume the endif |
| 1130 | self.bump(); |
| 1131 | |
| 1132 | // Be more permissive with what follows endif |
| 1133 | self.skip_ws(); |
| 1134 | |
| 1135 | // Handle common patterns after endif: |
| 1136 | // 1. Comments: endif # comment |
| 1137 | // 2. Whitespace at end of file |
| 1138 | // 3. Newlines |
| 1139 | if self.current() == Some(COMMENT) { |
| 1140 | self.parse_comment(); |
| 1141 | } else if self.current() == Some(NEWLINE) { |
| 1142 | self.bump(); |
| 1143 | } else if self.current() == Some(WHITESPACE) { |
| 1144 | // Skip whitespace without an error |
| 1145 | self.skip_ws(); |
| 1146 | if self.current() == Some(NEWLINE) { |
| 1147 | self.bump(); |
| 1148 | } |
| 1149 | // If we're at EOF after whitespace, that's fine too |
| 1150 | } else if !self.is_at_eof() { |
| 1151 | // For any other tokens, be lenient and just consume until EOL |
| 1152 | // This makes the parser more resilient to various "endif" formattings |
| 1153 | while !self.is_at_eof() && self.current() != Some(NEWLINE) { |
| 1154 | self.bump(); |
| 1155 | } |
| 1156 | if self.current() == Some(NEWLINE) { |
| 1157 | self.bump(); |
| 1158 | } |
| 1159 | } |
| 1160 | // If we're at EOF after endif, that's fine |
| 1161 | |
| 1162 | self.builder.finish_node(); // finish CONDITIONAL_ENDIF |
| 1163 | true |
| 1164 | } |
| 1165 | } |
| 1166 | _ => false, |
| 1167 | } |
| 1168 | } |
| 1169 | |
| 1170 | fn parse_conditional(&mut self) { |
| 1171 | self.builder.start_node(CONDITIONAL.into()); |
| 1172 | |
| 1173 | // Start the initial conditional (ifdef/ifndef/ifeq/ifneq) |
| 1174 | self.builder.start_node(CONDITIONAL_IF.into()); |
| 1175 | |
| 1176 | // Parse the conditional keyword |
| 1177 | let Some(token) = self.parse_conditional_keyword() else { |
| 1178 | self.skip_until_newline(); |
| 1179 | self.builder.finish_node(); // finish CONDITIONAL_IF |
| 1180 | self.builder.finish_node(); // finish CONDITIONAL |
| 1181 | return; |
| 1182 | }; |
| 1183 | |
| 1184 | // Skip whitespace after keyword |
| 1185 | self.skip_ws(); |
| 1186 | |
| 1187 | // Parse the condition based on keyword type |
| 1188 | match token.as_str() { |
| 1189 | "ifdef" | "ifndef" => { |
| 1190 | self.parse_simple_condition(); |
| 1191 | } |
| 1192 | "ifeq" | "ifneq" => { |
| 1193 | self.parse_parenthesized_expr(); |
| 1194 | } |
| 1195 | _ => unreachable!("Invalid conditional token"), |
| 1196 | } |
| 1197 | |
| 1198 | // Skip any trailing whitespace and check for inline comments |
| 1199 | self.skip_ws(); |
| 1200 | if self.current() == Some(COMMENT) { |
| 1201 | self.parse_comment(); |
| 1202 | } |
| 1203 | // Note: expect_eol is already called by parse_simple_condition() and parse_parenthesized_expr() |
| 1204 | |
| 1205 | self.builder.finish_node(); // finish CONDITIONAL_IF |
| 1206 | |
| 1207 | // Parse the conditional body |
| 1208 | let mut depth = 1; |
| 1209 | |
| 1210 | // More reliable loop detection |
| 1211 | let mut position_count = std::collections::HashMap::<usize, usize>::new(); |
| 1212 | let max_repetitions = 15; // Permissive but safe limit |
| 1213 | |
| 1214 | while depth > 0 && !self.is_at_eof() { |
| 1215 | // Track position to detect infinite loops |
| 1216 | let current_pos = self.tokens.len(); |
| 1217 | *position_count.entry(current_pos).or_insert(0) += 1; |
| 1218 | |
| 1219 | // If we've seen the same position too many times, break |
| 1220 | // This prevents infinite loops while allowing complex parsing |
| 1221 | if position_count.get(¤t_pos).unwrap() > &max_repetitions { |
| 1222 | // Instead of adding an error, just break out silently |
| 1223 | // to avoid breaking tests that expect no errors |
| 1224 | break; |
| 1225 | } |
| 1226 | |
| 1227 | match self.current() { |
| 1228 | None => { |
| 1229 | self.error("unterminated conditional (missing endif)".to_string()); |
| 1230 | break; |
| 1231 | } |
| 1232 | Some(IDENTIFIER) => { |
| 1233 | let token = self.tokens.last().unwrap().1.clone(); |
| 1234 | if !self.handle_conditional_token(&token, &mut depth) { |
| 1235 | if token == "include" || token == "-include" || token == "sinclude" { |
| 1236 | self.parse_include(); |
| 1237 | } else { |
| 1238 | self.parse_normal_content(); |
| 1239 | } |
| 1240 | } |
| 1241 | } |
| 1242 | Some(INDENT) => self.parse_recipe_line(), |
| 1243 | Some(WHITESPACE) => self.bump(), |
| 1244 | Some(COMMENT) => self.parse_comment(), |
| 1245 | Some(NEWLINE) => self.bump(), |
| 1246 | Some(DOLLAR) => self.parse_normal_content(), |
| 1247 | Some(QUOTE) => self.parse_quoted_string(), |
| 1248 | Some(_) => { |
| 1249 | // Be more tolerant of unexpected tokens in conditionals |
| 1250 | self.bump(); |
| 1251 | } |
| 1252 | } |
| 1253 | } |
| 1254 | |
| 1255 | self.builder.finish_node(); |
| 1256 | } |
| 1257 | |
| 1258 | // Helper to parse normal content (either assignment or rule) |
| 1259 | fn parse_normal_content(&mut self) { |
| 1260 | // Skip any leading whitespace |
| 1261 | self.skip_ws(); |
| 1262 | |
| 1263 | // Check if this could be a variable assignment |
| 1264 | if self.is_assignment_line() { |
| 1265 | self.parse_assignment(); |
| 1266 | } else { |
| 1267 | // Try to handle as a rule |
| 1268 | self.parse_rule(); |
| 1269 | } |
| 1270 | } |
| 1271 | |
| 1272 | fn parse_include(&mut self) { |
| 1273 | self.builder.start_node(INCLUDE.into()); |
| 1274 | |
| 1275 | // Consume include keyword variant |
| 1276 | if self.current() != Some(IDENTIFIER) |
| 1277 | || (!["include", "-include", "sinclude"] |
| 1278 | .contains(&self.tokens.last().unwrap().1.as_str())) |
| 1279 | { |
| 1280 | self.error("expected include directive".to_string()); |
| 1281 | self.builder.finish_node(); |
| 1282 | return; |
| 1283 | } |
| 1284 | self.bump(); |
| 1285 | self.skip_ws(); |
| 1286 | |
| 1287 | // Parse file paths |
| 1288 | self.builder.start_node(EXPR.into()); |
| 1289 | let mut found_path = false; |
| 1290 | |
| 1291 | while !self.is_at_eof() && self.current() != Some(NEWLINE) { |
| 1292 | match self.current() { |
| 1293 | Some(WHITESPACE) => self.skip_ws(), |
| 1294 | Some(DOLLAR) => { |
| 1295 | found_path = true; |
| 1296 | self.parse_variable_reference(); |
| 1297 | } |
| 1298 | Some(_) => { |
| 1299 | // Accept any token as part of the path |
| 1300 | found_path = true; |
| 1301 | self.bump(); |
| 1302 | } |
| 1303 | None => break, |
| 1304 | } |
| 1305 | } |
| 1306 | |
| 1307 | if !found_path { |
| 1308 | self.error("expected file path after include".to_string()); |
| 1309 | } |
| 1310 | |
| 1311 | self.builder.finish_node(); |
| 1312 | |
| 1313 | // Expect newline |
| 1314 | if self.current() == Some(NEWLINE) { |
| 1315 | self.bump(); |
| 1316 | } else if !self.is_at_eof() { |
| 1317 | self.error("expected newline after include".to_string()); |
| 1318 | self.skip_until_newline(); |
| 1319 | } |
| 1320 | |
| 1321 | self.builder.finish_node(); |
| 1322 | } |
| 1323 | |
| 1324 | /// Parse a `vpath` directive in one of its three forms: |
| 1325 | /// |
| 1326 | /// - `vpath PATTERN DIRS` - add a search path for files matching PATTERN |
| 1327 | /// - `vpath PATTERN` - clear the search path for PATTERN |
| 1328 | /// - `vpath` - clear every `vpath` setting |
| 1329 | /// |
| 1330 | /// Produces a `VPATH` node containing the keyword token, optional |
| 1331 | /// pattern (as an IDENTIFIER) and an optional EXPR holding the |
| 1332 | /// directory list. |
| 1333 | fn parse_vpath(&mut self) { |
| 1334 | self.builder.start_node(VPATH.into()); |
| 1335 | // Consume the `vpath` keyword. |
| 1336 | self.bump(); |
| 1337 | self.skip_ws(); |
| 1338 | |
| 1339 | // Optional pattern (rest of header until whitespace). |
| 1340 | if self.current().is_some() && self.current() != Some(NEWLINE) { |
| 1341 | // The pattern token sequence (until whitespace or newline). |
| 1342 | while let Some(kind) = self.current() { |
| 1343 | match kind { |
| 1344 | WHITESPACE | NEWLINE => break, |
| 1345 | _ => self.bump(), |
| 1346 | } |
| 1347 | } |
| 1348 | self.skip_ws(); |
| 1349 | |
| 1350 | // Optional directory list (everything else on the line). |
| 1351 | if self.current().is_some() && self.current() != Some(NEWLINE) { |
| 1352 | self.builder.start_node(EXPR.into()); |
| 1353 | while self.current().is_some() && self.current() != Some(NEWLINE) { |
| 1354 | self.bump(); |
| 1355 | } |
| 1356 | self.builder.finish_node(); |
| 1357 | } |
| 1358 | } |
| 1359 | |
| 1360 | // Consume the trailing newline. |
| 1361 | if self.current() == Some(NEWLINE) { |
| 1362 | self.bump(); |
| 1363 | } |
| 1364 | self.builder.finish_node(); |
| 1365 | } |
| 1366 | |
| 1367 | /// Parse a `define`/`endef` multi-line variable definition. |
| 1368 | /// |
| 1369 | /// Produces a `VARIABLE` node structured like a regular assignment: |
| 1370 | /// |
| 1371 | /// - the `define` keyword itself (kept as an `IDENTIFIER` token); |
| 1372 | /// - the variable's identifier; |
| 1373 | /// - the assignment operator (defaults to `=` if absent); |
| 1374 | /// - an `EXPR` node containing the verbatim body (without the |
| 1375 | /// surrounding newlines that bracket it); |
| 1376 | /// - the closing `endef` token. |
| 1377 | /// |
| 1378 | /// Because the body is wrapped in an `EXPR` node, the existing |
| 1379 | /// `VariableDefinition::name()` / `assignment_operator()` / |
| 1380 | /// `raw_value()` accessors work transparently for `define` blocks. |
| 1381 | fn parse_define(&mut self) { |
| 1382 | self.builder.start_node(VARIABLE.into()); |
| 1383 | |
| 1384 | // Consume the `define` keyword itself. |
| 1385 | self.bump(); |
| 1386 | // Optional whitespace then the variable name (an IDENTIFIER). |
| 1387 | self.skip_ws(); |
| 1388 | if self.current() == Some(IDENTIFIER) { |
| 1389 | self.bump(); |
| 1390 | } |
| 1391 | self.skip_ws(); |
| 1392 | // Optional assignment operator (e.g. `:=`, `+=`, `?=`). |
| 1393 | if self.current() == Some(OPERATOR) { |
| 1394 | self.bump(); |
| 1395 | } |
| 1396 | // Skip any trailing whitespace on the header line. |
| 1397 | self.skip_ws(); |
| 1398 | // Consume the header-terminating newline (kept as a child). |
| 1399 | if self.current() == Some(NEWLINE) { |
| 1400 | self.bump(); |
| 1401 | } |
| 1402 | |
| 1403 | // The body of the define lives in an EXPR node so that |
| 1404 | // `raw_value()` returns it. We consume token-by-token until we |
| 1405 | // see an `endef` line at depth 0, tracking nested `define`. |
| 1406 | self.builder.start_node(EXPR.into()); |
| 1407 | let mut depth: usize = 1; |
| 1408 | 'body: while !self.is_at_eof() { |
| 1409 | match self.first_token_on_line() { |
| 1410 | Some("endef") => { |
| 1411 | depth -= 1; |
| 1412 | if depth == 0 { |
| 1413 | break 'body; |
| 1414 | } |
| 1415 | } |
| 1416 | Some("define") => depth += 1, |
| 1417 | _ => {} |
| 1418 | } |
| 1419 | // Consume one line into the EXPR body. |
| 1420 | self.skip_until_newline(); |
| 1421 | } |
| 1422 | self.builder.finish_node(); // EXPR |
| 1423 | |
| 1424 | // Consume the closing `endef` line itself (if we found it). |
| 1425 | if depth == 0 { |
| 1426 | self.skip_until_newline(); |
| 1427 | } else { |
| 1428 | self.error("missing `endef` for `define`".to_string()); |
| 1429 | } |
| 1430 | |
| 1431 | self.builder.finish_node(); |
| 1432 | } |
| 1433 | |
| 1434 | /// Return the text of the first non-whitespace token on the current |
| 1435 | /// line, if it is an identifier. Used to detect `define`/`endef`. |
| 1436 | fn first_token_on_line(&self) -> Option<&str> { |
| 1437 | self.tokens |
| 1438 | .iter() |
| 1439 | .rev() |
| 1440 | .find(|(kind, _)| !matches!(*kind, WHITESPACE | INDENT)) |
| 1441 | .filter(|(kind, _)| *kind == IDENTIFIER) |
| 1442 | .map(|(_, text)| text.as_str()) |
| 1443 | } |
| 1444 | |
| 1445 | fn parse_identifier_token(&mut self) -> bool { |
| 1446 | let token = &self.tokens.last().unwrap().1; |
| 1447 | |
| 1448 | // Handle special cases first |
| 1449 | if token.starts_with("%") { |
| 1450 | self.parse_rule(); |
| 1451 | return true; |
| 1452 | } |
| 1453 | |
| 1454 | if Self::is_conditional_start(token) |
| 1455 | && matches!(self.variant, None | Some(MakefileVariant::GNUMake)) |
| 1456 | { |
| 1457 | self.parse_conditional(); |
| 1458 | return true; |
| 1459 | } |
| 1460 | |
| 1461 | if token == "include" || token == "-include" || token == "sinclude" { |
| 1462 | self.parse_include(); |
| 1463 | return true; |
| 1464 | } |
| 1465 | |
| 1466 | if token == "define" { |
| 1467 | self.parse_define(); |
| 1468 | return true; |
| 1469 | } |
| 1470 | |
| 1471 | if token == "vpath" { |
| 1472 | self.parse_vpath(); |
| 1473 | return true; |
| 1474 | } |
| 1475 | |
| 1476 | // Handle normal content (assignment or rule) |
| 1477 | self.parse_normal_content(); |
| 1478 | true |
| 1479 | } |
| 1480 | |
| 1481 | fn parse_token(&mut self) -> bool { |
| 1482 | match self.current() { |
| 1483 | None => false, |
| 1484 | Some(IDENTIFIER) => { |
| 1485 | let token = &self.tokens.last().unwrap().1; |
| 1486 | if self.is_conditional_directive(token) |
| 1487 | && matches!(self.variant, None | Some(MakefileVariant::GNUMake)) |
| 1488 | { |
| 1489 | self.parse_conditional(); |
| 1490 | true |
| 1491 | } else { |
| 1492 | self.parse_identifier_token() |
| 1493 | } |
| 1494 | } |
| 1495 | Some(DOLLAR) => { |
| 1496 | self.parse_normal_content(); |
| 1497 | true |
| 1498 | } |
| 1499 | Some(NEWLINE) => { |
| 1500 | self.builder.start_node(BLANK_LINE.into()); |
| 1501 | self.bump(); |
| 1502 | self.builder.finish_node(); |
| 1503 | true |
| 1504 | } |
| 1505 | Some(COMMENT) => { |
| 1506 | self.parse_comment(); |
| 1507 | true |
| 1508 | } |
| 1509 | Some(WHITESPACE) => { |
| 1510 | // Special case for trailing whitespace |
| 1511 | if self.is_end_of_file_or_newline_after_whitespace() { |
| 1512 | // If the whitespace is just before EOF or a newline, consume it all without errors |
| 1513 | // to be more lenient with final whitespace |
| 1514 | self.skip_ws(); |
| 1515 | return true; |
| 1516 | } |
| 1517 | |
| 1518 | // Special case for indented lines that might be part of help text or documentation |
| 1519 | // Look ahead to see what comes after the whitespace |
| 1520 | let look_ahead_pos = self.tokens.len().saturating_sub(1); |
| 1521 | let mut is_documentation_or_help = false; |
| 1522 | |
| 1523 | if look_ahead_pos > 0 { |
| 1524 | let next_token = &self.tokens[look_ahead_pos - 1]; |
| 1525 | // Consider this documentation if it's an identifier starting with @, a comment, |
| 1526 | // or any reasonable text |
| 1527 | if next_token.0 == IDENTIFIER |
| 1528 | || next_token.0 == COMMENT |
| 1529 | || next_token.0 == TEXT |
| 1530 | { |
| 1531 | is_documentation_or_help = true; |
| 1532 | } |
| 1533 | } |
| 1534 | |
| 1535 | if is_documentation_or_help { |
| 1536 | // For documentation/help text lines, just consume all tokens until newline |
| 1537 | // without generating errors |
| 1538 | self.skip_ws(); |
| 1539 | while self.current().is_some() && self.current() != Some(NEWLINE) { |
| 1540 | self.bump(); |
| 1541 | } |
| 1542 | if self.current() == Some(NEWLINE) { |
| 1543 | self.bump(); |
| 1544 | } |
| 1545 | } else { |
| 1546 | self.skip_ws(); |
| 1547 | } |
| 1548 | true |
| 1549 | } |
| 1550 | Some(INDENT) => { |
| 1551 | // We'll consume the INDENT token |
| 1552 | self.bump(); |
| 1553 | |
| 1554 | // Consume the rest of the line |
| 1555 | while !self.is_at_eof() && self.current() != Some(NEWLINE) { |
| 1556 | self.bump(); |
| 1557 | } |
| 1558 | if self.current() == Some(NEWLINE) { |
| 1559 | self.bump(); |
| 1560 | } |
| 1561 | true |
| 1562 | } |
| 1563 | Some(kind) => { |
| 1564 | // `error()` already consumes the offending token; bumping |
| 1565 | // again here would pop past the end of the stack when |
| 1566 | // this is the last token. |
| 1567 | self.error(format!("unexpected token {:?}", kind)); |
| 1568 | true |
| 1569 | } |
| 1570 | } |
| 1571 | } |
| 1572 | |
| 1573 | fn parse(mut self) -> Parse { |
| 1574 | self.builder.start_node(ROOT.into()); |
| 1575 | |
| 1576 | while self.parse_token() {} |
| 1577 | |
| 1578 | self.builder.finish_node(); |
| 1579 | |
| 1580 | Parse { |
| 1581 | green_node: self.builder.finish(), |
| 1582 | errors: self.errors, |
| 1583 | positioned_errors: self.positioned_errors, |
| 1584 | } |
| 1585 | } |
| 1586 | |
| 1587 | // Simplify the is_assignment_line method by making it more direct |
| 1588 | fn is_assignment_line(&mut self) -> bool { |
| 1589 | let assignment_ops = ["=", ":=", "::=", ":::=", "+=", "?=", "!="]; |
| 1590 | let mut pos = self.tokens.len().saturating_sub(1); |
| 1591 | let mut seen_identifier = false; |
| 1592 | let mut seen_directive = false; // export or override prefix |
| 1593 | |
| 1594 | while pos > 0 { |
| 1595 | let (kind, text) = &self.tokens[pos]; |
| 1596 | |
| 1597 | match kind { |
| 1598 | NEWLINE => break, |
| 1599 | IDENTIFIER if text == "export" || text == "override" => seen_directive = true, |
| 1600 | IDENTIFIER if !seen_identifier => seen_identifier = true, |
| 1601 | OPERATOR if assignment_ops.contains(&text.as_str()) => { |
| 1602 | return seen_identifier || seen_directive |
| 1603 | } |
| 1604 | OPERATOR if text == ":" || text == "::" => return false, // It's a rule if we see a colon first |
| 1605 | WHITESPACE => (), |
| 1606 | _ if seen_directive => return true, // Everything after export/override is part of the assignment |
| 1607 | _ => return false, |
| 1608 | } |
| 1609 | pos = pos.saturating_sub(1); |
| 1610 | } |
| 1611 | // Bare "export VARNAME" (without assignment operator) is a valid GNU Make directive |
| 1612 | seen_directive |
| 1613 | } |
| 1614 | |
| 1615 | /// Advance one token, adding it to the current branch of the tree builder. |
| 1616 | fn bump(&mut self) { |
| 1617 | let (kind, text) = self.tokens.pop().unwrap(); |
| 1618 | // Track backslash-run parity: each backslash flips the flag, any |
| 1619 | // other token clears it. See `pending_backslash_escape`. |
| 1620 | self.pending_backslash_escape = kind == BACKSLASH && !self.pending_backslash_escape; |
| 1621 | self.builder.token(kind.into(), text.as_str()); |
| 1622 | if self.current_token_index > 0 { |
| 1623 | self.current_token_index -= 1; |
| 1624 | } |
| 1625 | } |
| 1626 | /// Peek at the first unprocessed token |
| 1627 | fn current(&self) -> Option<SyntaxKind> { |
| 1628 | self.tokens.last().map(|(kind, _)| *kind) |
| 1629 | } |
| 1630 | |
| 1631 | fn expect_eol(&mut self) { |
| 1632 | // Skip any whitespace before looking for a newline |
| 1633 | self.skip_ws(); |
| 1634 | |
| 1635 | // GNU Make allows a comment at the end of a directive line. |
| 1636 | if self.current() == Some(COMMENT) { |
| 1637 | self.bump(); |
| 1638 | } |
| 1639 | |
| 1640 | match self.current() { |
| 1641 | Some(NEWLINE) => { |
| 1642 | self.bump(); |
| 1643 | } |
| 1644 | None => { |
| 1645 | // End of file is also acceptable |
| 1646 | } |
| 1647 | n => { |
| 1648 | self.error(format!("expected newline, got {:?}", n)); |
| 1649 | // Try to recover by skipping to the next newline |
| 1650 | self.skip_until_newline(); |
| 1651 | } |
| 1652 | } |
| 1653 | } |
| 1654 | |
| 1655 | // Helper to check if we're at EOF |
| 1656 | fn is_at_eof(&self) -> bool { |
| 1657 | self.current().is_none() |
| 1658 | } |
| 1659 | |
| 1660 | // Helper to check if we're at EOF or there's only whitespace left |
| 1661 | fn is_at_eof_or_only_whitespace(&self) -> bool { |
| 1662 | if self.is_at_eof() { |
| 1663 | return true; |
| 1664 | } |
| 1665 | |
| 1666 | // Check if only whitespace and newlines remain |
| 1667 | self.tokens |
| 1668 | .iter() |
| 1669 | .rev() |
| 1670 | .all(|(kind, _)| matches!(*kind, WHITESPACE | NEWLINE)) |
| 1671 | } |
| 1672 | |
| 1673 | fn skip_ws(&mut self) { |
| 1674 | while self.current() == Some(WHITESPACE) { |
| 1675 | self.bump() |
| 1676 | } |
| 1677 | } |
| 1678 | |
| 1679 | fn skip_until_newline(&mut self) { |
| 1680 | while !self.is_at_eof() && self.current() != Some(NEWLINE) { |
| 1681 | self.bump(); |
| 1682 | } |
| 1683 | if self.current() == Some(NEWLINE) { |
| 1684 | self.bump(); |
| 1685 | } |
| 1686 | } |
| 1687 | |
| 1688 | // Helper to handle nested parentheses and collect tokens until matching closing parenthesis |
| 1689 | fn consume_balanced_parens(&mut self, start_paren_count: usize) -> usize { |
| 1690 | let mut paren_count = start_paren_count; |
| 1691 | |
| 1692 | while paren_count > 0 && self.current().is_some() { |
| 1693 | match self.current() { |
| 1694 | Some(LPAREN) => { |
| 1695 | paren_count += 1; |
| 1696 | self.bump(); |
| 1697 | } |
| 1698 | Some(RPAREN) => { |
| 1699 | paren_count -= 1; |
| 1700 | self.bump(); |
| 1701 | if paren_count == 0 { |
| 1702 | break; |
| 1703 | } |
| 1704 | } |
| 1705 | Some(DOLLAR) => { |
| 1706 | // Handle nested variable references |
| 1707 | self.parse_variable_reference(); |
| 1708 | } |
| 1709 | Some(_) => self.bump(), |
| 1710 | None => { |
| 1711 | self.error("unclosed parenthesis".to_string()); |
| 1712 | break; |
| 1713 | } |
| 1714 | } |
| 1715 | } |
| 1716 | |
| 1717 | paren_count |
| 1718 | } |
| 1719 | |
| 1720 | // Helper to check if we're near the end of the file with just whitespace |
| 1721 | fn is_end_of_file_or_newline_after_whitespace(&self) -> bool { |
| 1722 | // Use our new helper method |
| 1723 | if self.is_at_eof_or_only_whitespace() { |
| 1724 | return true; |
| 1725 | } |
| 1726 | |
| 1727 | // If there are 1 or 0 tokens left, we're at EOF |
| 1728 | if self.tokens.len() <= 1 { |
| 1729 | return true; |
| 1730 | } |
| 1731 | |
| 1732 | false |
| 1733 | } |
| 1734 | } |
| 1735 | |
| 1736 | let mut tokens = lex(text); |
| 1737 | |
| 1738 | // Build token positions in forward order before reversing |
| 1739 | let mut token_positions = Vec::with_capacity(tokens.len()); |
| 1740 | let mut position = rowan::TextSize::from(0); |
| 1741 | for (_kind, text) in &tokens { |
| 1742 | let start = position; |
| 1743 | let end = start + rowan::TextSize::of(text.as_str()); |
| 1744 | token_positions.push((start, end)); |
| 1745 | position = end; |
| 1746 | } |
| 1747 | |
| 1748 | let current_token_index = tokens.len().saturating_sub(1); |
| 1749 | tokens.reverse(); |
| 1750 | Parser { |
| 1751 | tokens, |
| 1752 | builder: GreenNodeBuilder::new(), |
| 1753 | errors: Vec::new(), |
| 1754 | positioned_errors: Vec::new(), |
| 1755 | token_positions, |
| 1756 | current_token_index, |
| 1757 | original_text: text.to_string(), |
| 1758 | variant, |
| 1759 | pending_backslash_escape: false, |
| 1760 | } |
| 1761 | .parse() |
| 1762 | } |
| 1763 | |
| 1764 | /// To work with the parse results we need a view into the |
| 1765 | /// green tree - the Syntax tree. |
| 1766 | /// It is also immutable, like a GreenNode, |
| 1767 | /// but it contains parent pointers, offsets, and |
| 1768 | /// has identity semantics. |
| 1769 | pub(crate) type SyntaxNode = rowan::SyntaxNode<Lang>; |
| 1770 | #[allow(unused)] |
| 1771 | type SyntaxToken = rowan::SyntaxToken<Lang>; |
| 1772 | #[allow(unused)] |
| 1773 | pub(crate) type SyntaxElement = rowan::NodeOrToken<SyntaxNode, SyntaxToken>; |
| 1774 | |
| 1775 | impl Parse { |
| 1776 | fn syntax(&self) -> SyntaxNode { |
| 1777 | SyntaxNode::new_root_mut(self.green_node.clone()) |
| 1778 | } |
| 1779 | |
| 1780 | pub(crate) fn root(&self) -> Makefile { |
| 1781 | Makefile::cast(self.syntax()).unwrap() |
| 1782 | } |
| 1783 | } |
| 1784 | |
| 1785 | /// Calculate line and column (both 0-indexed) for the given offset in the tree. |
| 1786 | /// Column is measured in bytes from the start of the line. |
| 1787 | fn line_col_at_offset(node: &SyntaxNode, offset: rowan::TextSize) -> (usize, usize) { |
| 1788 | let root = node.ancestors().last().unwrap_or_else(|| node.clone()); |
| 1789 | let mut line = 0; |
| 1790 | let mut last_newline_offset = rowan::TextSize::from(0); |
| 1791 | |
| 1792 | for element in root.preorder_with_tokens() { |
| 1793 | if let rowan::WalkEvent::Enter(rowan::NodeOrToken::Token(token)) = element { |
| 1794 | if token.text_range().start() >= offset { |
| 1795 | break; |
| 1796 | } |
| 1797 | |
| 1798 | // Count newlines and track position of last one |
| 1799 | for (idx, _) in token.text().match_indices('\n') { |
| 1800 | line += 1; |
| 1801 | last_newline_offset = |
| 1802 | token.text_range().start() + rowan::TextSize::from((idx + 1) as u32); |
| 1803 | } |
| 1804 | } |
| 1805 | } |
| 1806 | |
| 1807 | let column: usize = (offset - last_newline_offset).into(); |
| 1808 | (line, column) |
| 1809 | } |
| 1810 | |
| 1811 | macro_rules! ast_node { |
| 1812 | ($ast:ident, $kind:ident) => { |
| 1813 | #[derive(Clone, PartialEq, Eq, Hash)] |
| 1814 | #[repr(transparent)] |
| 1815 | /// An AST node for $ast |
| 1816 | pub struct $ast(SyntaxNode); |
| 1817 | |
| 1818 | impl AstNode for $ast { |
| 1819 | type Language = Lang; |
| 1820 | |
| 1821 | fn can_cast(kind: SyntaxKind) -> bool { |
| 1822 | kind == $kind |
| 1823 | } |
| 1824 | |
| 1825 | fn cast(syntax: SyntaxNode) -> Option<Self> { |
| 1826 | if Self::can_cast(syntax.kind()) { |
| 1827 | Some(Self(syntax)) |
| 1828 | } else { |
| 1829 | None |
| 1830 | } |
| 1831 | } |
| 1832 | |
| 1833 | fn syntax(&self) -> &SyntaxNode { |
| 1834 | &self.0 |
| 1835 | } |
| 1836 | } |
| 1837 | |
| 1838 | impl $ast { |
| 1839 | /// Get the line number (0-indexed) where this node starts. |
| 1840 | pub fn line(&self) -> usize { |
| 1841 | line_col_at_offset(&self.0, self.0.text_range().start()).0 |
| 1842 | } |
| 1843 | |
| 1844 | /// Get the column number (0-indexed, in bytes) where this node starts. |
| 1845 | pub fn column(&self) -> usize { |
| 1846 | line_col_at_offset(&self.0, self.0.text_range().start()).1 |
| 1847 | } |
| 1848 | |
| 1849 | /// Get both line and column (0-indexed) where this node starts. |
| 1850 | /// Returns (line, column) where column is measured in bytes from the start of the line. |
| 1851 | pub fn line_col(&self) -> (usize, usize) { |
| 1852 | line_col_at_offset(&self.0, self.0.text_range().start()) |
| 1853 | } |
| 1854 | } |
| 1855 | |
| 1856 | impl core::fmt::Display for $ast { |
| 1857 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { |
| 1858 | write!(f, "{}", self.0.text()) |
| 1859 | } |
| 1860 | } |
| 1861 | }; |
| 1862 | } |
| 1863 | |
| 1864 | ast_node!(Makefile, ROOT); |
| 1865 | |
| 1866 | impl Makefile { |
| 1867 | /// Capture an independent snapshot of this makefile. |
| 1868 | /// |
| 1869 | /// The returned value shares the underlying immutable green-node data |
| 1870 | /// with `self` at the time of the call, but lives in its own mutable |
| 1871 | /// tree: subsequent mutations to `self` do not propagate to the snapshot. |
| 1872 | /// Pair with [`Self::tree_eq`] to detect later mutations. |
| 1873 | pub fn snapshot(&self) -> Self { |
| 1874 | Makefile(SyntaxNode::new_root_mut(self.0.green().into_owned())) |
| 1875 | } |
| 1876 | |
| 1877 | /// Returns true iff the syntax trees of `self` and `other` are |
| 1878 | /// value-equal. An O(1) pointer-identity fast path makes this free for |
| 1879 | /// trees that still share state with a recent `snapshot()`. |
| 1880 | pub fn tree_eq(&self, other: &Self) -> bool { |
| 1881 | let a = self.0.green(); |
| 1882 | let b = other.0.green(); |
| 1883 | let a_ref: &rowan::GreenNodeData = &a; |
| 1884 | let b_ref: &rowan::GreenNodeData = &b; |
| 1885 | std::ptr::eq(a_ref as *const _, b_ref as *const _) || a_ref == b_ref |
| 1886 | } |
| 1887 | } |
| 1888 | |
| 1889 | ast_node!(Rule, RULE); |
| 1890 | ast_node!(Recipe, RECIPE); |
| 1891 | ast_node!(Identifier, IDENTIFIER); |
| 1892 | ast_node!(VariableDefinition, VARIABLE); |
| 1893 | ast_node!(Include, INCLUDE); |
| 1894 | ast_node!(Vpath, VPATH); |
| 1895 | ast_node!(ArchiveMembers, ARCHIVE_MEMBERS); |
| 1896 | ast_node!(ArchiveMember, ARCHIVE_MEMBER); |
| 1897 | ast_node!(Conditional, CONDITIONAL); |
| 1898 | |
| 1899 | /// A reference to a variable in the makefile, e.g. `$(FOO)` or `${BAR}`. |
| 1900 | /// |
| 1901 | /// This wraps an EXPR syntax node whose first token is `$` followed by `(` or `{`. |
| 1902 | #[derive(Clone, PartialEq, Eq, Hash)] |
| 1903 | pub struct VariableReference(SyntaxNode); |
| 1904 | |
| 1905 | impl VariableReference { |
| 1906 | /// Try to cast a syntax node into a VariableReference. |
| 1907 | /// |
| 1908 | /// Returns `Some` if the node is an EXPR whose first token is `$` followed by |
| 1909 | /// `(`, `{`, or an identifier (for single-character variables like `$X`). |
| 1910 | pub fn cast(syntax: SyntaxNode) -> Option<Self> { |
| 1911 | if syntax.kind() != EXPR { |
| 1912 | return None; |
| 1913 | } |
| 1914 | let mut tokens = syntax |
| 1915 | .children_with_tokens() |
| 1916 | .filter_map(|it| it.into_token()); |
| 1917 | let first = tokens.next()?; |
| 1918 | if first.kind() != DOLLAR { |
| 1919 | return None; |
| 1920 | } |
| 1921 | // Accept $(...), ${...}, or $X (single-char) |
| 1922 | tokens.next()?; |
| 1923 | Some(Self(syntax)) |
| 1924 | } |
| 1925 | |
| 1926 | /// Get the syntax node backing this variable reference. |
| 1927 | pub fn syntax(&self) -> &SyntaxNode { |
| 1928 | &self.0 |
| 1929 | } |
| 1930 | |
| 1931 | /// Get the name of the referenced variable. |
| 1932 | /// |
| 1933 | /// For simple references like `$(FOO)`, returns `"FOO"`. |
| 1934 | /// For function calls like `$(wildcard *.c)`, returns `"wildcard"`. |
| 1935 | /// |
| 1936 | /// Note: Variable references inside recipes are not parsed into the syntax tree |
| 1937 | /// (recipes are stored as raw text). This only finds references in variable values, |
| 1938 | /// prerequisites, and targets. |
| 1939 | /// |
| 1940 | /// # Example |
| 1941 | /// ``` |
| 1942 | /// use makefile_lossless::Makefile; |
| 1943 | /// let makefile: Makefile = "CFLAGS = $(BASE_FLAGS) -Wall\n".parse().unwrap(); |
| 1944 | /// let refs: Vec<_> = makefile.variable_references().collect(); |
| 1945 | /// assert_eq!(refs[0].name(), Some("BASE_FLAGS".to_string())); |
| 1946 | /// ``` |
| 1947 | pub fn name(&self) -> Option<String> { |
| 1948 | // After $ and (, the first IDENTIFIER token is the variable/function name |
| 1949 | self.0 |
| 1950 | .children_with_tokens() |
| 1951 | .filter_map(|it| it.into_token()) |
| 1952 | .find(|t| t.kind() == IDENTIFIER) |
| 1953 | .map(|t| t.text().to_string()) |
| 1954 | } |
| 1955 | |
| 1956 | /// Check if this is a function call rather than a simple variable reference. |
| 1957 | /// |
| 1958 | /// Returns `true` if the content after the function name contains whitespace |
| 1959 | /// or commas, indicating arguments (e.g. `$(subst a,b,text)` vs `$(CC)`). |
| 1960 | /// |
| 1961 | /// # Example |
| 1962 | /// ``` |
| 1963 | /// use makefile_lossless::Makefile; |
| 1964 | /// let makefile: Makefile = "FILES = $(wildcard *.c)\n".parse().unwrap(); |
| 1965 | /// let refs: Vec<_> = makefile.variable_references().collect(); |
| 1966 | /// assert!(refs[0].is_function_call()); |
| 1967 | /// ``` |
| 1968 | pub fn is_function_call(&self) -> bool { |
| 1969 | let mut tokens = self |
| 1970 | .0 |
| 1971 | .children_with_tokens() |
| 1972 | .filter_map(|it| it.into_token()); |
| 1973 | |
| 1974 | // Skip $ and opening paren/brace |
| 1975 | let Some(dollar) = tokens.next() else { |
| 1976 | return false; |
| 1977 | }; |
| 1978 | if dollar.kind() != DOLLAR { |
| 1979 | return false; |
| 1980 | } |
| 1981 | let Some(open) = tokens.next() else { |
| 1982 | return false; |
| 1983 | }; |
| 1984 | if open.kind() != LPAREN && open.kind() != LBRACE { |
| 1985 | return false; |
| 1986 | } |
| 1987 | |
| 1988 | // Skip the function name (first IDENTIFIER) |
| 1989 | let Some(ident) = tokens.next() else { |
| 1990 | return false; |
| 1991 | }; |
| 1992 | if ident.kind() != IDENTIFIER { |
| 1993 | return false; |
| 1994 | } |
| 1995 | |
| 1996 | // If the next token is whitespace or comma, it's a function call |
| 1997 | match tokens.next() { |
| 1998 | Some(t) => t.kind() == WHITESPACE || t.kind() == COMMA, |
| 1999 | None => false, |
| 2000 | } |
| 2001 | } |
| 2002 | |
| 2003 | /// Count the number of comma-separated arguments in a function call. |
| 2004 | /// |
| 2005 | /// Returns 0 for simple variable references. For function calls, counts |
| 2006 | /// the commas at depth 0 (not inside nested parentheses) plus 1. |
| 2007 | /// |
| 2008 | /// # Example |
| 2009 | /// ``` |
| 2010 | /// use makefile_lossless::Makefile; |
| 2011 | /// let makefile: Makefile = "X = $(subst a,b,text)\n".parse().unwrap(); |
| 2012 | /// let refs: Vec<_> = makefile.variable_references().collect(); |
| 2013 | /// assert_eq!(refs[0].argument_count(), 3); |
| 2014 | /// ``` |
| 2015 | pub fn argument_count(&self) -> usize { |
| 2016 | if !self.is_function_call() { |
| 2017 | return 0; |
| 2018 | } |
| 2019 | |
| 2020 | let mut commas = 0; |
| 2021 | let mut depth = 0; |
| 2022 | let mut past_name = false; |
| 2023 | |
| 2024 | for element in self.0.children_with_tokens() { |
| 2025 | let Some(token) = element.as_token() else { |
| 2026 | // Child nodes (nested EXPR) don't contain top-level commas |
| 2027 | continue; |
| 2028 | }; |
| 2029 | match token.kind() { |
| 2030 | IDENTIFIER if !past_name => { |
| 2031 | past_name = true; |
| 2032 | } |
| 2033 | DOLLAR | LPAREN | LBRACE if !past_name => {} |
| 2034 | LPAREN => depth += 1, |
| 2035 | RPAREN if depth > 0 => depth -= 1, |
| 2036 | COMMA if depth == 0 && past_name => commas += 1, |
| 2037 | _ => {} |
| 2038 | } |
| 2039 | } |
| 2040 | |
| 2041 | if past_name { |
| 2042 | commas + 1 |
| 2043 | } else { |
| 2044 | 0 |
| 2045 | } |
| 2046 | } |
| 2047 | |
| 2048 | /// Determine which argument (0-based) the given byte offset falls into. |
| 2049 | /// |
| 2050 | /// Returns `None` if the offset is not inside this reference or if this |
| 2051 | /// is not a function call. |
| 2052 | /// |
| 2053 | /// # Example |
| 2054 | /// ``` |
| 2055 | /// use makefile_lossless::Makefile; |
| 2056 | /// let makefile: Makefile = "X = $(subst a,b,text)\n".parse().unwrap(); |
| 2057 | /// let refs: Vec<_> = makefile.variable_references().collect(); |
| 2058 | /// // offset 12 is 'a' (first arg), offset 14 is 'b' (second arg), offset 16 is 't' (third arg) |
| 2059 | /// assert_eq!(refs[0].argument_index_at_offset(12), Some(0)); |
| 2060 | /// assert_eq!(refs[0].argument_index_at_offset(14), Some(1)); |
| 2061 | /// assert_eq!(refs[0].argument_index_at_offset(16), Some(2)); |
| 2062 | /// ``` |
| 2063 | pub fn argument_index_at_offset(&self, offset: usize) -> Option<usize> { |
| 2064 | if !self.is_function_call() { |
| 2065 | return None; |
| 2066 | } |
| 2067 | |
| 2068 | let ref_start: usize = self.0.text_range().start().into(); |
| 2069 | let ref_end: usize = self.0.text_range().end().into(); |
| 2070 | if offset < ref_start || offset > ref_end { |
| 2071 | return None; |
| 2072 | } |
| 2073 | |
| 2074 | let mut arg_index = 0; |
| 2075 | let mut depth = 0; |
| 2076 | let mut past_name = false; |
| 2077 | |
| 2078 | for element in self.0.children_with_tokens() { |
| 2079 | let Some(token) = element.as_token() else { |
| 2080 | continue; |
| 2081 | }; |
| 2082 | let token_end: usize = token.text_range().end().into(); |
| 2083 | |
| 2084 | match token.kind() { |
| 2085 | IDENTIFIER if !past_name => { |
| 2086 | past_name = true; |
| 2087 | } |
| 2088 | DOLLAR | LPAREN | LBRACE if !past_name => {} |
| 2089 | LPAREN => depth += 1, |
| 2090 | RPAREN if depth > 0 => depth -= 1, |
| 2091 | COMMA if depth == 0 && past_name => { |
| 2092 | if offset < token_end { |
| 2093 | return Some(arg_index); |
| 2094 | } |
| 2095 | arg_index += 1; |
| 2096 | } |
| 2097 | _ => {} |
| 2098 | } |
| 2099 | } |
| 2100 | |
| 2101 | if past_name { |
| 2102 | Some(arg_index) |
| 2103 | } else { |
| 2104 | None |
| 2105 | } |
| 2106 | } |
| 2107 | |
| 2108 | /// Get the line number (0-indexed) where this reference starts. |
| 2109 | pub fn line(&self) -> usize { |
| 2110 | line_col_at_offset(&self.0, self.0.text_range().start()).0 |
| 2111 | } |
| 2112 | |
| 2113 | /// Get the column number (0-indexed, in bytes) where this reference starts. |
| 2114 | pub fn column(&self) -> usize { |
| 2115 | line_col_at_offset(&self.0, self.0.text_range().start()).1 |
| 2116 | } |
| 2117 | |
| 2118 | /// Get both line and column (0-indexed) where this reference starts. |
| 2119 | pub fn line_col(&self) -> (usize, usize) { |
| 2120 | line_col_at_offset(&self.0, self.0.text_range().start()) |
| 2121 | } |
| 2122 | |
| 2123 | /// Get the text range of this reference in the source. |
| 2124 | pub fn text_range(&self) -> rowan::TextRange { |
| 2125 | self.0.text_range() |
| 2126 | } |
| 2127 | } |
| 2128 | |
| 2129 | impl core::fmt::Display for VariableReference { |
| 2130 | fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> Result<(), core::fmt::Error> { |
| 2131 | write!(f, "{}", self.0.text()) |
| 2132 | } |
| 2133 | } |
| 2134 | |
| 2135 | impl Recipe { |
| 2136 | /// Get the text content of this recipe line (the command to execute) |
| 2137 | /// |
| 2138 | /// For single-line recipes, this returns the command text excluding the |
| 2139 | /// leading tab and trailing newline. |
| 2140 | /// |
| 2141 | /// For multi-line recipes (with backslash continuations), this returns the |
| 2142 | /// full text including the internal newlines and continuation-line indentation, |
| 2143 | /// but still excluding the leading tab of the first line and the final newline. |
| 2144 | /// This preserves the exact content needed for a lossless round-trip. |
| 2145 | /// |
| 2146 | /// For comment-only lines, this returns an empty string. |
| 2147 | pub fn text(&self) -> String { |
| 2148 | let tokens: Vec<_> = self |
| 2149 | .syntax() |
| 2150 | .children_with_tokens() |
| 2151 | .filter_map(|it| it.as_token().cloned()) |
| 2152 | .collect(); |
| 2153 | |
| 2154 | if tokens.is_empty() { |
| 2155 | return String::new(); |
| 2156 | } |
| 2157 | |
| 2158 | // Skip the first token if it's the leading INDENT |
| 2159 | let start = if tokens.first().map(|t| t.kind()) == Some(INDENT) { |
| 2160 | 1 |
| 2161 | } else { |
| 2162 | 0 |
| 2163 | }; |
| 2164 | |
| 2165 | // Skip the last token if it's the trailing NEWLINE |
| 2166 | let end = if tokens.last().map(|t| t.kind()) == Some(NEWLINE) { |
| 2167 | tokens.len() - 1 |
| 2168 | } else { |
| 2169 | tokens.len() |
| 2170 | }; |
| 2171 | |
| 2172 | // Include TEXT, NEWLINE (internal continuation), and INDENT (continuation indent) tokens, |
| 2173 | // but skip COMMENT tokens (those are returned by comment()). |
| 2174 | // For INDENT tokens after a continuation newline, strip the leading tab character. |
| 2175 | let mut after_newline = false; |
| 2176 | tokens[start..end] |
| 2177 | .iter() |
| 2178 | .filter_map(|t| match t.kind() { |
| 2179 | TEXT => { |
| 2180 | after_newline = false; |
| 2181 | Some(t.text().to_string()) |
| 2182 | } |
| 2183 | NEWLINE => { |
| 2184 | after_newline = true; |
| 2185 | Some(t.text().to_string()) |
| 2186 | } |
| 2187 | INDENT if after_newline => { |
| 2188 | after_newline = false; |
| 2189 | // Strip the leading tab from continuation-line indentation |
| 2190 | let text = t.text(); |
| 2191 | Some(text.strip_prefix('\t').unwrap_or(text).to_string()) |
| 2192 | } |
| 2193 | _ => None, |
| 2194 | }) |
| 2195 | .collect() |
| 2196 | } |
| 2197 | |
| 2198 | /// Get the indentation string of this recipe line. |
| 2199 | /// |
| 2200 | /// Returns the leading indentation (typically a tab character) of this recipe line, |
| 2201 | /// or `None` if no indent token is present. |
| 2202 | /// |
| 2203 | /// # Example |
| 2204 | /// ``` |
| 2205 | /// use makefile_lossless::Makefile; |
| 2206 | /// |
| 2207 | /// let makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 2208 | /// let rule = makefile.rules().next().unwrap(); |
| 2209 | /// let recipe = rule.recipe_nodes().next().unwrap(); |
| 2210 | /// assert_eq!(recipe.indent(), Some("\t".to_string())); |
| 2211 | /// ``` |
| 2212 | pub fn indent(&self) -> Option<String> { |
| 2213 | self.syntax().children_with_tokens().find_map(|it| { |
| 2214 | if let Some(token) = it.as_token() { |
| 2215 | if token.kind() == INDENT { |
| 2216 | return Some(token.text().to_string()); |
| 2217 | } |
| 2218 | } |
| 2219 | None |
| 2220 | }) |
| 2221 | } |
| 2222 | |
| 2223 | /// Get the comment content of this recipe line, if any |
| 2224 | /// |
| 2225 | /// Returns the comment text (including the '#' character) if this recipe |
| 2226 | /// line contains a comment, or None if there is no comment. |
| 2227 | /// |
| 2228 | /// # Example |
| 2229 | /// ``` |
| 2230 | /// use makefile_lossless::Makefile; |
| 2231 | /// |
| 2232 | /// let makefile: Makefile = "all:\n\t# This is a comment\n\techo hello\n".parse().unwrap(); |
| 2233 | /// let rule = makefile.rules().next().unwrap(); |
| 2234 | /// let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 2235 | /// assert_eq!(recipes[0].comment(), Some("# This is a comment".to_string())); |
| 2236 | /// assert_eq!(recipes[1].comment(), None); |
| 2237 | /// ``` |
| 2238 | pub fn comment(&self) -> Option<String> { |
| 2239 | self.syntax() |
| 2240 | .children_with_tokens() |
| 2241 | .filter_map(|it| { |
| 2242 | if let Some(token) = it.as_token() { |
| 2243 | if token.kind() == COMMENT { |
| 2244 | return Some(token.text().to_string()); |
| 2245 | } |
| 2246 | } |
| 2247 | None |
| 2248 | }) |
| 2249 | .next() |
| 2250 | } |
| 2251 | |
| 2252 | /// Get the full content of this recipe line |
| 2253 | /// |
| 2254 | /// Returns all content including command text, comments, and internal whitespace, |
| 2255 | /// but excluding the leading indent. This is useful for getting the complete |
| 2256 | /// content of a recipe line regardless of whether it's a command, comment, or both. |
| 2257 | /// |
| 2258 | /// # Example |
| 2259 | /// ``` |
| 2260 | /// use makefile_lossless::Makefile; |
| 2261 | /// |
| 2262 | /// let makefile: Makefile = "all:\n\techo hello # inline comment\n".parse().unwrap(); |
| 2263 | /// let rule = makefile.rules().next().unwrap(); |
| 2264 | /// let recipe = rule.recipe_nodes().next().unwrap(); |
| 2265 | /// assert_eq!(recipe.full(), "echo hello # inline comment"); |
| 2266 | /// ``` |
| 2267 | pub fn full(&self) -> String { |
| 2268 | self.syntax() |
| 2269 | .children_with_tokens() |
| 2270 | .filter_map(|it| { |
| 2271 | if let Some(token) = it.as_token() { |
| 2272 | // Include TEXT and COMMENT tokens, but skip INDENT and NEWLINE |
| 2273 | if token.kind() == TEXT || token.kind() == COMMENT { |
| 2274 | return Some(token.text().to_string()); |
| 2275 | } |
| 2276 | } |
| 2277 | None |
| 2278 | }) |
| 2279 | .collect::<Vec<_>>() |
| 2280 | .join("") |
| 2281 | } |
| 2282 | |
| 2283 | /// Get the parent rule containing this recipe |
| 2284 | /// |
| 2285 | /// # Example |
| 2286 | /// ``` |
| 2287 | /// use makefile_lossless::Makefile; |
| 2288 | /// |
| 2289 | /// let makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 2290 | /// let rule = makefile.rules().next().unwrap(); |
| 2291 | /// let recipe = rule.recipe_nodes().next().unwrap(); |
| 2292 | /// let parent = recipe.parent().unwrap(); |
| 2293 | /// assert_eq!(parent.targets().collect::<Vec<_>>(), vec!["all"]); |
| 2294 | /// ``` |
| 2295 | pub fn parent(&self) -> Option<Rule> { |
| 2296 | self.syntax().parent().and_then(Rule::cast) |
| 2297 | } |
| 2298 | |
| 2299 | /// Get the source range of this recipe node. |
| 2300 | pub fn text_range(&self) -> rowan::TextRange { |
| 2301 | self.syntax().text_range() |
| 2302 | } |
| 2303 | |
| 2304 | /// Check if this recipe has the silent prefix (@) |
| 2305 | /// |
| 2306 | /// # Example |
| 2307 | /// ``` |
| 2308 | /// use makefile_lossless::Makefile; |
| 2309 | /// |
| 2310 | /// let makefile: Makefile = "all:\n\t@echo hello\n\techo world\n".parse().unwrap(); |
| 2311 | /// let rule = makefile.rules().next().unwrap(); |
| 2312 | /// let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 2313 | /// assert!(recipes[0].is_silent()); |
| 2314 | /// assert!(!recipes[1].is_silent()); |
| 2315 | /// ``` |
| 2316 | pub fn is_silent(&self) -> bool { |
| 2317 | let text = self.text(); |
| 2318 | text.starts_with('@') || text.starts_with("-@") || text.starts_with("+@") |
| 2319 | } |
| 2320 | |
| 2321 | /// Check if this recipe has the ignore-errors prefix (-) |
| 2322 | /// |
| 2323 | /// # Example |
| 2324 | /// ``` |
| 2325 | /// use makefile_lossless::Makefile; |
| 2326 | /// |
| 2327 | /// let makefile: Makefile = "all:\n\t-echo hello\n\techo world\n".parse().unwrap(); |
| 2328 | /// let rule = makefile.rules().next().unwrap(); |
| 2329 | /// let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 2330 | /// assert!(recipes[0].is_ignore_errors()); |
| 2331 | /// assert!(!recipes[1].is_ignore_errors()); |
| 2332 | /// ``` |
| 2333 | pub fn is_ignore_errors(&self) -> bool { |
| 2334 | let text = self.text(); |
| 2335 | text.starts_with('-') || text.starts_with("@-") || text.starts_with("+-") |
| 2336 | } |
| 2337 | |
| 2338 | /// Set the command prefix for this recipe |
| 2339 | /// |
| 2340 | /// The prefix can contain `@` (silent), `-` (ignore errors), and/or `+` (always execute). |
| 2341 | /// Pass an empty string to remove all prefixes. |
| 2342 | /// |
| 2343 | /// # Example |
| 2344 | /// ``` |
| 2345 | /// use makefile_lossless::Makefile; |
| 2346 | /// |
| 2347 | /// let mut makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 2348 | /// let rule = makefile.rules().next().unwrap(); |
| 2349 | /// let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 2350 | /// recipe.set_prefix("@"); |
| 2351 | /// assert_eq!(recipe.text(), "@echo hello"); |
| 2352 | /// assert!(recipe.is_silent()); |
| 2353 | /// ``` |
| 2354 | pub fn set_prefix(&mut self, prefix: &str) { |
| 2355 | let text = self.text(); |
| 2356 | |
| 2357 | // Strip existing prefix characters |
| 2358 | let stripped = text.trim_start_matches(['@', '-', '+']); |
| 2359 | |
| 2360 | // Build new text with the new prefix |
| 2361 | let new_text = format!("{}{}", prefix, stripped); |
| 2362 | |
| 2363 | self.replace_text(&new_text); |
| 2364 | } |
| 2365 | |
| 2366 | /// Replace the text content of this recipe line |
| 2367 | /// |
| 2368 | /// # Example |
| 2369 | /// ``` |
| 2370 | /// use makefile_lossless::Makefile; |
| 2371 | /// |
| 2372 | /// let mut makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 2373 | /// let rule = makefile.rules().next().unwrap(); |
| 2374 | /// let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 2375 | /// recipe.replace_text("echo world"); |
| 2376 | /// assert_eq!(recipe.text(), "echo world"); |
| 2377 | /// ``` |
| 2378 | pub fn replace_text(&mut self, new_text: &str) { |
| 2379 | let node = self.syntax(); |
| 2380 | let parent = node.parent().expect("Recipe node must have a parent"); |
| 2381 | let node_index = node.index(); |
| 2382 | |
| 2383 | // Build a new RECIPE node with the new text |
| 2384 | let mut builder = GreenNodeBuilder::new(); |
| 2385 | builder.start_node(RECIPE.into()); |
| 2386 | |
| 2387 | // Preserve the existing INDENT token if present |
| 2388 | if let Some(indent_token) = node |
| 2389 | .children_with_tokens() |
| 2390 | .find(|it| it.as_token().map(|t| t.kind() == INDENT).unwrap_or(false)) |
| 2391 | { |
| 2392 | builder.token(INDENT.into(), indent_token.as_token().unwrap().text()); |
| 2393 | } else { |
| 2394 | builder.token(INDENT.into(), "\t"); |
| 2395 | } |
| 2396 | |
| 2397 | builder.token(TEXT.into(), new_text); |
| 2398 | |
| 2399 | // Preserve the existing NEWLINE token if present |
| 2400 | if let Some(newline_token) = node |
| 2401 | .children_with_tokens() |
| 2402 | .find(|it| it.as_token().map(|t| t.kind() == NEWLINE).unwrap_or(false)) |
| 2403 | { |
| 2404 | builder.token(NEWLINE.into(), newline_token.as_token().unwrap().text()); |
| 2405 | } else { |
| 2406 | builder.token(NEWLINE.into(), "\n"); |
| 2407 | } |
| 2408 | |
| 2409 | builder.finish_node(); |
| 2410 | let new_syntax = SyntaxNode::new_root_mut(builder.finish()); |
| 2411 | |
| 2412 | // Replace the old node with the new one |
| 2413 | parent.splice_children(node_index..node_index + 1, vec![new_syntax.into()]); |
| 2414 | |
| 2415 | // Update self to point to the new node |
| 2416 | // Note: index() returns position among all siblings (nodes + tokens) |
| 2417 | // so we need to use children_with_tokens() and filter for the node |
| 2418 | *self = parent |
| 2419 | .children_with_tokens() |
| 2420 | .nth(node_index) |
| 2421 | .and_then(|element| element.into_node()) |
| 2422 | .and_then(Recipe::cast) |
| 2423 | .expect("New recipe node should exist at the same index"); |
| 2424 | } |
| 2425 | |
| 2426 | /// Insert a new recipe line before this one |
| 2427 | /// |
| 2428 | /// # Example |
| 2429 | /// ``` |
| 2430 | /// use makefile_lossless::Makefile; |
| 2431 | /// |
| 2432 | /// let mut makefile: Makefile = "all:\n\techo world\n".parse().unwrap(); |
| 2433 | /// let mut rule = makefile.rules().next().unwrap(); |
| 2434 | /// let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 2435 | /// recipe.insert_before("echo hello"); |
| 2436 | /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["echo hello", "echo world"]); |
| 2437 | /// ``` |
| 2438 | pub fn insert_before(&self, text: &str) { |
| 2439 | let node = self.syntax(); |
| 2440 | let parent = node.parent().expect("Recipe node must have a parent"); |
| 2441 | let node_index = node.index(); |
| 2442 | |
| 2443 | // Build a new RECIPE node |
| 2444 | let mut builder = GreenNodeBuilder::new(); |
| 2445 | builder.start_node(RECIPE.into()); |
| 2446 | builder.token(INDENT.into(), "\t"); |
| 2447 | builder.token(TEXT.into(), text); |
| 2448 | builder.token(NEWLINE.into(), "\n"); |
| 2449 | builder.finish_node(); |
| 2450 | let new_syntax = SyntaxNode::new_root_mut(builder.finish()); |
| 2451 | |
| 2452 | // Insert before this recipe |
| 2453 | parent.splice_children(node_index..node_index, vec![new_syntax.into()]); |
| 2454 | } |
| 2455 | |
| 2456 | /// Insert a new recipe line after this one |
| 2457 | /// |
| 2458 | /// # Example |
| 2459 | /// ``` |
| 2460 | /// use makefile_lossless::Makefile; |
| 2461 | /// |
| 2462 | /// let mut makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 2463 | /// let mut rule = makefile.rules().next().unwrap(); |
| 2464 | /// let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 2465 | /// recipe.insert_after("echo world"); |
| 2466 | /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["echo hello", "echo world"]); |
| 2467 | /// ``` |
| 2468 | pub fn insert_after(&self, text: &str) { |
| 2469 | let node = self.syntax(); |
| 2470 | let parent = node.parent().expect("Recipe node must have a parent"); |
| 2471 | let node_index = node.index(); |
| 2472 | |
| 2473 | // Build a new RECIPE node |
| 2474 | let mut builder = GreenNodeBuilder::new(); |
| 2475 | builder.start_node(RECIPE.into()); |
| 2476 | builder.token(INDENT.into(), "\t"); |
| 2477 | builder.token(TEXT.into(), text); |
| 2478 | builder.token(NEWLINE.into(), "\n"); |
| 2479 | builder.finish_node(); |
| 2480 | let new_syntax = SyntaxNode::new_root_mut(builder.finish()); |
| 2481 | |
| 2482 | // Insert after this recipe |
| 2483 | parent.splice_children(node_index + 1..node_index + 1, vec![new_syntax.into()]); |
| 2484 | } |
| 2485 | |
| 2486 | /// Remove this recipe line from its parent |
| 2487 | /// |
| 2488 | /// # Example |
| 2489 | /// ``` |
| 2490 | /// use makefile_lossless::Makefile; |
| 2491 | /// |
| 2492 | /// let mut makefile: Makefile = "all:\n\techo hello\n\techo world\n".parse().unwrap(); |
| 2493 | /// let mut rule = makefile.rules().next().unwrap(); |
| 2494 | /// let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 2495 | /// recipe.remove(); |
| 2496 | /// assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["echo world"]); |
| 2497 | /// ``` |
| 2498 | pub fn remove(&self) { |
| 2499 | let node = self.syntax(); |
| 2500 | let parent = node.parent().expect("Recipe node must have a parent"); |
| 2501 | let node_index = node.index(); |
| 2502 | |
| 2503 | // Remove this recipe node from its parent |
| 2504 | parent.splice_children(node_index..node_index + 1, vec![]); |
| 2505 | } |
| 2506 | |
| 2507 | /// Iterate `$(VAR)` and `${VAR}` variable references inside this recipe. |
| 2508 | /// |
| 2509 | /// Recipe bodies are stored as raw text, so [`Makefile::variable_references`] |
| 2510 | /// does not descend into them. This method scans the recipe's text directly |
| 2511 | /// and yields each reference with its absolute source range. |
| 2512 | /// |
| 2513 | /// Function calls (`$(shell ...)`, anything with whitespace or commas after |
| 2514 | /// the name) and automatic variables (`$@`, `$<`, numeric `$1`) are skipped; |
| 2515 | /// only plain variable references are returned. |
| 2516 | /// |
| 2517 | /// # Example |
| 2518 | /// ``` |
| 2519 | /// use makefile_lossless::Makefile; |
| 2520 | /// |
| 2521 | /// let makefile: Makefile = "all:\n\techo $(FOO) ${BAR}\n".parse().unwrap(); |
| 2522 | /// let rule = makefile.rules().next().unwrap(); |
| 2523 | /// let recipe = rule.recipe_nodes().next().unwrap(); |
| 2524 | /// let names: Vec<_> = recipe |
| 2525 | /// .variable_references() |
| 2526 | /// .iter() |
| 2527 | /// .map(|r| r.name().to_string()) |
| 2528 | /// .collect(); |
| 2529 | /// assert_eq!(names, vec!["FOO", "BAR"]); |
| 2530 | /// ``` |
| 2531 | pub fn variable_references(&self) -> Vec<RecipeVariableReference> { |
| 2532 | let mut out = Vec::new(); |
| 2533 | for token in self |
| 2534 | .syntax() |
| 2535 | .children_with_tokens() |
| 2536 | .filter_map(|it| it.into_token()) |
| 2537 | .filter(|t| t.kind() == TEXT) |
| 2538 | { |
| 2539 | let base: u32 = token.text_range().start().into(); |
| 2540 | scan_recipe_variable_refs(token.text(), base, &mut out); |
| 2541 | } |
| 2542 | out |
| 2543 | } |
| 2544 | } |
| 2545 | |
| 2546 | /// A `$(VAR)` or `${VAR}` reference found inside a recipe body. |
| 2547 | /// |
| 2548 | /// Recipes are stored as raw text, so these references have no backing syntax |
| 2549 | /// node; this type carries just the variable name and its absolute source range. |
| 2550 | #[derive(Clone, Debug, PartialEq, Eq)] |
| 2551 | pub struct RecipeVariableReference { |
| 2552 | name: String, |
| 2553 | range: rowan::TextRange, |
| 2554 | } |
| 2555 | |
| 2556 | impl RecipeVariableReference { |
| 2557 | /// The referenced variable name (without the surrounding `$(...)`). |
| 2558 | pub fn name(&self) -> &str { |
| 2559 | &self.name |
| 2560 | } |
| 2561 | |
| 2562 | /// The absolute source range covering just the variable name. |
| 2563 | pub fn text_range(&self) -> rowan::TextRange { |
| 2564 | self.range |
| 2565 | } |
| 2566 | } |
| 2567 | |
| 2568 | /// Scan `text` for `$(VAR)` / `${VAR}` references, pushing each onto `out` with |
| 2569 | /// ranges offset by `base` (the absolute start of `text` in the source). |
| 2570 | fn scan_recipe_variable_refs(text: &str, base: u32, out: &mut Vec<RecipeVariableReference>) { |
| 2571 | let bytes = text.as_bytes(); |
| 2572 | let mut i = 0; |
| 2573 | while i < bytes.len() { |
| 2574 | if bytes[i] != b'$' || i + 1 >= bytes.len() { |
| 2575 | i += 1; |
| 2576 | continue; |
| 2577 | } |
| 2578 | let close = match bytes[i + 1] { |
| 2579 | b'(' => b')', |
| 2580 | b'{' => b'}', |
| 2581 | _ => { |
| 2582 | i += 2; |
| 2583 | continue; |
| 2584 | } |
| 2585 | }; |
| 2586 | let name_start = i + 2; |
| 2587 | let Some(rel_end) = bytes[name_start..].iter().position(|&b| b == close) else { |
| 2588 | i += 2; |
| 2589 | continue; |
| 2590 | }; |
| 2591 | let name_end = name_start + rel_end; |
| 2592 | let name = &text[name_start..name_end]; |
| 2593 | // Skip function calls like $(shell ...): a name with whitespace inside. |
| 2594 | if name.is_empty() || name.contains(char::is_whitespace) { |
| 2595 | i = name_end + 1; |
| 2596 | continue; |
| 2597 | } |
| 2598 | // Skip pure-numeric automatic variables ($1, $2, ...). |
| 2599 | if name.chars().all(|c| c.is_ascii_digit()) { |
| 2600 | i = name_end + 1; |
| 2601 | continue; |
| 2602 | } |
| 2603 | out.push(RecipeVariableReference { |
| 2604 | name: name.to_owned(), |
| 2605 | range: rowan::TextRange::new( |
| 2606 | rowan::TextSize::from(base + name_start as u32), |
| 2607 | rowan::TextSize::from(base + name_end as u32), |
| 2608 | ), |
| 2609 | }); |
| 2610 | i = name_end + 1; |
| 2611 | } |
| 2612 | } |
| 2613 | |
| 2614 | /// |
| 2615 | /// This removes trailing NEWLINE tokens from the end of a RULE node to avoid |
| 2616 | /// extra blank lines at the end of a file when the last rule is removed. |
| 2617 | pub(crate) fn trim_trailing_newlines(node: &SyntaxNode) { |
| 2618 | // Collect all trailing NEWLINE tokens at the end of the rule and within RECIPE nodes |
| 2619 | let mut newlines_to_remove = vec![]; |
| 2620 | let mut current = node.last_child_or_token(); |
| 2621 | |
| 2622 | while let Some(element) = current { |
| 2623 | match &element { |
| 2624 | rowan::NodeOrToken::Token(token) if token.kind() == NEWLINE => { |
| 2625 | newlines_to_remove.push(token.clone()); |
| 2626 | current = token.prev_sibling_or_token(); |
| 2627 | } |
| 2628 | rowan::NodeOrToken::Node(n) if n.kind() == RECIPE => { |
| 2629 | // Also check for trailing newlines in the RECIPE node |
| 2630 | let mut recipe_current = n.last_child_or_token(); |
| 2631 | while let Some(recipe_element) = recipe_current { |
| 2632 | match &recipe_element { |
| 2633 | rowan::NodeOrToken::Token(token) if token.kind() == NEWLINE => { |
| 2634 | newlines_to_remove.push(token.clone()); |
| 2635 | recipe_current = token.prev_sibling_or_token(); |
| 2636 | } |
| 2637 | _ => break, |
| 2638 | } |
| 2639 | } |
| 2640 | break; // Stop after checking the last RECIPE node |
| 2641 | } |
| 2642 | _ => break, |
| 2643 | } |
| 2644 | } |
| 2645 | |
| 2646 | // Remove all but one trailing newline (keep at least one) |
| 2647 | // Remove from highest index to lowest to avoid index shifts |
| 2648 | if newlines_to_remove.len() > 1 { |
| 2649 | // Sort by index descending |
| 2650 | newlines_to_remove.sort_by_key(|t| std::cmp::Reverse(t.index())); |
| 2651 | |
| 2652 | for token in newlines_to_remove.iter().take(newlines_to_remove.len() - 1) { |
| 2653 | let parent = token.parent().unwrap(); |
| 2654 | let idx = token.index(); |
| 2655 | parent.splice_children(idx..idx + 1, vec![]); |
| 2656 | } |
| 2657 | } |
| 2658 | } |
| 2659 | |
| 2660 | /// Helper function to remove a node along with its preceding comments and up to 1 empty line. |
| 2661 | /// |
| 2662 | /// This walks backward from the node, removing: |
| 2663 | /// - The node itself |
| 2664 | /// - All preceding comments (COMMENT tokens) |
| 2665 | /// - Up to 1 empty line (consecutive NEWLINE tokens) |
| 2666 | /// - Any WHITESPACE tokens between these elements |
| 2667 | pub(crate) fn remove_with_preceding_comments(node: &SyntaxNode, parent: &SyntaxNode) { |
| 2668 | let mut collected_elements = vec![]; |
| 2669 | let mut found_comment = false; |
| 2670 | |
| 2671 | // Walk backward to collect preceding comments, newlines, and whitespace |
| 2672 | let mut current = node.prev_sibling_or_token(); |
| 2673 | while let Some(element) = current { |
| 2674 | match &element { |
| 2675 | rowan::NodeOrToken::Token(token) => match token.kind() { |
| 2676 | COMMENT => { |
| 2677 | if token.text().starts_with("#!") { |
| 2678 | break; // Don't remove shebang lines |
| 2679 | } |
| 2680 | found_comment = true; |
| 2681 | collected_elements.push(element.clone()); |
| 2682 | } |
| 2683 | NEWLINE | WHITESPACE => { |
| 2684 | collected_elements.push(element.clone()); |
| 2685 | } |
| 2686 | _ => break, // Hit something else, stop |
| 2687 | }, |
| 2688 | rowan::NodeOrToken::Node(n) => { |
| 2689 | // Handle BLANK_LINE nodes which wrap newlines |
| 2690 | if n.kind() == BLANK_LINE { |
| 2691 | collected_elements.push(element.clone()); |
| 2692 | } else { |
| 2693 | break; // Hit another node type, stop |
| 2694 | } |
| 2695 | } |
| 2696 | } |
| 2697 | current = element.prev_sibling_or_token(); |
| 2698 | } |
| 2699 | |
| 2700 | // Determine which preceding elements to remove |
| 2701 | // If we found comments, remove them along with up to 1 blank line |
| 2702 | let mut elements_to_remove = vec![]; |
| 2703 | let mut consecutive_newlines = 0; |
| 2704 | for element in collected_elements.iter().rev() { |
| 2705 | let should_remove = match element { |
| 2706 | rowan::NodeOrToken::Token(token) => match token.kind() { |
| 2707 | COMMENT => { |
| 2708 | consecutive_newlines = 0; |
| 2709 | found_comment |
| 2710 | } |
| 2711 | NEWLINE => { |
| 2712 | consecutive_newlines += 1; |
| 2713 | found_comment && consecutive_newlines <= 1 |
| 2714 | } |
| 2715 | WHITESPACE => found_comment, |
| 2716 | _ => false, |
| 2717 | }, |
| 2718 | rowan::NodeOrToken::Node(n) => { |
| 2719 | // Handle BLANK_LINE nodes (count as newlines) |
| 2720 | if n.kind() == BLANK_LINE { |
| 2721 | consecutive_newlines += 1; |
| 2722 | found_comment && consecutive_newlines <= 1 |
| 2723 | } else { |
| 2724 | false |
| 2725 | } |
| 2726 | } |
| 2727 | }; |
| 2728 | |
| 2729 | if should_remove { |
| 2730 | elements_to_remove.push(element.clone()); |
| 2731 | } |
| 2732 | } |
| 2733 | |
| 2734 | // Remove elements in reverse order (from highest index to lowest) to avoid index shifts |
| 2735 | // Start with the node itself, then preceding elements |
| 2736 | let mut all_to_remove = vec![rowan::NodeOrToken::Node(node.clone())]; |
| 2737 | all_to_remove.extend(elements_to_remove.into_iter().rev()); |
| 2738 | |
| 2739 | // Sort by index in descending order |
| 2740 | all_to_remove.sort_by_key(|el| std::cmp::Reverse(el.index())); |
| 2741 | |
| 2742 | for element in all_to_remove { |
| 2743 | let idx = element.index(); |
| 2744 | parent.splice_children(idx..idx + 1, vec![]); |
| 2745 | } |
| 2746 | } |
| 2747 | |
| 2748 | impl FromStr for Rule { |
| 2749 | type Err = crate::Error; |
| 2750 | |
| 2751 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 2752 | Rule::parse(s).to_rule_result() |
| 2753 | } |
| 2754 | } |
| 2755 | |
| 2756 | impl FromStr for Makefile { |
| 2757 | type Err = crate::Error; |
| 2758 | |
| 2759 | fn from_str(s: &str) -> Result<Self, Self::Err> { |
| 2760 | Makefile::parse(s).to_result() |
| 2761 | } |
| 2762 | } |
| 2763 | |
| 2764 | #[cfg(test)] |
| 2765 | mod tests { |
| 2766 | use super::*; |
| 2767 | use crate::ast::makefile::MakefileItem; |
| 2768 | use crate::pattern::matches_pattern; |
| 2769 | |
| 2770 | #[test] |
| 2771 | fn test_conditionals() { |
| 2772 | // We'll use relaxed parsing for conditionals |
| 2773 | |
| 2774 | // Basic conditionals - ifdef/ifndef |
| 2775 | let code = "ifdef DEBUG\n DEBUG_FLAG := 1\nendif\n"; |
| 2776 | let mut buf = code.as_bytes(); |
| 2777 | let makefile = Makefile::read_relaxed(&mut buf).expect("Failed to parse basic ifdef"); |
| 2778 | assert!(makefile.code().contains("DEBUG_FLAG")); |
| 2779 | |
| 2780 | // Basic conditionals - ifeq/ifneq |
| 2781 | let code = |
| 2782 | "ifeq ($(OS),Windows_NT)\n RESULT := windows\nelse\n RESULT := unix\nendif\n"; |
| 2783 | let mut buf = code.as_bytes(); |
| 2784 | let makefile = Makefile::read_relaxed(&mut buf).expect("Failed to parse ifeq/ifneq"); |
| 2785 | assert!(makefile.code().contains("RESULT")); |
| 2786 | assert!(makefile.code().contains("windows")); |
| 2787 | |
| 2788 | // Nested conditionals with else |
| 2789 | let code = "ifdef DEBUG\n CFLAGS += -g\n ifdef VERBOSE\n CFLAGS += -v\n endif\nelse\n CFLAGS += -O2\nendif\n"; |
| 2790 | let mut buf = code.as_bytes(); |
| 2791 | let makefile = Makefile::read_relaxed(&mut buf) |
| 2792 | .expect("Failed to parse nested conditionals with else"); |
| 2793 | assert!(makefile.code().contains("CFLAGS")); |
| 2794 | assert!(makefile.code().contains("VERBOSE")); |
| 2795 | |
| 2796 | // Empty conditionals |
| 2797 | let code = "ifdef DEBUG\nendif\n"; |
| 2798 | let mut buf = code.as_bytes(); |
| 2799 | let makefile = |
| 2800 | Makefile::read_relaxed(&mut buf).expect("Failed to parse empty conditionals"); |
| 2801 | assert!(makefile.code().contains("ifdef DEBUG")); |
| 2802 | |
| 2803 | // Conditionals with else ifeq |
| 2804 | let code = "ifeq ($(OS),Windows)\n EXT := .exe\nelse ifeq ($(OS),Linux)\n EXT := .bin\nelse\n EXT := .out\nendif\n"; |
| 2805 | let mut buf = code.as_bytes(); |
| 2806 | let makefile = |
| 2807 | Makefile::read_relaxed(&mut buf).expect("Failed to parse conditionals with else ifeq"); |
| 2808 | assert!(makefile.code().contains("EXT")); |
| 2809 | |
| 2810 | // Invalid conditionals - this should generate parse errors but still produce a Makefile |
| 2811 | let code = "ifXYZ DEBUG\nDEBUG := 1\nendif\n"; |
| 2812 | let mut buf = code.as_bytes(); |
| 2813 | let makefile = Makefile::read_relaxed(&mut buf).expect("Failed to parse with recovery"); |
| 2814 | assert!(makefile.code().contains("DEBUG")); |
| 2815 | |
| 2816 | // Missing condition - this should also generate parse errors but still produce a Makefile |
| 2817 | let code = "ifdef \nDEBUG := 1\nendif\n"; |
| 2818 | let mut buf = code.as_bytes(); |
| 2819 | let makefile = Makefile::read_relaxed(&mut buf) |
| 2820 | .expect("Failed to parse with recovery - missing condition"); |
| 2821 | assert!(makefile.code().contains("DEBUG")); |
| 2822 | } |
| 2823 | |
| 2824 | #[test] |
| 2825 | fn test_variable_named_like_conditional() { |
| 2826 | // A variable whose name starts with "if" must not be mistaken for a |
| 2827 | // conditional directive (regression: `ifpkg` parsed as `ifdef`). |
| 2828 | let code = "ifpkg = $(if $(filter foo,bar),baz)\n"; |
| 2829 | let makefile: Makefile = code.parse().expect("ifpkg variable should parse"); |
| 2830 | assert_eq!(code, makefile.to_string()); |
| 2831 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 2832 | assert_eq!(1, vars.len()); |
| 2833 | assert_eq!(Some("ifpkg".to_string()), vars[0].name()); |
| 2834 | } |
| 2835 | |
| 2836 | #[test] |
| 2837 | fn test_conditional_with_trailing_comment() { |
| 2838 | let code = "ifeq ($(X), linux) # extra features\nFOO = bar\nendif\n"; |
| 2839 | let makefile: Makefile = code.parse().expect("trailing comment should parse"); |
| 2840 | assert_eq!(code, makefile.to_string()); |
| 2841 | } |
| 2842 | |
| 2843 | #[test] |
| 2844 | fn test_rule_with_continuation_in_targets() { |
| 2845 | let code = "a b \\\nc: dep\n\techo hi\n"; |
| 2846 | let makefile: Makefile = code.parse().expect("continuation in targets should parse"); |
| 2847 | assert_eq!(code, makefile.to_string()); |
| 2848 | let rules: Vec<_> = makefile.rules().collect(); |
| 2849 | assert_eq!(1, rules.len()); |
| 2850 | assert_eq!( |
| 2851 | vec!["a".to_string(), "b".to_string(), "c".to_string()], |
| 2852 | rules[0].targets().collect::<Vec<_>>() |
| 2853 | ); |
| 2854 | } |
| 2855 | |
| 2856 | #[test] |
| 2857 | fn test_rule_with_indented_continuation_in_targets() { |
| 2858 | // The continued target line is tab-indented; the indent delimits |
| 2859 | // targets rather than becoming part of the target name. |
| 2860 | let code = "a b \\\n\tc: dep\n\techo hi\n"; |
| 2861 | let makefile: Makefile = code |
| 2862 | .parse() |
| 2863 | .expect("indented target continuation should parse"); |
| 2864 | assert_eq!(code, makefile.to_string()); |
| 2865 | let rules: Vec<_> = makefile.rules().collect(); |
| 2866 | assert_eq!(1, rules.len()); |
| 2867 | assert_eq!( |
| 2868 | vec!["a".to_string(), "b".to_string(), "c".to_string()], |
| 2869 | rules[0].targets().collect::<Vec<_>>() |
| 2870 | ); |
| 2871 | } |
| 2872 | |
| 2873 | #[test] |
| 2874 | fn test_rule_with_continuation_in_prerequisites() { |
| 2875 | // A prerequisite list continued onto a tab-indented line. The |
| 2876 | // continuation must not be folded into a prerequisite word, and the |
| 2877 | // continued prerequisites must still be recognised. |
| 2878 | let code = "all: a b \\\n\tc d\n\techo hi\n"; |
| 2879 | let makefile: Makefile = code |
| 2880 | .parse() |
| 2881 | .expect("prerequisite continuation should parse"); |
| 2882 | assert_eq!(code, makefile.to_string()); |
| 2883 | let rules: Vec<_> = makefile.rules().collect(); |
| 2884 | assert_eq!(1, rules.len()); |
| 2885 | assert_eq!( |
| 2886 | vec![ |
| 2887 | "a".to_string(), |
| 2888 | "b".to_string(), |
| 2889 | "c".to_string(), |
| 2890 | "d".to_string() |
| 2891 | ], |
| 2892 | rules[0].prerequisites().collect::<Vec<_>>() |
| 2893 | ); |
| 2894 | } |
| 2895 | |
| 2896 | #[test] |
| 2897 | fn test_rule_prerequisite_escaped_backslash_not_continuation() { |
| 2898 | // An escaped backslash (`\\`) ending a prerequisite line is a literal |
| 2899 | // backslash, not a continuation, so the next line is a recipe. |
| 2900 | let code = "all: a b\\\\\n\techo hi\n"; |
| 2901 | let makefile: Makefile = code.parse().expect("escaped backslash should parse"); |
| 2902 | assert_eq!(code, makefile.to_string()); |
| 2903 | let rules: Vec<_> = makefile.rules().collect(); |
| 2904 | assert_eq!(1, rules.len()); |
| 2905 | assert_eq!( |
| 2906 | vec!["a".to_string(), "b\\\\".to_string()], |
| 2907 | rules[0].prerequisites().collect::<Vec<_>>() |
| 2908 | ); |
| 2909 | assert_eq!( |
| 2910 | vec!["echo hi".to_string()], |
| 2911 | rules[0].recipes().collect::<Vec<_>>() |
| 2912 | ); |
| 2913 | } |
| 2914 | |
| 2915 | #[test] |
| 2916 | fn test_assignment_with_tab_continuation() { |
| 2917 | // A variable value continued onto a tab-indented line, as commonly |
| 2918 | // seen in debian/rules. The continuation must not be mistaken for a |
| 2919 | // recipe line (which previously produced a spurious "recipe line is |
| 2920 | // not attached to any target" error). |
| 2921 | let code = "NATIVE_ARCHS += alpha arc hppa \\\n\triscv64 sh4 sparc\n"; |
| 2922 | let makefile: Makefile = code.parse().expect("tab continuation should parse"); |
| 2923 | assert_eq!(code, makefile.to_string()); |
| 2924 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 2925 | assert_eq!(1, vars.len()); |
| 2926 | assert_eq!(Some("NATIVE_ARCHS".to_string()), vars[0].name()); |
| 2927 | assert_eq!( |
| 2928 | Some("alpha arc hppa \\\n\triscv64 sh4 sparc".to_string()), |
| 2929 | vars[0].raw_value() |
| 2930 | ); |
| 2931 | } |
| 2932 | |
| 2933 | #[test] |
| 2934 | fn test_assignment_escaped_backslash_not_continuation() { |
| 2935 | // A value ending in an escaped backslash (`\\`) is a literal backslash, |
| 2936 | // not a line continuation, so the following line is not folded into the |
| 2937 | // value. An odd run of backslashes still continues the line. |
| 2938 | let code = "VAR = foo \\\\\n\tbar\n"; |
| 2939 | let makefile: Makefile = code.parse().expect("escaped backslash should parse"); |
| 2940 | assert_eq!(code, makefile.to_string()); |
| 2941 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 2942 | assert_eq!(1, vars.len()); |
| 2943 | assert_eq!(Some("foo \\\\".to_string()), vars[0].raw_value()); |
| 2944 | |
| 2945 | let code = "VAR = foo \\\\\\\n\tbar\n"; |
| 2946 | let makefile: Makefile = code.parse().expect("odd backslash run should parse"); |
| 2947 | assert_eq!(code, makefile.to_string()); |
| 2948 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 2949 | assert_eq!(Some("foo \\\\\\\n\tbar".to_string()), vars[0].raw_value()); |
| 2950 | } |
| 2951 | |
| 2952 | #[test] |
| 2953 | fn test_define_endef() { |
| 2954 | let code = "define greeting\n\techo hello\n\techo world\nendef\n\nall:\n\t$(greeting)\n"; |
| 2955 | let makefile: Makefile = code.parse().expect("define/endef should parse"); |
| 2956 | assert_eq!(code, makefile.to_string()); |
| 2957 | assert_eq!(1, makefile.rules().count()); |
| 2958 | } |
| 2959 | |
| 2960 | #[test] |
| 2961 | fn test_define_endef_nested() { |
| 2962 | let code = "define outer\ndefine inner\nbody\nendef\nendef\n"; |
| 2963 | let makefile: Makefile = code.parse().expect("nested define/endef should parse"); |
| 2964 | assert_eq!(code, makefile.to_string()); |
| 2965 | } |
| 2966 | |
| 2967 | #[test] |
| 2968 | fn test_parse_simple() { |
| 2969 | const SIMPLE: &str = r#"VARIABLE = value |
| 2970 | |
| 2971 | rule: dependency |
| 2972 | command |
| 2973 | "#; |
| 2974 | let parsed = parse(SIMPLE, None); |
| 2975 | assert!(parsed.errors.is_empty()); |
| 2976 | let node = parsed.syntax(); |
| 2977 | assert_eq!( |
| 2978 | format!("{:#?}", node), |
| 2979 | r#"[email protected] |
| 2980 | [email protected] |
| 2981 | [email protected] "VARIABLE" |
| 2982 | [email protected] " " |
| 2983 | [email protected] "=" |
| 2984 | [email protected] " " |
| 2985 | [email protected] |
| 2986 | [email protected] "value" |
| 2987 | [email protected] "\n" |
| 2988 | [email protected] |
| 2989 | [email protected] "\n" |
| 2990 | [email protected] |
| 2991 | [email protected] |
| 2992 | [email protected] "rule" |
| 2993 | [email protected] ":" |
| 2994 | [email protected] " " |
| 2995 | [email protected] |
| 2996 | [email protected] |
| 2997 | [email protected] "dependency" |
| 2998 | [email protected] "\n" |
| 2999 | [email protected] |
| 3000 | [email protected] "\t" |
| 3001 | [email protected] "command" |
| 3002 | [email protected] "\n" |
| 3003 | "# |
| 3004 | ); |
| 3005 | |
| 3006 | let root = parsed.root(); |
| 3007 | |
| 3008 | let mut rules = root.rules().collect::<Vec<_>>(); |
| 3009 | assert_eq!(rules.len(), 1); |
| 3010 | let rule = rules.pop().unwrap(); |
| 3011 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["rule"]); |
| 3012 | assert_eq!(rule.prerequisites().collect::<Vec<_>>(), vec!["dependency"]); |
| 3013 | assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command"]); |
| 3014 | |
| 3015 | let mut variables = root.variable_definitions().collect::<Vec<_>>(); |
| 3016 | assert_eq!(variables.len(), 1); |
| 3017 | let variable = variables.pop().unwrap(); |
| 3018 | assert_eq!(variable.name(), Some("VARIABLE".to_string())); |
| 3019 | assert_eq!(variable.raw_value(), Some("value".to_string())); |
| 3020 | } |
| 3021 | |
| 3022 | #[test] |
| 3023 | fn test_parse_export_assign() { |
| 3024 | const EXPORT: &str = r#"export VARIABLE := value |
| 3025 | "#; |
| 3026 | let parsed = parse(EXPORT, None); |
| 3027 | assert!(parsed.errors.is_empty()); |
| 3028 | let node = parsed.syntax(); |
| 3029 | assert_eq!( |
| 3030 | format!("{:#?}", node), |
| 3031 | r#"[email protected] |
| 3032 | [email protected] |
| 3033 | [email protected] "export" |
| 3034 | [email protected] " " |
| 3035 | [email protected] "VARIABLE" |
| 3036 | [email protected] " " |
| 3037 | [email protected] ":=" |
| 3038 | [email protected] " " |
| 3039 | [email protected] |
| 3040 | [email protected] "value" |
| 3041 | [email protected] "\n" |
| 3042 | "# |
| 3043 | ); |
| 3044 | |
| 3045 | let root = parsed.root(); |
| 3046 | |
| 3047 | let mut variables = root.variable_definitions().collect::<Vec<_>>(); |
| 3048 | assert_eq!(variables.len(), 1); |
| 3049 | let variable = variables.pop().unwrap(); |
| 3050 | assert_eq!(variable.name(), Some("VARIABLE".to_string())); |
| 3051 | assert_eq!(variable.raw_value(), Some("value".to_string())); |
| 3052 | } |
| 3053 | |
| 3054 | #[test] |
| 3055 | fn test_parse_multiple_prerequisites() { |
| 3056 | const MULTIPLE_PREREQUISITES: &str = r#"rule: dependency1 dependency2 |
| 3057 | command |
| 3058 | |
| 3059 | "#; |
| 3060 | let parsed = parse(MULTIPLE_PREREQUISITES, None); |
| 3061 | assert!(parsed.errors.is_empty()); |
| 3062 | let node = parsed.syntax(); |
| 3063 | assert_eq!( |
| 3064 | format!("{:#?}", node), |
| 3065 | r#"[email protected] |
| 3066 | [email protected] |
| 3067 | [email protected] |
| 3068 | [email protected] "rule" |
| 3069 | [email protected] ":" |
| 3070 | [email protected] " " |
| 3071 | [email protected] |
| 3072 | [email protected] |
| 3073 | [email protected] "dependency1" |
| 3074 | [email protected] " " |
| 3075 | [email protected] |
| 3076 | [email protected] "dependency2" |
| 3077 | [email protected] "\n" |
| 3078 | [email protected] |
| 3079 | [email protected] "\t" |
| 3080 | [email protected] "command" |
| 3081 | [email protected] "\n" |
| 3082 | [email protected] "\n" |
| 3083 | "# |
| 3084 | ); |
| 3085 | let root = parsed.root(); |
| 3086 | |
| 3087 | let rule = root.rules().next().unwrap(); |
| 3088 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["rule"]); |
| 3089 | assert_eq!( |
| 3090 | rule.prerequisites().collect::<Vec<_>>(), |
| 3091 | vec!["dependency1", "dependency2"] |
| 3092 | ); |
| 3093 | assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command"]); |
| 3094 | } |
| 3095 | |
| 3096 | #[test] |
| 3097 | fn test_add_rule() { |
| 3098 | let mut makefile = Makefile::new(); |
| 3099 | let rule = makefile.add_rule("rule"); |
| 3100 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["rule"]); |
| 3101 | assert_eq!( |
| 3102 | rule.prerequisites().collect::<Vec<_>>(), |
| 3103 | Vec::<String>::new() |
| 3104 | ); |
| 3105 | |
| 3106 | assert_eq!(makefile.to_string(), "rule:\n"); |
| 3107 | } |
| 3108 | |
| 3109 | #[test] |
| 3110 | fn test_add_rule_with_shebang() { |
| 3111 | // Regression test for bug where add_rule() panics on makefiles with shebangs |
| 3112 | let content = r#"#!/usr/bin/make -f |
| 3113 | |
| 3114 | build: blah |
| 3115 | $(MAKE) install |
| 3116 | |
| 3117 | clean: |
| 3118 | dh_clean |
| 3119 | "#; |
| 3120 | |
| 3121 | let mut makefile = Makefile::read_relaxed(content.as_bytes()).unwrap(); |
| 3122 | let initial_count = makefile.rules().count(); |
| 3123 | assert_eq!(initial_count, 2); |
| 3124 | |
| 3125 | // This should not panic |
| 3126 | let rule = makefile.add_rule("build-indep"); |
| 3127 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["build-indep"]); |
| 3128 | |
| 3129 | // Should have one more rule now |
| 3130 | assert_eq!(makefile.rules().count(), initial_count + 1); |
| 3131 | } |
| 3132 | |
| 3133 | #[test] |
| 3134 | fn test_add_rule_formatting() { |
| 3135 | // Regression test for formatting issues when adding rules |
| 3136 | let content = r#"build: blah |
| 3137 | $(MAKE) install |
| 3138 | |
| 3139 | clean: |
| 3140 | dh_clean |
| 3141 | "#; |
| 3142 | |
| 3143 | let mut makefile = Makefile::read_relaxed(content.as_bytes()).unwrap(); |
| 3144 | let mut rule = makefile.add_rule("build-indep"); |
| 3145 | rule.add_prerequisite("build").unwrap(); |
| 3146 | |
| 3147 | let expected = r#"build: blah |
| 3148 | $(MAKE) install |
| 3149 | |
| 3150 | clean: |
| 3151 | dh_clean |
| 3152 | |
| 3153 | build-indep: build |
| 3154 | "#; |
| 3155 | |
| 3156 | assert_eq!(makefile.to_string(), expected); |
| 3157 | } |
| 3158 | |
| 3159 | #[test] |
| 3160 | fn test_push_command() { |
| 3161 | let mut makefile = Makefile::new(); |
| 3162 | let mut rule = makefile.add_rule("rule"); |
| 3163 | |
| 3164 | // Add commands in place to the rule |
| 3165 | rule.push_command("command"); |
| 3166 | rule.push_command("command2"); |
| 3167 | |
| 3168 | // Check the commands in the rule |
| 3169 | assert_eq!( |
| 3170 | rule.recipes().collect::<Vec<_>>(), |
| 3171 | vec!["command", "command2"] |
| 3172 | ); |
| 3173 | |
| 3174 | // Add a third command |
| 3175 | rule.push_command("command3"); |
| 3176 | assert_eq!( |
| 3177 | rule.recipes().collect::<Vec<_>>(), |
| 3178 | vec!["command", "command2", "command3"] |
| 3179 | ); |
| 3180 | |
| 3181 | // Check if the makefile was modified |
| 3182 | assert_eq!( |
| 3183 | makefile.to_string(), |
| 3184 | "rule:\n\tcommand\n\tcommand2\n\tcommand3\n" |
| 3185 | ); |
| 3186 | |
| 3187 | // The rule should have the same string representation |
| 3188 | assert_eq!( |
| 3189 | rule.to_string(), |
| 3190 | "rule:\n\tcommand\n\tcommand2\n\tcommand3\n" |
| 3191 | ); |
| 3192 | } |
| 3193 | |
| 3194 | #[test] |
| 3195 | fn test_replace_command() { |
| 3196 | let mut makefile = Makefile::new(); |
| 3197 | let mut rule = makefile.add_rule("rule"); |
| 3198 | |
| 3199 | // Add commands in place |
| 3200 | rule.push_command("command"); |
| 3201 | rule.push_command("command2"); |
| 3202 | |
| 3203 | // Check the commands in the rule |
| 3204 | assert_eq!( |
| 3205 | rule.recipes().collect::<Vec<_>>(), |
| 3206 | vec!["command", "command2"] |
| 3207 | ); |
| 3208 | |
| 3209 | // Replace the first command |
| 3210 | rule.replace_command(0, "new command"); |
| 3211 | assert_eq!( |
| 3212 | rule.recipes().collect::<Vec<_>>(), |
| 3213 | vec!["new command", "command2"] |
| 3214 | ); |
| 3215 | |
| 3216 | // Check if the makefile was modified |
| 3217 | assert_eq!(makefile.to_string(), "rule:\n\tnew command\n\tcommand2\n"); |
| 3218 | |
| 3219 | // The rule should have the same string representation |
| 3220 | assert_eq!(rule.to_string(), "rule:\n\tnew command\n\tcommand2\n"); |
| 3221 | } |
| 3222 | |
| 3223 | #[test] |
| 3224 | fn test_replace_command_with_comments() { |
| 3225 | // Regression test for bug where replace_command() inserts instead of replacing |
| 3226 | // when the rule contains comments |
| 3227 | let content = b"override_dh_strip:\n\t# no longer necessary after buster\n\tdh_strip --dbgsym-migration='amule-dbg (<< 1:2.3.2-2~)'\n"; |
| 3228 | |
| 3229 | let makefile = Makefile::read_relaxed(&content[..]).unwrap(); |
| 3230 | |
| 3231 | let mut rule = makefile.rules().next().unwrap(); |
| 3232 | |
| 3233 | // Before replacement, there should be 2 recipe nodes (comment + command) |
| 3234 | assert_eq!(rule.recipe_nodes().count(), 2); |
| 3235 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 3236 | assert_eq!(recipes[0].text(), ""); // comment-only |
| 3237 | assert_eq!( |
| 3238 | recipes[1].text(), |
| 3239 | "dh_strip --dbgsym-migration='amule-dbg (<< 1:2.3.2-2~)'" |
| 3240 | ); |
| 3241 | |
| 3242 | // Replace the second recipe (index 1, the actual command) |
| 3243 | assert!(rule.replace_command(1, "dh_strip")); |
| 3244 | |
| 3245 | // After replacement, there should still be 2 recipe nodes |
| 3246 | assert_eq!(rule.recipe_nodes().count(), 2); |
| 3247 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 3248 | assert_eq!(recipes[0].text(), ""); // comment still there |
| 3249 | assert_eq!(recipes[1].text(), "dh_strip"); |
| 3250 | } |
| 3251 | |
| 3252 | #[test] |
| 3253 | fn test_parse_rule_without_newline() { |
| 3254 | let rule = "rule: dependency\n\tcommand".parse::<Rule>().unwrap(); |
| 3255 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["rule"]); |
| 3256 | assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command"]); |
| 3257 | let rule = "rule: dependency".parse::<Rule>().unwrap(); |
| 3258 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["rule"]); |
| 3259 | assert_eq!(rule.recipes().collect::<Vec<_>>(), Vec::<String>::new()); |
| 3260 | } |
| 3261 | |
| 3262 | #[test] |
| 3263 | fn test_parse_makefile_without_newline() { |
| 3264 | let makefile = "rule: dependency\n\tcommand".parse::<Makefile>().unwrap(); |
| 3265 | assert_eq!(makefile.rules().count(), 1); |
| 3266 | } |
| 3267 | |
| 3268 | #[test] |
| 3269 | fn test_from_reader() { |
| 3270 | let makefile = Makefile::from_reader("rule: dependency\n\tcommand".as_bytes()).unwrap(); |
| 3271 | assert_eq!(makefile.rules().count(), 1); |
| 3272 | } |
| 3273 | |
| 3274 | #[test] |
| 3275 | fn test_parse_with_tab_after_last_newline() { |
| 3276 | let makefile = Makefile::from_reader("rule: dependency\n\tcommand\n\t".as_bytes()).unwrap(); |
| 3277 | assert_eq!(makefile.rules().count(), 1); |
| 3278 | } |
| 3279 | |
| 3280 | #[test] |
| 3281 | fn test_parse_with_space_after_last_newline() { |
| 3282 | let makefile = Makefile::from_reader("rule: dependency\n\tcommand\n ".as_bytes()).unwrap(); |
| 3283 | assert_eq!(makefile.rules().count(), 1); |
| 3284 | } |
| 3285 | |
| 3286 | #[test] |
| 3287 | fn test_parse_with_comment_after_last_newline() { |
| 3288 | let makefile = |
| 3289 | Makefile::from_reader("rule: dependency\n\tcommand\n#comment".as_bytes()).unwrap(); |
| 3290 | assert_eq!(makefile.rules().count(), 1); |
| 3291 | } |
| 3292 | |
| 3293 | #[test] |
| 3294 | fn test_parse_with_variable_rule() { |
| 3295 | let makefile = |
| 3296 | Makefile::from_reader("RULE := rule\n$(RULE): dependency\n\tcommand".as_bytes()) |
| 3297 | .unwrap(); |
| 3298 | |
| 3299 | // Check variable definition |
| 3300 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3301 | assert_eq!(vars.len(), 1); |
| 3302 | assert_eq!(vars[0].name(), Some("RULE".to_string())); |
| 3303 | assert_eq!(vars[0].raw_value(), Some("rule".to_string())); |
| 3304 | |
| 3305 | // Check rule |
| 3306 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3307 | assert_eq!(rules.len(), 1); |
| 3308 | assert_eq!(rules[0].targets().collect::<Vec<_>>(), vec!["$(RULE)"]); |
| 3309 | assert_eq!( |
| 3310 | rules[0].prerequisites().collect::<Vec<_>>(), |
| 3311 | vec!["dependency"] |
| 3312 | ); |
| 3313 | assert_eq!(rules[0].recipes().collect::<Vec<_>>(), vec!["command"]); |
| 3314 | } |
| 3315 | |
| 3316 | #[test] |
| 3317 | fn test_parse_with_variable_dependency() { |
| 3318 | let makefile = |
| 3319 | Makefile::from_reader("DEP := dependency\nrule: $(DEP)\n\tcommand".as_bytes()).unwrap(); |
| 3320 | |
| 3321 | // Check variable definition |
| 3322 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3323 | assert_eq!(vars.len(), 1); |
| 3324 | assert_eq!(vars[0].name(), Some("DEP".to_string())); |
| 3325 | assert_eq!(vars[0].raw_value(), Some("dependency".to_string())); |
| 3326 | |
| 3327 | // Check rule |
| 3328 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3329 | assert_eq!(rules.len(), 1); |
| 3330 | assert_eq!(rules[0].targets().collect::<Vec<_>>(), vec!["rule"]); |
| 3331 | assert_eq!(rules[0].prerequisites().collect::<Vec<_>>(), vec!["$(DEP)"]); |
| 3332 | assert_eq!(rules[0].recipes().collect::<Vec<_>>(), vec!["command"]); |
| 3333 | } |
| 3334 | |
| 3335 | #[test] |
| 3336 | fn test_parse_with_variable_command() { |
| 3337 | let makefile = |
| 3338 | Makefile::from_reader("COM := command\nrule: dependency\n\t$(COM)".as_bytes()).unwrap(); |
| 3339 | |
| 3340 | // Check variable definition |
| 3341 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3342 | assert_eq!(vars.len(), 1); |
| 3343 | assert_eq!(vars[0].name(), Some("COM".to_string())); |
| 3344 | assert_eq!(vars[0].raw_value(), Some("command".to_string())); |
| 3345 | |
| 3346 | // Check rule |
| 3347 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3348 | assert_eq!(rules.len(), 1); |
| 3349 | assert_eq!(rules[0].targets().collect::<Vec<_>>(), vec!["rule"]); |
| 3350 | assert_eq!( |
| 3351 | rules[0].prerequisites().collect::<Vec<_>>(), |
| 3352 | vec!["dependency"] |
| 3353 | ); |
| 3354 | assert_eq!(rules[0].recipes().collect::<Vec<_>>(), vec!["$(COM)"]); |
| 3355 | } |
| 3356 | |
| 3357 | #[test] |
| 3358 | fn test_regular_line_error_reporting() { |
| 3359 | let input = "rule target\n\tcommand"; |
| 3360 | |
| 3361 | // Test both APIs with one input |
| 3362 | let parsed = parse(input, None); |
| 3363 | let direct_error = &parsed.errors[0]; |
| 3364 | |
| 3365 | // Verify error is detected with correct details |
| 3366 | assert_eq!(direct_error.line, 2); |
| 3367 | assert!( |
| 3368 | direct_error.message.contains("expected"), |
| 3369 | "Error message should contain 'expected': {}", |
| 3370 | direct_error.message |
| 3371 | ); |
| 3372 | assert_eq!(direct_error.context, "\tcommand"); |
| 3373 | |
| 3374 | // Check public API |
| 3375 | let reader_result = Makefile::from_reader(input.as_bytes()); |
| 3376 | let parse_error = match reader_result { |
| 3377 | Ok(_) => panic!("Expected Parse error from from_reader"), |
| 3378 | Err(err) => match err { |
| 3379 | self::Error::Parse(parse_err) => parse_err, |
| 3380 | _ => panic!("Expected Parse error"), |
| 3381 | }, |
| 3382 | }; |
| 3383 | |
| 3384 | // Verify formatting includes line number and context |
| 3385 | let error_text = parse_error.to_string(); |
| 3386 | assert!(error_text.contains("Error at line 2:")); |
| 3387 | assert!(error_text.contains("2| \tcommand")); |
| 3388 | } |
| 3389 | |
| 3390 | #[test] |
| 3391 | fn test_parsing_error_context_with_bad_syntax() { |
| 3392 | // Input with unusual characters to ensure they're preserved |
| 3393 | let input = "#begin comment\n\t(╯°□°)╯︵ ┻━┻\n#end comment"; |
| 3394 | |
| 3395 | // With our relaxed parsing, verify we either get a proper error or parse successfully |
| 3396 | match Makefile::from_reader(input.as_bytes()) { |
| 3397 | Ok(makefile) => { |
| 3398 | // If it parses successfully, our parser is robust enough to handle unusual characters |
| 3399 | assert_eq!( |
| 3400 | makefile.rules().count(), |
| 3401 | 0, |
| 3402 | "Should not have found any rules" |
| 3403 | ); |
| 3404 | } |
| 3405 | Err(err) => match err { |
| 3406 | self::Error::Parse(error) => { |
| 3407 | // Verify error details are properly reported |
| 3408 | assert!(error.errors[0].line >= 2, "Error line should be at least 2"); |
| 3409 | assert!( |
| 3410 | !error.errors[0].context.is_empty(), |
| 3411 | "Error context should not be empty" |
| 3412 | ); |
| 3413 | } |
| 3414 | _ => panic!("Unexpected error type"), |
| 3415 | }, |
| 3416 | }; |
| 3417 | } |
| 3418 | |
| 3419 | #[test] |
| 3420 | fn test_error_message_format() { |
| 3421 | // Test the error formatter directly |
| 3422 | let parse_error = ParseError { |
| 3423 | errors: vec![ErrorInfo { |
| 3424 | message: "test error".to_string(), |
| 3425 | line: 42, |
| 3426 | context: "some problematic code".to_string(), |
| 3427 | }], |
| 3428 | }; |
| 3429 | |
| 3430 | let error_text = parse_error.to_string(); |
| 3431 | assert!(error_text.contains("Error at line 42: test error")); |
| 3432 | assert!(error_text.contains("42| some problematic code")); |
| 3433 | } |
| 3434 | |
| 3435 | #[test] |
| 3436 | fn test_line_number_calculation() { |
| 3437 | // Test inputs for various error locations |
| 3438 | let test_cases = [ |
| 3439 | ("rule dependency\n\tcommand", 2), // Missing colon |
| 3440 | ("#comment\n\t(╯°□°)╯︵ ┻━┻", 2), // Strange characters |
| 3441 | ("var = value\n#comment\n\tindented line", 3), // Indented line not part of a rule |
| 3442 | ]; |
| 3443 | |
| 3444 | for (input, expected_line) in test_cases { |
| 3445 | // Attempt to parse the input |
| 3446 | match input.parse::<Makefile>() { |
| 3447 | Ok(_) => { |
| 3448 | // If the parser succeeds, that's fine - our parser is more robust |
| 3449 | // Skip assertions when there's no error to check |
| 3450 | continue; |
| 3451 | } |
| 3452 | Err(err) => { |
| 3453 | if let Error::Parse(parse_err) = err { |
| 3454 | // Verify error line number matches expected line |
| 3455 | assert_eq!( |
| 3456 | parse_err.errors[0].line, expected_line, |
| 3457 | "Line number should match the expected line" |
| 3458 | ); |
| 3459 | |
| 3460 | // If the error is about indentation, check that the context includes the tab |
| 3461 | if parse_err.errors[0].message.contains("indented") { |
| 3462 | assert!( |
| 3463 | parse_err.errors[0].context.starts_with('\t'), |
| 3464 | "Context for indentation errors should include the tab character" |
| 3465 | ); |
| 3466 | } |
| 3467 | } else { |
| 3468 | panic!("Expected parse error, got: {:?}", err); |
| 3469 | } |
| 3470 | } |
| 3471 | } |
| 3472 | } |
| 3473 | } |
| 3474 | |
| 3475 | #[test] |
| 3476 | fn test_conditional_features() { |
| 3477 | // Simple use of variables in conditionals |
| 3478 | let code = r#" |
| 3479 | # Set variables based on DEBUG flag |
| 3480 | ifdef DEBUG |
| 3481 | CFLAGS += -g -DDEBUG |
| 3482 | else |
| 3483 | CFLAGS = -O2 |
| 3484 | endif |
| 3485 | |
| 3486 | # Define a build rule |
| 3487 | all: $(OBJS) |
| 3488 | $(CC) $(CFLAGS) -o $@ $^ |
| 3489 | "#; |
| 3490 | |
| 3491 | let mut buf = code.as_bytes(); |
| 3492 | let makefile = |
| 3493 | Makefile::read_relaxed(&mut buf).expect("Failed to parse conditional features"); |
| 3494 | |
| 3495 | // Instead of checking for variable definitions which might not get created |
| 3496 | // due to conditionals, let's verify that we can parse the content without errors |
| 3497 | assert!(!makefile.code().is_empty(), "Makefile has content"); |
| 3498 | |
| 3499 | // Check that we detected a rule |
| 3500 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3501 | assert!(!rules.is_empty(), "Should have found rules"); |
| 3502 | |
| 3503 | // Verify conditional presence in the original code |
| 3504 | assert!(code.contains("ifdef DEBUG")); |
| 3505 | assert!(code.contains("endif")); |
| 3506 | |
| 3507 | // Also try with an explicitly defined variable |
| 3508 | let code_with_var = r#" |
| 3509 | # Define a variable first |
| 3510 | CC = gcc |
| 3511 | |
| 3512 | ifdef DEBUG |
| 3513 | CFLAGS += -g -DDEBUG |
| 3514 | else |
| 3515 | CFLAGS = -O2 |
| 3516 | endif |
| 3517 | |
| 3518 | all: $(OBJS) |
| 3519 | $(CC) $(CFLAGS) -o $@ $^ |
| 3520 | "#; |
| 3521 | |
| 3522 | let mut buf = code_with_var.as_bytes(); |
| 3523 | let makefile = |
| 3524 | Makefile::read_relaxed(&mut buf).expect("Failed to parse with explicit variable"); |
| 3525 | |
| 3526 | // Now we should definitely find at least the CC variable |
| 3527 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3528 | assert!( |
| 3529 | !vars.is_empty(), |
| 3530 | "Should have found at least the CC variable definition" |
| 3531 | ); |
| 3532 | } |
| 3533 | |
| 3534 | #[test] |
| 3535 | fn test_include_directive() { |
| 3536 | let parsed = parse( |
| 3537 | "include config.mk\ninclude $(TOPDIR)/rules.mk\ninclude *.mk\n", |
| 3538 | None, |
| 3539 | ); |
| 3540 | assert!(parsed.errors.is_empty()); |
| 3541 | let node = parsed.syntax(); |
| 3542 | assert!(format!("{:#?}", node).contains("INCLUDE@")); |
| 3543 | } |
| 3544 | |
| 3545 | #[test] |
| 3546 | fn test_export_variables() { |
| 3547 | let parsed = parse("export SHELL := /bin/bash\n", None); |
| 3548 | assert!(parsed.errors.is_empty()); |
| 3549 | let makefile = parsed.root(); |
| 3550 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3551 | assert_eq!(vars.len(), 1); |
| 3552 | let shell_var = vars |
| 3553 | .iter() |
| 3554 | .find(|v| v.name() == Some("SHELL".to_string())) |
| 3555 | .unwrap(); |
| 3556 | assert!(shell_var.raw_value().unwrap().contains("bin/bash")); |
| 3557 | } |
| 3558 | |
| 3559 | #[test] |
| 3560 | fn test_bare_export_variable() { |
| 3561 | // "export VARNAME" without assignment operator is a valid GNU Make directive |
| 3562 | // that exports a previously-defined variable. |
| 3563 | let parsed = parse( |
| 3564 | "DEB_CFLAGS_MAINT_APPEND = -Wno-error\nexport DEB_CFLAGS_MAINT_APPEND\n\n%:\n\tdh $@\n", |
| 3565 | None, |
| 3566 | ); |
| 3567 | assert!(parsed.errors.is_empty(), "errors: {:?}", parsed.errors); |
| 3568 | let makefile = parsed.root(); |
| 3569 | // The bare export should be parsed as a variable, not a rule |
| 3570 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3571 | assert_eq!(vars.len(), 2); |
| 3572 | // The pattern rule should be found |
| 3573 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3574 | assert_eq!(rules.len(), 1); |
| 3575 | assert!(rules[0].targets().any(|t| t == "%")); |
| 3576 | // build-arch should match via the pattern rule |
| 3577 | assert!(makefile.find_rule_by_target_pattern("build-arch").is_some()); |
| 3578 | } |
| 3579 | |
| 3580 | #[test] |
| 3581 | fn test_bare_export_at_eof() { |
| 3582 | // Bare "export VARNAME" at end of file (no trailing newline) |
| 3583 | let parsed = parse("VAR = value\nexport VAR", None); |
| 3584 | assert!(parsed.errors.is_empty(), "errors: {:?}", parsed.errors); |
| 3585 | let makefile = parsed.root(); |
| 3586 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3587 | assert_eq!(vars.len(), 2); |
| 3588 | assert_eq!(makefile.rules().count(), 0); |
| 3589 | } |
| 3590 | |
| 3591 | #[test] |
| 3592 | fn test_bare_export_does_not_eat_include() { |
| 3593 | // Bare "export VARNAME" must not consume subsequent include directives |
| 3594 | let parsed = parse("VAR = value\nexport VAR\ninclude other.mk\n", None); |
| 3595 | assert!(parsed.errors.is_empty(), "errors: {:?}", parsed.errors); |
| 3596 | let makefile = parsed.root(); |
| 3597 | assert_eq!(makefile.includes().count(), 1); |
| 3598 | assert_eq!( |
| 3599 | makefile.included_files().collect::<Vec<_>>(), |
| 3600 | vec!["other.mk"] |
| 3601 | ); |
| 3602 | } |
| 3603 | |
| 3604 | #[test] |
| 3605 | fn test_bare_export_multiple() { |
| 3606 | // Multiple bare exports in a row |
| 3607 | let parsed = parse( |
| 3608 | "A = 1\nB = 2\nexport A\nexport B\n\nall:\n\techo done\n", |
| 3609 | None, |
| 3610 | ); |
| 3611 | assert!(parsed.errors.is_empty(), "errors: {:?}", parsed.errors); |
| 3612 | let makefile = parsed.root(); |
| 3613 | assert_eq!(makefile.variable_definitions().count(), 4); |
| 3614 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3615 | assert_eq!(rules.len(), 1); |
| 3616 | assert!(rules[0].targets().any(|t| t == "all")); |
| 3617 | } |
| 3618 | |
| 3619 | #[test] |
| 3620 | fn test_parse_error_does_not_cross_lines() { |
| 3621 | // A line that fails to parse as a rule (no colon) must not |
| 3622 | // consume tokens from subsequent lines. |
| 3623 | let parsed = parse("notarule\n\nbuild-arch:\n\techo arch\n", None); |
| 3624 | let makefile = parsed.root(); |
| 3625 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3626 | // The "notarule" line may produce an error, but build-arch must still be found |
| 3627 | assert!( |
| 3628 | rules.iter().any(|r| r.targets().any(|t| t == "build-arch")), |
| 3629 | "build-arch rule should be parsed despite earlier error; rules: {:?}", |
| 3630 | rules |
| 3631 | .iter() |
| 3632 | .map(|r| r.targets().collect::<Vec<_>>()) |
| 3633 | .collect::<Vec<_>>() |
| 3634 | ); |
| 3635 | } |
| 3636 | |
| 3637 | #[test] |
| 3638 | fn test_pyfai_rules_full() { |
| 3639 | // Real-world pyFAI debian/rules that triggered #1131043 |
| 3640 | let input = "\ |
| 3641 | #!/usr/bin/make -f |
| 3642 | |
| 3643 | export DH_VERBOSE=1 |
| 3644 | export PYBUILD_NAME=pyfai |
| 3645 | |
| 3646 | DEB_CFLAGS_MAINT_APPEND = -Wno-error=incompatible-pointer-types |
| 3647 | export DEB_CFLAGS_MAINT_APPEND |
| 3648 | |
| 3649 | PY3VER := $(shell py3versions -dv) |
| 3650 | |
| 3651 | include /usr/share/dpkg/pkg-info.mk # sets SOURCE_DATE_EPOCH |
| 3652 | |
| 3653 | %: |
| 3654 | \tdh $@ --buildsystem=pybuild |
| 3655 | |
| 3656 | override_dh_auto_build-arch: |
| 3657 | \tPYBUILD_BUILD_ARGS=\"-Ccompile-args=--verbose\" dh_auto_build |
| 3658 | |
| 3659 | override_dh_auto_build-indep: override_dh_auto_build-arch |
| 3660 | \tsphinx-build -N -bhtml doc/source build/html |
| 3661 | |
| 3662 | override_dh_auto_test: |
| 3663 | |
| 3664 | execute_after_dh_auto_install: |
| 3665 | \tdh_install -p pyfai debian/python3-pyfai/usr/bin /usr |
| 3666 | "; |
| 3667 | let parsed = parse(input, None); |
| 3668 | let makefile = parsed.root(); |
| 3669 | |
| 3670 | // Include must be detected |
| 3671 | assert_eq!(makefile.includes().count(), 1); |
| 3672 | |
| 3673 | // Pattern rule must be found |
| 3674 | assert!( |
| 3675 | makefile.find_rule_by_target_pattern("build-arch").is_some(), |
| 3676 | "build-arch should match via %: pattern rule" |
| 3677 | ); |
| 3678 | assert!( |
| 3679 | makefile |
| 3680 | .find_rule_by_target_pattern("build-indep") |
| 3681 | .is_some(), |
| 3682 | "build-indep should match via %: pattern rule" |
| 3683 | ); |
| 3684 | |
| 3685 | // All override/execute_after rules must be found |
| 3686 | let rule_targets: Vec<Vec<String>> = |
| 3687 | makefile.rules().map(|r| r.targets().collect()).collect(); |
| 3688 | assert!( |
| 3689 | rule_targets.iter().any(|t| t.contains(&"%".to_string())), |
| 3690 | "missing %: rule; got: {:?}", |
| 3691 | rule_targets |
| 3692 | ); |
| 3693 | assert!( |
| 3694 | rule_targets |
| 3695 | .iter() |
| 3696 | .any(|t| t.contains(&"override_dh_auto_build-arch".to_string())), |
| 3697 | "missing override_dh_auto_build-arch; got: {:?}", |
| 3698 | rule_targets |
| 3699 | ); |
| 3700 | assert!( |
| 3701 | rule_targets |
| 3702 | .iter() |
| 3703 | .any(|t| t.contains(&"override_dh_auto_test".to_string())), |
| 3704 | "missing override_dh_auto_test; got: {:?}", |
| 3705 | rule_targets |
| 3706 | ); |
| 3707 | assert!( |
| 3708 | rule_targets |
| 3709 | .iter() |
| 3710 | .any(|t| t.contains(&"execute_after_dh_auto_install".to_string())), |
| 3711 | "missing execute_after_dh_auto_install; got: {:?}", |
| 3712 | rule_targets |
| 3713 | ); |
| 3714 | } |
| 3715 | |
| 3716 | #[test] |
| 3717 | fn test_variable_scopes() { |
| 3718 | let parsed = parse( |
| 3719 | "SIMPLE = value\nIMMEDIATE := value\nCONDITIONAL ?= value\nAPPEND += value\n", |
| 3720 | None, |
| 3721 | ); |
| 3722 | assert!(parsed.errors.is_empty()); |
| 3723 | let makefile = parsed.root(); |
| 3724 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 3725 | assert_eq!(vars.len(), 4); |
| 3726 | let var_names: Vec<_> = vars.iter().filter_map(|v| v.name()).collect(); |
| 3727 | assert!(var_names.contains(&"SIMPLE".to_string())); |
| 3728 | assert!(var_names.contains(&"IMMEDIATE".to_string())); |
| 3729 | assert!(var_names.contains(&"CONDITIONAL".to_string())); |
| 3730 | assert!(var_names.contains(&"APPEND".to_string())); |
| 3731 | } |
| 3732 | |
| 3733 | #[test] |
| 3734 | fn test_pattern_rule_parsing() { |
| 3735 | let parsed = parse("%.o: %.c\n\t$(CC) -c -o $@ $<\n", None); |
| 3736 | assert!(parsed.errors.is_empty()); |
| 3737 | let makefile = parsed.root(); |
| 3738 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 3739 | assert_eq!(rules.len(), 1); |
| 3740 | assert_eq!(rules[0].targets().next().unwrap(), "%.o"); |
| 3741 | assert!(rules[0].recipes().next().unwrap().contains("$@")); |
| 3742 | } |
| 3743 | |
| 3744 | #[test] |
| 3745 | fn test_include_variants() { |
| 3746 | // Test all variants of include directives |
| 3747 | let makefile_str = "include simple.mk\n-include optional.mk\nsinclude synonym.mk\ninclude $(VAR)/generated.mk\n"; |
| 3748 | let parsed = parse(makefile_str, None); |
| 3749 | assert!(parsed.errors.is_empty()); |
| 3750 | |
| 3751 | // Get the syntax tree for inspection |
| 3752 | let node = parsed.syntax(); |
| 3753 | let debug_str = format!("{:#?}", node); |
| 3754 | |
| 3755 | // Check that all includes are correctly parsed as INCLUDE nodes |
| 3756 | assert_eq!(debug_str.matches("INCLUDE@").count(), 4); |
| 3757 | |
| 3758 | // Check that we can access the includes through the AST |
| 3759 | let makefile = parsed.root(); |
| 3760 | |
| 3761 | // Count all child nodes that are INCLUDE kind |
| 3762 | let include_count = makefile |
| 3763 | .syntax() |
| 3764 | .children() |
| 3765 | .filter(|child| child.kind() == INCLUDE) |
| 3766 | .count(); |
| 3767 | assert_eq!(include_count, 4); |
| 3768 | |
| 3769 | // Test variable expansion in include paths |
| 3770 | assert!(makefile |
| 3771 | .included_files() |
| 3772 | .any(|path| path.contains("$(VAR)"))); |
| 3773 | } |
| 3774 | |
| 3775 | #[test] |
| 3776 | fn test_include_api() { |
| 3777 | // Test the API for working with include directives |
| 3778 | let makefile_str = "include simple.mk\n-include optional.mk\nsinclude synonym.mk\n"; |
| 3779 | let makefile: Makefile = makefile_str.parse().unwrap(); |
| 3780 | |
| 3781 | // Test the includes method |
| 3782 | let includes: Vec<_> = makefile.includes().collect(); |
| 3783 | assert_eq!(includes.len(), 3); |
| 3784 | |
| 3785 | // Test the is_optional method |
| 3786 | assert!(!includes[0].is_optional()); // include |
| 3787 | assert!(includes[1].is_optional()); // -include |
| 3788 | assert!(includes[2].is_optional()); // sinclude |
| 3789 | |
| 3790 | // Test the included_files method |
| 3791 | let files: Vec<_> = makefile.included_files().collect(); |
| 3792 | assert_eq!(files, vec!["simple.mk", "optional.mk", "synonym.mk"]); |
| 3793 | |
| 3794 | // Test the path method on Include |
| 3795 | assert_eq!(includes[0].path(), Some("simple.mk".to_string())); |
| 3796 | assert_eq!(includes[1].path(), Some("optional.mk".to_string())); |
| 3797 | assert_eq!(includes[2].path(), Some("synonym.mk".to_string())); |
| 3798 | } |
| 3799 | |
| 3800 | #[test] |
| 3801 | fn test_include_integration() { |
| 3802 | // Test include directives in realistic makefile contexts |
| 3803 | |
| 3804 | // Case 1: With .PHONY (which was a source of the original issue) |
| 3805 | let phony_makefile = Makefile::from_reader( |
| 3806 | ".PHONY: build\n\nVERBOSE ?= 0\n\n# comment\n-include .env\n\nrule: dependency\n\tcommand" |
| 3807 | .as_bytes() |
| 3808 | ).unwrap(); |
| 3809 | |
| 3810 | // We expect 2 rules: .PHONY and rule |
| 3811 | assert_eq!(phony_makefile.rules().count(), 2); |
| 3812 | |
| 3813 | // But only one non-special rule (not starting with '.') |
| 3814 | let normal_rules_count = phony_makefile |
| 3815 | .rules() |
| 3816 | .filter(|r| !r.targets().any(|t| t.starts_with('.'))) |
| 3817 | .count(); |
| 3818 | assert_eq!(normal_rules_count, 1); |
| 3819 | |
| 3820 | // Verify we have the include directive |
| 3821 | assert_eq!(phony_makefile.includes().count(), 1); |
| 3822 | assert_eq!(phony_makefile.included_files().next().unwrap(), ".env"); |
| 3823 | |
| 3824 | // Case 2: Without .PHONY, just a regular rule and include |
| 3825 | let simple_makefile = Makefile::from_reader( |
| 3826 | "\n\nVERBOSE ?= 0\n\n# comment\n-include .env\n\nrule: dependency\n\tcommand" |
| 3827 | .as_bytes(), |
| 3828 | ) |
| 3829 | .unwrap(); |
| 3830 | assert_eq!(simple_makefile.rules().count(), 1); |
| 3831 | assert_eq!(simple_makefile.includes().count(), 1); |
| 3832 | } |
| 3833 | |
| 3834 | #[test] |
| 3835 | fn test_real_conditional_directives() { |
| 3836 | // Basic if/else conditional |
| 3837 | let conditional = "ifdef DEBUG\nCFLAGS = -g\nelse\nCFLAGS = -O2\nendif\n"; |
| 3838 | let mut buf = conditional.as_bytes(); |
| 3839 | let makefile = |
| 3840 | Makefile::read_relaxed(&mut buf).expect("Failed to parse basic if/else conditional"); |
| 3841 | let code = makefile.code(); |
| 3842 | assert!(code.contains("ifdef DEBUG")); |
| 3843 | assert!(code.contains("else")); |
| 3844 | assert!(code.contains("endif")); |
| 3845 | |
| 3846 | // ifdef with nested ifdef |
| 3847 | let nested = "ifdef DEBUG\nCFLAGS = -g\nifdef VERBOSE\nCFLAGS += -v\nendif\nendif\n"; |
| 3848 | let mut buf = nested.as_bytes(); |
| 3849 | let makefile = Makefile::read_relaxed(&mut buf).expect("Failed to parse nested ifdef"); |
| 3850 | let code = makefile.code(); |
| 3851 | assert!(code.contains("ifdef DEBUG")); |
| 3852 | assert!(code.contains("ifdef VERBOSE")); |
| 3853 | |
| 3854 | // ifeq form |
| 3855 | let ifeq = "ifeq ($(OS),Windows_NT)\nTARGET = app.exe\nelse\nTARGET = app\nendif\n"; |
| 3856 | let mut buf = ifeq.as_bytes(); |
| 3857 | let makefile = Makefile::read_relaxed(&mut buf).expect("Failed to parse ifeq form"); |
| 3858 | let code = makefile.code(); |
| 3859 | assert!(code.contains("ifeq")); |
| 3860 | assert!(code.contains("Windows_NT")); |
| 3861 | } |
| 3862 | |
| 3863 | #[test] |
| 3864 | fn test_indented_text_outside_rules() { |
| 3865 | // Simple help target with echo commands |
| 3866 | let help_text = "help:\n\t@echo \"Available targets:\"\n\t@echo \" help show help\"\n"; |
| 3867 | let parsed = parse(help_text, None); |
| 3868 | assert!(parsed.errors.is_empty()); |
| 3869 | |
| 3870 | // Verify recipes are correctly parsed |
| 3871 | let root = parsed.root(); |
| 3872 | let rules = root.rules().collect::<Vec<_>>(); |
| 3873 | assert_eq!(rules.len(), 1); |
| 3874 | |
| 3875 | let help_rule = &rules[0]; |
| 3876 | let recipes = help_rule.recipes().collect::<Vec<_>>(); |
| 3877 | assert_eq!(recipes.len(), 2); |
| 3878 | assert!(recipes[0].contains("Available targets")); |
| 3879 | assert!(recipes[1].contains("help")); |
| 3880 | } |
| 3881 | |
| 3882 | #[test] |
| 3883 | fn test_comment_handling_in_recipes() { |
| 3884 | // Create a recipe with a comment line |
| 3885 | let recipe_comment = "build:\n\t# This is a comment\n\tgcc -o app main.c\n"; |
| 3886 | |
| 3887 | // Parse the recipe |
| 3888 | let parsed = parse(recipe_comment, None); |
| 3889 | |
| 3890 | // Verify no parsing errors |
| 3891 | assert!( |
| 3892 | parsed.errors.is_empty(), |
| 3893 | "Should parse recipe with comments without errors" |
| 3894 | ); |
| 3895 | |
| 3896 | // Check rule structure |
| 3897 | let root = parsed.root(); |
| 3898 | let rules = root.rules().collect::<Vec<_>>(); |
| 3899 | assert_eq!(rules.len(), 1, "Should find exactly one rule"); |
| 3900 | |
| 3901 | // Check the rule has the correct name |
| 3902 | let build_rule = &rules[0]; |
| 3903 | assert_eq!( |
| 3904 | build_rule.targets().collect::<Vec<_>>(), |
| 3905 | vec!["build"], |
| 3906 | "Rule should have 'build' as target" |
| 3907 | ); |
| 3908 | |
| 3909 | // Check recipes are parsed correctly |
| 3910 | // recipes() now returns all recipe nodes including comment-only lines |
| 3911 | let recipes = build_rule.recipe_nodes().collect::<Vec<_>>(); |
| 3912 | assert_eq!(recipes.len(), 2, "Should find two recipe nodes"); |
| 3913 | |
| 3914 | // First recipe should be comment-only |
| 3915 | assert_eq!(recipes[0].text(), ""); |
| 3916 | assert_eq!( |
| 3917 | recipes[0].comment(), |
| 3918 | Some("# This is a comment".to_string()) |
| 3919 | ); |
| 3920 | |
| 3921 | // Second recipe should be the command |
| 3922 | assert_eq!(recipes[1].text(), "gcc -o app main.c"); |
| 3923 | assert_eq!(recipes[1].comment(), None); |
| 3924 | } |
| 3925 | |
| 3926 | #[test] |
| 3927 | fn test_multiline_variables() { |
| 3928 | // Simple multiline variable test |
| 3929 | let multiline = "SOURCES = main.c \\\n util.c\n"; |
| 3930 | |
| 3931 | // Parse the multiline variable |
| 3932 | let parsed = parse(multiline, None); |
| 3933 | |
| 3934 | // We can extract the variable even with errors (since backslash handling is not perfect) |
| 3935 | let root = parsed.root(); |
| 3936 | let vars = root.variable_definitions().collect::<Vec<_>>(); |
| 3937 | assert!(!vars.is_empty(), "Should find at least one variable"); |
| 3938 | |
| 3939 | // Test other multiline variable forms |
| 3940 | |
| 3941 | // := assignment operator |
| 3942 | let operators = "CFLAGS := -Wall \\\n -Werror\n"; |
| 3943 | let parsed_operators = parse(operators, None); |
| 3944 | |
| 3945 | // Extract variable with := operator |
| 3946 | let root = parsed_operators.root(); |
| 3947 | let vars = root.variable_definitions().collect::<Vec<_>>(); |
| 3948 | assert!( |
| 3949 | !vars.is_empty(), |
| 3950 | "Should find at least one variable with := operator" |
| 3951 | ); |
| 3952 | |
| 3953 | // += assignment operator |
| 3954 | let append = "LDFLAGS += -L/usr/lib \\\n -lm\n"; |
| 3955 | let parsed_append = parse(append, None); |
| 3956 | |
| 3957 | // Extract variable with += operator |
| 3958 | let root = parsed_append.root(); |
| 3959 | let vars = root.variable_definitions().collect::<Vec<_>>(); |
| 3960 | assert!( |
| 3961 | !vars.is_empty(), |
| 3962 | "Should find at least one variable with += operator" |
| 3963 | ); |
| 3964 | } |
| 3965 | |
| 3966 | #[test] |
| 3967 | fn test_whitespace_and_eof_handling() { |
| 3968 | // Test 1: File ending with blank lines |
| 3969 | let blank_lines = "VAR = value\n\n\n"; |
| 3970 | |
| 3971 | let parsed_blank = parse(blank_lines, None); |
| 3972 | |
| 3973 | // We should be able to extract the variable definition |
| 3974 | let root = parsed_blank.root(); |
| 3975 | let vars = root.variable_definitions().collect::<Vec<_>>(); |
| 3976 | assert_eq!( |
| 3977 | vars.len(), |
| 3978 | 1, |
| 3979 | "Should find one variable in blank lines test" |
| 3980 | ); |
| 3981 | |
| 3982 | // Test 2: File ending with space |
| 3983 | let trailing_space = "VAR = value \n"; |
| 3984 | |
| 3985 | let parsed_space = parse(trailing_space, None); |
| 3986 | |
| 3987 | // We should be able to extract the variable definition |
| 3988 | let root = parsed_space.root(); |
| 3989 | let vars = root.variable_definitions().collect::<Vec<_>>(); |
| 3990 | assert_eq!( |
| 3991 | vars.len(), |
| 3992 | 1, |
| 3993 | "Should find one variable in trailing space test" |
| 3994 | ); |
| 3995 | |
| 3996 | // Test 3: No final newline |
| 3997 | let no_newline = "VAR = value"; |
| 3998 | |
| 3999 | let parsed_no_newline = parse(no_newline, None); |
| 4000 | |
| 4001 | // Regardless of parsing errors, we should be able to extract the variable |
| 4002 | let root = parsed_no_newline.root(); |
| 4003 | let vars = root.variable_definitions().collect::<Vec<_>>(); |
| 4004 | assert_eq!(vars.len(), 1, "Should find one variable in no newline test"); |
| 4005 | assert_eq!( |
| 4006 | vars[0].name(), |
| 4007 | Some("VAR".to_string()), |
| 4008 | "Variable name should be VAR" |
| 4009 | ); |
| 4010 | } |
| 4011 | |
| 4012 | #[test] |
| 4013 | fn test_complex_variable_references() { |
| 4014 | // Simple function call |
| 4015 | let wildcard = "SOURCES = $(wildcard *.c)\n"; |
| 4016 | let parsed = parse(wildcard, None); |
| 4017 | assert!(parsed.errors.is_empty()); |
| 4018 | |
| 4019 | // Nested variable reference |
| 4020 | let nested = "PREFIX = /usr\nBINDIR = $(PREFIX)/bin\n"; |
| 4021 | let parsed = parse(nested, None); |
| 4022 | assert!(parsed.errors.is_empty()); |
| 4023 | |
| 4024 | // Function with complex arguments |
| 4025 | let patsubst = "OBJECTS = $(patsubst %.c,%.o,$(SOURCES))\n"; |
| 4026 | let parsed = parse(patsubst, None); |
| 4027 | assert!(parsed.errors.is_empty()); |
| 4028 | } |
| 4029 | |
| 4030 | #[test] |
| 4031 | fn test_complex_variable_references_minimal() { |
| 4032 | // Simple function call |
| 4033 | let wildcard = "SOURCES = $(wildcard *.c)\n"; |
| 4034 | let parsed = parse(wildcard, None); |
| 4035 | assert!(parsed.errors.is_empty()); |
| 4036 | |
| 4037 | // Nested variable reference |
| 4038 | let nested = "PREFIX = /usr\nBINDIR = $(PREFIX)/bin\n"; |
| 4039 | let parsed = parse(nested, None); |
| 4040 | assert!(parsed.errors.is_empty()); |
| 4041 | |
| 4042 | // Function with complex arguments |
| 4043 | let patsubst = "OBJECTS = $(patsubst %.c,%.o,$(SOURCES))\n"; |
| 4044 | let parsed = parse(patsubst, None); |
| 4045 | assert!(parsed.errors.is_empty()); |
| 4046 | } |
| 4047 | |
| 4048 | #[test] |
| 4049 | fn test_multiline_variable_with_backslash() { |
| 4050 | let content = r#" |
| 4051 | LONG_VAR = This is a long variable \ |
| 4052 | that continues on the next line \ |
| 4053 | and even one more line |
| 4054 | "#; |
| 4055 | |
| 4056 | // For now, we'll use relaxed parsing since the backslash handling isn't fully implemented |
| 4057 | let mut buf = content.as_bytes(); |
| 4058 | let makefile = |
| 4059 | Makefile::read_relaxed(&mut buf).expect("Failed to parse multiline variable"); |
| 4060 | |
| 4061 | // Check that we can extract the variable even with errors |
| 4062 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 4063 | assert_eq!( |
| 4064 | vars.len(), |
| 4065 | 1, |
| 4066 | "Expected 1 variable but found {}", |
| 4067 | vars.len() |
| 4068 | ); |
| 4069 | let var_value = vars[0].raw_value(); |
| 4070 | assert!(var_value.is_some(), "Variable value is None"); |
| 4071 | |
| 4072 | // The value might not be perfect due to relaxed parsing, but it should contain most of the content |
| 4073 | let value_str = var_value.unwrap(); |
| 4074 | assert!( |
| 4075 | value_str.contains("long variable"), |
| 4076 | "Value doesn't contain expected content" |
| 4077 | ); |
| 4078 | } |
| 4079 | |
| 4080 | #[test] |
| 4081 | fn test_multiline_variable_with_mixed_operators() { |
| 4082 | let content = r#" |
| 4083 | PREFIX ?= /usr/local |
| 4084 | CFLAGS := -Wall -O2 \ |
| 4085 | -I$(PREFIX)/include \ |
| 4086 | -DDEBUG |
| 4087 | "#; |
| 4088 | // Use relaxed parsing for now |
| 4089 | let mut buf = content.as_bytes(); |
| 4090 | let makefile = Makefile::read_relaxed(&mut buf) |
| 4091 | .expect("Failed to parse multiline variable with operators"); |
| 4092 | |
| 4093 | // Check that we can extract variables even with errors |
| 4094 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 4095 | assert!( |
| 4096 | !vars.is_empty(), |
| 4097 | "Expected at least 1 variable, found {}", |
| 4098 | vars.len() |
| 4099 | ); |
| 4100 | |
| 4101 | // Check PREFIX variable |
| 4102 | let prefix_var = vars |
| 4103 | .iter() |
| 4104 | .find(|v| v.name().unwrap_or_default() == "PREFIX"); |
| 4105 | assert!(prefix_var.is_some(), "Expected to find PREFIX variable"); |
| 4106 | assert!( |
| 4107 | prefix_var.unwrap().raw_value().is_some(), |
| 4108 | "PREFIX variable has no value" |
| 4109 | ); |
| 4110 | |
| 4111 | // CFLAGS may be parsed incompletely but should exist in some form |
| 4112 | let cflags_var = vars |
| 4113 | .iter() |
| 4114 | .find(|v| v.name().unwrap_or_default().contains("CFLAGS")); |
| 4115 | assert!( |
| 4116 | cflags_var.is_some(), |
| 4117 | "Expected to find CFLAGS variable (or part of it)" |
| 4118 | ); |
| 4119 | } |
| 4120 | |
| 4121 | #[test] |
| 4122 | fn test_indented_help_text() { |
| 4123 | let content = r#" |
| 4124 | .PHONY: help |
| 4125 | help: |
| 4126 | @echo "Available targets:" |
| 4127 | @echo " build - Build the project" |
| 4128 | @echo " test - Run tests" |
| 4129 | @echo " clean - Remove build artifacts" |
| 4130 | "#; |
| 4131 | // Use relaxed parsing for now |
| 4132 | let mut buf = content.as_bytes(); |
| 4133 | let makefile = |
| 4134 | Makefile::read_relaxed(&mut buf).expect("Failed to parse indented help text"); |
| 4135 | |
| 4136 | // Check that we can extract rules even with errors |
| 4137 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 4138 | assert!(!rules.is_empty(), "Expected at least one rule"); |
| 4139 | |
| 4140 | // Find help rule |
| 4141 | let help_rule = rules.iter().find(|r| r.targets().any(|t| t == "help")); |
| 4142 | assert!(help_rule.is_some(), "Expected to find help rule"); |
| 4143 | |
| 4144 | // Check recipes - they might not be perfectly parsed but should exist |
| 4145 | let recipes = help_rule.unwrap().recipes().collect::<Vec<_>>(); |
| 4146 | assert!( |
| 4147 | !recipes.is_empty(), |
| 4148 | "Expected at least one recipe line in help rule" |
| 4149 | ); |
| 4150 | assert!( |
| 4151 | recipes.iter().any(|r| r.contains("Available targets")), |
| 4152 | "Expected to find 'Available targets' in recipes" |
| 4153 | ); |
| 4154 | } |
| 4155 | |
| 4156 | #[test] |
| 4157 | fn test_indented_lines_in_conditionals() { |
| 4158 | let content = r#" |
| 4159 | ifdef DEBUG |
| 4160 | CFLAGS += -g -DDEBUG |
| 4161 | # This is a comment inside conditional |
| 4162 | ifdef VERBOSE |
| 4163 | CFLAGS += -v |
| 4164 | endif |
| 4165 | endif |
| 4166 | "#; |
| 4167 | // Use relaxed parsing for conditionals with indented lines |
| 4168 | let mut buf = content.as_bytes(); |
| 4169 | let makefile = Makefile::read_relaxed(&mut buf) |
| 4170 | .expect("Failed to parse indented lines in conditionals"); |
| 4171 | |
| 4172 | // Check that we detected conditionals |
| 4173 | let code = makefile.code(); |
| 4174 | assert!(code.contains("ifdef DEBUG")); |
| 4175 | assert!(code.contains("ifdef VERBOSE")); |
| 4176 | assert!(code.contains("endif")); |
| 4177 | } |
| 4178 | |
| 4179 | #[test] |
| 4180 | fn test_recipe_with_colon() { |
| 4181 | let content = r#" |
| 4182 | build: |
| 4183 | @echo "Building at: $(shell date)" |
| 4184 | gcc -o program main.c |
| 4185 | "#; |
| 4186 | let parsed = parse(content, None); |
| 4187 | assert!( |
| 4188 | parsed.errors.is_empty(), |
| 4189 | "Failed to parse recipe with colon: {:?}", |
| 4190 | parsed.errors |
| 4191 | ); |
| 4192 | } |
| 4193 | |
| 4194 | #[test] |
| 4195 | fn test_double_colon_rules() { |
| 4196 | let content = r#" |
| 4197 | %.o :: %.c |
| 4198 | $(CC) -c $< -o $@ |
| 4199 | |
| 4200 | # Double colon allows multiple rules for same target |
| 4201 | all:: prerequisite1 |
| 4202 | @echo "First rule for all" |
| 4203 | |
| 4204 | all:: prerequisite2 |
| 4205 | @echo "Second rule for all" |
| 4206 | "#; |
| 4207 | let parsed = parse(content, None); |
| 4208 | assert!( |
| 4209 | parsed.errors.is_empty(), |
| 4210 | "Failed to parse double colon rules: {:?}", |
| 4211 | parsed.errors |
| 4212 | ); |
| 4213 | |
| 4214 | let makefile = parsed.root(); |
| 4215 | let rules: Vec<_> = makefile.rules().collect(); |
| 4216 | assert_eq!(rules.len(), 3); |
| 4217 | |
| 4218 | // All rules should be double-colon |
| 4219 | for rule in &rules { |
| 4220 | assert!(rule.is_double_colon()); |
| 4221 | } |
| 4222 | |
| 4223 | // Check targets |
| 4224 | assert_eq!(rules[0].targets().collect::<Vec<_>>(), vec!["%.o"]); |
| 4225 | assert_eq!(rules[1].targets().collect::<Vec<_>>(), vec!["all"]); |
| 4226 | assert_eq!(rules[2].targets().collect::<Vec<_>>(), vec!["all"]); |
| 4227 | |
| 4228 | // Check prerequisites |
| 4229 | assert_eq!( |
| 4230 | rules[1].prerequisites().collect::<Vec<_>>(), |
| 4231 | vec!["prerequisite1"] |
| 4232 | ); |
| 4233 | assert_eq!( |
| 4234 | rules[2].prerequisites().collect::<Vec<_>>(), |
| 4235 | vec!["prerequisite2"] |
| 4236 | ); |
| 4237 | } |
| 4238 | |
| 4239 | #[test] |
| 4240 | fn test_else_conditional_directives() { |
| 4241 | // Test else ifeq |
| 4242 | let content = r#" |
| 4243 | ifeq ($(OS),Windows_NT) |
| 4244 | TARGET = windows |
| 4245 | else ifeq ($(OS),Darwin) |
| 4246 | TARGET = macos |
| 4247 | else ifeq ($(OS),Linux) |
| 4248 | TARGET = linux |
| 4249 | else |
| 4250 | TARGET = unknown |
| 4251 | endif |
| 4252 | "#; |
| 4253 | let mut buf = content.as_bytes(); |
| 4254 | let makefile = |
| 4255 | Makefile::read_relaxed(&mut buf).expect("Failed to parse else ifeq directive"); |
| 4256 | assert!(makefile.code().contains("else ifeq")); |
| 4257 | assert!(makefile.code().contains("TARGET")); |
| 4258 | |
| 4259 | // Test else ifdef |
| 4260 | let content = r#" |
| 4261 | ifdef WINDOWS |
| 4262 | TARGET = windows |
| 4263 | else ifdef DARWIN |
| 4264 | TARGET = macos |
| 4265 | else ifdef LINUX |
| 4266 | TARGET = linux |
| 4267 | else |
| 4268 | TARGET = unknown |
| 4269 | endif |
| 4270 | "#; |
| 4271 | let mut buf = content.as_bytes(); |
| 4272 | let makefile = |
| 4273 | Makefile::read_relaxed(&mut buf).expect("Failed to parse else ifdef directive"); |
| 4274 | assert!(makefile.code().contains("else ifdef")); |
| 4275 | |
| 4276 | // Test else ifndef |
| 4277 | let content = r#" |
| 4278 | ifndef NOWINDOWS |
| 4279 | TARGET = windows |
| 4280 | else ifndef NODARWIN |
| 4281 | TARGET = macos |
| 4282 | else |
| 4283 | TARGET = linux |
| 4284 | endif |
| 4285 | "#; |
| 4286 | let mut buf = content.as_bytes(); |
| 4287 | let makefile = |
| 4288 | Makefile::read_relaxed(&mut buf).expect("Failed to parse else ifndef directive"); |
| 4289 | assert!(makefile.code().contains("else ifndef")); |
| 4290 | |
| 4291 | // Test else ifneq |
| 4292 | let content = r#" |
| 4293 | ifneq ($(OS),Windows_NT) |
| 4294 | TARGET = not_windows |
| 4295 | else ifneq ($(OS),Darwin) |
| 4296 | TARGET = not_macos |
| 4297 | else |
| 4298 | TARGET = darwin |
| 4299 | endif |
| 4300 | "#; |
| 4301 | let mut buf = content.as_bytes(); |
| 4302 | let makefile = |
| 4303 | Makefile::read_relaxed(&mut buf).expect("Failed to parse else ifneq directive"); |
| 4304 | assert!(makefile.code().contains("else ifneq")); |
| 4305 | } |
| 4306 | |
| 4307 | #[test] |
| 4308 | fn test_complex_else_conditionals() { |
| 4309 | // Test complex nested else conditionals with mixed types |
| 4310 | let content = r#"VAR1 := foo |
| 4311 | VAR2 := bar |
| 4312 | |
| 4313 | ifeq ($(VAR1),foo) |
| 4314 | RESULT := foo_matched |
| 4315 | else ifdef VAR2 |
| 4316 | RESULT := var2_defined |
| 4317 | else ifndef VAR3 |
| 4318 | RESULT := var3_not_defined |
| 4319 | else |
| 4320 | RESULT := final_else |
| 4321 | endif |
| 4322 | |
| 4323 | all: |
| 4324 | @echo $(RESULT) |
| 4325 | "#; |
| 4326 | let mut buf = content.as_bytes(); |
| 4327 | let makefile = |
| 4328 | Makefile::read_relaxed(&mut buf).expect("Failed to parse complex else conditionals"); |
| 4329 | |
| 4330 | // Verify the structure is preserved |
| 4331 | let code = makefile.code(); |
| 4332 | assert!(code.contains("ifeq ($(VAR1),foo)")); |
| 4333 | assert!(code.contains("else ifdef VAR2")); |
| 4334 | assert!(code.contains("else ifndef VAR3")); |
| 4335 | assert!(code.contains("else")); |
| 4336 | assert!(code.contains("endif")); |
| 4337 | assert!(code.contains("RESULT")); |
| 4338 | |
| 4339 | // Verify rules are still parsed correctly |
| 4340 | let rules: Vec<_> = makefile.rules().collect(); |
| 4341 | assert_eq!(rules.len(), 1); |
| 4342 | assert_eq!(rules[0].targets().collect::<Vec<_>>(), vec!["all"]); |
| 4343 | } |
| 4344 | |
| 4345 | #[test] |
| 4346 | fn test_conditional_token_structure() { |
| 4347 | // Test that conditionals have proper token structure |
| 4348 | let content = r#"ifdef VAR1 |
| 4349 | X := 1 |
| 4350 | else ifdef VAR2 |
| 4351 | X := 2 |
| 4352 | else |
| 4353 | X := 3 |
| 4354 | endif |
| 4355 | "#; |
| 4356 | let mut buf = content.as_bytes(); |
| 4357 | let makefile = Makefile::read_relaxed(&mut buf).unwrap(); |
| 4358 | |
| 4359 | // Check that we can traverse the syntax tree |
| 4360 | let syntax = makefile.syntax(); |
| 4361 | |
| 4362 | // Find CONDITIONAL nodes |
| 4363 | let mut found_conditional = false; |
| 4364 | let mut found_conditional_if = false; |
| 4365 | let mut found_conditional_else = false; |
| 4366 | let mut found_conditional_endif = false; |
| 4367 | |
| 4368 | fn check_node( |
| 4369 | node: &SyntaxNode, |
| 4370 | found_cond: &mut bool, |
| 4371 | found_if: &mut bool, |
| 4372 | found_else: &mut bool, |
| 4373 | found_endif: &mut bool, |
| 4374 | ) { |
| 4375 | match node.kind() { |
| 4376 | SyntaxKind::CONDITIONAL => *found_cond = true, |
| 4377 | SyntaxKind::CONDITIONAL_IF => *found_if = true, |
| 4378 | SyntaxKind::CONDITIONAL_ELSE => *found_else = true, |
| 4379 | SyntaxKind::CONDITIONAL_ENDIF => *found_endif = true, |
| 4380 | _ => {} |
| 4381 | } |
| 4382 | |
| 4383 | for child in node.children() { |
| 4384 | check_node(&child, found_cond, found_if, found_else, found_endif); |
| 4385 | } |
| 4386 | } |
| 4387 | |
| 4388 | check_node( |
| 4389 | syntax, |
| 4390 | &mut found_conditional, |
| 4391 | &mut found_conditional_if, |
| 4392 | &mut found_conditional_else, |
| 4393 | &mut found_conditional_endif, |
| 4394 | ); |
| 4395 | |
| 4396 | assert!(found_conditional, "Should have CONDITIONAL node"); |
| 4397 | assert!(found_conditional_if, "Should have CONDITIONAL_IF node"); |
| 4398 | assert!(found_conditional_else, "Should have CONDITIONAL_ELSE node"); |
| 4399 | assert!( |
| 4400 | found_conditional_endif, |
| 4401 | "Should have CONDITIONAL_ENDIF node" |
| 4402 | ); |
| 4403 | } |
| 4404 | |
| 4405 | #[test] |
| 4406 | fn test_ambiguous_assignment_vs_rule() { |
| 4407 | // Test case: Variable assignment with equals sign |
| 4408 | const VAR_ASSIGNMENT: &str = "VARIABLE = value\n"; |
| 4409 | |
| 4410 | let mut buf = std::io::Cursor::new(VAR_ASSIGNMENT); |
| 4411 | let makefile = |
| 4412 | Makefile::read_relaxed(&mut buf).expect("Failed to parse variable assignment"); |
| 4413 | |
| 4414 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 4415 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 4416 | |
| 4417 | assert_eq!(vars.len(), 1, "Expected 1 variable, found {}", vars.len()); |
| 4418 | assert_eq!(rules.len(), 0, "Expected 0 rules, found {}", rules.len()); |
| 4419 | |
| 4420 | assert_eq!(vars[0].name(), Some("VARIABLE".to_string())); |
| 4421 | |
| 4422 | // Test case: Simple rule with colon |
| 4423 | const SIMPLE_RULE: &str = "target: dependency\n"; |
| 4424 | |
| 4425 | let mut buf = std::io::Cursor::new(SIMPLE_RULE); |
| 4426 | let makefile = Makefile::read_relaxed(&mut buf).expect("Failed to parse simple rule"); |
| 4427 | |
| 4428 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 4429 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 4430 | |
| 4431 | assert_eq!(vars.len(), 0, "Expected 0 variables, found {}", vars.len()); |
| 4432 | assert_eq!(rules.len(), 1, "Expected 1 rule, found {}", rules.len()); |
| 4433 | |
| 4434 | let rule = &rules[0]; |
| 4435 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["target"]); |
| 4436 | } |
| 4437 | |
| 4438 | #[test] |
| 4439 | fn test_nested_conditionals() { |
| 4440 | let content = r#" |
| 4441 | ifdef RELEASE |
| 4442 | CFLAGS += -O3 |
| 4443 | ifndef DEBUG |
| 4444 | ifneq ($(ARCH),arm) |
| 4445 | CFLAGS += -march=native |
| 4446 | else |
| 4447 | CFLAGS += -mcpu=cortex-a72 |
| 4448 | endif |
| 4449 | endif |
| 4450 | endif |
| 4451 | "#; |
| 4452 | // Use relaxed parsing for nested conditionals test |
| 4453 | let mut buf = content.as_bytes(); |
| 4454 | let makefile = |
| 4455 | Makefile::read_relaxed(&mut buf).expect("Failed to parse nested conditionals"); |
| 4456 | |
| 4457 | // Check that we detected conditionals |
| 4458 | let code = makefile.code(); |
| 4459 | assert!(code.contains("ifdef RELEASE")); |
| 4460 | assert!(code.contains("ifndef DEBUG")); |
| 4461 | assert!(code.contains("ifneq")); |
| 4462 | } |
| 4463 | |
| 4464 | #[test] |
| 4465 | fn test_space_indented_recipes() { |
| 4466 | // This test is expected to fail with current implementation |
| 4467 | // It should pass once the parser is more flexible with indentation |
| 4468 | let content = r#" |
| 4469 | build: |
| 4470 | @echo "Building with spaces instead of tabs" |
| 4471 | gcc -o program main.c |
| 4472 | "#; |
| 4473 | // Use relaxed parsing for now |
| 4474 | let mut buf = content.as_bytes(); |
| 4475 | let makefile = |
| 4476 | Makefile::read_relaxed(&mut buf).expect("Failed to parse space-indented recipes"); |
| 4477 | |
| 4478 | // Check that we can extract rules even with errors |
| 4479 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 4480 | assert!(!rules.is_empty(), "Expected at least one rule"); |
| 4481 | |
| 4482 | // Find build rule |
| 4483 | let build_rule = rules.iter().find(|r| r.targets().any(|t| t == "build")); |
| 4484 | assert!(build_rule.is_some(), "Expected to find build rule"); |
| 4485 | } |
| 4486 | |
| 4487 | #[test] |
| 4488 | fn test_complex_variable_functions() { |
| 4489 | let content = r#" |
| 4490 | FILES := $(shell find . -name "*.c") |
| 4491 | OBJS := $(patsubst %.c,%.o,$(FILES)) |
| 4492 | NAME := $(if $(PROGRAM),$(PROGRAM),a.out) |
| 4493 | HEADERS := ${wildcard *.h} |
| 4494 | "#; |
| 4495 | let parsed = parse(content, None); |
| 4496 | assert!( |
| 4497 | parsed.errors.is_empty(), |
| 4498 | "Failed to parse complex variable functions: {:?}", |
| 4499 | parsed.errors |
| 4500 | ); |
| 4501 | } |
| 4502 | |
| 4503 | #[test] |
| 4504 | fn test_nested_variable_expansions() { |
| 4505 | let content = r#" |
| 4506 | VERSION = 1.0 |
| 4507 | PACKAGE = myapp |
| 4508 | TARBALL = $(PACKAGE)-$(VERSION).tar.gz |
| 4509 | INSTALL_PATH = $(shell echo $(PREFIX) | sed 's/\/$//') |
| 4510 | "#; |
| 4511 | let parsed = parse(content, None); |
| 4512 | assert!( |
| 4513 | parsed.errors.is_empty(), |
| 4514 | "Failed to parse nested variable expansions: {:?}", |
| 4515 | parsed.errors |
| 4516 | ); |
| 4517 | } |
| 4518 | |
| 4519 | #[test] |
| 4520 | fn test_special_directives() { |
| 4521 | let content = r#" |
| 4522 | # Special makefile directives |
| 4523 | .PHONY: all clean |
| 4524 | .SUFFIXES: .c .o |
| 4525 | .DEFAULT: all |
| 4526 | |
| 4527 | # Variable definition and export directive |
| 4528 | export PATH := /usr/bin:/bin |
| 4529 | "#; |
| 4530 | // Use relaxed parsing to allow for special directives |
| 4531 | let mut buf = content.as_bytes(); |
| 4532 | let makefile = |
| 4533 | Makefile::read_relaxed(&mut buf).expect("Failed to parse special directives"); |
| 4534 | |
| 4535 | // Check that we can extract rules even with errors |
| 4536 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 4537 | |
| 4538 | // Find phony rule |
| 4539 | let phony_rule = rules |
| 4540 | .iter() |
| 4541 | .find(|r| r.targets().any(|t| t.contains(".PHONY"))); |
| 4542 | assert!(phony_rule.is_some(), "Expected to find .PHONY rule"); |
| 4543 | |
| 4544 | // Check that variables can be extracted |
| 4545 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 4546 | assert!(!vars.is_empty(), "Expected to find at least one variable"); |
| 4547 | } |
| 4548 | |
| 4549 | // Comprehensive Test combining multiple issues |
| 4550 | |
| 4551 | #[test] |
| 4552 | fn test_comprehensive_real_world_makefile() { |
| 4553 | // Simple makefile with basic elements |
| 4554 | let content = r#" |
| 4555 | # Basic variable assignment |
| 4556 | VERSION = 1.0.0 |
| 4557 | |
| 4558 | # Phony target |
| 4559 | .PHONY: all clean |
| 4560 | |
| 4561 | # Simple rule |
| 4562 | all: |
| 4563 | echo "Building version $(VERSION)" |
| 4564 | |
| 4565 | # Another rule with dependencies |
| 4566 | clean: |
| 4567 | rm -f *.o |
| 4568 | "#; |
| 4569 | |
| 4570 | // Parse the content |
| 4571 | let parsed = parse(content, None); |
| 4572 | |
| 4573 | // Check that parsing succeeded |
| 4574 | assert!(parsed.errors.is_empty(), "Expected no parsing errors"); |
| 4575 | |
| 4576 | // Check that we found variables |
| 4577 | let variables = parsed.root().variable_definitions().collect::<Vec<_>>(); |
| 4578 | assert!(!variables.is_empty(), "Expected at least one variable"); |
| 4579 | assert_eq!( |
| 4580 | variables[0].name(), |
| 4581 | Some("VERSION".to_string()), |
| 4582 | "Expected VERSION variable" |
| 4583 | ); |
| 4584 | |
| 4585 | // Check that we found rules |
| 4586 | let rules = parsed.root().rules().collect::<Vec<_>>(); |
| 4587 | assert!(!rules.is_empty(), "Expected at least one rule"); |
| 4588 | |
| 4589 | // Check for specific rules |
| 4590 | let rule_targets: Vec<String> = rules |
| 4591 | .iter() |
| 4592 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 4593 | .collect(); |
| 4594 | assert!( |
| 4595 | rule_targets.contains(&".PHONY".to_string()), |
| 4596 | "Expected .PHONY rule" |
| 4597 | ); |
| 4598 | assert!( |
| 4599 | rule_targets.contains(&"all".to_string()), |
| 4600 | "Expected 'all' rule" |
| 4601 | ); |
| 4602 | assert!( |
| 4603 | rule_targets.contains(&"clean".to_string()), |
| 4604 | "Expected 'clean' rule" |
| 4605 | ); |
| 4606 | } |
| 4607 | |
| 4608 | #[test] |
| 4609 | fn test_indented_help_text_outside_rules() { |
| 4610 | // Create test content with indented help text |
| 4611 | let content = r#" |
| 4612 | # Targets with help text |
| 4613 | help: |
| 4614 | @echo "Available targets:" |
| 4615 | @echo " build build the project" |
| 4616 | @echo " test run tests" |
| 4617 | @echo " clean clean build artifacts" |
| 4618 | |
| 4619 | # Another target |
| 4620 | clean: |
| 4621 | rm -rf build/ |
| 4622 | "#; |
| 4623 | |
| 4624 | // Parse the content |
| 4625 | let parsed = parse(content, None); |
| 4626 | |
| 4627 | // Verify parsing succeeded |
| 4628 | assert!( |
| 4629 | parsed.errors.is_empty(), |
| 4630 | "Failed to parse indented help text" |
| 4631 | ); |
| 4632 | |
| 4633 | // Check that we found the expected rules |
| 4634 | let rules = parsed.root().rules().collect::<Vec<_>>(); |
| 4635 | assert_eq!(rules.len(), 2, "Expected to find two rules"); |
| 4636 | |
| 4637 | // Find the rules by target |
| 4638 | let help_rule = rules |
| 4639 | .iter() |
| 4640 | .find(|r| r.targets().any(|t| t == "help")) |
| 4641 | .expect("Expected to find help rule"); |
| 4642 | |
| 4643 | let clean_rule = rules |
| 4644 | .iter() |
| 4645 | .find(|r| r.targets().any(|t| t == "clean")) |
| 4646 | .expect("Expected to find clean rule"); |
| 4647 | |
| 4648 | // Check help rule has expected recipe lines |
| 4649 | let help_recipes = help_rule.recipes().collect::<Vec<_>>(); |
| 4650 | assert!( |
| 4651 | !help_recipes.is_empty(), |
| 4652 | "Help rule should have recipe lines" |
| 4653 | ); |
| 4654 | assert!( |
| 4655 | help_recipes |
| 4656 | .iter() |
| 4657 | .any(|line| line.contains("Available targets")), |
| 4658 | "Help recipes should include 'Available targets' line" |
| 4659 | ); |
| 4660 | |
| 4661 | // Check clean rule has expected recipe |
| 4662 | let clean_recipes = clean_rule.recipes().collect::<Vec<_>>(); |
| 4663 | assert!( |
| 4664 | !clean_recipes.is_empty(), |
| 4665 | "Clean rule should have recipe lines" |
| 4666 | ); |
| 4667 | assert!( |
| 4668 | clean_recipes.iter().any(|line| line.contains("rm -rf")), |
| 4669 | "Clean recipes should include 'rm -rf' command" |
| 4670 | ); |
| 4671 | } |
| 4672 | |
| 4673 | #[test] |
| 4674 | fn test_makefile1_phony_pattern() { |
| 4675 | // Replicate the specific pattern in Makefile_1 that caused issues |
| 4676 | let content = "#line 2145\n.PHONY: $(PHONY)\n"; |
| 4677 | |
| 4678 | // Parse the content |
| 4679 | let result = parse(content, None); |
| 4680 | |
| 4681 | // Verify no parsing errors |
| 4682 | assert!( |
| 4683 | result.errors.is_empty(), |
| 4684 | "Failed to parse .PHONY: $(PHONY) pattern" |
| 4685 | ); |
| 4686 | |
| 4687 | // Check that the rule was parsed correctly |
| 4688 | let rules = result.root().rules().collect::<Vec<_>>(); |
| 4689 | assert_eq!(rules.len(), 1, "Expected 1 rule"); |
| 4690 | assert_eq!( |
| 4691 | rules[0].targets().next().unwrap(), |
| 4692 | ".PHONY", |
| 4693 | "Expected .PHONY rule" |
| 4694 | ); |
| 4695 | |
| 4696 | // Check that the prerequisite contains the variable reference |
| 4697 | let prereqs = rules[0].prerequisites().collect::<Vec<_>>(); |
| 4698 | assert_eq!(prereqs.len(), 1, "Expected 1 prerequisite"); |
| 4699 | assert_eq!(prereqs[0], "$(PHONY)", "Expected $(PHONY) prerequisite"); |
| 4700 | } |
| 4701 | |
| 4702 | #[test] |
| 4703 | fn test_skip_until_newline_behavior() { |
| 4704 | // Test the skip_until_newline function to cover the != vs == mutant |
| 4705 | let input = "text without newline"; |
| 4706 | let parsed = parse(input, None); |
| 4707 | // This should handle gracefully without infinite loops |
| 4708 | assert!(parsed.errors.is_empty() || !parsed.errors.is_empty()); |
| 4709 | |
| 4710 | let input_with_newline = "text\nafter newline"; |
| 4711 | let parsed2 = parse(input_with_newline, None); |
| 4712 | assert!(parsed2.errors.is_empty() || !parsed2.errors.is_empty()); |
| 4713 | } |
| 4714 | |
| 4715 | #[test] |
| 4716 | #[ignore] // Ignored until proper handling of orphaned indented lines is implemented |
| 4717 | fn test_error_with_indent_token() { |
| 4718 | // Test the error logic with INDENT token to cover the ! deletion mutant |
| 4719 | let input = "\tinvalid indented line"; |
| 4720 | let parsed = parse(input, None); |
| 4721 | // Should produce an error about indented line not part of a rule |
| 4722 | assert!(!parsed.errors.is_empty()); |
| 4723 | |
| 4724 | let error_msg = &parsed.errors[0].message; |
| 4725 | assert!(error_msg.contains("recipe commences before first target")); |
| 4726 | } |
| 4727 | |
| 4728 | #[test] |
| 4729 | fn test_conditional_token_handling() { |
| 4730 | // Test conditional token handling to cover the == vs != mutant |
| 4731 | let input = r#" |
| 4732 | ifndef VAR |
| 4733 | CFLAGS = -DTEST |
| 4734 | endif |
| 4735 | "#; |
| 4736 | let parsed = parse(input, None); |
| 4737 | // Test that parsing doesn't panic and produces some result |
| 4738 | let makefile = parsed.root(); |
| 4739 | let _vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 4740 | // Should handle conditionals, possibly with errors but without crashing |
| 4741 | |
| 4742 | // Test with nested conditionals |
| 4743 | let nested = r#" |
| 4744 | ifdef DEBUG |
| 4745 | ifndef RELEASE |
| 4746 | CFLAGS = -g |
| 4747 | endif |
| 4748 | endif |
| 4749 | "#; |
| 4750 | let parsed_nested = parse(nested, None); |
| 4751 | // Test that parsing doesn't panic |
| 4752 | let _makefile = parsed_nested.root(); |
| 4753 | } |
| 4754 | |
| 4755 | #[test] |
| 4756 | fn test_include_vs_conditional_logic() { |
| 4757 | // Test the include vs conditional logic to cover the == vs != mutant at line 743 |
| 4758 | let input = r#" |
| 4759 | include file.mk |
| 4760 | ifdef VAR |
| 4761 | VALUE = 1 |
| 4762 | endif |
| 4763 | "#; |
| 4764 | let parsed = parse(input, None); |
| 4765 | // Test that parsing doesn't panic and produces some result |
| 4766 | let makefile = parsed.root(); |
| 4767 | let includes = makefile.includes().collect::<Vec<_>>(); |
| 4768 | // Should recognize include directive |
| 4769 | assert!(!includes.is_empty() || !parsed.errors.is_empty()); |
| 4770 | |
| 4771 | // Test with -include |
| 4772 | let optional_include = r#" |
| 4773 | -include optional.mk |
| 4774 | ifndef VAR |
| 4775 | VALUE = default |
| 4776 | endif |
| 4777 | "#; |
| 4778 | let parsed2 = parse(optional_include, None); |
| 4779 | // Test that parsing doesn't panic |
| 4780 | let _makefile = parsed2.root(); |
| 4781 | } |
| 4782 | |
| 4783 | #[test] |
| 4784 | fn test_balanced_parens_counting() { |
| 4785 | // Test balanced parentheses parsing to cover the += vs -= mutant |
| 4786 | let input = r#" |
| 4787 | VAR = $(call func,$(nested,arg),extra) |
| 4788 | COMPLEX = $(if $(condition),$(then_val),$(else_val)) |
| 4789 | "#; |
| 4790 | let parsed = parse(input, None); |
| 4791 | assert!(parsed.errors.is_empty()); |
| 4792 | |
| 4793 | let makefile = parsed.root(); |
| 4794 | let vars = makefile.variable_definitions().collect::<Vec<_>>(); |
| 4795 | assert_eq!(vars.len(), 2); |
| 4796 | } |
| 4797 | |
| 4798 | #[test] |
| 4799 | fn test_documentation_lookahead() { |
| 4800 | // Test the documentation lookahead logic to cover the - vs + mutant at line 895 |
| 4801 | let input = r#" |
| 4802 | # Documentation comment |
| 4803 | help: |
| 4804 | @echo "Usage instructions" |
| 4805 | @echo "More help text" |
| 4806 | "#; |
| 4807 | let parsed = parse(input, None); |
| 4808 | assert!(parsed.errors.is_empty()); |
| 4809 | |
| 4810 | let makefile = parsed.root(); |
| 4811 | let rules = makefile.rules().collect::<Vec<_>>(); |
| 4812 | assert_eq!(rules.len(), 1); |
| 4813 | assert_eq!(rules[0].targets().next().unwrap(), "help"); |
| 4814 | } |
| 4815 | |
| 4816 | #[test] |
| 4817 | fn test_edge_case_empty_input() { |
| 4818 | // Test with empty input |
| 4819 | let parsed = parse("", None); |
| 4820 | assert!(parsed.errors.is_empty()); |
| 4821 | |
| 4822 | // Test with only whitespace |
| 4823 | let parsed2 = parse(" \n \n", None); |
| 4824 | // Some parsers might report warnings/errors for whitespace-only input |
| 4825 | // Just ensure it doesn't crash |
| 4826 | let _makefile = parsed2.root(); |
| 4827 | } |
| 4828 | |
| 4829 | #[test] |
| 4830 | fn test_malformed_conditional_recovery() { |
| 4831 | // Test parser recovery from malformed conditionals |
| 4832 | let input = r#" |
| 4833 | ifdef |
| 4834 | # Missing condition variable |
| 4835 | endif |
| 4836 | "#; |
| 4837 | let parsed = parse(input, None); |
| 4838 | // Parser should either handle gracefully or report appropriate errors |
| 4839 | // Not checking for specific error since parsing strategy may vary |
| 4840 | assert!(parsed.errors.is_empty() || !parsed.errors.is_empty()); |
| 4841 | } |
| 4842 | |
| 4843 | #[test] |
| 4844 | fn test_replace_rule() { |
| 4845 | let mut makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap(); |
| 4846 | let new_rule: Rule = "new_rule:\n\tnew_command\n".parse().unwrap(); |
| 4847 | |
| 4848 | makefile.replace_rule(0, new_rule).unwrap(); |
| 4849 | |
| 4850 | let targets: Vec<_> = makefile |
| 4851 | .rules() |
| 4852 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 4853 | .collect(); |
| 4854 | assert_eq!(targets, vec!["new_rule", "rule2"]); |
| 4855 | |
| 4856 | let recipes: Vec<_> = makefile.rules().next().unwrap().recipes().collect(); |
| 4857 | assert_eq!(recipes, vec!["new_command"]); |
| 4858 | } |
| 4859 | |
| 4860 | #[test] |
| 4861 | fn test_replace_rule_out_of_bounds() { |
| 4862 | let mut makefile: Makefile = "rule1:\n\tcommand1\n".parse().unwrap(); |
| 4863 | let new_rule: Rule = "new_rule:\n\tnew_command\n".parse().unwrap(); |
| 4864 | |
| 4865 | let result = makefile.replace_rule(5, new_rule); |
| 4866 | assert!(result.is_err()); |
| 4867 | } |
| 4868 | |
| 4869 | #[test] |
| 4870 | fn test_remove_rule() { |
| 4871 | let mut makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\nrule3:\n\tcommand3\n" |
| 4872 | .parse() |
| 4873 | .unwrap(); |
| 4874 | |
| 4875 | let removed = makefile.remove_rule(1).unwrap(); |
| 4876 | assert_eq!(removed.targets().collect::<Vec<_>>(), vec!["rule2"]); |
| 4877 | |
| 4878 | let remaining_targets: Vec<_> = makefile |
| 4879 | .rules() |
| 4880 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 4881 | .collect(); |
| 4882 | assert_eq!(remaining_targets, vec!["rule1", "rule3"]); |
| 4883 | assert_eq!(makefile.rules().count(), 2); |
| 4884 | } |
| 4885 | |
| 4886 | #[test] |
| 4887 | fn test_remove_rule_out_of_bounds() { |
| 4888 | let mut makefile: Makefile = "rule1:\n\tcommand1\n".parse().unwrap(); |
| 4889 | |
| 4890 | let result = makefile.remove_rule(5); |
| 4891 | assert!(result.is_err()); |
| 4892 | } |
| 4893 | |
| 4894 | #[test] |
| 4895 | fn test_insert_rule() { |
| 4896 | let mut makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap(); |
| 4897 | let new_rule: Rule = "inserted_rule:\n\tinserted_command\n".parse().unwrap(); |
| 4898 | |
| 4899 | makefile.insert_rule(1, new_rule).unwrap(); |
| 4900 | |
| 4901 | let targets: Vec<_> = makefile |
| 4902 | .rules() |
| 4903 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 4904 | .collect(); |
| 4905 | assert_eq!(targets, vec!["rule1", "inserted_rule", "rule2"]); |
| 4906 | assert_eq!(makefile.rules().count(), 3); |
| 4907 | } |
| 4908 | |
| 4909 | #[test] |
| 4910 | fn test_insert_rule_at_end() { |
| 4911 | let mut makefile: Makefile = "rule1:\n\tcommand1\n".parse().unwrap(); |
| 4912 | let new_rule: Rule = "end_rule:\n\tend_command\n".parse().unwrap(); |
| 4913 | |
| 4914 | makefile.insert_rule(1, new_rule).unwrap(); |
| 4915 | |
| 4916 | let targets: Vec<_> = makefile |
| 4917 | .rules() |
| 4918 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 4919 | .collect(); |
| 4920 | assert_eq!(targets, vec!["rule1", "end_rule"]); |
| 4921 | } |
| 4922 | |
| 4923 | #[test] |
| 4924 | fn test_insert_rule_out_of_bounds() { |
| 4925 | let mut makefile: Makefile = "rule1:\n\tcommand1\n".parse().unwrap(); |
| 4926 | let new_rule: Rule = "new_rule:\n\tnew_command\n".parse().unwrap(); |
| 4927 | |
| 4928 | let result = makefile.insert_rule(5, new_rule); |
| 4929 | assert!(result.is_err()); |
| 4930 | } |
| 4931 | |
| 4932 | #[test] |
| 4933 | fn test_insert_rule_preserves_blank_line_spacing_at_end() { |
| 4934 | // Test that inserting at the end preserves blank line spacing |
| 4935 | let input = "rule1:\n\tcommand1\n\nrule2:\n\tcommand2\n"; |
| 4936 | let mut makefile: Makefile = input.parse().unwrap(); |
| 4937 | let new_rule = Rule::new(&["rule3"], &[], &["command3"]); |
| 4938 | |
| 4939 | makefile.insert_rule(2, new_rule).unwrap(); |
| 4940 | |
| 4941 | let expected = "rule1:\n\tcommand1\n\nrule2:\n\tcommand2\n\nrule3:\n\tcommand3\n"; |
| 4942 | assert_eq!(makefile.to_string(), expected); |
| 4943 | } |
| 4944 | |
| 4945 | #[test] |
| 4946 | fn test_insert_rule_adds_blank_lines_when_missing() { |
| 4947 | // Test that inserting adds blank lines even when input has none |
| 4948 | let input = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n"; |
| 4949 | let mut makefile: Makefile = input.parse().unwrap(); |
| 4950 | let new_rule = Rule::new(&["rule3"], &[], &["command3"]); |
| 4951 | |
| 4952 | makefile.insert_rule(2, new_rule).unwrap(); |
| 4953 | |
| 4954 | let expected = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n\nrule3:\n\tcommand3\n"; |
| 4955 | assert_eq!(makefile.to_string(), expected); |
| 4956 | } |
| 4957 | |
| 4958 | #[test] |
| 4959 | fn test_remove_command() { |
| 4960 | let mut rule: Rule = "rule:\n\tcommand1\n\tcommand2\n\tcommand3\n" |
| 4961 | .parse() |
| 4962 | .unwrap(); |
| 4963 | |
| 4964 | rule.remove_command(1); |
| 4965 | let recipes: Vec<_> = rule.recipes().collect(); |
| 4966 | assert_eq!(recipes, vec!["command1", "command3"]); |
| 4967 | assert_eq!(rule.recipe_count(), 2); |
| 4968 | } |
| 4969 | |
| 4970 | #[test] |
| 4971 | fn test_remove_command_out_of_bounds() { |
| 4972 | let mut rule: Rule = "rule:\n\tcommand1\n".parse().unwrap(); |
| 4973 | |
| 4974 | let result = rule.remove_command(5); |
| 4975 | assert!(!result); |
| 4976 | } |
| 4977 | |
| 4978 | #[test] |
| 4979 | fn test_insert_command() { |
| 4980 | let mut rule: Rule = "rule:\n\tcommand1\n\tcommand3\n".parse().unwrap(); |
| 4981 | |
| 4982 | rule.insert_command(1, "command2"); |
| 4983 | let recipes: Vec<_> = rule.recipes().collect(); |
| 4984 | assert_eq!(recipes, vec!["command1", "command2", "command3"]); |
| 4985 | } |
| 4986 | |
| 4987 | #[test] |
| 4988 | fn test_insert_command_at_end() { |
| 4989 | let mut rule: Rule = "rule:\n\tcommand1\n".parse().unwrap(); |
| 4990 | |
| 4991 | rule.insert_command(1, "command2"); |
| 4992 | let recipes: Vec<_> = rule.recipes().collect(); |
| 4993 | assert_eq!(recipes, vec!["command1", "command2"]); |
| 4994 | } |
| 4995 | |
| 4996 | #[test] |
| 4997 | fn test_insert_command_in_empty_rule() { |
| 4998 | let mut rule: Rule = "rule:\n".parse().unwrap(); |
| 4999 | |
| 5000 | rule.insert_command(0, "new_command"); |
| 5001 | let recipes: Vec<_> = rule.recipes().collect(); |
| 5002 | assert_eq!(recipes, vec!["new_command"]); |
| 5003 | } |
| 5004 | |
| 5005 | #[test] |
| 5006 | fn test_recipe_count() { |
| 5007 | let rule1: Rule = "rule:\n".parse().unwrap(); |
| 5008 | assert_eq!(rule1.recipe_count(), 0); |
| 5009 | |
| 5010 | let rule2: Rule = "rule:\n\tcommand1\n\tcommand2\n".parse().unwrap(); |
| 5011 | assert_eq!(rule2.recipe_count(), 2); |
| 5012 | } |
| 5013 | |
| 5014 | #[test] |
| 5015 | fn test_clear_commands() { |
| 5016 | let mut rule: Rule = "rule:\n\tcommand1\n\tcommand2\n\tcommand3\n" |
| 5017 | .parse() |
| 5018 | .unwrap(); |
| 5019 | |
| 5020 | rule.clear_commands(); |
| 5021 | assert_eq!(rule.recipe_count(), 0); |
| 5022 | |
| 5023 | let recipes: Vec<_> = rule.recipes().collect(); |
| 5024 | assert_eq!(recipes, Vec::<String>::new()); |
| 5025 | |
| 5026 | // Rule target should still be preserved |
| 5027 | let targets: Vec<_> = rule.targets().collect(); |
| 5028 | assert_eq!(targets, vec!["rule"]); |
| 5029 | } |
| 5030 | |
| 5031 | #[test] |
| 5032 | fn test_clear_commands_empty_rule() { |
| 5033 | let mut rule: Rule = "rule:\n".parse().unwrap(); |
| 5034 | |
| 5035 | rule.clear_commands(); |
| 5036 | assert_eq!(rule.recipe_count(), 0); |
| 5037 | |
| 5038 | let targets: Vec<_> = rule.targets().collect(); |
| 5039 | assert_eq!(targets, vec!["rule"]); |
| 5040 | } |
| 5041 | |
| 5042 | #[test] |
| 5043 | fn test_rule_manipulation_preserves_structure() { |
| 5044 | // Test that makefile structure (comments, variables, etc.) is preserved during rule manipulation |
| 5045 | let input = r#"# Comment |
| 5046 | VAR = value |
| 5047 | |
| 5048 | rule1: |
| 5049 | command1 |
| 5050 | |
| 5051 | # Another comment |
| 5052 | rule2: |
| 5053 | command2 |
| 5054 | |
| 5055 | VAR2 = value2 |
| 5056 | "#; |
| 5057 | |
| 5058 | let mut makefile: Makefile = input.parse().unwrap(); |
| 5059 | let new_rule: Rule = "new_rule:\n\tnew_command\n".parse().unwrap(); |
| 5060 | |
| 5061 | // Insert rule in the middle |
| 5062 | makefile.insert_rule(1, new_rule).unwrap(); |
| 5063 | |
| 5064 | // Check that rules are correct |
| 5065 | let targets: Vec<_> = makefile |
| 5066 | .rules() |
| 5067 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 5068 | .collect(); |
| 5069 | assert_eq!(targets, vec!["rule1", "new_rule", "rule2"]); |
| 5070 | |
| 5071 | // Check that variables are preserved |
| 5072 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 5073 | assert_eq!(vars.len(), 2); |
| 5074 | |
| 5075 | // The structure should be preserved in the output |
| 5076 | let output = makefile.code(); |
| 5077 | assert!(output.contains("# Comment")); |
| 5078 | assert!(output.contains("VAR = value")); |
| 5079 | assert!(output.contains("# Another comment")); |
| 5080 | assert!(output.contains("VAR2 = value2")); |
| 5081 | } |
| 5082 | |
| 5083 | #[test] |
| 5084 | fn test_replace_rule_with_multiple_targets() { |
| 5085 | let mut makefile: Makefile = "target1 target2: dep\n\tcommand\n".parse().unwrap(); |
| 5086 | let new_rule: Rule = "new_target: new_dep\n\tnew_command\n".parse().unwrap(); |
| 5087 | |
| 5088 | makefile.replace_rule(0, new_rule).unwrap(); |
| 5089 | |
| 5090 | let targets: Vec<_> = makefile |
| 5091 | .rules() |
| 5092 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 5093 | .collect(); |
| 5094 | assert_eq!(targets, vec!["new_target"]); |
| 5095 | } |
| 5096 | |
| 5097 | #[test] |
| 5098 | fn test_empty_makefile_operations() { |
| 5099 | let mut makefile = Makefile::new(); |
| 5100 | |
| 5101 | // Test operations on empty makefile |
| 5102 | assert!(makefile |
| 5103 | .replace_rule(0, "rule:\n\tcommand\n".parse().unwrap()) |
| 5104 | .is_err()); |
| 5105 | assert!(makefile.remove_rule(0).is_err()); |
| 5106 | |
| 5107 | // Insert into empty makefile should work |
| 5108 | let new_rule: Rule = "first_rule:\n\tcommand\n".parse().unwrap(); |
| 5109 | makefile.insert_rule(0, new_rule).unwrap(); |
| 5110 | assert_eq!(makefile.rules().count(), 1); |
| 5111 | } |
| 5112 | |
| 5113 | #[test] |
| 5114 | fn test_command_operations_preserve_indentation() { |
| 5115 | let mut rule: Rule = "rule:\n\t\tdeep_indent\n\tshallow_indent\n" |
| 5116 | .parse() |
| 5117 | .unwrap(); |
| 5118 | |
| 5119 | rule.insert_command(1, "middle_command"); |
| 5120 | let recipes: Vec<_> = rule.recipes().collect(); |
| 5121 | assert_eq!( |
| 5122 | recipes, |
| 5123 | vec!["\tdeep_indent", "middle_command", "shallow_indent"] |
| 5124 | ); |
| 5125 | } |
| 5126 | |
| 5127 | #[test] |
| 5128 | fn test_rule_operations_with_variables_and_includes() { |
| 5129 | let input = r#"VAR1 = value1 |
| 5130 | include common.mk |
| 5131 | |
| 5132 | rule1: |
| 5133 | command1 |
| 5134 | |
| 5135 | VAR2 = value2 |
| 5136 | include other.mk |
| 5137 | |
| 5138 | rule2: |
| 5139 | command2 |
| 5140 | "#; |
| 5141 | |
| 5142 | let mut makefile: Makefile = input.parse().unwrap(); |
| 5143 | |
| 5144 | // Remove middle rule |
| 5145 | makefile.remove_rule(0).unwrap(); |
| 5146 | |
| 5147 | // Verify structure is preserved |
| 5148 | let output = makefile.code(); |
| 5149 | assert!(output.contains("VAR1 = value1")); |
| 5150 | assert!(output.contains("include common.mk")); |
| 5151 | assert!(output.contains("VAR2 = value2")); |
| 5152 | assert!(output.contains("include other.mk")); |
| 5153 | |
| 5154 | // Only rule2 should remain |
| 5155 | assert_eq!(makefile.rules().count(), 1); |
| 5156 | let remaining_targets: Vec<_> = makefile |
| 5157 | .rules() |
| 5158 | .flat_map(|r| r.targets().collect::<Vec<_>>()) |
| 5159 | .collect(); |
| 5160 | assert_eq!(remaining_targets, vec!["rule2"]); |
| 5161 | } |
| 5162 | |
| 5163 | #[test] |
| 5164 | fn test_command_manipulation_edge_cases() { |
| 5165 | // Test with rule that has no commands |
| 5166 | let mut empty_rule: Rule = "empty:\n".parse().unwrap(); |
| 5167 | assert_eq!(empty_rule.recipe_count(), 0); |
| 5168 | |
| 5169 | empty_rule.insert_command(0, "first_command"); |
| 5170 | assert_eq!(empty_rule.recipe_count(), 1); |
| 5171 | |
| 5172 | // Test clearing already empty rule |
| 5173 | let mut empty_rule2: Rule = "empty:\n".parse().unwrap(); |
| 5174 | empty_rule2.clear_commands(); |
| 5175 | assert_eq!(empty_rule2.recipe_count(), 0); |
| 5176 | } |
| 5177 | |
| 5178 | #[test] |
| 5179 | fn test_large_makefile_performance() { |
| 5180 | // Create a makefile with many rules to test performance doesn't degrade |
| 5181 | let mut makefile = Makefile::new(); |
| 5182 | |
| 5183 | // Add 100 rules |
| 5184 | for i in 0..100 { |
| 5185 | let rule_name = format!("rule{}", i); |
| 5186 | makefile |
| 5187 | .add_rule(&rule_name) |
| 5188 | .push_command(&format!("command{}", i)); |
| 5189 | } |
| 5190 | |
| 5191 | assert_eq!(makefile.rules().count(), 100); |
| 5192 | |
| 5193 | // Replace rule in the middle - should be efficient |
| 5194 | let new_rule: Rule = "middle_rule:\n\tmiddle_command\n".parse().unwrap(); |
| 5195 | makefile.replace_rule(50, new_rule).unwrap(); |
| 5196 | |
| 5197 | // Verify the change |
| 5198 | let rule_50_targets: Vec<_> = makefile.rules().nth(50).unwrap().targets().collect(); |
| 5199 | assert_eq!(rule_50_targets, vec!["middle_rule"]); |
| 5200 | |
| 5201 | assert_eq!(makefile.rules().count(), 100); // Count unchanged |
| 5202 | } |
| 5203 | |
| 5204 | #[test] |
| 5205 | fn test_complex_recipe_manipulation() { |
| 5206 | let mut complex_rule: Rule = r#"complex: |
| 5207 | @echo "Starting build" |
| 5208 | $(CC) $(CFLAGS) -o $@ $< |
| 5209 | @echo "Build complete" |
| 5210 | chmod +x $@ |
| 5211 | "# |
| 5212 | .parse() |
| 5213 | .unwrap(); |
| 5214 | |
| 5215 | assert_eq!(complex_rule.recipe_count(), 4); |
| 5216 | |
| 5217 | // Remove the echo statements, keep the actual build commands |
| 5218 | complex_rule.remove_command(0); // Remove first echo |
| 5219 | complex_rule.remove_command(1); // Remove second echo (now at index 1, not 2) |
| 5220 | |
| 5221 | let final_recipes: Vec<_> = complex_rule.recipes().collect(); |
| 5222 | assert_eq!(final_recipes.len(), 2); |
| 5223 | assert!(final_recipes[0].contains("$(CC)")); |
| 5224 | assert!(final_recipes[1].contains("chmod")); |
| 5225 | } |
| 5226 | |
| 5227 | #[test] |
| 5228 | fn test_variable_definition_remove() { |
| 5229 | let makefile: Makefile = r#"VAR1 = value1 |
| 5230 | VAR2 = value2 |
| 5231 | VAR3 = value3 |
| 5232 | "# |
| 5233 | .parse() |
| 5234 | .unwrap(); |
| 5235 | |
| 5236 | // Verify we have 3 variables |
| 5237 | assert_eq!(makefile.variable_definitions().count(), 3); |
| 5238 | |
| 5239 | // Remove the second variable |
| 5240 | let mut var2 = makefile |
| 5241 | .variable_definitions() |
| 5242 | .nth(1) |
| 5243 | .expect("Should have second variable"); |
| 5244 | assert_eq!(var2.name(), Some("VAR2".to_string())); |
| 5245 | var2.remove(); |
| 5246 | |
| 5247 | // Verify we now have 2 variables and VAR2 is gone |
| 5248 | assert_eq!(makefile.variable_definitions().count(), 2); |
| 5249 | let var_names: Vec<_> = makefile |
| 5250 | .variable_definitions() |
| 5251 | .filter_map(|v| v.name()) |
| 5252 | .collect(); |
| 5253 | assert_eq!(var_names, vec!["VAR1", "VAR3"]); |
| 5254 | } |
| 5255 | |
| 5256 | #[test] |
| 5257 | fn test_variable_definition_set_value() { |
| 5258 | let makefile: Makefile = "VAR = old_value\n".parse().unwrap(); |
| 5259 | |
| 5260 | let mut var = makefile |
| 5261 | .variable_definitions() |
| 5262 | .next() |
| 5263 | .expect("Should have variable"); |
| 5264 | assert_eq!(var.raw_value(), Some("old_value".to_string())); |
| 5265 | |
| 5266 | // Change the value |
| 5267 | var.set_value("new_value"); |
| 5268 | |
| 5269 | // Verify the value changed |
| 5270 | assert_eq!(var.raw_value(), Some("new_value".to_string())); |
| 5271 | assert!(makefile.code().contains("VAR = new_value")); |
| 5272 | } |
| 5273 | |
| 5274 | #[test] |
| 5275 | fn test_variable_definition_set_value_preserves_format() { |
| 5276 | let makefile: Makefile = "export VAR := old_value\n".parse().unwrap(); |
| 5277 | |
| 5278 | let mut var = makefile |
| 5279 | .variable_definitions() |
| 5280 | .next() |
| 5281 | .expect("Should have variable"); |
| 5282 | assert_eq!(var.raw_value(), Some("old_value".to_string())); |
| 5283 | |
| 5284 | // Change the value |
| 5285 | var.set_value("new_value"); |
| 5286 | |
| 5287 | // Verify the value changed but format preserved |
| 5288 | assert_eq!(var.raw_value(), Some("new_value".to_string())); |
| 5289 | let code = makefile.code(); |
| 5290 | assert!(code.contains("export"), "Should preserve export prefix"); |
| 5291 | assert!(code.contains(":="), "Should preserve := operator"); |
| 5292 | assert!(code.contains("new_value"), "Should have new value"); |
| 5293 | } |
| 5294 | |
| 5295 | #[test] |
| 5296 | fn test_makefile_find_variable() { |
| 5297 | let makefile: Makefile = r#"VAR1 = value1 |
| 5298 | VAR2 = value2 |
| 5299 | VAR3 = value3 |
| 5300 | "# |
| 5301 | .parse() |
| 5302 | .unwrap(); |
| 5303 | |
| 5304 | // Find existing variable |
| 5305 | let vars: Vec<_> = makefile.find_variable("VAR2").collect(); |
| 5306 | assert_eq!(vars.len(), 1); |
| 5307 | assert_eq!(vars[0].name(), Some("VAR2".to_string())); |
| 5308 | assert_eq!(vars[0].raw_value(), Some("value2".to_string())); |
| 5309 | |
| 5310 | // Try to find non-existent variable |
| 5311 | assert_eq!(makefile.find_variable("NONEXISTENT").count(), 0); |
| 5312 | } |
| 5313 | |
| 5314 | #[test] |
| 5315 | fn test_makefile_find_variable_with_export() { |
| 5316 | let makefile: Makefile = r#"VAR1 = value1 |
| 5317 | export VAR2 := value2 |
| 5318 | VAR3 = value3 |
| 5319 | "# |
| 5320 | .parse() |
| 5321 | .unwrap(); |
| 5322 | |
| 5323 | // Find exported variable |
| 5324 | let vars: Vec<_> = makefile.find_variable("VAR2").collect(); |
| 5325 | assert_eq!(vars.len(), 1); |
| 5326 | assert_eq!(vars[0].name(), Some("VAR2".to_string())); |
| 5327 | assert_eq!(vars[0].raw_value(), Some("value2".to_string())); |
| 5328 | } |
| 5329 | |
| 5330 | #[test] |
| 5331 | fn test_variable_definition_is_export() { |
| 5332 | let makefile: Makefile = r#"VAR1 = value1 |
| 5333 | export VAR2 := value2 |
| 5334 | export VAR3 = value3 |
| 5335 | VAR4 := value4 |
| 5336 | "# |
| 5337 | .parse() |
| 5338 | .unwrap(); |
| 5339 | |
| 5340 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 5341 | assert_eq!(vars.len(), 4); |
| 5342 | |
| 5343 | assert!(!vars[0].is_export()); |
| 5344 | assert!(vars[1].is_export()); |
| 5345 | assert!(vars[2].is_export()); |
| 5346 | assert!(!vars[3].is_export()); |
| 5347 | } |
| 5348 | |
| 5349 | #[test] |
| 5350 | fn test_makefile_find_variable_multiple() { |
| 5351 | let makefile: Makefile = r#"VAR1 = value1 |
| 5352 | VAR1 = value2 |
| 5353 | VAR2 = other |
| 5354 | VAR1 = value3 |
| 5355 | "# |
| 5356 | .parse() |
| 5357 | .unwrap(); |
| 5358 | |
| 5359 | // Find all VAR1 definitions |
| 5360 | let vars: Vec<_> = makefile.find_variable("VAR1").collect(); |
| 5361 | assert_eq!(vars.len(), 3); |
| 5362 | assert_eq!(vars[0].raw_value(), Some("value1".to_string())); |
| 5363 | assert_eq!(vars[1].raw_value(), Some("value2".to_string())); |
| 5364 | assert_eq!(vars[2].raw_value(), Some("value3".to_string())); |
| 5365 | |
| 5366 | // Find VAR2 |
| 5367 | let var2s: Vec<_> = makefile.find_variable("VAR2").collect(); |
| 5368 | assert_eq!(var2s.len(), 1); |
| 5369 | assert_eq!(var2s[0].raw_value(), Some("other".to_string())); |
| 5370 | } |
| 5371 | |
| 5372 | #[test] |
| 5373 | fn test_variable_remove_and_find() { |
| 5374 | let makefile: Makefile = r#"VAR1 = value1 |
| 5375 | VAR2 = value2 |
| 5376 | VAR3 = value3 |
| 5377 | "# |
| 5378 | .parse() |
| 5379 | .unwrap(); |
| 5380 | |
| 5381 | // Find and remove VAR2 |
| 5382 | let mut var2 = makefile |
| 5383 | .find_variable("VAR2") |
| 5384 | .next() |
| 5385 | .expect("Should find VAR2"); |
| 5386 | var2.remove(); |
| 5387 | |
| 5388 | // Verify VAR2 is gone |
| 5389 | assert_eq!(makefile.find_variable("VAR2").count(), 0); |
| 5390 | |
| 5391 | // Verify other variables still exist |
| 5392 | assert_eq!(makefile.find_variable("VAR1").count(), 1); |
| 5393 | assert_eq!(makefile.find_variable("VAR3").count(), 1); |
| 5394 | } |
| 5395 | |
| 5396 | #[test] |
| 5397 | fn test_variable_remove_with_comment() { |
| 5398 | let makefile: Makefile = r#"VAR1 = value1 |
| 5399 | # This is a comment about VAR2 |
| 5400 | VAR2 = value2 |
| 5401 | VAR3 = value3 |
| 5402 | "# |
| 5403 | .parse() |
| 5404 | .unwrap(); |
| 5405 | |
| 5406 | // Remove VAR2 |
| 5407 | let mut var2 = makefile |
| 5408 | .variable_definitions() |
| 5409 | .nth(1) |
| 5410 | .expect("Should have second variable"); |
| 5411 | assert_eq!(var2.name(), Some("VAR2".to_string())); |
| 5412 | var2.remove(); |
| 5413 | |
| 5414 | // Verify the comment is also removed |
| 5415 | assert_eq!(makefile.code(), "VAR1 = value1\nVAR3 = value3\n"); |
| 5416 | } |
| 5417 | |
| 5418 | #[test] |
| 5419 | fn test_variable_remove_with_multiple_comments() { |
| 5420 | let makefile: Makefile = r#"VAR1 = value1 |
| 5421 | # Comment line 1 |
| 5422 | # Comment line 2 |
| 5423 | # Comment line 3 |
| 5424 | VAR2 = value2 |
| 5425 | VAR3 = value3 |
| 5426 | "# |
| 5427 | .parse() |
| 5428 | .unwrap(); |
| 5429 | |
| 5430 | // Remove VAR2 |
| 5431 | let mut var2 = makefile |
| 5432 | .variable_definitions() |
| 5433 | .nth(1) |
| 5434 | .expect("Should have second variable"); |
| 5435 | var2.remove(); |
| 5436 | |
| 5437 | // Verify all comments are removed |
| 5438 | assert_eq!(makefile.code(), "VAR1 = value1\nVAR3 = value3\n"); |
| 5439 | } |
| 5440 | |
| 5441 | #[test] |
| 5442 | fn test_variable_remove_with_empty_line() { |
| 5443 | let makefile: Makefile = r#"VAR1 = value1 |
| 5444 | |
| 5445 | # Comment about VAR2 |
| 5446 | VAR2 = value2 |
| 5447 | VAR3 = value3 |
| 5448 | "# |
| 5449 | .parse() |
| 5450 | .unwrap(); |
| 5451 | |
| 5452 | // Remove VAR2 |
| 5453 | let mut var2 = makefile |
| 5454 | .variable_definitions() |
| 5455 | .nth(1) |
| 5456 | .expect("Should have second variable"); |
| 5457 | var2.remove(); |
| 5458 | |
| 5459 | // Verify comment and up to 1 empty line are removed |
| 5460 | // Should have VAR1, then newline, then VAR3 (empty line removed) |
| 5461 | assert_eq!(makefile.code(), "VAR1 = value1\nVAR3 = value3\n"); |
| 5462 | } |
| 5463 | |
| 5464 | #[test] |
| 5465 | fn test_variable_remove_with_multiple_empty_lines() { |
| 5466 | let makefile: Makefile = r#"VAR1 = value1 |
| 5467 | |
| 5468 | |
| 5469 | # Comment about VAR2 |
| 5470 | VAR2 = value2 |
| 5471 | VAR3 = value3 |
| 5472 | "# |
| 5473 | .parse() |
| 5474 | .unwrap(); |
| 5475 | |
| 5476 | // Remove VAR2 |
| 5477 | let mut var2 = makefile |
| 5478 | .variable_definitions() |
| 5479 | .nth(1) |
| 5480 | .expect("Should have second variable"); |
| 5481 | var2.remove(); |
| 5482 | |
| 5483 | // Verify comment and only 1 empty line are removed (one empty line preserved) |
| 5484 | // Should preserve one empty line before where VAR2 was |
| 5485 | assert_eq!(makefile.code(), "VAR1 = value1\n\nVAR3 = value3\n"); |
| 5486 | } |
| 5487 | |
| 5488 | #[test] |
| 5489 | fn test_rule_remove_with_comment() { |
| 5490 | let makefile: Makefile = r#"rule1: |
| 5491 | command1 |
| 5492 | |
| 5493 | # Comment about rule2 |
| 5494 | rule2: |
| 5495 | command2 |
| 5496 | rule3: |
| 5497 | command3 |
| 5498 | "# |
| 5499 | .parse() |
| 5500 | .unwrap(); |
| 5501 | |
| 5502 | // Remove rule2 |
| 5503 | let rule2 = makefile.rules().nth(1).expect("Should have second rule"); |
| 5504 | rule2.remove().unwrap(); |
| 5505 | |
| 5506 | // Verify the comment is removed |
| 5507 | // Note: The empty line after rule1 is part of rule1's text, not a sibling, so it's preserved |
| 5508 | assert_eq!( |
| 5509 | makefile.code(), |
| 5510 | "rule1:\n\tcommand1\n\nrule3:\n\tcommand3\n" |
| 5511 | ); |
| 5512 | } |
| 5513 | |
| 5514 | #[test] |
| 5515 | fn test_variable_remove_preserves_shebang() { |
| 5516 | let makefile: Makefile = r#"#!/usr/bin/make -f |
| 5517 | # This is a regular comment |
| 5518 | VAR1 = value1 |
| 5519 | VAR2 = value2 |
| 5520 | "# |
| 5521 | .parse() |
| 5522 | .unwrap(); |
| 5523 | |
| 5524 | // Remove VAR1 |
| 5525 | let mut var1 = makefile.variable_definitions().next().unwrap(); |
| 5526 | var1.remove(); |
| 5527 | |
| 5528 | // Verify the shebang is preserved but regular comment is removed |
| 5529 | let code = makefile.code(); |
| 5530 | assert!(code.starts_with("#!/usr/bin/make -f")); |
| 5531 | assert!(!code.contains("regular comment")); |
| 5532 | assert!(!code.contains("VAR1")); |
| 5533 | assert!(code.contains("VAR2")); |
| 5534 | } |
| 5535 | |
| 5536 | #[test] |
| 5537 | fn test_variable_remove_preserves_subsequent_comments() { |
| 5538 | let makefile: Makefile = r#"VAR1 = value1 |
| 5539 | # Comment about VAR2 |
| 5540 | VAR2 = value2 |
| 5541 | |
| 5542 | # Comment about VAR3 |
| 5543 | VAR3 = value3 |
| 5544 | "# |
| 5545 | .parse() |
| 5546 | .unwrap(); |
| 5547 | |
| 5548 | // Remove VAR2 |
| 5549 | let mut var2 = makefile |
| 5550 | .variable_definitions() |
| 5551 | .nth(1) |
| 5552 | .expect("Should have second variable"); |
| 5553 | var2.remove(); |
| 5554 | |
| 5555 | // Verify preceding comment is removed but subsequent comment/empty line are preserved |
| 5556 | let code = makefile.code(); |
| 5557 | assert_eq!( |
| 5558 | code, |
| 5559 | "VAR1 = value1\n\n# Comment about VAR3\nVAR3 = value3\n" |
| 5560 | ); |
| 5561 | } |
| 5562 | |
| 5563 | #[test] |
| 5564 | fn test_variable_remove_after_shebang_preserves_empty_line() { |
| 5565 | let makefile: Makefile = r#"#!/usr/bin/make -f |
| 5566 | export DEB_LDFLAGS_MAINT_APPEND = -Wl,--as-needed |
| 5567 | |
| 5568 | %: |
| 5569 | dh $@ |
| 5570 | "# |
| 5571 | .parse() |
| 5572 | .unwrap(); |
| 5573 | |
| 5574 | // Remove the variable |
| 5575 | let mut var = makefile.variable_definitions().next().unwrap(); |
| 5576 | var.remove(); |
| 5577 | |
| 5578 | // Verify shebang is preserved and empty line after variable is preserved |
| 5579 | assert_eq!(makefile.code(), "#!/usr/bin/make -f\n\n%:\n\tdh $@\n"); |
| 5580 | } |
| 5581 | |
| 5582 | #[test] |
| 5583 | fn test_rule_add_prerequisite() { |
| 5584 | let mut rule: Rule = "target: dep1\n".parse().unwrap(); |
| 5585 | rule.add_prerequisite("dep2").unwrap(); |
| 5586 | assert_eq!( |
| 5587 | rule.prerequisites().collect::<Vec<_>>(), |
| 5588 | vec!["dep1", "dep2"] |
| 5589 | ); |
| 5590 | // Verify proper spacing |
| 5591 | assert_eq!(rule.to_string(), "target: dep1 dep2\n"); |
| 5592 | } |
| 5593 | |
| 5594 | #[test] |
| 5595 | fn test_rule_add_prerequisite_to_rule_without_prereqs() { |
| 5596 | // Regression test for missing space after colon when adding first prerequisite |
| 5597 | let mut rule: Rule = "target:\n".parse().unwrap(); |
| 5598 | rule.add_prerequisite("dep1").unwrap(); |
| 5599 | assert_eq!(rule.prerequisites().collect::<Vec<_>>(), vec!["dep1"]); |
| 5600 | // Should have space after colon |
| 5601 | assert_eq!(rule.to_string(), "target: dep1\n"); |
| 5602 | } |
| 5603 | |
| 5604 | #[test] |
| 5605 | fn test_rule_remove_prerequisite() { |
| 5606 | let mut rule: Rule = "target: dep1 dep2 dep3\n".parse().unwrap(); |
| 5607 | assert!(rule.remove_prerequisite("dep2").unwrap()); |
| 5608 | assert_eq!( |
| 5609 | rule.prerequisites().collect::<Vec<_>>(), |
| 5610 | vec!["dep1", "dep3"] |
| 5611 | ); |
| 5612 | assert!(!rule.remove_prerequisite("nonexistent").unwrap()); |
| 5613 | } |
| 5614 | |
| 5615 | #[test] |
| 5616 | fn test_rule_set_prerequisites() { |
| 5617 | let mut rule: Rule = "target: old_dep\n".parse().unwrap(); |
| 5618 | rule.set_prerequisites(vec!["new_dep1", "new_dep2"]) |
| 5619 | .unwrap(); |
| 5620 | assert_eq!( |
| 5621 | rule.prerequisites().collect::<Vec<_>>(), |
| 5622 | vec!["new_dep1", "new_dep2"] |
| 5623 | ); |
| 5624 | } |
| 5625 | |
| 5626 | #[test] |
| 5627 | fn test_rule_set_prerequisites_empty() { |
| 5628 | let mut rule: Rule = "target: dep1 dep2\n".parse().unwrap(); |
| 5629 | rule.set_prerequisites(vec![]).unwrap(); |
| 5630 | assert_eq!(rule.prerequisites().collect::<Vec<_>>().len(), 0); |
| 5631 | } |
| 5632 | |
| 5633 | #[test] |
| 5634 | fn test_rule_add_target() { |
| 5635 | let mut rule: Rule = "target1: dep1\n".parse().unwrap(); |
| 5636 | rule.add_target("target2").unwrap(); |
| 5637 | assert_eq!( |
| 5638 | rule.targets().collect::<Vec<_>>(), |
| 5639 | vec!["target1", "target2"] |
| 5640 | ); |
| 5641 | } |
| 5642 | |
| 5643 | #[test] |
| 5644 | fn test_rule_set_targets() { |
| 5645 | let mut rule: Rule = "old_target: dependency\n".parse().unwrap(); |
| 5646 | rule.set_targets(vec!["new_target1", "new_target2"]) |
| 5647 | .unwrap(); |
| 5648 | assert_eq!( |
| 5649 | rule.targets().collect::<Vec<_>>(), |
| 5650 | vec!["new_target1", "new_target2"] |
| 5651 | ); |
| 5652 | } |
| 5653 | |
| 5654 | #[test] |
| 5655 | fn test_rule_set_targets_empty() { |
| 5656 | let mut rule: Rule = "target: dep1\n".parse().unwrap(); |
| 5657 | let result = rule.set_targets(vec![]); |
| 5658 | assert!(result.is_err()); |
| 5659 | // Verify target wasn't changed |
| 5660 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["target"]); |
| 5661 | } |
| 5662 | |
| 5663 | #[test] |
| 5664 | fn test_rule_has_target() { |
| 5665 | let rule: Rule = "target1 target2: dependency\n".parse().unwrap(); |
| 5666 | assert!(rule.has_target("target1")); |
| 5667 | assert!(rule.has_target("target2")); |
| 5668 | assert!(!rule.has_target("target3")); |
| 5669 | assert!(!rule.has_target("nonexistent")); |
| 5670 | } |
| 5671 | |
| 5672 | #[test] |
| 5673 | fn test_rule_rename_target() { |
| 5674 | let mut rule: Rule = "old_target: dependency\n".parse().unwrap(); |
| 5675 | assert!(rule.rename_target("old_target", "new_target").unwrap()); |
| 5676 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["new_target"]); |
| 5677 | // Try renaming non-existent target |
| 5678 | assert!(!rule.rename_target("nonexistent", "something").unwrap()); |
| 5679 | } |
| 5680 | |
| 5681 | #[test] |
| 5682 | fn test_rule_rename_target_multiple() { |
| 5683 | let mut rule: Rule = "target1 target2 target3: dependency\n".parse().unwrap(); |
| 5684 | assert!(rule.rename_target("target2", "renamed_target").unwrap()); |
| 5685 | assert_eq!( |
| 5686 | rule.targets().collect::<Vec<_>>(), |
| 5687 | vec!["target1", "renamed_target", "target3"] |
| 5688 | ); |
| 5689 | } |
| 5690 | |
| 5691 | #[test] |
| 5692 | fn test_rule_remove_target() { |
| 5693 | let mut rule: Rule = "target1 target2 target3: dependency\n".parse().unwrap(); |
| 5694 | assert!(rule.remove_target("target2").unwrap()); |
| 5695 | assert_eq!( |
| 5696 | rule.targets().collect::<Vec<_>>(), |
| 5697 | vec!["target1", "target3"] |
| 5698 | ); |
| 5699 | // Try removing non-existent target |
| 5700 | assert!(!rule.remove_target("nonexistent").unwrap()); |
| 5701 | } |
| 5702 | |
| 5703 | #[test] |
| 5704 | fn test_rule_remove_target_last() { |
| 5705 | let mut rule: Rule = "single_target: dependency\n".parse().unwrap(); |
| 5706 | let result = rule.remove_target("single_target"); |
| 5707 | assert!(result.is_err()); |
| 5708 | // Verify target wasn't removed |
| 5709 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["single_target"]); |
| 5710 | } |
| 5711 | |
| 5712 | #[test] |
| 5713 | fn test_rule_target_manipulation_preserves_prerequisites() { |
| 5714 | let mut rule: Rule = "target1 target2: dep1 dep2\n\tcommand".parse().unwrap(); |
| 5715 | |
| 5716 | // Remove a target |
| 5717 | rule.remove_target("target1").unwrap(); |
| 5718 | assert_eq!(rule.targets().collect::<Vec<_>>(), vec!["target2"]); |
| 5719 | assert_eq!( |
| 5720 | rule.prerequisites().collect::<Vec<_>>(), |
| 5721 | vec!["dep1", "dep2"] |
| 5722 | ); |
| 5723 | assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command"]); |
| 5724 | |
| 5725 | // Add a target |
| 5726 | rule.add_target("target3").unwrap(); |
| 5727 | assert_eq!( |
| 5728 | rule.targets().collect::<Vec<_>>(), |
| 5729 | vec!["target2", "target3"] |
| 5730 | ); |
| 5731 | assert_eq!( |
| 5732 | rule.prerequisites().collect::<Vec<_>>(), |
| 5733 | vec!["dep1", "dep2"] |
| 5734 | ); |
| 5735 | assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command"]); |
| 5736 | |
| 5737 | // Rename a target |
| 5738 | rule.rename_target("target2", "renamed").unwrap(); |
| 5739 | assert_eq!( |
| 5740 | rule.targets().collect::<Vec<_>>(), |
| 5741 | vec!["renamed", "target3"] |
| 5742 | ); |
| 5743 | assert_eq!( |
| 5744 | rule.prerequisites().collect::<Vec<_>>(), |
| 5745 | vec!["dep1", "dep2"] |
| 5746 | ); |
| 5747 | assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["command"]); |
| 5748 | } |
| 5749 | |
| 5750 | #[test] |
| 5751 | fn test_rule_remove() { |
| 5752 | let makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap(); |
| 5753 | let rule = makefile.find_rule_by_target("rule1").unwrap(); |
| 5754 | rule.remove().unwrap(); |
| 5755 | assert_eq!(makefile.rules().count(), 1); |
| 5756 | assert!(makefile.find_rule_by_target("rule1").is_none()); |
| 5757 | assert!(makefile.find_rule_by_target("rule2").is_some()); |
| 5758 | } |
| 5759 | |
| 5760 | #[test] |
| 5761 | fn test_rule_remove_last_trims_blank_lines() { |
| 5762 | // Regression test for bug where removing the last rule left trailing blank lines |
| 5763 | let makefile: Makefile = |
| 5764 | "%:\n\tdh $@\n\noverride_dh_missing:\n\tdh_missing --fail-missing\n" |
| 5765 | .parse() |
| 5766 | .unwrap(); |
| 5767 | |
| 5768 | // Remove the last rule (override_dh_missing) |
| 5769 | let rule = makefile.find_rule_by_target("override_dh_missing").unwrap(); |
| 5770 | rule.remove().unwrap(); |
| 5771 | |
| 5772 | // Should not have trailing blank line |
| 5773 | assert_eq!(makefile.code(), "%:\n\tdh $@\n"); |
| 5774 | assert_eq!(makefile.rules().count(), 1); |
| 5775 | } |
| 5776 | |
| 5777 | #[test] |
| 5778 | fn test_makefile_find_rule_by_target() { |
| 5779 | let makefile: Makefile = "rule1:\n\tcommand1\nrule2:\n\tcommand2\n".parse().unwrap(); |
| 5780 | let rule = makefile.find_rule_by_target("rule2"); |
| 5781 | assert!(rule.is_some()); |
| 5782 | assert_eq!(rule.unwrap().targets().collect::<Vec<_>>(), vec!["rule2"]); |
| 5783 | assert!(makefile.find_rule_by_target("nonexistent").is_none()); |
| 5784 | } |
| 5785 | |
| 5786 | #[test] |
| 5787 | fn test_makefile_find_rules_by_target() { |
| 5788 | let makefile: Makefile = "rule1:\n\tcommand1\nrule1:\n\tcommand2\nrule2:\n\tcommand3\n" |
| 5789 | .parse() |
| 5790 | .unwrap(); |
| 5791 | assert_eq!(makefile.find_rules_by_target("rule1").count(), 2); |
| 5792 | assert_eq!(makefile.find_rules_by_target("rule2").count(), 1); |
| 5793 | assert_eq!(makefile.find_rules_by_target("nonexistent").count(), 0); |
| 5794 | } |
| 5795 | |
| 5796 | #[test] |
| 5797 | fn test_makefile_find_rule_by_target_pattern_simple() { |
| 5798 | let makefile: Makefile = "%.o: %.c\n\t$(CC) -c $<\n".parse().unwrap(); |
| 5799 | let rule = makefile.find_rule_by_target_pattern("foo.o"); |
| 5800 | assert!(rule.is_some()); |
| 5801 | assert_eq!(rule.unwrap().targets().next().unwrap(), "%.o"); |
| 5802 | } |
| 5803 | |
| 5804 | #[test] |
| 5805 | fn test_makefile_find_rule_by_target_pattern_no_match() { |
| 5806 | let makefile: Makefile = "%.o: %.c\n\t$(CC) -c $<\n".parse().unwrap(); |
| 5807 | let rule = makefile.find_rule_by_target_pattern("foo.c"); |
| 5808 | assert!(rule.is_none()); |
| 5809 | } |
| 5810 | |
| 5811 | #[test] |
| 5812 | fn test_makefile_find_rule_by_target_pattern_exact() { |
| 5813 | let makefile: Makefile = "foo.o: foo.c\n\t$(CC) -c $<\n".parse().unwrap(); |
| 5814 | let rule = makefile.find_rule_by_target_pattern("foo.o"); |
| 5815 | assert!(rule.is_some()); |
| 5816 | assert_eq!(rule.unwrap().targets().next().unwrap(), "foo.o"); |
| 5817 | } |
| 5818 | |
| 5819 | #[test] |
| 5820 | fn test_makefile_find_rule_by_target_pattern_prefix() { |
| 5821 | let makefile: Makefile = "lib%.a: %.o\n\tar rcs $@ $<\n".parse().unwrap(); |
| 5822 | let rule = makefile.find_rule_by_target_pattern("libfoo.a"); |
| 5823 | assert!(rule.is_some()); |
| 5824 | assert_eq!(rule.unwrap().targets().next().unwrap(), "lib%.a"); |
| 5825 | } |
| 5826 | |
| 5827 | #[test] |
| 5828 | fn test_makefile_find_rule_by_target_pattern_suffix() { |
| 5829 | let makefile: Makefile = "%_test.o: %.c\n\t$(CC) -c $<\n".parse().unwrap(); |
| 5830 | let rule = makefile.find_rule_by_target_pattern("foo_test.o"); |
| 5831 | assert!(rule.is_some()); |
| 5832 | assert_eq!(rule.unwrap().targets().next().unwrap(), "%_test.o"); |
| 5833 | } |
| 5834 | |
| 5835 | #[test] |
| 5836 | fn test_makefile_find_rule_by_target_pattern_middle() { |
| 5837 | let makefile: Makefile = "lib%_debug.a: %.o\n\tar rcs $@ $<\n".parse().unwrap(); |
| 5838 | let rule = makefile.find_rule_by_target_pattern("libfoo_debug.a"); |
| 5839 | assert!(rule.is_some()); |
| 5840 | assert_eq!(rule.unwrap().targets().next().unwrap(), "lib%_debug.a"); |
| 5841 | } |
| 5842 | |
| 5843 | #[test] |
| 5844 | fn test_makefile_find_rule_by_target_pattern_wildcard_only() { |
| 5845 | let makefile: Makefile = "%: %.c\n\t$(CC) -o $@ $<\n".parse().unwrap(); |
| 5846 | let rule = makefile.find_rule_by_target_pattern("anything"); |
| 5847 | assert!(rule.is_some()); |
| 5848 | assert_eq!(rule.unwrap().targets().next().unwrap(), "%"); |
| 5849 | } |
| 5850 | |
| 5851 | #[test] |
| 5852 | fn test_makefile_find_rules_by_target_pattern_multiple() { |
| 5853 | let makefile: Makefile = "%.o: %.c\n\t$(CC) -c $<\n%.o: %.s\n\t$(AS) -o $@ $<\n" |
| 5854 | .parse() |
| 5855 | .unwrap(); |
| 5856 | let rules: Vec<_> = makefile.find_rules_by_target_pattern("foo.o").collect(); |
| 5857 | assert_eq!(rules.len(), 2); |
| 5858 | } |
| 5859 | |
| 5860 | #[test] |
| 5861 | fn test_makefile_find_rules_by_target_pattern_mixed() { |
| 5862 | let makefile: Makefile = |
| 5863 | "%.o: %.c\n\t$(CC) -c $<\nfoo.o: foo.h\n\t$(CC) -c foo.c\nbar.txt: baz.txt\n\tcp $< $@\n" |
| 5864 | .parse() |
| 5865 | .unwrap(); |
| 5866 | let rules: Vec<_> = makefile.find_rules_by_target_pattern("foo.o").collect(); |
| 5867 | assert_eq!(rules.len(), 2); // Matches both %.o and foo.o |
| 5868 | let rules: Vec<_> = makefile.find_rules_by_target_pattern("bar.txt").collect(); |
| 5869 | assert_eq!(rules.len(), 1); // Only exact match |
| 5870 | } |
| 5871 | |
| 5872 | #[test] |
| 5873 | fn test_makefile_find_rules_by_target_pattern_no_wildcard() { |
| 5874 | let makefile: Makefile = "foo.o: foo.c\n\t$(CC) -c $<\n".parse().unwrap(); |
| 5875 | let rules: Vec<_> = makefile.find_rules_by_target_pattern("foo.o").collect(); |
| 5876 | assert_eq!(rules.len(), 1); |
| 5877 | let rules: Vec<_> = makefile.find_rules_by_target_pattern("bar.o").collect(); |
| 5878 | assert_eq!(rules.len(), 0); |
| 5879 | } |
| 5880 | |
| 5881 | #[test] |
| 5882 | fn test_matches_pattern_exact() { |
| 5883 | assert!(matches_pattern("foo.o", "foo.o")); |
| 5884 | assert!(!matches_pattern("foo.o", "bar.o")); |
| 5885 | } |
| 5886 | |
| 5887 | #[test] |
| 5888 | fn test_matches_pattern_suffix() { |
| 5889 | assert!(matches_pattern("%.o", "foo.o")); |
| 5890 | assert!(matches_pattern("%.o", "bar.o")); |
| 5891 | assert!(matches_pattern("%.o", "baz/qux.o")); |
| 5892 | assert!(!matches_pattern("%.o", "foo.c")); |
| 5893 | } |
| 5894 | |
| 5895 | #[test] |
| 5896 | fn test_matches_pattern_prefix() { |
| 5897 | assert!(matches_pattern("lib%.a", "libfoo.a")); |
| 5898 | assert!(matches_pattern("lib%.a", "libbar.a")); |
| 5899 | assert!(!matches_pattern("lib%.a", "foo.a")); |
| 5900 | assert!(!matches_pattern("lib%.a", "lib.a")); |
| 5901 | } |
| 5902 | |
| 5903 | #[test] |
| 5904 | fn test_matches_pattern_middle() { |
| 5905 | assert!(matches_pattern("lib%_debug.a", "libfoo_debug.a")); |
| 5906 | assert!(matches_pattern("lib%_debug.a", "libbar_debug.a")); |
| 5907 | assert!(!matches_pattern("lib%_debug.a", "libfoo.a")); |
| 5908 | assert!(!matches_pattern("lib%_debug.a", "foo_debug.a")); |
| 5909 | } |
| 5910 | |
| 5911 | #[test] |
| 5912 | fn test_matches_pattern_wildcard_only() { |
| 5913 | assert!(matches_pattern("%", "anything")); |
| 5914 | assert!(matches_pattern("%", "foo.o")); |
| 5915 | // GNU make: stem must be non-empty, so "%" does NOT match "" |
| 5916 | assert!(!matches_pattern("%", "")); |
| 5917 | } |
| 5918 | |
| 5919 | #[test] |
| 5920 | fn test_matches_pattern_empty_stem() { |
| 5921 | // GNU make: stem must be non-empty |
| 5922 | assert!(!matches_pattern("%.o", ".o")); // stem would be empty |
| 5923 | assert!(!matches_pattern("lib%", "lib")); // stem would be empty |
| 5924 | assert!(!matches_pattern("lib%.a", "lib.a")); // stem would be empty |
| 5925 | } |
| 5926 | |
| 5927 | #[test] |
| 5928 | fn test_matches_pattern_multiple_wildcards_not_supported() { |
| 5929 | // GNU make does NOT support multiple % in pattern rules |
| 5930 | // These should not match (fall back to exact match) |
| 5931 | assert!(!matches_pattern("%foo%bar", "xfooybarz")); |
| 5932 | assert!(!matches_pattern("lib%.so.%", "libfoo.so.1")); |
| 5933 | } |
| 5934 | |
| 5935 | #[test] |
| 5936 | fn test_makefile_add_phony_target() { |
| 5937 | let mut makefile = Makefile::new(); |
| 5938 | makefile.add_phony_target("clean").unwrap(); |
| 5939 | assert!(makefile.is_phony("clean")); |
| 5940 | assert_eq!(makefile.phony_targets().collect::<Vec<_>>(), vec!["clean"]); |
| 5941 | } |
| 5942 | |
| 5943 | #[test] |
| 5944 | fn test_makefile_add_phony_target_existing() { |
| 5945 | let mut makefile: Makefile = ".PHONY: test\n".parse().unwrap(); |
| 5946 | makefile.add_phony_target("clean").unwrap(); |
| 5947 | assert!(makefile.is_phony("test")); |
| 5948 | assert!(makefile.is_phony("clean")); |
| 5949 | let targets: Vec<_> = makefile.phony_targets().collect(); |
| 5950 | assert!(targets.contains(&"test".to_string())); |
| 5951 | assert!(targets.contains(&"clean".to_string())); |
| 5952 | } |
| 5953 | |
| 5954 | #[test] |
| 5955 | fn test_makefile_remove_phony_target() { |
| 5956 | let mut makefile: Makefile = ".PHONY: clean test\n".parse().unwrap(); |
| 5957 | assert!(makefile.remove_phony_target("clean").unwrap()); |
| 5958 | assert!(!makefile.is_phony("clean")); |
| 5959 | assert!(makefile.is_phony("test")); |
| 5960 | assert!(!makefile.remove_phony_target("nonexistent").unwrap()); |
| 5961 | } |
| 5962 | |
| 5963 | #[test] |
| 5964 | fn test_makefile_remove_phony_target_last() { |
| 5965 | let mut makefile: Makefile = ".PHONY: clean\n".parse().unwrap(); |
| 5966 | assert!(makefile.remove_phony_target("clean").unwrap()); |
| 5967 | assert!(!makefile.is_phony("clean")); |
| 5968 | // .PHONY rule should be removed entirely |
| 5969 | assert!(makefile.find_rule_by_target(".PHONY").is_none()); |
| 5970 | } |
| 5971 | |
| 5972 | #[test] |
| 5973 | fn test_makefile_is_phony() { |
| 5974 | let makefile: Makefile = ".PHONY: clean test\n".parse().unwrap(); |
| 5975 | assert!(makefile.is_phony("clean")); |
| 5976 | assert!(makefile.is_phony("test")); |
| 5977 | assert!(!makefile.is_phony("build")); |
| 5978 | } |
| 5979 | |
| 5980 | #[test] |
| 5981 | fn test_makefile_phony_targets() { |
| 5982 | let makefile: Makefile = ".PHONY: clean test build\n".parse().unwrap(); |
| 5983 | let phony_targets: Vec<_> = makefile.phony_targets().collect(); |
| 5984 | assert_eq!(phony_targets, vec!["clean", "test", "build"]); |
| 5985 | } |
| 5986 | |
| 5987 | #[test] |
| 5988 | fn test_makefile_phony_targets_empty() { |
| 5989 | let makefile = Makefile::new(); |
| 5990 | assert_eq!(makefile.phony_targets().count(), 0); |
| 5991 | } |
| 5992 | |
| 5993 | #[test] |
| 5994 | fn test_makefile_remove_first_phony_target_no_extra_space() { |
| 5995 | let mut makefile: Makefile = ".PHONY: clean test build\n".parse().unwrap(); |
| 5996 | assert!(makefile.remove_phony_target("clean").unwrap()); |
| 5997 | let result = makefile.to_string(); |
| 5998 | assert_eq!(result, ".PHONY: test build\n"); |
| 5999 | } |
| 6000 | |
| 6001 | #[test] |
| 6002 | fn test_recipe_with_leading_comments_and_blank_lines() { |
| 6003 | // Regression test for bug where recipes with leading comments and blank lines |
| 6004 | // were not parsed correctly. The parser would stop parsing recipes when it |
| 6005 | // encountered a newline, missing subsequent recipe lines. |
| 6006 | let makefile_text = r#"#!/usr/bin/make |
| 6007 | |
| 6008 | %: |
| 6009 | dh $@ |
| 6010 | |
| 6011 | override_dh_build: |
| 6012 | # The next line is empty |
| 6013 | |
| 6014 | dh_python3 |
| 6015 | "#; |
| 6016 | let makefile = Makefile::read_relaxed(makefile_text.as_bytes()).unwrap(); |
| 6017 | |
| 6018 | let rules: Vec<_> = makefile.rules().collect(); |
| 6019 | assert_eq!(rules.len(), 2, "Expected 2 rules"); |
| 6020 | |
| 6021 | // First rule: % |
| 6022 | let rule0 = &rules[0]; |
| 6023 | assert_eq!(rule0.targets().collect::<Vec<_>>(), vec!["%"]); |
| 6024 | assert_eq!(rule0.recipes().collect::<Vec<_>>(), vec!["dh $@"]); |
| 6025 | |
| 6026 | // Second rule: override_dh_build |
| 6027 | let rule1 = &rules[1]; |
| 6028 | assert_eq!( |
| 6029 | rule1.targets().collect::<Vec<_>>(), |
| 6030 | vec!["override_dh_build"] |
| 6031 | ); |
| 6032 | |
| 6033 | // The key assertion: we should have at least the actual command recipe |
| 6034 | let recipes: Vec<_> = rule1.recipes().collect(); |
| 6035 | assert!( |
| 6036 | !recipes.is_empty(), |
| 6037 | "Expected at least one recipe for override_dh_build, got none" |
| 6038 | ); |
| 6039 | assert!( |
| 6040 | recipes.contains(&"dh_python3".to_string()), |
| 6041 | "Expected 'dh_python3' in recipes, got: {:?}", |
| 6042 | recipes |
| 6043 | ); |
| 6044 | } |
| 6045 | |
| 6046 | #[test] |
| 6047 | fn test_rule_parse_preserves_trailing_blank_lines() { |
| 6048 | // Regression test: ensure that trailing blank lines are preserved |
| 6049 | // when parsing a rule and using it with replace_rule() |
| 6050 | let input = r#"override_dh_systemd_enable: |
| 6051 | dh_systemd_enable -pracoon |
| 6052 | |
| 6053 | override_dh_install: |
| 6054 | dh_install |
| 6055 | "#; |
| 6056 | |
| 6057 | let mut mf: Makefile = input.parse().unwrap(); |
| 6058 | |
| 6059 | // Get first rule and convert to string |
| 6060 | let rule = mf.rules().next().unwrap(); |
| 6061 | let rule_text = rule.to_string(); |
| 6062 | |
| 6063 | // Should include trailing blank line |
| 6064 | assert_eq!( |
| 6065 | rule_text, |
| 6066 | "override_dh_systemd_enable:\n\tdh_systemd_enable -pracoon\n\n" |
| 6067 | ); |
| 6068 | |
| 6069 | // Modify the text |
| 6070 | let modified = |
| 6071 | rule_text.replace("override_dh_systemd_enable:", "override_dh_installsystemd:"); |
| 6072 | |
| 6073 | // Parse back - should preserve trailing blank line |
| 6074 | let new_rule: Rule = modified.parse().unwrap(); |
| 6075 | assert_eq!( |
| 6076 | new_rule.to_string(), |
| 6077 | "override_dh_installsystemd:\n\tdh_systemd_enable -pracoon\n\n" |
| 6078 | ); |
| 6079 | |
| 6080 | // Replace in makefile |
| 6081 | mf.replace_rule(0, new_rule).unwrap(); |
| 6082 | |
| 6083 | // Verify blank line is still present in output |
| 6084 | let output = mf.to_string(); |
| 6085 | assert!( |
| 6086 | output.contains( |
| 6087 | "override_dh_installsystemd:\n\tdh_systemd_enable -pracoon\n\noverride_dh_install:" |
| 6088 | ), |
| 6089 | "Blank line between rules should be preserved. Got: {:?}", |
| 6090 | output |
| 6091 | ); |
| 6092 | } |
| 6093 | |
| 6094 | #[test] |
| 6095 | fn test_rule_parse_round_trip_with_trailing_newlines() { |
| 6096 | // Test that parsing and stringifying a rule preserves exact trailing newlines |
| 6097 | let test_cases = vec![ |
| 6098 | "rule:\n\tcommand\n", // One newline |
| 6099 | "rule:\n\tcommand\n\n", // Two newlines (blank line) |
| 6100 | "rule:\n\tcommand\n\n\n", // Three newlines (two blank lines) |
| 6101 | ]; |
| 6102 | |
| 6103 | for rule_text in test_cases { |
| 6104 | let rule: Rule = rule_text.parse().unwrap(); |
| 6105 | let result = rule.to_string(); |
| 6106 | assert_eq!(rule_text, result, "Round-trip failed for {:?}", rule_text); |
| 6107 | } |
| 6108 | } |
| 6109 | |
| 6110 | #[test] |
| 6111 | fn test_rule_clone() { |
| 6112 | // Test that Rule can be cloned and produces an identical copy |
| 6113 | let rule_text = "rule:\n\tcommand\n\n"; |
| 6114 | let rule: Rule = rule_text.parse().unwrap(); |
| 6115 | let cloned = rule.clone(); |
| 6116 | |
| 6117 | // Both should produce the same string representation |
| 6118 | assert_eq!(rule.to_string(), cloned.to_string()); |
| 6119 | assert_eq!(rule.to_string(), rule_text); |
| 6120 | assert_eq!(cloned.to_string(), rule_text); |
| 6121 | |
| 6122 | // Verify targets and recipes are the same |
| 6123 | assert_eq!( |
| 6124 | rule.targets().collect::<Vec<_>>(), |
| 6125 | cloned.targets().collect::<Vec<_>>() |
| 6126 | ); |
| 6127 | assert_eq!( |
| 6128 | rule.recipes().collect::<Vec<_>>(), |
| 6129 | cloned.recipes().collect::<Vec<_>>() |
| 6130 | ); |
| 6131 | } |
| 6132 | |
| 6133 | #[test] |
| 6134 | fn test_makefile_clone() { |
| 6135 | // Test that Makefile and other AST nodes can be cloned |
| 6136 | let input = "VAR = value\n\nrule:\n\tcommand\n"; |
| 6137 | let makefile: Makefile = input.parse().unwrap(); |
| 6138 | let cloned = makefile.clone(); |
| 6139 | |
| 6140 | // Both should produce the same string representation |
| 6141 | assert_eq!(makefile.to_string(), cloned.to_string()); |
| 6142 | assert_eq!(makefile.to_string(), input); |
| 6143 | |
| 6144 | // Verify rule count is the same |
| 6145 | assert_eq!(makefile.rules().count(), cloned.rules().count()); |
| 6146 | |
| 6147 | // Verify variable definitions are the same |
| 6148 | assert_eq!( |
| 6149 | makefile.variable_definitions().count(), |
| 6150 | cloned.variable_definitions().count() |
| 6151 | ); |
| 6152 | } |
| 6153 | |
| 6154 | #[test] |
| 6155 | fn test_conditional_with_recipe_line() { |
| 6156 | // Test that conditionals with recipe lines (tab-indented) work correctly |
| 6157 | let input = "ifeq (,$(X))\n\t./run-tests\nendif\n"; |
| 6158 | let parsed = parse(input, None); |
| 6159 | |
| 6160 | // Should parse without errors |
| 6161 | assert!( |
| 6162 | parsed.errors.is_empty(), |
| 6163 | "Expected no parse errors, but got: {:?}", |
| 6164 | parsed.errors |
| 6165 | ); |
| 6166 | |
| 6167 | // Should preserve the code |
| 6168 | let mf = parsed.root(); |
| 6169 | assert_eq!(mf.code(), input); |
| 6170 | } |
| 6171 | |
| 6172 | #[test] |
| 6173 | fn test_conditional_in_rule_recipe() { |
| 6174 | // Test conditional inside a rule's recipe section |
| 6175 | let input = "override_dh_auto_test:\nifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS)))\n\t./run-tests\nendif\n"; |
| 6176 | let parsed = parse(input, None); |
| 6177 | |
| 6178 | // Should parse without errors |
| 6179 | assert!( |
| 6180 | parsed.errors.is_empty(), |
| 6181 | "Expected no parse errors, but got: {:?}", |
| 6182 | parsed.errors |
| 6183 | ); |
| 6184 | |
| 6185 | // Should preserve the code |
| 6186 | let mf = parsed.root(); |
| 6187 | assert_eq!(mf.code(), input); |
| 6188 | |
| 6189 | // Should have exactly one rule |
| 6190 | assert_eq!(mf.rules().count(), 1); |
| 6191 | } |
| 6192 | |
| 6193 | #[test] |
| 6194 | fn test_rule_items() { |
| 6195 | use crate::RuleItem; |
| 6196 | |
| 6197 | // Test rule with both recipes and conditionals |
| 6198 | let input = r#"test: |
| 6199 | echo "before" |
| 6200 | ifeq (,$(filter nocheck,$(DEB_BUILD_OPTIONS))) |
| 6201 | ./run-tests |
| 6202 | endif |
| 6203 | echo "after" |
| 6204 | "#; |
| 6205 | let rule: Rule = input.parse().unwrap(); |
| 6206 | |
| 6207 | let items: Vec<_> = rule.items().collect(); |
| 6208 | assert_eq!( |
| 6209 | items.len(), |
| 6210 | 3, |
| 6211 | "Expected 3 items: recipe, conditional, recipe" |
| 6212 | ); |
| 6213 | |
| 6214 | // Check first item is a recipe |
| 6215 | match &items[0] { |
| 6216 | RuleItem::Recipe(r) => assert_eq!(r, "echo \"before\""), |
| 6217 | RuleItem::Conditional(_) => panic!("Expected recipe, got conditional"), |
| 6218 | } |
| 6219 | |
| 6220 | // Check second item is a conditional |
| 6221 | match &items[1] { |
| 6222 | RuleItem::Conditional(c) => { |
| 6223 | assert_eq!(c.conditional_type(), Some("ifeq".to_string())); |
| 6224 | } |
| 6225 | RuleItem::Recipe(_) => panic!("Expected conditional, got recipe"), |
| 6226 | } |
| 6227 | |
| 6228 | // Check third item is a recipe |
| 6229 | match &items[2] { |
| 6230 | RuleItem::Recipe(r) => assert_eq!(r, "echo \"after\""), |
| 6231 | RuleItem::Conditional(_) => panic!("Expected recipe, got conditional"), |
| 6232 | } |
| 6233 | |
| 6234 | // Test rule with only recipes (no conditionals) |
| 6235 | let simple_rule: Rule = "simple:\n\techo one\n\techo two\n".parse().unwrap(); |
| 6236 | let simple_items: Vec<_> = simple_rule.items().collect(); |
| 6237 | assert_eq!(simple_items.len(), 2); |
| 6238 | |
| 6239 | match &simple_items[0] { |
| 6240 | RuleItem::Recipe(r) => assert_eq!(r, "echo one"), |
| 6241 | _ => panic!("Expected recipe"), |
| 6242 | } |
| 6243 | |
| 6244 | match &simple_items[1] { |
| 6245 | RuleItem::Recipe(r) => assert_eq!(r, "echo two"), |
| 6246 | _ => panic!("Expected recipe"), |
| 6247 | } |
| 6248 | |
| 6249 | // Test rule with only conditional (no plain recipes) |
| 6250 | let cond_only: Rule = "condtest:\nifeq (a,b)\n\techo yes\nendif\n" |
| 6251 | .parse() |
| 6252 | .unwrap(); |
| 6253 | let cond_items: Vec<_> = cond_only.items().collect(); |
| 6254 | assert_eq!(cond_items.len(), 1); |
| 6255 | |
| 6256 | match &cond_items[0] { |
| 6257 | RuleItem::Conditional(c) => { |
| 6258 | assert_eq!(c.conditional_type(), Some("ifeq".to_string())); |
| 6259 | } |
| 6260 | _ => panic!("Expected conditional"), |
| 6261 | } |
| 6262 | } |
| 6263 | |
| 6264 | #[test] |
| 6265 | fn test_conditionals_iterator() { |
| 6266 | let makefile: Makefile = r#"ifdef DEBUG |
| 6267 | VAR = debug |
| 6268 | endif |
| 6269 | |
| 6270 | ifndef RELEASE |
| 6271 | OTHER = dev |
| 6272 | endif |
| 6273 | "# |
| 6274 | .parse() |
| 6275 | .unwrap(); |
| 6276 | |
| 6277 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 6278 | assert_eq!(conditionals.len(), 2); |
| 6279 | |
| 6280 | assert_eq!( |
| 6281 | conditionals[0].conditional_type(), |
| 6282 | Some("ifdef".to_string()) |
| 6283 | ); |
| 6284 | assert_eq!( |
| 6285 | conditionals[1].conditional_type(), |
| 6286 | Some("ifndef".to_string()) |
| 6287 | ); |
| 6288 | } |
| 6289 | |
| 6290 | #[test] |
| 6291 | fn test_conditional_type_and_condition() { |
| 6292 | let makefile: Makefile = r#"ifdef DEBUG |
| 6293 | VAR = debug |
| 6294 | endif |
| 6295 | "# |
| 6296 | .parse() |
| 6297 | .unwrap(); |
| 6298 | |
| 6299 | let conditional = makefile.conditionals().next().unwrap(); |
| 6300 | assert_eq!(conditional.conditional_type(), Some("ifdef".to_string())); |
| 6301 | assert_eq!(conditional.condition(), Some("DEBUG".to_string())); |
| 6302 | } |
| 6303 | |
| 6304 | #[test] |
| 6305 | fn test_conditional_has_else() { |
| 6306 | let makefile_with_else: Makefile = r#"ifdef DEBUG |
| 6307 | VAR = debug |
| 6308 | else |
| 6309 | VAR = release |
| 6310 | endif |
| 6311 | "# |
| 6312 | .parse() |
| 6313 | .unwrap(); |
| 6314 | |
| 6315 | let conditional = makefile_with_else.conditionals().next().unwrap(); |
| 6316 | assert!(conditional.has_else()); |
| 6317 | |
| 6318 | let makefile_without_else: Makefile = r#"ifdef DEBUG |
| 6319 | VAR = debug |
| 6320 | endif |
| 6321 | "# |
| 6322 | .parse() |
| 6323 | .unwrap(); |
| 6324 | |
| 6325 | let conditional = makefile_without_else.conditionals().next().unwrap(); |
| 6326 | assert!(!conditional.has_else()); |
| 6327 | } |
| 6328 | |
| 6329 | #[test] |
| 6330 | fn test_conditional_if_body() { |
| 6331 | let makefile: Makefile = r#"ifdef DEBUG |
| 6332 | VAR = debug |
| 6333 | endif |
| 6334 | "# |
| 6335 | .parse() |
| 6336 | .unwrap(); |
| 6337 | |
| 6338 | let conditional = makefile.conditionals().next().unwrap(); |
| 6339 | let if_body = conditional.if_body(); |
| 6340 | assert!(if_body.is_some()); |
| 6341 | assert!(if_body.unwrap().contains("VAR = debug")); |
| 6342 | } |
| 6343 | |
| 6344 | #[test] |
| 6345 | fn test_conditional_else_body() { |
| 6346 | let makefile: Makefile = r#"ifdef DEBUG |
| 6347 | VAR = debug |
| 6348 | else |
| 6349 | VAR = release |
| 6350 | endif |
| 6351 | "# |
| 6352 | .parse() |
| 6353 | .unwrap(); |
| 6354 | |
| 6355 | let conditional = makefile.conditionals().next().unwrap(); |
| 6356 | let else_body = conditional.else_body(); |
| 6357 | assert!(else_body.is_some()); |
| 6358 | assert!(else_body.unwrap().contains("VAR = release")); |
| 6359 | } |
| 6360 | |
| 6361 | #[test] |
| 6362 | fn test_add_conditional_ifdef() { |
| 6363 | let mut makefile = Makefile::new(); |
| 6364 | let result = makefile.add_conditional("ifdef", "DEBUG", "VAR = debug\n", None); |
| 6365 | assert!(result.is_ok()); |
| 6366 | |
| 6367 | let code = makefile.to_string(); |
| 6368 | assert!(code.contains("ifdef DEBUG")); |
| 6369 | assert!(code.contains("VAR = debug")); |
| 6370 | assert!(code.contains("endif")); |
| 6371 | } |
| 6372 | |
| 6373 | #[test] |
| 6374 | fn test_add_conditional_with_else() { |
| 6375 | let mut makefile = Makefile::new(); |
| 6376 | let result = |
| 6377 | makefile.add_conditional("ifdef", "DEBUG", "VAR = debug\n", Some("VAR = release\n")); |
| 6378 | assert!(result.is_ok()); |
| 6379 | |
| 6380 | let code = makefile.to_string(); |
| 6381 | assert!(code.contains("ifdef DEBUG")); |
| 6382 | assert!(code.contains("VAR = debug")); |
| 6383 | assert!(code.contains("else")); |
| 6384 | assert!(code.contains("VAR = release")); |
| 6385 | assert!(code.contains("endif")); |
| 6386 | } |
| 6387 | |
| 6388 | #[test] |
| 6389 | fn test_add_conditional_invalid_type() { |
| 6390 | let mut makefile = Makefile::new(); |
| 6391 | let result = makefile.add_conditional("invalid", "DEBUG", "VAR = debug\n", None); |
| 6392 | assert!(result.is_err()); |
| 6393 | } |
| 6394 | |
| 6395 | #[test] |
| 6396 | fn test_add_conditional_formatting() { |
| 6397 | let mut makefile: Makefile = "VAR1 = value1\n".parse().unwrap(); |
| 6398 | let result = makefile.add_conditional("ifdef", "DEBUG", "VAR = debug\n", None); |
| 6399 | assert!(result.is_ok()); |
| 6400 | |
| 6401 | let code = makefile.to_string(); |
| 6402 | // Should have a blank line before the conditional |
| 6403 | assert!(code.contains("\n\nifdef DEBUG")); |
| 6404 | } |
| 6405 | |
| 6406 | #[test] |
| 6407 | fn test_conditional_remove() { |
| 6408 | let makefile: Makefile = r#"ifdef DEBUG |
| 6409 | VAR = debug |
| 6410 | endif |
| 6411 | |
| 6412 | VAR2 = value2 |
| 6413 | "# |
| 6414 | .parse() |
| 6415 | .unwrap(); |
| 6416 | |
| 6417 | let mut conditional = makefile.conditionals().next().unwrap(); |
| 6418 | let result = conditional.remove(); |
| 6419 | assert!(result.is_ok()); |
| 6420 | |
| 6421 | let code = makefile.to_string(); |
| 6422 | assert!(!code.contains("ifdef DEBUG")); |
| 6423 | assert!(!code.contains("VAR = debug")); |
| 6424 | assert!(code.contains("VAR2 = value2")); |
| 6425 | } |
| 6426 | |
| 6427 | #[test] |
| 6428 | fn test_add_conditional_ifndef() { |
| 6429 | let mut makefile = Makefile::new(); |
| 6430 | let result = makefile.add_conditional("ifndef", "NDEBUG", "VAR = enabled\n", None); |
| 6431 | assert!(result.is_ok()); |
| 6432 | |
| 6433 | let code = makefile.to_string(); |
| 6434 | assert!(code.contains("ifndef NDEBUG")); |
| 6435 | assert!(code.contains("VAR = enabled")); |
| 6436 | assert!(code.contains("endif")); |
| 6437 | } |
| 6438 | |
| 6439 | #[test] |
| 6440 | fn test_add_conditional_ifeq() { |
| 6441 | let mut makefile = Makefile::new(); |
| 6442 | let result = makefile.add_conditional("ifeq", "($(OS),Linux)", "VAR = linux\n", None); |
| 6443 | assert!(result.is_ok()); |
| 6444 | |
| 6445 | let code = makefile.to_string(); |
| 6446 | assert!(code.contains("ifeq ($(OS),Linux)")); |
| 6447 | assert!(code.contains("VAR = linux")); |
| 6448 | assert!(code.contains("endif")); |
| 6449 | } |
| 6450 | |
| 6451 | #[test] |
| 6452 | fn test_add_conditional_ifneq() { |
| 6453 | let mut makefile = Makefile::new(); |
| 6454 | let result = makefile.add_conditional("ifneq", "($(OS),Windows)", "VAR = unix\n", None); |
| 6455 | assert!(result.is_ok()); |
| 6456 | |
| 6457 | let code = makefile.to_string(); |
| 6458 | assert!(code.contains("ifneq ($(OS),Windows)")); |
| 6459 | assert!(code.contains("VAR = unix")); |
| 6460 | assert!(code.contains("endif")); |
| 6461 | } |
| 6462 | |
| 6463 | #[test] |
| 6464 | fn test_conditional_api_integration() { |
| 6465 | // Create a makefile with a rule and a variable |
| 6466 | let mut makefile: Makefile = r#"VAR1 = value1 |
| 6467 | |
| 6468 | rule1: |
| 6469 | command1 |
| 6470 | "# |
| 6471 | .parse() |
| 6472 | .unwrap(); |
| 6473 | |
| 6474 | // Add a conditional |
| 6475 | makefile |
| 6476 | .add_conditional("ifdef", "DEBUG", "CFLAGS += -g\n", Some("CFLAGS += -O2\n")) |
| 6477 | .unwrap(); |
| 6478 | |
| 6479 | // Verify the conditional was added |
| 6480 | assert_eq!(makefile.conditionals().count(), 1); |
| 6481 | let conditional = makefile.conditionals().next().unwrap(); |
| 6482 | assert_eq!(conditional.conditional_type(), Some("ifdef".to_string())); |
| 6483 | assert_eq!(conditional.condition(), Some("DEBUG".to_string())); |
| 6484 | assert!(conditional.has_else()); |
| 6485 | |
| 6486 | // Verify the original content is preserved |
| 6487 | assert_eq!(makefile.variable_definitions().count(), 1); |
| 6488 | assert_eq!(makefile.rules().count(), 1); |
| 6489 | } |
| 6490 | |
| 6491 | #[test] |
| 6492 | fn test_conditional_if_items() { |
| 6493 | let makefile: Makefile = r#"ifdef DEBUG |
| 6494 | VAR = debug |
| 6495 | rule: |
| 6496 | command |
| 6497 | endif |
| 6498 | "# |
| 6499 | .parse() |
| 6500 | .unwrap(); |
| 6501 | |
| 6502 | let cond = makefile.conditionals().next().unwrap(); |
| 6503 | let items: Vec<_> = cond.if_items().collect(); |
| 6504 | assert_eq!(items.len(), 2); // One variable, one rule |
| 6505 | |
| 6506 | match &items[0] { |
| 6507 | MakefileItem::Variable(v) => { |
| 6508 | assert_eq!(v.name(), Some("VAR".to_string())); |
| 6509 | } |
| 6510 | _ => panic!("Expected variable"), |
| 6511 | } |
| 6512 | |
| 6513 | match &items[1] { |
| 6514 | MakefileItem::Rule(r) => { |
| 6515 | assert!(r.targets().any(|t| t == "rule")); |
| 6516 | } |
| 6517 | _ => panic!("Expected rule"), |
| 6518 | } |
| 6519 | } |
| 6520 | |
| 6521 | #[test] |
| 6522 | fn test_conditional_else_items() { |
| 6523 | let makefile: Makefile = r#"ifdef DEBUG |
| 6524 | VAR = debug |
| 6525 | else |
| 6526 | VAR2 = release |
| 6527 | rule2: |
| 6528 | command |
| 6529 | endif |
| 6530 | "# |
| 6531 | .parse() |
| 6532 | .unwrap(); |
| 6533 | |
| 6534 | let cond = makefile.conditionals().next().unwrap(); |
| 6535 | let items: Vec<_> = cond.else_items().collect(); |
| 6536 | assert_eq!(items.len(), 2); // One variable, one rule |
| 6537 | |
| 6538 | match &items[0] { |
| 6539 | MakefileItem::Variable(v) => { |
| 6540 | assert_eq!(v.name(), Some("VAR2".to_string())); |
| 6541 | } |
| 6542 | _ => panic!("Expected variable"), |
| 6543 | } |
| 6544 | |
| 6545 | match &items[1] { |
| 6546 | MakefileItem::Rule(r) => { |
| 6547 | assert!(r.targets().any(|t| t == "rule2")); |
| 6548 | } |
| 6549 | _ => panic!("Expected rule"), |
| 6550 | } |
| 6551 | } |
| 6552 | |
| 6553 | #[test] |
| 6554 | fn test_conditional_add_if_item() { |
| 6555 | let makefile: Makefile = "ifdef DEBUG\nendif\n".parse().unwrap(); |
| 6556 | let mut cond = makefile.conditionals().next().unwrap(); |
| 6557 | |
| 6558 | // Parse a variable from a temporary makefile |
| 6559 | let temp: Makefile = "CFLAGS = -g\n".parse().unwrap(); |
| 6560 | let var = temp.variable_definitions().next().unwrap(); |
| 6561 | cond.add_if_item(MakefileItem::Variable(var)); |
| 6562 | |
| 6563 | let code = makefile.to_string(); |
| 6564 | assert!(code.contains("CFLAGS = -g")); |
| 6565 | |
| 6566 | // Verify it's in the if branch |
| 6567 | let cond = makefile.conditionals().next().unwrap(); |
| 6568 | assert_eq!(cond.if_items().count(), 1); |
| 6569 | } |
| 6570 | |
| 6571 | #[test] |
| 6572 | fn test_conditional_add_else_item() { |
| 6573 | let makefile: Makefile = "ifdef DEBUG\nVAR=1\nendif\n".parse().unwrap(); |
| 6574 | let mut cond = makefile.conditionals().next().unwrap(); |
| 6575 | |
| 6576 | // Parse a variable from a temporary makefile |
| 6577 | let temp: Makefile = "CFLAGS = -O2\n".parse().unwrap(); |
| 6578 | let var = temp.variable_definitions().next().unwrap(); |
| 6579 | cond.add_else_item(MakefileItem::Variable(var)); |
| 6580 | |
| 6581 | let code = makefile.to_string(); |
| 6582 | assert!(code.contains("else")); |
| 6583 | assert!(code.contains("CFLAGS = -O2")); |
| 6584 | |
| 6585 | // Verify it's in the else branch |
| 6586 | let cond = makefile.conditionals().next().unwrap(); |
| 6587 | assert_eq!(cond.else_items().count(), 1); |
| 6588 | } |
| 6589 | |
| 6590 | #[test] |
| 6591 | fn test_add_conditional_with_items() { |
| 6592 | let mut makefile = Makefile::new(); |
| 6593 | |
| 6594 | // Parse items from temporary makefiles |
| 6595 | let temp1: Makefile = "CFLAGS = -g\n".parse().unwrap(); |
| 6596 | let var1 = temp1.variable_definitions().next().unwrap(); |
| 6597 | |
| 6598 | let temp2: Makefile = "CFLAGS = -O2\n".parse().unwrap(); |
| 6599 | let var2 = temp2.variable_definitions().next().unwrap(); |
| 6600 | |
| 6601 | let temp3: Makefile = "debug:\n\techo debug\n".parse().unwrap(); |
| 6602 | let rule1 = temp3.rules().next().unwrap(); |
| 6603 | |
| 6604 | let result = makefile.add_conditional_with_items( |
| 6605 | "ifdef", |
| 6606 | "DEBUG", |
| 6607 | vec![MakefileItem::Variable(var1), MakefileItem::Rule(rule1)], |
| 6608 | Some(vec![MakefileItem::Variable(var2)]), |
| 6609 | ); |
| 6610 | |
| 6611 | assert!(result.is_ok()); |
| 6612 | |
| 6613 | let code = makefile.to_string(); |
| 6614 | assert!(code.contains("ifdef DEBUG")); |
| 6615 | assert!(code.contains("CFLAGS = -g")); |
| 6616 | assert!(code.contains("debug:")); |
| 6617 | assert!(code.contains("else")); |
| 6618 | assert!(code.contains("CFLAGS = -O2")); |
| 6619 | } |
| 6620 | |
| 6621 | #[test] |
| 6622 | fn test_conditional_items_with_nested_conditional() { |
| 6623 | let makefile: Makefile = r#"ifdef DEBUG |
| 6624 | VAR = debug |
| 6625 | ifdef VERBOSE |
| 6626 | VAR2 = verbose |
| 6627 | endif |
| 6628 | endif |
| 6629 | "# |
| 6630 | .parse() |
| 6631 | .unwrap(); |
| 6632 | |
| 6633 | let cond = makefile.conditionals().next().unwrap(); |
| 6634 | let items: Vec<_> = cond.if_items().collect(); |
| 6635 | assert_eq!(items.len(), 2); // One variable, one nested conditional |
| 6636 | |
| 6637 | match &items[0] { |
| 6638 | MakefileItem::Variable(v) => { |
| 6639 | assert_eq!(v.name(), Some("VAR".to_string())); |
| 6640 | } |
| 6641 | _ => panic!("Expected variable"), |
| 6642 | } |
| 6643 | |
| 6644 | match &items[1] { |
| 6645 | MakefileItem::Conditional(c) => { |
| 6646 | assert_eq!(c.conditional_type(), Some("ifdef".to_string())); |
| 6647 | } |
| 6648 | _ => panic!("Expected conditional"), |
| 6649 | } |
| 6650 | } |
| 6651 | |
| 6652 | #[test] |
| 6653 | fn test_conditional_items_with_include() { |
| 6654 | let makefile: Makefile = r#"ifdef DEBUG |
| 6655 | include debug.mk |
| 6656 | VAR = debug |
| 6657 | endif |
| 6658 | "# |
| 6659 | .parse() |
| 6660 | .unwrap(); |
| 6661 | |
| 6662 | let cond = makefile.conditionals().next().unwrap(); |
| 6663 | let items: Vec<_> = cond.if_items().collect(); |
| 6664 | assert_eq!(items.len(), 2); // One include, one variable |
| 6665 | |
| 6666 | match &items[0] { |
| 6667 | MakefileItem::Include(i) => { |
| 6668 | assert_eq!(i.path(), Some("debug.mk".to_string())); |
| 6669 | } |
| 6670 | _ => panic!("Expected include"), |
| 6671 | } |
| 6672 | |
| 6673 | match &items[1] { |
| 6674 | MakefileItem::Variable(v) => { |
| 6675 | assert_eq!(v.name(), Some("VAR".to_string())); |
| 6676 | } |
| 6677 | _ => panic!("Expected variable"), |
| 6678 | } |
| 6679 | } |
| 6680 | |
| 6681 | #[test] |
| 6682 | fn test_makefile_items_iterator() { |
| 6683 | let makefile: Makefile = r#"VAR = value |
| 6684 | ifdef DEBUG |
| 6685 | CFLAGS = -g |
| 6686 | endif |
| 6687 | rule: |
| 6688 | command |
| 6689 | include common.mk |
| 6690 | "# |
| 6691 | .parse() |
| 6692 | .unwrap(); |
| 6693 | |
| 6694 | // First verify we can find each type individually |
| 6695 | // variable_definitions() is recursive, so it finds VAR and CFLAGS (inside conditional) |
| 6696 | assert_eq!(makefile.variable_definitions().count(), 2); |
| 6697 | assert_eq!(makefile.conditionals().count(), 1); |
| 6698 | assert_eq!(makefile.rules().count(), 1); |
| 6699 | |
| 6700 | let items: Vec<_> = makefile.items().collect(); |
| 6701 | // Note: include directives might not be at top level, need to check |
| 6702 | assert!( |
| 6703 | items.len() >= 3, |
| 6704 | "Expected at least 3 items, got {}", |
| 6705 | items.len() |
| 6706 | ); |
| 6707 | |
| 6708 | match &items[0] { |
| 6709 | MakefileItem::Variable(v) => { |
| 6710 | assert_eq!(v.name(), Some("VAR".to_string())); |
| 6711 | } |
| 6712 | _ => panic!("Expected variable at position 0"), |
| 6713 | } |
| 6714 | |
| 6715 | match &items[1] { |
| 6716 | MakefileItem::Conditional(c) => { |
| 6717 | assert_eq!(c.conditional_type(), Some("ifdef".to_string())); |
| 6718 | } |
| 6719 | _ => panic!("Expected conditional at position 1"), |
| 6720 | } |
| 6721 | |
| 6722 | match &items[2] { |
| 6723 | MakefileItem::Rule(r) => { |
| 6724 | let targets: Vec<_> = r.targets().collect(); |
| 6725 | assert_eq!(targets, vec!["rule"]); |
| 6726 | } |
| 6727 | _ => panic!("Expected rule at position 2"), |
| 6728 | } |
| 6729 | } |
| 6730 | |
| 6731 | #[test] |
| 6732 | fn test_conditional_unwrap() { |
| 6733 | let makefile: Makefile = r#"ifdef DEBUG |
| 6734 | VAR = debug |
| 6735 | rule: |
| 6736 | command |
| 6737 | endif |
| 6738 | "# |
| 6739 | .parse() |
| 6740 | .unwrap(); |
| 6741 | |
| 6742 | let mut cond = makefile.conditionals().next().unwrap(); |
| 6743 | cond.unwrap().unwrap(); |
| 6744 | |
| 6745 | let code = makefile.to_string(); |
| 6746 | let expected = "VAR = debug\nrule:\n\tcommand\n"; |
| 6747 | assert_eq!(code, expected); |
| 6748 | |
| 6749 | // Should have no conditionals now |
| 6750 | assert_eq!(makefile.conditionals().count(), 0); |
| 6751 | |
| 6752 | // Should still have the variable and rule |
| 6753 | assert_eq!(makefile.variable_definitions().count(), 1); |
| 6754 | assert_eq!(makefile.rules().count(), 1); |
| 6755 | } |
| 6756 | |
| 6757 | #[test] |
| 6758 | fn test_conditional_unwrap_with_else_fails() { |
| 6759 | let makefile: Makefile = r#"ifdef DEBUG |
| 6760 | VAR = debug |
| 6761 | else |
| 6762 | VAR = release |
| 6763 | endif |
| 6764 | "# |
| 6765 | .parse() |
| 6766 | .unwrap(); |
| 6767 | |
| 6768 | let mut cond = makefile.conditionals().next().unwrap(); |
| 6769 | let result = cond.unwrap(); |
| 6770 | |
| 6771 | assert!(result.is_err()); |
| 6772 | assert!(result |
| 6773 | .unwrap_err() |
| 6774 | .to_string() |
| 6775 | .contains("Cannot unwrap conditional with else clause")); |
| 6776 | } |
| 6777 | |
| 6778 | #[test] |
| 6779 | fn test_conditional_unwrap_nested() { |
| 6780 | let makefile: Makefile = r#"ifdef OUTER |
| 6781 | VAR = outer |
| 6782 | ifdef INNER |
| 6783 | VAR2 = inner |
| 6784 | endif |
| 6785 | endif |
| 6786 | "# |
| 6787 | .parse() |
| 6788 | .unwrap(); |
| 6789 | |
| 6790 | // Unwrap the outer conditional |
| 6791 | let mut outer_cond = makefile.conditionals().next().unwrap(); |
| 6792 | outer_cond.unwrap().unwrap(); |
| 6793 | |
| 6794 | let code = makefile.to_string(); |
| 6795 | let expected = "VAR = outer\nifdef INNER\nVAR2 = inner\nendif\n"; |
| 6796 | assert_eq!(code, expected); |
| 6797 | } |
| 6798 | |
| 6799 | #[test] |
| 6800 | fn test_conditional_unwrap_empty() { |
| 6801 | let makefile: Makefile = r#"ifdef DEBUG |
| 6802 | endif |
| 6803 | "# |
| 6804 | .parse() |
| 6805 | .unwrap(); |
| 6806 | |
| 6807 | let mut cond = makefile.conditionals().next().unwrap(); |
| 6808 | cond.unwrap().unwrap(); |
| 6809 | |
| 6810 | let code = makefile.to_string(); |
| 6811 | assert_eq!(code, ""); |
| 6812 | } |
| 6813 | |
| 6814 | #[test] |
| 6815 | fn test_rule_parent() { |
| 6816 | let makefile: Makefile = r#"all: |
| 6817 | echo "test" |
| 6818 | "# |
| 6819 | .parse() |
| 6820 | .unwrap(); |
| 6821 | |
| 6822 | let rule = makefile.rules().next().unwrap(); |
| 6823 | let parent = rule.parent(); |
| 6824 | // Parent is ROOT node which doesn't cast to MakefileItem |
| 6825 | assert!(parent.is_none()); |
| 6826 | } |
| 6827 | |
| 6828 | #[test] |
| 6829 | fn test_item_parent_in_conditional() { |
| 6830 | let makefile: Makefile = r#"ifdef DEBUG |
| 6831 | VAR = debug |
| 6832 | rule: |
| 6833 | command |
| 6834 | endif |
| 6835 | "# |
| 6836 | .parse() |
| 6837 | .unwrap(); |
| 6838 | |
| 6839 | let cond = makefile.conditionals().next().unwrap(); |
| 6840 | |
| 6841 | // Get items from the conditional |
| 6842 | let items: Vec<_> = cond.if_items().collect(); |
| 6843 | assert_eq!(items.len(), 2); |
| 6844 | |
| 6845 | // Check variable parent is the conditional |
| 6846 | if let MakefileItem::Variable(var) = &items[0] { |
| 6847 | let parent = var.parent(); |
| 6848 | assert!(parent.is_some()); |
| 6849 | if let Some(MakefileItem::Conditional(_)) = parent { |
| 6850 | // Expected - parent is a conditional |
| 6851 | } else { |
| 6852 | panic!("Expected variable parent to be a Conditional"); |
| 6853 | } |
| 6854 | } else { |
| 6855 | panic!("Expected first item to be a Variable"); |
| 6856 | } |
| 6857 | |
| 6858 | // Check rule parent is the conditional |
| 6859 | if let MakefileItem::Rule(rule) = &items[1] { |
| 6860 | let parent = rule.parent(); |
| 6861 | assert!(parent.is_some()); |
| 6862 | if let Some(MakefileItem::Conditional(_)) = parent { |
| 6863 | // Expected - parent is a conditional |
| 6864 | } else { |
| 6865 | panic!("Expected rule parent to be a Conditional"); |
| 6866 | } |
| 6867 | } else { |
| 6868 | panic!("Expected second item to be a Rule"); |
| 6869 | } |
| 6870 | } |
| 6871 | |
| 6872 | #[test] |
| 6873 | fn test_nested_conditional_parent() { |
| 6874 | let makefile: Makefile = r#"ifdef OUTER |
| 6875 | VAR = outer |
| 6876 | ifdef INNER |
| 6877 | VAR2 = inner |
| 6878 | endif |
| 6879 | endif |
| 6880 | "# |
| 6881 | .parse() |
| 6882 | .unwrap(); |
| 6883 | |
| 6884 | let outer_cond = makefile.conditionals().next().unwrap(); |
| 6885 | |
| 6886 | // Get inner conditional from outer conditional's items |
| 6887 | let items: Vec<_> = outer_cond.if_items().collect(); |
| 6888 | |
| 6889 | // Find the nested conditional |
| 6890 | let inner_cond = items |
| 6891 | .iter() |
| 6892 | .find_map(|item| { |
| 6893 | if let MakefileItem::Conditional(c) = item { |
| 6894 | Some(c) |
| 6895 | } else { |
| 6896 | None |
| 6897 | } |
| 6898 | }) |
| 6899 | .unwrap(); |
| 6900 | |
| 6901 | // Inner conditional's parent should be the outer conditional |
| 6902 | let parent = inner_cond.parent(); |
| 6903 | assert!(parent.is_some()); |
| 6904 | if let Some(MakefileItem::Conditional(_)) = parent { |
| 6905 | // Expected - parent is a conditional |
| 6906 | } else { |
| 6907 | panic!("Expected inner conditional's parent to be a Conditional"); |
| 6908 | } |
| 6909 | } |
| 6910 | |
| 6911 | #[test] |
| 6912 | fn test_line_col() { |
| 6913 | let text = r#"# Comment at line 0 |
| 6914 | VAR1 = value1 |
| 6915 | VAR2 = value2 |
| 6916 | |
| 6917 | rule1: dep1 dep2 |
| 6918 | command1 |
| 6919 | command2 |
| 6920 | |
| 6921 | rule2: |
| 6922 | command3 |
| 6923 | |
| 6924 | ifdef DEBUG |
| 6925 | CFLAGS = -g |
| 6926 | endif |
| 6927 | "#; |
| 6928 | let makefile: Makefile = text.parse().unwrap(); |
| 6929 | |
| 6930 | // Test variable definition line numbers |
| 6931 | // variable_definitions() is recursive, so it finds VAR1, VAR2, and CFLAGS (inside conditional) |
| 6932 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 6933 | assert_eq!(vars.len(), 3); |
| 6934 | |
| 6935 | // VAR1 starts at line 1 |
| 6936 | assert_eq!(vars[0].line(), 1); |
| 6937 | assert_eq!(vars[0].column(), 0); |
| 6938 | assert_eq!(vars[0].line_col(), (1, 0)); |
| 6939 | |
| 6940 | // VAR2 starts at line 2 |
| 6941 | assert_eq!(vars[1].line(), 2); |
| 6942 | assert_eq!(vars[1].column(), 0); |
| 6943 | |
| 6944 | // CFLAGS starts at line 12 (inside ifdef DEBUG) |
| 6945 | assert_eq!(vars[2].line(), 12); |
| 6946 | assert_eq!(vars[2].column(), 0); |
| 6947 | |
| 6948 | // Test rule line numbers |
| 6949 | let rules: Vec<_> = makefile.rules().collect(); |
| 6950 | assert_eq!(rules.len(), 2); |
| 6951 | |
| 6952 | // rule1 starts at line 4 |
| 6953 | assert_eq!(rules[0].line(), 4); |
| 6954 | assert_eq!(rules[0].column(), 0); |
| 6955 | assert_eq!(rules[0].line_col(), (4, 0)); |
| 6956 | |
| 6957 | // rule2 starts at line 8 |
| 6958 | assert_eq!(rules[1].line(), 8); |
| 6959 | assert_eq!(rules[1].column(), 0); |
| 6960 | |
| 6961 | // Test conditional line numbers |
| 6962 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 6963 | assert_eq!(conditionals.len(), 1); |
| 6964 | |
| 6965 | // ifdef DEBUG starts at line 11 |
| 6966 | assert_eq!(conditionals[0].line(), 11); |
| 6967 | assert_eq!(conditionals[0].column(), 0); |
| 6968 | assert_eq!(conditionals[0].line_col(), (11, 0)); |
| 6969 | } |
| 6970 | |
| 6971 | #[test] |
| 6972 | fn test_line_col_multiline() { |
| 6973 | let text = "SOURCES = \\\n\tfile1.c \\\n\tfile2.c\n\ntarget: $(SOURCES)\n\tgcc -o target $(SOURCES)\n"; |
| 6974 | let makefile: Makefile = text.parse().unwrap(); |
| 6975 | |
| 6976 | // Variable definition starts at line 0 |
| 6977 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 6978 | assert_eq!(vars.len(), 1); |
| 6979 | assert_eq!(vars[0].line(), 0); |
| 6980 | assert_eq!(vars[0].column(), 0); |
| 6981 | |
| 6982 | // Rule starts at line 4 |
| 6983 | let rules: Vec<_> = makefile.rules().collect(); |
| 6984 | assert_eq!(rules.len(), 1); |
| 6985 | assert_eq!(rules[0].line(), 4); |
| 6986 | assert_eq!(rules[0].column(), 0); |
| 6987 | } |
| 6988 | |
| 6989 | #[test] |
| 6990 | fn test_line_col_includes() { |
| 6991 | let text = "VAR = value\n\ninclude config.mk\n-include optional.mk\n"; |
| 6992 | let makefile: Makefile = text.parse().unwrap(); |
| 6993 | |
| 6994 | // Variable at line 0 |
| 6995 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 6996 | assert_eq!(vars[0].line(), 0); |
| 6997 | |
| 6998 | // Includes at lines 2 and 3 |
| 6999 | let includes: Vec<_> = makefile.includes().collect(); |
| 7000 | assert_eq!(includes.len(), 2); |
| 7001 | assert_eq!(includes[0].line(), 2); |
| 7002 | assert_eq!(includes[0].column(), 0); |
| 7003 | assert_eq!(includes[1].line(), 3); |
| 7004 | assert_eq!(includes[1].column(), 0); |
| 7005 | } |
| 7006 | |
| 7007 | #[test] |
| 7008 | fn test_conditional_in_rule_vs_toplevel() { |
| 7009 | // Conditional immediately after rule (no blank line) - part of rule |
| 7010 | let text1 = r#"rule: |
| 7011 | command |
| 7012 | ifeq (,$(X)) |
| 7013 | test |
| 7014 | endif |
| 7015 | "#; |
| 7016 | let makefile: Makefile = text1.parse().unwrap(); |
| 7017 | let rules: Vec<_> = makefile.rules().collect(); |
| 7018 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7019 | |
| 7020 | assert_eq!(rules.len(), 1); |
| 7021 | assert_eq!( |
| 7022 | conditionals.len(), |
| 7023 | 0, |
| 7024 | "Conditional should be part of rule, not top-level" |
| 7025 | ); |
| 7026 | |
| 7027 | // Conditional after blank line - top-level |
| 7028 | let text2 = r#"rule: |
| 7029 | command |
| 7030 | |
| 7031 | ifeq (,$(X)) |
| 7032 | test |
| 7033 | endif |
| 7034 | "#; |
| 7035 | let makefile: Makefile = text2.parse().unwrap(); |
| 7036 | let rules: Vec<_> = makefile.rules().collect(); |
| 7037 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7038 | |
| 7039 | assert_eq!(rules.len(), 1); |
| 7040 | assert_eq!( |
| 7041 | conditionals.len(), |
| 7042 | 1, |
| 7043 | "Conditional after blank line should be top-level" |
| 7044 | ); |
| 7045 | assert_eq!(conditionals[0].line(), 3); |
| 7046 | } |
| 7047 | |
| 7048 | #[test] |
| 7049 | fn test_nested_conditionals_line_tracking() { |
| 7050 | let text = r#"ifdef OUTER |
| 7051 | VAR1 = value1 |
| 7052 | ifdef INNER |
| 7053 | VAR2 = value2 |
| 7054 | endif |
| 7055 | VAR3 = value3 |
| 7056 | endif |
| 7057 | "#; |
| 7058 | let makefile: Makefile = text.parse().unwrap(); |
| 7059 | |
| 7060 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7061 | assert_eq!( |
| 7062 | conditionals.len(), |
| 7063 | 1, |
| 7064 | "Only outer conditional should be top-level" |
| 7065 | ); |
| 7066 | assert_eq!(conditionals[0].line(), 0); |
| 7067 | assert_eq!(conditionals[0].column(), 0); |
| 7068 | } |
| 7069 | |
| 7070 | #[test] |
| 7071 | fn test_conditional_else_line_tracking() { |
| 7072 | let text = r#"VAR1 = before |
| 7073 | |
| 7074 | ifdef DEBUG |
| 7075 | DEBUG_FLAGS = -g |
| 7076 | else |
| 7077 | DEBUG_FLAGS = -O2 |
| 7078 | endif |
| 7079 | |
| 7080 | VAR2 = after |
| 7081 | "#; |
| 7082 | let makefile: Makefile = text.parse().unwrap(); |
| 7083 | |
| 7084 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7085 | assert_eq!(conditionals.len(), 1); |
| 7086 | assert_eq!(conditionals[0].line(), 2); |
| 7087 | assert_eq!(conditionals[0].column(), 0); |
| 7088 | } |
| 7089 | |
| 7090 | #[test] |
| 7091 | fn test_broken_conditional_endif_without_if() { |
| 7092 | // endif without matching if - parser should handle gracefully |
| 7093 | let text = "VAR = value\nendif\n"; |
| 7094 | let makefile = Makefile::read_relaxed(&mut text.as_bytes()).unwrap(); |
| 7095 | |
| 7096 | // Should parse without crashing |
| 7097 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 7098 | assert_eq!(vars.len(), 1); |
| 7099 | assert_eq!(vars[0].line(), 0); |
| 7100 | } |
| 7101 | |
| 7102 | #[test] |
| 7103 | fn test_broken_conditional_else_without_if() { |
| 7104 | // else without matching if |
| 7105 | let text = "VAR = value\nelse\nVAR2 = other\n"; |
| 7106 | let makefile = Makefile::read_relaxed(&mut text.as_bytes()).unwrap(); |
| 7107 | |
| 7108 | // Should parse without crashing |
| 7109 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 7110 | assert!(!vars.is_empty(), "Should parse at least the first variable"); |
| 7111 | assert_eq!(vars[0].line(), 0); |
| 7112 | } |
| 7113 | |
| 7114 | #[test] |
| 7115 | fn test_broken_conditional_missing_endif() { |
| 7116 | // ifdef without matching endif |
| 7117 | let text = r#"ifdef DEBUG |
| 7118 | DEBUG_FLAGS = -g |
| 7119 | VAR = value |
| 7120 | "#; |
| 7121 | let makefile = Makefile::read_relaxed(&mut text.as_bytes()).unwrap(); |
| 7122 | |
| 7123 | // Should parse without crashing |
| 7124 | assert!(makefile.code().contains("ifdef DEBUG")); |
| 7125 | } |
| 7126 | |
| 7127 | #[test] |
| 7128 | fn test_multiple_conditionals_line_tracking() { |
| 7129 | let text = r#"ifdef A |
| 7130 | VAR_A = a |
| 7131 | endif |
| 7132 | |
| 7133 | ifdef B |
| 7134 | VAR_B = b |
| 7135 | endif |
| 7136 | |
| 7137 | ifdef C |
| 7138 | VAR_C = c |
| 7139 | endif |
| 7140 | "#; |
| 7141 | let makefile: Makefile = text.parse().unwrap(); |
| 7142 | |
| 7143 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7144 | assert_eq!(conditionals.len(), 3); |
| 7145 | assert_eq!(conditionals[0].line(), 0); |
| 7146 | assert_eq!(conditionals[1].line(), 4); |
| 7147 | assert_eq!(conditionals[2].line(), 8); |
| 7148 | } |
| 7149 | |
| 7150 | #[test] |
| 7151 | fn test_conditional_with_multiple_else_ifeq() { |
| 7152 | let text = r#"ifeq ($(OS),Windows) |
| 7153 | EXT = .exe |
| 7154 | else ifeq ($(OS),Linux) |
| 7155 | EXT = .bin |
| 7156 | else |
| 7157 | EXT = .out |
| 7158 | endif |
| 7159 | "#; |
| 7160 | let makefile = Makefile::read_relaxed(&mut text.as_bytes()).unwrap(); |
| 7161 | |
| 7162 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7163 | assert_eq!(conditionals.len(), 1); |
| 7164 | assert_eq!(conditionals[0].line(), 0); |
| 7165 | assert_eq!(conditionals[0].column(), 0); |
| 7166 | } |
| 7167 | |
| 7168 | #[test] |
| 7169 | fn test_conditional_types_line_tracking() { |
| 7170 | let text = r#"ifdef VAR1 |
| 7171 | A = 1 |
| 7172 | endif |
| 7173 | |
| 7174 | ifndef VAR2 |
| 7175 | B = 2 |
| 7176 | endif |
| 7177 | |
| 7178 | ifeq ($(X),y) |
| 7179 | C = 3 |
| 7180 | endif |
| 7181 | |
| 7182 | ifneq ($(Y),n) |
| 7183 | D = 4 |
| 7184 | endif |
| 7185 | "#; |
| 7186 | let makefile: Makefile = text.parse().unwrap(); |
| 7187 | |
| 7188 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7189 | assert_eq!(conditionals.len(), 4); |
| 7190 | |
| 7191 | assert_eq!(conditionals[0].line(), 0); // ifdef |
| 7192 | assert_eq!( |
| 7193 | conditionals[0].conditional_type(), |
| 7194 | Some("ifdef".to_string()) |
| 7195 | ); |
| 7196 | |
| 7197 | assert_eq!(conditionals[1].line(), 4); // ifndef |
| 7198 | assert_eq!( |
| 7199 | conditionals[1].conditional_type(), |
| 7200 | Some("ifndef".to_string()) |
| 7201 | ); |
| 7202 | |
| 7203 | assert_eq!(conditionals[2].line(), 8); // ifeq |
| 7204 | assert_eq!(conditionals[2].conditional_type(), Some("ifeq".to_string())); |
| 7205 | |
| 7206 | assert_eq!(conditionals[3].line(), 12); // ifneq |
| 7207 | assert_eq!( |
| 7208 | conditionals[3].conditional_type(), |
| 7209 | Some("ifneq".to_string()) |
| 7210 | ); |
| 7211 | } |
| 7212 | |
| 7213 | #[test] |
| 7214 | fn test_conditional_in_rule_with_recipes() { |
| 7215 | let text = r#"test: |
| 7216 | echo "start" |
| 7217 | ifdef VERBOSE |
| 7218 | echo "verbose mode" |
| 7219 | endif |
| 7220 | echo "end" |
| 7221 | "#; |
| 7222 | let makefile: Makefile = text.parse().unwrap(); |
| 7223 | |
| 7224 | let rules: Vec<_> = makefile.rules().collect(); |
| 7225 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7226 | |
| 7227 | assert_eq!(rules.len(), 1); |
| 7228 | assert_eq!(rules[0].line(), 0); |
| 7229 | // Conditional is part of the rule, not top-level |
| 7230 | assert_eq!(conditionals.len(), 0); |
| 7231 | } |
| 7232 | |
| 7233 | #[test] |
| 7234 | fn test_broken_conditional_double_else() { |
| 7235 | // Two else clauses in one conditional |
| 7236 | let text = r#"ifdef DEBUG |
| 7237 | A = 1 |
| 7238 | else |
| 7239 | B = 2 |
| 7240 | else |
| 7241 | C = 3 |
| 7242 | endif |
| 7243 | "#; |
| 7244 | let makefile = Makefile::read_relaxed(&mut text.as_bytes()).unwrap(); |
| 7245 | |
| 7246 | // Should parse without crashing, though it's malformed |
| 7247 | assert!(makefile.code().contains("ifdef DEBUG")); |
| 7248 | } |
| 7249 | |
| 7250 | #[test] |
| 7251 | fn test_broken_conditional_mismatched_nesting() { |
| 7252 | // Mismatched nesting - more endifs than ifs |
| 7253 | let text = r#"ifdef A |
| 7254 | VAR = value |
| 7255 | endif |
| 7256 | endif |
| 7257 | "#; |
| 7258 | let makefile = Makefile::read_relaxed(&mut text.as_bytes()).unwrap(); |
| 7259 | |
| 7260 | // Should parse without crashing |
| 7261 | // The extra endif will be parsed separately, so we may get more than 1 item |
| 7262 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7263 | assert!( |
| 7264 | !conditionals.is_empty(), |
| 7265 | "Should parse at least the first conditional" |
| 7266 | ); |
| 7267 | } |
| 7268 | |
| 7269 | #[test] |
| 7270 | fn test_conditional_with_comment_line_tracking() { |
| 7271 | let text = r#"# This is a comment |
| 7272 | ifdef DEBUG |
| 7273 | # Another comment |
| 7274 | CFLAGS = -g |
| 7275 | endif |
| 7276 | # Final comment |
| 7277 | "#; |
| 7278 | let makefile: Makefile = text.parse().unwrap(); |
| 7279 | |
| 7280 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7281 | assert_eq!(conditionals.len(), 1); |
| 7282 | assert_eq!(conditionals[0].line(), 1); |
| 7283 | assert_eq!(conditionals[0].column(), 0); |
| 7284 | } |
| 7285 | |
| 7286 | #[test] |
| 7287 | fn test_conditional_after_variable_with_blank_lines() { |
| 7288 | let text = r#"VAR1 = value1 |
| 7289 | |
| 7290 | |
| 7291 | ifdef DEBUG |
| 7292 | VAR2 = value2 |
| 7293 | endif |
| 7294 | "#; |
| 7295 | let makefile: Makefile = text.parse().unwrap(); |
| 7296 | |
| 7297 | let vars: Vec<_> = makefile.variable_definitions().collect(); |
| 7298 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7299 | |
| 7300 | // variable_definitions() is recursive, so it finds VAR1 and VAR2 (inside conditional) |
| 7301 | assert_eq!(vars.len(), 2); |
| 7302 | assert_eq!(vars[0].line(), 0); // VAR1 |
| 7303 | assert_eq!(vars[1].line(), 4); // VAR2 |
| 7304 | |
| 7305 | assert_eq!(conditionals.len(), 1); |
| 7306 | assert_eq!(conditionals[0].line(), 3); |
| 7307 | } |
| 7308 | |
| 7309 | #[test] |
| 7310 | fn test_empty_conditional_line_tracking() { |
| 7311 | let text = r#"ifdef DEBUG |
| 7312 | endif |
| 7313 | |
| 7314 | ifndef RELEASE |
| 7315 | endif |
| 7316 | "#; |
| 7317 | let makefile: Makefile = text.parse().unwrap(); |
| 7318 | |
| 7319 | let conditionals: Vec<_> = makefile.conditionals().collect(); |
| 7320 | assert_eq!(conditionals.len(), 2); |
| 7321 | assert_eq!(conditionals[0].line(), 0); |
| 7322 | assert_eq!(conditionals[1].line(), 3); |
| 7323 | } |
| 7324 | |
| 7325 | #[test] |
| 7326 | fn test_recipe_line_tracking() { |
| 7327 | let text = r#"build: |
| 7328 | echo "Building..." |
| 7329 | gcc -o app main.c |
| 7330 | echo "Done" |
| 7331 | |
| 7332 | test: |
| 7333 | ./run-tests |
| 7334 | "#; |
| 7335 | let makefile: Makefile = text.parse().unwrap(); |
| 7336 | |
| 7337 | // Test first rule's recipes |
| 7338 | let rule1 = makefile.rules().next().expect("Should have first rule"); |
| 7339 | let recipes: Vec<_> = rule1.recipe_nodes().collect(); |
| 7340 | assert_eq!(recipes.len(), 3); |
| 7341 | |
| 7342 | assert_eq!(recipes[0].text(), "echo \"Building...\""); |
| 7343 | assert_eq!(recipes[0].line(), 1); |
| 7344 | assert_eq!(recipes[0].column(), 0); |
| 7345 | |
| 7346 | assert_eq!(recipes[1].text(), "gcc -o app main.c"); |
| 7347 | assert_eq!(recipes[1].line(), 2); |
| 7348 | assert_eq!(recipes[1].column(), 0); |
| 7349 | |
| 7350 | assert_eq!(recipes[2].text(), "echo \"Done\""); |
| 7351 | assert_eq!(recipes[2].line(), 3); |
| 7352 | assert_eq!(recipes[2].column(), 0); |
| 7353 | |
| 7354 | // Test second rule's recipes |
| 7355 | let rule2 = makefile.rules().nth(1).expect("Should have second rule"); |
| 7356 | let recipes2: Vec<_> = rule2.recipe_nodes().collect(); |
| 7357 | assert_eq!(recipes2.len(), 1); |
| 7358 | |
| 7359 | assert_eq!(recipes2[0].text(), "./run-tests"); |
| 7360 | assert_eq!(recipes2[0].line(), 6); |
| 7361 | assert_eq!(recipes2[0].column(), 0); |
| 7362 | } |
| 7363 | |
| 7364 | #[test] |
| 7365 | fn test_recipe_with_variables_line_tracking() { |
| 7366 | let text = r#"install: |
| 7367 | mkdir -p $(DESTDIR) |
| 7368 | cp $(BINARY) $(DESTDIR)/ |
| 7369 | "#; |
| 7370 | let makefile: Makefile = text.parse().unwrap(); |
| 7371 | let rule = makefile.rules().next().expect("Should have rule"); |
| 7372 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7373 | |
| 7374 | assert_eq!(recipes.len(), 2); |
| 7375 | assert_eq!(recipes[0].line(), 1); |
| 7376 | assert_eq!(recipes[1].line(), 2); |
| 7377 | } |
| 7378 | |
| 7379 | #[test] |
| 7380 | fn test_recipe_text_no_leading_tab() { |
| 7381 | // Test that Recipe::text() does not include the leading tab |
| 7382 | let text = "test:\n\techo hello\n\t\techo nested\n\t echo with spaces\n"; |
| 7383 | let makefile: Makefile = text.parse().unwrap(); |
| 7384 | let rule = makefile.rules().next().expect("Should have rule"); |
| 7385 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7386 | |
| 7387 | assert_eq!(recipes.len(), 3); |
| 7388 | |
| 7389 | // Debug: print syntax tree for the first recipe |
| 7390 | eprintln!("Recipe 0 syntax tree:\n{:#?}", recipes[0].syntax()); |
| 7391 | |
| 7392 | // First recipe: single tab |
| 7393 | assert_eq!(recipes[0].text(), "echo hello"); |
| 7394 | |
| 7395 | // Second recipe: double tab (nested) |
| 7396 | eprintln!("Recipe 1 syntax tree:\n{:#?}", recipes[1].syntax()); |
| 7397 | assert_eq!(recipes[1].text(), "\techo nested"); |
| 7398 | |
| 7399 | // Third recipe: tab followed by spaces |
| 7400 | eprintln!("Recipe 2 syntax tree:\n{:#?}", recipes[2].syntax()); |
| 7401 | assert_eq!(recipes[2].text(), " echo with spaces"); |
| 7402 | } |
| 7403 | |
| 7404 | #[test] |
| 7405 | fn test_recipe_parent() { |
| 7406 | let makefile: Makefile = "all: dep\n\techo hello\n".parse().unwrap(); |
| 7407 | let rule = makefile.rules().next().unwrap(); |
| 7408 | let recipe = rule.recipe_nodes().next().unwrap(); |
| 7409 | |
| 7410 | let parent = recipe.parent().expect("Recipe should have parent"); |
| 7411 | assert_eq!(parent.targets().collect::<Vec<_>>(), vec!["all"]); |
| 7412 | assert_eq!(parent.prerequisites().collect::<Vec<_>>(), vec!["dep"]); |
| 7413 | } |
| 7414 | |
| 7415 | #[test] |
| 7416 | fn test_recipe_is_silent_various_prefixes() { |
| 7417 | let makefile: Makefile = r#"test: |
| 7418 | @echo silent |
| 7419 | -echo ignore |
| 7420 | +echo always |
| 7421 | @-echo silent_ignore |
| 7422 | -@echo ignore_silent |
| 7423 | +@echo always_silent |
| 7424 | echo normal |
| 7425 | "# |
| 7426 | .parse() |
| 7427 | .unwrap(); |
| 7428 | |
| 7429 | let rule = makefile.rules().next().unwrap(); |
| 7430 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7431 | |
| 7432 | assert_eq!(recipes.len(), 7); |
| 7433 | assert!(recipes[0].is_silent(), "@echo should be silent"); |
| 7434 | assert!(!recipes[1].is_silent(), "-echo should not be silent"); |
| 7435 | assert!(!recipes[2].is_silent(), "+echo should not be silent"); |
| 7436 | assert!(recipes[3].is_silent(), "@-echo should be silent"); |
| 7437 | assert!(recipes[4].is_silent(), "-@echo should be silent"); |
| 7438 | assert!(recipes[5].is_silent(), "+@echo should be silent"); |
| 7439 | assert!(!recipes[6].is_silent(), "echo should not be silent"); |
| 7440 | } |
| 7441 | |
| 7442 | #[test] |
| 7443 | fn test_recipe_is_ignore_errors_various_prefixes() { |
| 7444 | let makefile: Makefile = r#"test: |
| 7445 | @echo silent |
| 7446 | -echo ignore |
| 7447 | +echo always |
| 7448 | @-echo silent_ignore |
| 7449 | -@echo ignore_silent |
| 7450 | +-echo always_ignore |
| 7451 | echo normal |
| 7452 | "# |
| 7453 | .parse() |
| 7454 | .unwrap(); |
| 7455 | |
| 7456 | let rule = makefile.rules().next().unwrap(); |
| 7457 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7458 | |
| 7459 | assert_eq!(recipes.len(), 7); |
| 7460 | assert!( |
| 7461 | !recipes[0].is_ignore_errors(), |
| 7462 | "@echo should not ignore errors" |
| 7463 | ); |
| 7464 | assert!(recipes[1].is_ignore_errors(), "-echo should ignore errors"); |
| 7465 | assert!( |
| 7466 | !recipes[2].is_ignore_errors(), |
| 7467 | "+echo should not ignore errors" |
| 7468 | ); |
| 7469 | assert!(recipes[3].is_ignore_errors(), "@-echo should ignore errors"); |
| 7470 | assert!(recipes[4].is_ignore_errors(), "-@echo should ignore errors"); |
| 7471 | assert!(recipes[5].is_ignore_errors(), "+-echo should ignore errors"); |
| 7472 | assert!( |
| 7473 | !recipes[6].is_ignore_errors(), |
| 7474 | "echo should not ignore errors" |
| 7475 | ); |
| 7476 | } |
| 7477 | |
| 7478 | #[test] |
| 7479 | fn test_recipe_set_prefix_add() { |
| 7480 | let makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 7481 | let rule = makefile.rules().next().unwrap(); |
| 7482 | let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 7483 | |
| 7484 | recipe.set_prefix("@"); |
| 7485 | assert_eq!(recipe.text(), "@echo hello"); |
| 7486 | assert!(recipe.is_silent()); |
| 7487 | } |
| 7488 | |
| 7489 | #[test] |
| 7490 | fn test_recipe_set_prefix_change() { |
| 7491 | let makefile: Makefile = "all:\n\t@echo hello\n".parse().unwrap(); |
| 7492 | let rule = makefile.rules().next().unwrap(); |
| 7493 | let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 7494 | |
| 7495 | recipe.set_prefix("-"); |
| 7496 | assert_eq!(recipe.text(), "-echo hello"); |
| 7497 | assert!(!recipe.is_silent()); |
| 7498 | assert!(recipe.is_ignore_errors()); |
| 7499 | } |
| 7500 | |
| 7501 | #[test] |
| 7502 | fn test_recipe_set_prefix_remove() { |
| 7503 | let makefile: Makefile = "all:\n\t@-echo hello\n".parse().unwrap(); |
| 7504 | let rule = makefile.rules().next().unwrap(); |
| 7505 | let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 7506 | |
| 7507 | recipe.set_prefix(""); |
| 7508 | assert_eq!(recipe.text(), "echo hello"); |
| 7509 | assert!(!recipe.is_silent()); |
| 7510 | assert!(!recipe.is_ignore_errors()); |
| 7511 | } |
| 7512 | |
| 7513 | #[test] |
| 7514 | fn test_recipe_set_prefix_combinations() { |
| 7515 | let makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 7516 | let rule = makefile.rules().next().unwrap(); |
| 7517 | let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 7518 | |
| 7519 | recipe.set_prefix("@-"); |
| 7520 | assert_eq!(recipe.text(), "@-echo hello"); |
| 7521 | assert!(recipe.is_silent()); |
| 7522 | assert!(recipe.is_ignore_errors()); |
| 7523 | |
| 7524 | recipe.set_prefix("-@"); |
| 7525 | assert_eq!(recipe.text(), "-@echo hello"); |
| 7526 | assert!(recipe.is_silent()); |
| 7527 | assert!(recipe.is_ignore_errors()); |
| 7528 | } |
| 7529 | |
| 7530 | #[test] |
| 7531 | fn test_recipe_replace_text_basic() { |
| 7532 | let makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 7533 | let rule = makefile.rules().next().unwrap(); |
| 7534 | let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 7535 | |
| 7536 | recipe.replace_text("echo world"); |
| 7537 | assert_eq!(recipe.text(), "echo world"); |
| 7538 | |
| 7539 | // Verify it's still accessible from the rule |
| 7540 | let rule = makefile.rules().next().unwrap(); |
| 7541 | assert_eq!(rule.recipes().collect::<Vec<_>>(), vec!["echo world"]); |
| 7542 | } |
| 7543 | |
| 7544 | #[test] |
| 7545 | fn test_recipe_replace_text_with_prefix() { |
| 7546 | let makefile: Makefile = "all:\n\t@echo hello\n".parse().unwrap(); |
| 7547 | let rule = makefile.rules().next().unwrap(); |
| 7548 | let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 7549 | |
| 7550 | recipe.replace_text("@echo goodbye"); |
| 7551 | assert_eq!(recipe.text(), "@echo goodbye"); |
| 7552 | assert!(recipe.is_silent()); |
| 7553 | } |
| 7554 | |
| 7555 | #[test] |
| 7556 | fn test_recipe_insert_before_single() { |
| 7557 | let makefile: Makefile = "all:\n\techo world\n".parse().unwrap(); |
| 7558 | let rule = makefile.rules().next().unwrap(); |
| 7559 | let recipe = rule.recipe_nodes().next().unwrap(); |
| 7560 | |
| 7561 | recipe.insert_before("echo hello"); |
| 7562 | |
| 7563 | let rule = makefile.rules().next().unwrap(); |
| 7564 | let recipes: Vec<_> = rule.recipes().collect(); |
| 7565 | assert_eq!(recipes, vec!["echo hello", "echo world"]); |
| 7566 | } |
| 7567 | |
| 7568 | #[test] |
| 7569 | fn test_recipe_insert_before_multiple() { |
| 7570 | let makefile: Makefile = "all:\n\techo one\n\techo two\n\techo three\n" |
| 7571 | .parse() |
| 7572 | .unwrap(); |
| 7573 | let rule = makefile.rules().next().unwrap(); |
| 7574 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7575 | |
| 7576 | // Insert before the second recipe |
| 7577 | recipes[1].insert_before("echo middle"); |
| 7578 | |
| 7579 | let rule = makefile.rules().next().unwrap(); |
| 7580 | let new_recipes: Vec<_> = rule.recipes().collect(); |
| 7581 | assert_eq!( |
| 7582 | new_recipes, |
| 7583 | vec!["echo one", "echo middle", "echo two", "echo three"] |
| 7584 | ); |
| 7585 | } |
| 7586 | |
| 7587 | #[test] |
| 7588 | fn test_recipe_insert_before_first() { |
| 7589 | let makefile: Makefile = "all:\n\techo one\n\techo two\n".parse().unwrap(); |
| 7590 | let rule = makefile.rules().next().unwrap(); |
| 7591 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7592 | |
| 7593 | recipes[0].insert_before("echo zero"); |
| 7594 | |
| 7595 | let rule = makefile.rules().next().unwrap(); |
| 7596 | let new_recipes: Vec<_> = rule.recipes().collect(); |
| 7597 | assert_eq!(new_recipes, vec!["echo zero", "echo one", "echo two"]); |
| 7598 | } |
| 7599 | |
| 7600 | #[test] |
| 7601 | fn test_recipe_insert_after_single() { |
| 7602 | let makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 7603 | let rule = makefile.rules().next().unwrap(); |
| 7604 | let recipe = rule.recipe_nodes().next().unwrap(); |
| 7605 | |
| 7606 | recipe.insert_after("echo world"); |
| 7607 | |
| 7608 | let rule = makefile.rules().next().unwrap(); |
| 7609 | let recipes: Vec<_> = rule.recipes().collect(); |
| 7610 | assert_eq!(recipes, vec!["echo hello", "echo world"]); |
| 7611 | } |
| 7612 | |
| 7613 | #[test] |
| 7614 | fn test_recipe_insert_after_multiple() { |
| 7615 | let makefile: Makefile = "all:\n\techo one\n\techo two\n\techo three\n" |
| 7616 | .parse() |
| 7617 | .unwrap(); |
| 7618 | let rule = makefile.rules().next().unwrap(); |
| 7619 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7620 | |
| 7621 | // Insert after the second recipe |
| 7622 | recipes[1].insert_after("echo middle"); |
| 7623 | |
| 7624 | let rule = makefile.rules().next().unwrap(); |
| 7625 | let new_recipes: Vec<_> = rule.recipes().collect(); |
| 7626 | assert_eq!( |
| 7627 | new_recipes, |
| 7628 | vec!["echo one", "echo two", "echo middle", "echo three"] |
| 7629 | ); |
| 7630 | } |
| 7631 | |
| 7632 | #[test] |
| 7633 | fn test_recipe_insert_after_last() { |
| 7634 | let makefile: Makefile = "all:\n\techo one\n\techo two\n".parse().unwrap(); |
| 7635 | let rule = makefile.rules().next().unwrap(); |
| 7636 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7637 | |
| 7638 | recipes[1].insert_after("echo three"); |
| 7639 | |
| 7640 | let rule = makefile.rules().next().unwrap(); |
| 7641 | let new_recipes: Vec<_> = rule.recipes().collect(); |
| 7642 | assert_eq!(new_recipes, vec!["echo one", "echo two", "echo three"]); |
| 7643 | } |
| 7644 | |
| 7645 | #[test] |
| 7646 | fn test_recipe_remove_single() { |
| 7647 | let makefile: Makefile = "all:\n\techo hello\n".parse().unwrap(); |
| 7648 | let rule = makefile.rules().next().unwrap(); |
| 7649 | let recipe = rule.recipe_nodes().next().unwrap(); |
| 7650 | |
| 7651 | recipe.remove(); |
| 7652 | |
| 7653 | let rule = makefile.rules().next().unwrap(); |
| 7654 | assert_eq!(rule.recipes().count(), 0); |
| 7655 | } |
| 7656 | |
| 7657 | #[test] |
| 7658 | fn test_recipe_remove_first() { |
| 7659 | let makefile: Makefile = "all:\n\techo one\n\techo two\n\techo three\n" |
| 7660 | .parse() |
| 7661 | .unwrap(); |
| 7662 | let rule = makefile.rules().next().unwrap(); |
| 7663 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7664 | |
| 7665 | recipes[0].remove(); |
| 7666 | |
| 7667 | let rule = makefile.rules().next().unwrap(); |
| 7668 | let new_recipes: Vec<_> = rule.recipes().collect(); |
| 7669 | assert_eq!(new_recipes, vec!["echo two", "echo three"]); |
| 7670 | } |
| 7671 | |
| 7672 | #[test] |
| 7673 | fn test_recipe_remove_middle() { |
| 7674 | let makefile: Makefile = "all:\n\techo one\n\techo two\n\techo three\n" |
| 7675 | .parse() |
| 7676 | .unwrap(); |
| 7677 | let rule = makefile.rules().next().unwrap(); |
| 7678 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7679 | |
| 7680 | recipes[1].remove(); |
| 7681 | |
| 7682 | let rule = makefile.rules().next().unwrap(); |
| 7683 | let new_recipes: Vec<_> = rule.recipes().collect(); |
| 7684 | assert_eq!(new_recipes, vec!["echo one", "echo three"]); |
| 7685 | } |
| 7686 | |
| 7687 | #[test] |
| 7688 | fn test_recipe_remove_last() { |
| 7689 | let makefile: Makefile = "all:\n\techo one\n\techo two\n\techo three\n" |
| 7690 | .parse() |
| 7691 | .unwrap(); |
| 7692 | let rule = makefile.rules().next().unwrap(); |
| 7693 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7694 | |
| 7695 | recipes[2].remove(); |
| 7696 | |
| 7697 | let rule = makefile.rules().next().unwrap(); |
| 7698 | let new_recipes: Vec<_> = rule.recipes().collect(); |
| 7699 | assert_eq!(new_recipes, vec!["echo one", "echo two"]); |
| 7700 | } |
| 7701 | |
| 7702 | #[test] |
| 7703 | fn test_recipe_multiple_operations() { |
| 7704 | let makefile: Makefile = "all:\n\techo one\n\techo two\n".parse().unwrap(); |
| 7705 | let rule = makefile.rules().next().unwrap(); |
| 7706 | let mut recipe = rule.recipe_nodes().next().unwrap(); |
| 7707 | |
| 7708 | // Replace text |
| 7709 | recipe.replace_text("echo modified"); |
| 7710 | assert_eq!(recipe.text(), "echo modified"); |
| 7711 | |
| 7712 | // Add prefix |
| 7713 | recipe.set_prefix("@"); |
| 7714 | assert_eq!(recipe.text(), "@echo modified"); |
| 7715 | |
| 7716 | // Insert after |
| 7717 | recipe.insert_after("echo three"); |
| 7718 | |
| 7719 | // Verify all changes |
| 7720 | let rule = makefile.rules().next().unwrap(); |
| 7721 | let recipes: Vec<_> = rule.recipes().collect(); |
| 7722 | assert_eq!(recipes, vec!["@echo modified", "echo three", "echo two"]); |
| 7723 | } |
| 7724 | |
| 7725 | #[test] |
| 7726 | fn test_from_str_relaxed_valid() { |
| 7727 | let input = "all: foo\n\tfoo bar\n"; |
| 7728 | let (makefile, errors) = Makefile::from_str_relaxed(input); |
| 7729 | assert!(errors.is_empty()); |
| 7730 | assert_eq!(makefile.rules().count(), 1); |
| 7731 | assert_eq!(makefile.to_string(), input); |
| 7732 | } |
| 7733 | |
| 7734 | #[test] |
| 7735 | fn test_from_str_relaxed_with_errors() { |
| 7736 | // "rule target\n\tcommand" produces a parse error (missing colon) |
| 7737 | let input = "rule target\n\tcommand\n"; |
| 7738 | let (makefile, errors) = Makefile::from_str_relaxed(input); |
| 7739 | assert!(!errors.is_empty()); |
| 7740 | // Round-trip preserves all text |
| 7741 | assert_eq!(makefile.to_string(), input); |
| 7742 | } |
| 7743 | |
| 7744 | #[test] |
| 7745 | fn test_positioned_errors_have_valid_ranges() { |
| 7746 | let input = "rule target\n\tcommand\n"; |
| 7747 | let parsed = Makefile::parse(input); |
| 7748 | assert!(!parsed.ok()); |
| 7749 | |
| 7750 | let positioned = parsed.positioned_errors(); |
| 7751 | assert!(!positioned.is_empty()); |
| 7752 | |
| 7753 | for err in positioned { |
| 7754 | // Range should be within the input |
| 7755 | let start: u32 = err.range.start().into(); |
| 7756 | let end: u32 = err.range.end().into(); |
| 7757 | assert!(start <= end); |
| 7758 | assert!((end as usize) <= input.len()); |
| 7759 | } |
| 7760 | } |
| 7761 | |
| 7762 | #[test] |
| 7763 | fn test_positioned_errors_point_to_error_location() { |
| 7764 | let input = "rule target\n\tcommand\n"; |
| 7765 | let parsed = Makefile::parse(input); |
| 7766 | assert!(!parsed.ok()); |
| 7767 | |
| 7768 | let positioned = parsed.positioned_errors(); |
| 7769 | assert!(!positioned.is_empty()); |
| 7770 | |
| 7771 | let err = &positioned[0]; |
| 7772 | let start: usize = err.range.start().into(); |
| 7773 | let end: usize = err.range.end().into(); |
| 7774 | // The error should point somewhere in the input |
| 7775 | let error_text = &input[start..end]; |
| 7776 | assert!(!error_text.is_empty()); |
| 7777 | |
| 7778 | // Tree should still be accessible |
| 7779 | let tree = parsed.tree(); |
| 7780 | assert_eq!(tree.to_string(), input); |
| 7781 | } |
| 7782 | |
| 7783 | #[test] |
| 7784 | fn test_tree_with_errors_preserves_text() { |
| 7785 | let input = "rule target\n\tcommand\nVAR = value\n"; |
| 7786 | let parsed = Makefile::parse(input); |
| 7787 | assert!(!parsed.ok()); |
| 7788 | |
| 7789 | let tree = parsed.tree(); |
| 7790 | assert_eq!(tree.to_string(), input); |
| 7791 | |
| 7792 | // Valid parts should still be accessible |
| 7793 | assert_eq!(tree.variable_definitions().count(), 1); |
| 7794 | } |
| 7795 | |
| 7796 | #[test] |
| 7797 | fn test_recipe_variable_references() { |
| 7798 | let makefile: Makefile = "all:\n\techo $(FOO) ${BAR}\n".parse().unwrap(); |
| 7799 | let rule = makefile.rules().next().unwrap(); |
| 7800 | let recipe = rule.recipe_nodes().next().unwrap(); |
| 7801 | let refs = recipe.variable_references(); |
| 7802 | let names: Vec<_> = refs.iter().map(|r| r.name()).collect(); |
| 7803 | assert_eq!(names, vec!["FOO", "BAR"]); |
| 7804 | |
| 7805 | // Ranges point at the variable names in the original source. |
| 7806 | let src = makefile.to_string(); |
| 7807 | for r in &refs { |
| 7808 | let range = r.text_range(); |
| 7809 | assert_eq!(&src[range], r.name()); |
| 7810 | } |
| 7811 | } |
| 7812 | |
| 7813 | #[test] |
| 7814 | fn test_recipe_variable_references_skips_functions_and_automatic() { |
| 7815 | let makefile: Makefile = "all:\n\t$(shell ls) $@ $1 $(REAL)\n".parse().unwrap(); |
| 7816 | let rule = makefile.rules().next().unwrap(); |
| 7817 | let recipe = rule.recipe_nodes().next().unwrap(); |
| 7818 | let names: Vec<_> = recipe |
| 7819 | .variable_references() |
| 7820 | .iter() |
| 7821 | .map(|r| r.name().to_string()) |
| 7822 | .collect(); |
| 7823 | assert_eq!(names, vec!["REAL"]); |
| 7824 | } |
| 7825 | |
| 7826 | #[test] |
| 7827 | fn test_recipe_variable_references_across_continuation() { |
| 7828 | let makefile: Makefile = "all:\n\techo $(FOO) \\\n\t $(BAR)\n".parse().unwrap(); |
| 7829 | let rule = makefile.rules().next().unwrap(); |
| 7830 | let recipe = rule.recipe_nodes().next().unwrap(); |
| 7831 | let refs = recipe.variable_references(); |
| 7832 | let names: Vec<_> = refs.iter().map(|r| r.name()).collect(); |
| 7833 | assert_eq!(names, vec!["FOO", "BAR"]); |
| 7834 | |
| 7835 | let src = makefile.to_string(); |
| 7836 | for r in &refs { |
| 7837 | assert_eq!(&src[r.text_range()], r.name()); |
| 7838 | } |
| 7839 | } |
| 7840 | } |
| 7841 | |
| 7842 | #[cfg(test)] |
| 7843 | mod test_continuation { |
| 7844 | use super::*; |
| 7845 | |
| 7846 | #[test] |
| 7847 | fn test_recipe_continuation_lines() { |
| 7848 | let makefile_content = r#"override_dh_autoreconf: |
| 7849 | set -x; [ -f binoculars-ng/src/Hkl/H5.hs.orig ] || \ |
| 7850 | dpkg --compare-versions '$(HDF5_VERSION)' '<<' 1.12.0 || \ |
| 7851 | sed -i.orig 's/H5L_info_t/H5L_info1_t/g;s/h5l_iterate/h5l_iterate1/g' binoculars-ng/src/Hkl/H5.hs |
| 7852 | dh_autoreconf |
| 7853 | "#; |
| 7854 | |
| 7855 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7856 | let rule = makefile.rules().next().unwrap(); |
| 7857 | |
| 7858 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7859 | |
| 7860 | // Should have 2 recipe nodes: one multi-line command and one single-line |
| 7861 | assert_eq!(recipes.len(), 2); |
| 7862 | |
| 7863 | // First recipe should contain all three physical lines with newlines preserved, |
| 7864 | // and the leading tab stripped from each continuation line |
| 7865 | let expected_first = "set -x; [ -f binoculars-ng/src/Hkl/H5.hs.orig ] || \\\n dpkg --compare-versions '$(HDF5_VERSION)' '<<' 1.12.0 || \\\n sed -i.orig 's/H5L_info_t/H5L_info1_t/g;s/h5l_iterate/h5l_iterate1/g' binoculars-ng/src/Hkl/H5.hs"; |
| 7866 | assert_eq!(recipes[0].text(), expected_first); |
| 7867 | |
| 7868 | // Second recipe should be the standalone dh_autoreconf line |
| 7869 | assert_eq!(recipes[1].text(), "dh_autoreconf"); |
| 7870 | } |
| 7871 | |
| 7872 | #[test] |
| 7873 | fn test_simple_continuation() { |
| 7874 | let makefile_content = "test:\n\techo hello && \\\n\t echo world\n"; |
| 7875 | |
| 7876 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7877 | let rule = makefile.rules().next().unwrap(); |
| 7878 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7879 | |
| 7880 | assert_eq!(recipes.len(), 1); |
| 7881 | assert_eq!(recipes[0].text(), "echo hello && \\\n echo world"); |
| 7882 | } |
| 7883 | |
| 7884 | #[test] |
| 7885 | fn test_multiple_continuations() { |
| 7886 | let makefile_content = "test:\n\techo line1 && \\\n\t echo line2 && \\\n\t echo line3 && \\\n\t echo line4\n"; |
| 7887 | |
| 7888 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7889 | let rule = makefile.rules().next().unwrap(); |
| 7890 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7891 | |
| 7892 | assert_eq!(recipes.len(), 1); |
| 7893 | assert_eq!( |
| 7894 | recipes[0].text(), |
| 7895 | "echo line1 && \\\n echo line2 && \\\n echo line3 && \\\n echo line4" |
| 7896 | ); |
| 7897 | } |
| 7898 | |
| 7899 | #[test] |
| 7900 | fn test_continuation_round_trip() { |
| 7901 | let makefile_content = "test:\n\techo hello && \\\n\t echo world\n\techo done\n"; |
| 7902 | |
| 7903 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7904 | let output = makefile.to_string(); |
| 7905 | |
| 7906 | // Should preserve the exact content |
| 7907 | assert_eq!(output, makefile_content); |
| 7908 | } |
| 7909 | |
| 7910 | #[test] |
| 7911 | fn test_continuation_with_silent_prefix() { |
| 7912 | let makefile_content = "test:\n\t@echo hello && \\\n\t echo world\n"; |
| 7913 | |
| 7914 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7915 | let rule = makefile.rules().next().unwrap(); |
| 7916 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7917 | |
| 7918 | assert_eq!(recipes.len(), 1); |
| 7919 | assert_eq!(recipes[0].text(), "@echo hello && \\\n echo world"); |
| 7920 | assert!(recipes[0].is_silent()); |
| 7921 | } |
| 7922 | |
| 7923 | #[test] |
| 7924 | fn test_mixed_continued_and_non_continued() { |
| 7925 | let makefile_content = r#"test: |
| 7926 | echo first |
| 7927 | echo second && \ |
| 7928 | echo third |
| 7929 | echo fourth |
| 7930 | "#; |
| 7931 | |
| 7932 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7933 | let rule = makefile.rules().next().unwrap(); |
| 7934 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7935 | |
| 7936 | assert_eq!(recipes.len(), 3); |
| 7937 | assert_eq!(recipes[0].text(), "echo first"); |
| 7938 | assert_eq!(recipes[1].text(), "echo second && \\\n echo third"); |
| 7939 | assert_eq!(recipes[2].text(), "echo fourth"); |
| 7940 | } |
| 7941 | |
| 7942 | #[test] |
| 7943 | fn test_continuation_replace_command() { |
| 7944 | let makefile_content = "test:\n\techo hello && \\\n\t echo world\n\techo done\n"; |
| 7945 | |
| 7946 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7947 | let mut rule = makefile.rules().next().unwrap(); |
| 7948 | |
| 7949 | // Replace the multi-line command |
| 7950 | rule.replace_command(0, "echo replaced"); |
| 7951 | |
| 7952 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7953 | assert_eq!(recipes.len(), 2); |
| 7954 | assert_eq!(recipes[0].text(), "echo replaced"); |
| 7955 | assert_eq!(recipes[1].text(), "echo done"); |
| 7956 | } |
| 7957 | |
| 7958 | #[test] |
| 7959 | fn test_continuation_count() { |
| 7960 | let makefile_content = "test:\n\techo hello && \\\n\t echo world\n\techo done\n"; |
| 7961 | |
| 7962 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7963 | let rule = makefile.rules().next().unwrap(); |
| 7964 | |
| 7965 | // Even though there are 3 physical lines, there should be 2 logical recipe nodes |
| 7966 | assert_eq!(rule.recipe_count(), 2); |
| 7967 | assert_eq!(rule.recipe_nodes().count(), 2); |
| 7968 | |
| 7969 | // recipes() should return one string per logical recipe node |
| 7970 | let recipes_list: Vec<_> = rule.recipes().collect(); |
| 7971 | assert_eq!( |
| 7972 | recipes_list, |
| 7973 | vec!["echo hello && \\\n echo world", "echo done"] |
| 7974 | ); |
| 7975 | } |
| 7976 | |
| 7977 | #[test] |
| 7978 | fn test_backslash_in_middle_of_line() { |
| 7979 | // Backslash not at end should not trigger continuation |
| 7980 | let makefile_content = "test:\n\techo hello\\nworld\n\techo done\n"; |
| 7981 | |
| 7982 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 7983 | let rule = makefile.rules().next().unwrap(); |
| 7984 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 7985 | |
| 7986 | assert_eq!(recipes.len(), 2); |
| 7987 | assert_eq!(recipes[0].text(), "echo hello\\nworld"); |
| 7988 | assert_eq!(recipes[1].text(), "echo done"); |
| 7989 | } |
| 7990 | |
| 7991 | #[test] |
| 7992 | fn test_shell_for_loop_with_continuation() { |
| 7993 | // Regression test for Debian bug #1128608 / GitHub issue (if any) |
| 7994 | // Ensures shell for loops with backslash continuations are treated as |
| 7995 | // a single recipe node and preserve the 'done' statement |
| 7996 | let makefile_content = r#"override_dh_installman: |
| 7997 | for i in foo bar; do \ |
| 7998 | pod2man --section=1 $$i ; \ |
| 7999 | done |
| 8000 | "#; |
| 8001 | |
| 8002 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 8003 | let rule = makefile.rules().next().unwrap(); |
| 8004 | |
| 8005 | // Should have exactly 1 recipe node containing the entire for loop |
| 8006 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 8007 | assert_eq!(recipes.len(), 1); |
| 8008 | |
| 8009 | // The recipe text should contain the complete for loop including 'done' |
| 8010 | let recipe_text = recipes[0].text(); |
| 8011 | let expected_recipe = "for i in foo bar; do \\\n\tpod2man --section=1 $$i ; \\\ndone"; |
| 8012 | assert_eq!(recipe_text, expected_recipe); |
| 8013 | |
| 8014 | // Round-trip should preserve the complete structure |
| 8015 | let output = makefile.to_string(); |
| 8016 | assert_eq!(output, makefile_content); |
| 8017 | } |
| 8018 | |
| 8019 | #[test] |
| 8020 | fn test_shell_for_loop_remove_command() { |
| 8021 | // Regression test: removing other commands shouldn't affect 'done' |
| 8022 | // This simulates lintian-brush modifying debian/rules files |
| 8023 | let makefile_content = r#"override_dh_installman: |
| 8024 | for i in foo bar; do \ |
| 8025 | pod2man --section=1 $$i ; \ |
| 8026 | done |
| 8027 | echo "Done with man pages" |
| 8028 | "#; |
| 8029 | |
| 8030 | let makefile = Makefile::read_relaxed(makefile_content.as_bytes()).unwrap(); |
| 8031 | let mut rule = makefile.rules().next().unwrap(); |
| 8032 | |
| 8033 | // Should have 2 recipe nodes: the for loop and the echo |
| 8034 | assert_eq!(rule.recipe_count(), 2); |
| 8035 | |
| 8036 | // Remove the second command (the echo) |
| 8037 | rule.remove_command(1); |
| 8038 | |
| 8039 | // Should now have only the for loop |
| 8040 | let recipes: Vec<_> = rule.recipe_nodes().collect(); |
| 8041 | assert_eq!(recipes.len(), 1); |
| 8042 | |
| 8043 | // The for loop should still be complete with 'done' |
| 8044 | let output = makefile.to_string(); |
| 8045 | let expected_output = r#"override_dh_installman: |
| 8046 | for i in foo bar; do \ |
| 8047 | pod2man --section=1 $$i ; \ |
| 8048 | done |
| 8049 | "#; |
| 8050 | assert_eq!(output, expected_output); |
| 8051 | } |
| 8052 | |
| 8053 | #[test] |
| 8054 | fn test_variable_reference_paren() { |
| 8055 | let makefile: Makefile = "CFLAGS = $(BASE_FLAGS) -Wall\n".parse().unwrap(); |
| 8056 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8057 | assert_eq!(refs.len(), 1); |
| 8058 | assert_eq!(refs[0].name(), Some("BASE_FLAGS".to_string())); |
| 8059 | assert_eq!(refs[0].to_string(), "$(BASE_FLAGS)"); |
| 8060 | } |
| 8061 | |
| 8062 | #[test] |
| 8063 | fn test_variable_reference_brace() { |
| 8064 | let makefile: Makefile = "CFLAGS = ${BASE_FLAGS} -Wall\n".parse().unwrap(); |
| 8065 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8066 | assert_eq!(refs.len(), 1); |
| 8067 | assert_eq!(refs[0].name(), Some("BASE_FLAGS".to_string())); |
| 8068 | assert_eq!(refs[0].to_string(), "${BASE_FLAGS}"); |
| 8069 | } |
| 8070 | |
| 8071 | #[test] |
| 8072 | fn test_variable_reference_in_prerequisites() { |
| 8073 | let makefile: Makefile = "all: $(TARGETS)\n".parse().unwrap(); |
| 8074 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8075 | let names: Vec<_> = refs.iter().filter_map(|r| r.name()).collect(); |
| 8076 | assert!(names.contains(&"TARGETS".to_string())); |
| 8077 | } |
| 8078 | |
| 8079 | #[test] |
| 8080 | fn test_variable_reference_multiple() { |
| 8081 | let makefile: Makefile = |
| 8082 | "CFLAGS = $(BASE_FLAGS) -Wall\nLDFLAGS = $(BASE_LDFLAGS) -lm\nall: $(TARGETS)\n" |
| 8083 | .parse() |
| 8084 | .unwrap(); |
| 8085 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8086 | let names: Vec<_> = refs.iter().filter_map(|r| r.name()).collect(); |
| 8087 | assert!(names.contains(&"BASE_FLAGS".to_string())); |
| 8088 | assert!(names.contains(&"BASE_LDFLAGS".to_string())); |
| 8089 | assert!(names.contains(&"TARGETS".to_string())); |
| 8090 | } |
| 8091 | |
| 8092 | #[test] |
| 8093 | fn test_variable_reference_nested() { |
| 8094 | let makefile: Makefile = "FOO = $($(INNER))\n".parse().unwrap(); |
| 8095 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8096 | let names: Vec<_> = refs.iter().filter_map(|r| r.name()).collect(); |
| 8097 | assert!(names.contains(&"INNER".to_string())); |
| 8098 | } |
| 8099 | |
| 8100 | #[test] |
| 8101 | fn test_variable_reference_line_col() { |
| 8102 | let makefile: Makefile = "A = 1\nB = $(FOO)\n".parse().unwrap(); |
| 8103 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8104 | assert_eq!(refs.len(), 1); |
| 8105 | assert_eq!(refs[0].name(), Some("FOO".to_string())); |
| 8106 | assert_eq!(refs[0].line(), 1); |
| 8107 | assert_eq!(refs[0].column(), 4); |
| 8108 | assert_eq!(refs[0].line_col(), (1, 4)); |
| 8109 | } |
| 8110 | |
| 8111 | #[test] |
| 8112 | fn test_variable_reference_no_refs() { |
| 8113 | let makefile: Makefile = "A = hello\nall:\n\techo done\n".parse().unwrap(); |
| 8114 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8115 | assert_eq!(refs.len(), 0); |
| 8116 | } |
| 8117 | |
| 8118 | #[test] |
| 8119 | fn test_variable_reference_mixed_styles() { |
| 8120 | let makefile: Makefile = "A = $(FOO) ${BAR}\n".parse().unwrap(); |
| 8121 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8122 | let names: Vec<_> = refs.iter().filter_map(|r| r.name()).collect(); |
| 8123 | assert_eq!(names.len(), 2); |
| 8124 | assert!(names.contains(&"FOO".to_string())); |
| 8125 | assert!(names.contains(&"BAR".to_string())); |
| 8126 | } |
| 8127 | |
| 8128 | #[test] |
| 8129 | fn test_brace_variable_in_prerequisites() { |
| 8130 | let makefile: Makefile = "all: ${OBJS}\n".parse().unwrap(); |
| 8131 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8132 | assert_eq!(refs.len(), 1); |
| 8133 | assert_eq!(refs[0].name(), Some("OBJS".to_string())); |
| 8134 | } |
| 8135 | |
| 8136 | #[test] |
| 8137 | fn test_parse_brace_variable_roundtrip() { |
| 8138 | let input = "CFLAGS = ${BASE_FLAGS} -Wall\n"; |
| 8139 | let makefile: Makefile = input.parse().unwrap(); |
| 8140 | assert_eq!(makefile.to_string(), input); |
| 8141 | } |
| 8142 | |
| 8143 | #[test] |
| 8144 | fn test_parse_nested_variable_in_value_roundtrip() { |
| 8145 | let input = "FOO = $(BAR) baz $(QUUX)\n"; |
| 8146 | let makefile: Makefile = input.parse().unwrap(); |
| 8147 | assert_eq!(makefile.to_string(), input); |
| 8148 | } |
| 8149 | |
| 8150 | #[test] |
| 8151 | fn test_is_function_call() { |
| 8152 | let makefile: Makefile = "FILES = $(wildcard *.c)\n".parse().unwrap(); |
| 8153 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8154 | assert_eq!(refs.len(), 1); |
| 8155 | assert!(refs[0].is_function_call()); |
| 8156 | } |
| 8157 | |
| 8158 | #[test] |
| 8159 | fn test_is_function_call_simple_variable() { |
| 8160 | let makefile: Makefile = "CFLAGS = $(CC)\n".parse().unwrap(); |
| 8161 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8162 | assert_eq!(refs.len(), 1); |
| 8163 | assert!(!refs[0].is_function_call()); |
| 8164 | } |
| 8165 | |
| 8166 | #[test] |
| 8167 | fn test_is_function_call_with_commas() { |
| 8168 | let makefile: Makefile = "X = $(subst a,b,text)\n".parse().unwrap(); |
| 8169 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8170 | assert_eq!(refs.len(), 1); |
| 8171 | assert!(refs[0].is_function_call()); |
| 8172 | } |
| 8173 | |
| 8174 | #[test] |
| 8175 | fn test_is_function_call_braces() { |
| 8176 | let makefile: Makefile = "FILES = ${wildcard *.c}\n".parse().unwrap(); |
| 8177 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8178 | assert_eq!(refs.len(), 1); |
| 8179 | assert!(refs[0].is_function_call()); |
| 8180 | } |
| 8181 | |
| 8182 | #[test] |
| 8183 | fn test_argument_count_simple_variable() { |
| 8184 | let makefile: Makefile = "CFLAGS = $(CC)\n".parse().unwrap(); |
| 8185 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8186 | assert_eq!(refs[0].argument_count(), 0); |
| 8187 | } |
| 8188 | |
| 8189 | #[test] |
| 8190 | fn test_argument_count_one_arg() { |
| 8191 | let makefile: Makefile = "FILES = $(wildcard *.c)\n".parse().unwrap(); |
| 8192 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8193 | assert_eq!(refs[0].argument_count(), 1); |
| 8194 | } |
| 8195 | |
| 8196 | #[test] |
| 8197 | fn test_argument_count_three_args() { |
| 8198 | let makefile: Makefile = "X = $(subst a,b,text)\n".parse().unwrap(); |
| 8199 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8200 | assert_eq!(refs[0].argument_count(), 3); |
| 8201 | } |
| 8202 | |
| 8203 | #[test] |
| 8204 | fn test_argument_index_at_offset_subst() { |
| 8205 | let makefile: Makefile = "X = $(subst a,b,text)\n".parse().unwrap(); |
| 8206 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8207 | // "X = $(subst a,b,text)" |
| 8208 | // 0123456789012345678901 |
| 8209 | // ^first arg (offset 12) |
| 8210 | // ^second arg (offset 14) |
| 8211 | // ^third arg (offset 16) |
| 8212 | assert_eq!(refs[0].argument_index_at_offset(12), Some(0)); |
| 8213 | assert_eq!(refs[0].argument_index_at_offset(14), Some(1)); |
| 8214 | assert_eq!(refs[0].argument_index_at_offset(16), Some(2)); |
| 8215 | } |
| 8216 | |
| 8217 | #[test] |
| 8218 | fn test_argument_index_at_offset_outside() { |
| 8219 | let makefile: Makefile = "X = $(subst a,b,text)\n".parse().unwrap(); |
| 8220 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8221 | // Before the reference |
| 8222 | assert_eq!(refs[0].argument_index_at_offset(0), None); |
| 8223 | // After the reference |
| 8224 | assert_eq!(refs[0].argument_index_at_offset(22), None); |
| 8225 | } |
| 8226 | |
| 8227 | #[test] |
| 8228 | fn test_argument_index_at_offset_simple_variable() { |
| 8229 | let makefile: Makefile = "CFLAGS = $(CC)\n".parse().unwrap(); |
| 8230 | let refs: Vec<_> = makefile.variable_references().collect(); |
| 8231 | assert_eq!(refs[0].argument_index_at_offset(11), None); |
| 8232 | } |
| 8233 | |
| 8234 | #[test] |
| 8235 | fn test_lex_braces() { |
| 8236 | use crate::lex::lex; |
| 8237 | let tokens = lex("${FOO}"); |
| 8238 | let kinds: Vec<_> = tokens.iter().map(|(k, _)| *k).collect(); |
| 8239 | assert!(kinds.contains(&DOLLAR)); |
| 8240 | assert!(kinds.contains(&LBRACE)); |
| 8241 | assert!(kinds.contains(&RBRACE)); |
| 8242 | } |
| 8243 | |
| 8244 | #[test] |
| 8245 | fn test_parse_quoted_string_inside_function_call() { |
| 8246 | // The lexer emits a balanced quoted string as one QUOTE token, so a |
| 8247 | // quoted argument with embedded parentheses must not break paren |
| 8248 | // balance tracking inside a $(...) expression. Lone or asymmetric |
| 8249 | // quotes (it's, foo'bar) must not swallow the rest of the line. |
| 8250 | let cases = [ |
| 8251 | "X = $(if a,'foo')\n", |
| 8252 | "X = $(if a,'foo (bar)')\n", |
| 8253 | "X = $(if a,'(')\n", |
| 8254 | "X = $(if a,')')\n", |
| 8255 | "X = $(if $(SKIP),-k 'not ($(call f,$(s),$(SKIP)))')\n", |
| 8256 | "X = foo'bar\nY = baz\n", |
| 8257 | "X = it's fine\n", |
| 8258 | "X = $(if a,it's)\n", |
| 8259 | "X = '\nY = bar\n", |
| 8260 | ]; |
| 8261 | for src in cases { |
| 8262 | let parsed: Makefile = src.parse().unwrap_or_else(|e| { |
| 8263 | panic!("failed to parse {src:?}: {e:?}"); |
| 8264 | }); |
| 8265 | assert_eq!(parsed.to_string(), src, "round-trip mismatch for {src:?}"); |
| 8266 | } |
| 8267 | } |
| 8268 | |
| 8269 | #[test] |
| 8270 | fn test_parse_unclosed_conditional_paren_does_not_panic() { |
| 8271 | // Found by cargo-fuzz: nested LPAREN inside ifeq()/ifneq() opened |
| 8272 | // an EXPR node that was only closed by the matching RPAREN. EOF |
| 8273 | // before the close left the green tree unbalanced and rowan |
| 8274 | // panicked in GreenNodeBuilder::finish. |
| 8275 | let cases = ["ifeq((", "ifeq(((((", "ifneq((", "ifeq(($(X)", "X = $(("]; |
| 8276 | for src in cases { |
| 8277 | let parse = crate::parse::Parse::<Makefile>::parse_makefile(src); |
| 8278 | assert_eq!( |
| 8279 | parse.tree().to_string(), |
| 8280 | src, |
| 8281 | "round-trip mismatch for {src:?}" |
| 8282 | ); |
| 8283 | } |
| 8284 | } |
| 8285 | |
| 8286 | #[test] |
| 8287 | fn test_parse_unexpected_tokens_at_top_level_does_not_panic() { |
| 8288 | // Found by cargo-fuzz: the top-level dispatcher's catch-all arm |
| 8289 | // bumped a token after `error()` had already consumed one, which |
| 8290 | // could pop past the end of the token stack. The parser must |
| 8291 | // tolerate arbitrary garbage without panicking, and the lossless |
| 8292 | // round-trip must still hold. |
| 8293 | let cases = ["(", "(\0(", ")", "(())", "\0", ",", ":", "((((((((((("]; |
| 8294 | for src in cases { |
| 8295 | let parse = crate::parse::Parse::<Makefile>::parse_makefile(src); |
| 8296 | assert_eq!( |
| 8297 | parse.tree().to_string(), |
| 8298 | src, |
| 8299 | "round-trip mismatch for {src:?}" |
| 8300 | ); |
| 8301 | } |
| 8302 | } |
| 8303 | } |