| 1 | use crate::SyntaxKind; |
| 2 | use std::iter::Peekable; |
| 3 | use std::str::Chars; |
| 4 | |
| 5 | #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] |
| 6 | enum LineType { |
| 7 | Recipe, |
| 8 | Other, |
| 9 | } |
| 10 | |
| 11 | pub struct Lexer<'a> { |
| 12 | input: Peekable<Chars<'a>>, |
| 13 | line_type: Option<LineType>, |
| 14 | continuation: bool, |
| 15 | /// Parity of the current backslash run: true once an odd number have been |
| 16 | /// emitted, so the next backslash is escaped (`\\`) and a following newline |
| 17 | /// is literal, not a continuation. Mirrors the parser's |
| 18 | /// `pending_backslash_escape`. |
| 19 | pending_backslash_escape: bool, |
| 20 | } |
| 21 | |
| 22 | impl<'a> Lexer<'a> { |
| 23 | pub fn new(input: &'a str) -> Self { |
| 24 | Lexer { |
| 25 | input: input.chars().peekable(), |
| 26 | continuation: false, |
| 27 | line_type: None, |
| 28 | pending_backslash_escape: false, |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | fn is_whitespace(c: char) -> bool { |
| 33 | c == ' ' || c == '\t' |
| 34 | } |
| 35 | |
| 36 | fn is_newline(c: char) -> bool { |
| 37 | c == '\n' || c == '\r' |
| 38 | } |
| 39 | |
| 40 | fn is_valid_identifier_char(c: char) -> bool { |
| 41 | c.is_ascii_alphabetic() |
| 42 | || c.is_ascii_digit() |
| 43 | || c == '_' |
| 44 | || c == '/' |
| 45 | || c == '.' |
| 46 | || c == '-' |
| 47 | || c == '%' |
| 48 | } |
| 49 | |
| 50 | /// Check whether a matching close-quote appears on the current line. |
| 51 | /// Make doesn't treat quotes as syntactic; we only group them so that |
| 52 | /// embedded parens don't confuse $(...) parsing. If the quote is |
| 53 | /// unterminated (or asymmetric, like `it's`), grouping would do more |
| 54 | /// harm than good — so we only group when there's a partner on the |
| 55 | /// same line. A backslash escapes the next character. |
| 56 | fn has_matching_close_quote(&self, quote: char) -> bool { |
| 57 | let mut probe = self.input.clone(); |
| 58 | probe.next(); // Skip the opening quote we already peeked. |
| 59 | while let Some(c) = probe.next() { |
| 60 | if Self::is_newline(c) { |
| 61 | return false; |
| 62 | } |
| 63 | if c == '\\' { |
| 64 | probe.next(); |
| 65 | continue; |
| 66 | } |
| 67 | if c == quote { |
| 68 | return true; |
| 69 | } |
| 70 | } |
| 71 | false |
| 72 | } |
| 73 | |
| 74 | fn read_quoted_string(&mut self) -> String { |
| 75 | let mut result = String::new(); |
| 76 | let quote = self.input.next().unwrap(); // Consume opening quote |
| 77 | result.push(quote); |
| 78 | |
| 79 | while let Some(&c) = self.input.peek() { |
| 80 | if c == quote { |
| 81 | result.push(c); |
| 82 | self.input.next(); |
| 83 | break; |
| 84 | } else if c == '\\' { |
| 85 | result.push(c); |
| 86 | self.input.next(); // Consume backslash |
| 87 | if let Some(next) = self.input.next() { |
| 88 | result.push(next); |
| 89 | } |
| 90 | } else { |
| 91 | result.push(c); |
| 92 | self.input.next(); |
| 93 | } |
| 94 | } |
| 95 | result |
| 96 | } |
| 97 | |
| 98 | fn read_while<F>(&mut self, predicate: F) -> String |
| 99 | where |
| 100 | F: Fn(char) -> bool, |
| 101 | { |
| 102 | let mut result = String::new(); |
| 103 | while let Some(&c) = self.input.peek() { |
| 104 | if predicate(c) { |
| 105 | result.push(c); |
| 106 | self.input.next(); |
| 107 | } else { |
| 108 | break; |
| 109 | } |
| 110 | } |
| 111 | result |
| 112 | } |
| 113 | |
| 114 | fn next_token(&mut self) -> Option<(SyntaxKind, String)> { |
| 115 | // A backslash continues the line only when it is not itself escaped by |
| 116 | // a preceding backslash. `escaped` is the run parity carried over from |
| 117 | // the previous token; clear the field here so any non-backslash token |
| 118 | // resets the run. |
| 119 | let escaped = self.pending_backslash_escape; |
| 120 | self.pending_backslash_escape = false; |
| 121 | if let Some(&c) = self.input.peek() { |
| 122 | match (c, self.line_type) { |
| 123 | ('\t', None) if !self.continuation => { |
| 124 | self.input.next(); |
| 125 | self.line_type = Some(LineType::Recipe); |
| 126 | return Some((SyntaxKind::INDENT, "\t".to_string())); |
| 127 | } |
| 128 | ('\t', None) => { |
| 129 | // Continuation line: tab is indent but not a recipe |
| 130 | self.input.next(); |
| 131 | self.line_type = Some(LineType::Other); |
| 132 | self.continuation = false; |
| 133 | return Some((SyntaxKind::INDENT, "\t".to_string())); |
| 134 | } |
| 135 | (' ', None) if !self.continuation => { |
| 136 | // Check if this is the start of a space-indented recipe (2 or 4 spaces) |
| 137 | let spaces = self.read_while(|ch| ch == ' '); |
| 138 | if spaces.len() >= 2 { |
| 139 | self.line_type = Some(LineType::Recipe); |
| 140 | return Some((SyntaxKind::INDENT, spaces)); |
| 141 | } else { |
| 142 | // If just a single space, treat as normal whitespace |
| 143 | self.line_type = Some(LineType::Other); |
| 144 | return Some((SyntaxKind::WHITESPACE, spaces)); |
| 145 | } |
| 146 | } |
| 147 | (' ', None) => { |
| 148 | // Continuation line: spaces are indent but not a recipe |
| 149 | let spaces = self.read_while(|ch| ch == ' '); |
| 150 | self.line_type = Some(LineType::Other); |
| 151 | self.continuation = false; |
| 152 | return Some((SyntaxKind::INDENT, spaces)); |
| 153 | } |
| 154 | (_, None) => { |
| 155 | self.line_type = Some(LineType::Other); |
| 156 | self.continuation = false; |
| 157 | } |
| 158 | (_, _) => {} |
| 159 | } |
| 160 | |
| 161 | match c { |
| 162 | c if Self::is_newline(c) => { |
| 163 | self.line_type = None; |
| 164 | return Some((SyntaxKind::NEWLINE, self.input.next()?.to_string())); |
| 165 | } |
| 166 | '#' => { |
| 167 | return Some(( |
| 168 | SyntaxKind::COMMENT, |
| 169 | self.read_while(|c| !Self::is_newline(c)), |
| 170 | )); |
| 171 | } |
| 172 | _ => {} |
| 173 | } |
| 174 | |
| 175 | match self.line_type.unwrap() { |
| 176 | LineType::Recipe => { |
| 177 | Some((SyntaxKind::TEXT, self.read_while(|c| !Self::is_newline(c)))) |
| 178 | } |
| 179 | LineType::Other => match c { |
| 180 | c if Self::is_whitespace(c) => { |
| 181 | Some((SyntaxKind::WHITESPACE, self.read_while(Self::is_whitespace))) |
| 182 | } |
| 183 | c if Self::is_valid_identifier_char(c) => Some(( |
| 184 | SyntaxKind::IDENTIFIER, |
| 185 | self.read_while(Self::is_valid_identifier_char), |
| 186 | )), |
| 187 | '"' | '\'' => { |
| 188 | if self.has_matching_close_quote(c) { |
| 189 | Some((SyntaxKind::QUOTE, self.read_quoted_string())) |
| 190 | } else { |
| 191 | // Lone quote — emit as a single-character QUOTE |
| 192 | // token so paren counting in $(...) still works. |
| 193 | self.input.next(); |
| 194 | Some((SyntaxKind::QUOTE, c.to_string())) |
| 195 | } |
| 196 | } |
| 197 | ':' | '=' | '?' | '+' => { |
| 198 | let text = self.input.next().unwrap().to_string() |
| 199 | + self |
| 200 | .read_while(|c| c == ':' || c == '=' || c == '?') |
| 201 | .as_str(); |
| 202 | Some((SyntaxKind::OPERATOR, text)) |
| 203 | } |
| 204 | '(' => { |
| 205 | self.input.next(); |
| 206 | Some((SyntaxKind::LPAREN, "(".to_string())) |
| 207 | } |
| 208 | ')' => { |
| 209 | self.input.next(); |
| 210 | Some((SyntaxKind::RPAREN, ")".to_string())) |
| 211 | } |
| 212 | '{' => { |
| 213 | self.input.next(); |
| 214 | Some((SyntaxKind::LBRACE, "{".to_string())) |
| 215 | } |
| 216 | '}' => { |
| 217 | self.input.next(); |
| 218 | Some((SyntaxKind::RBRACE, "}".to_string())) |
| 219 | } |
| 220 | '$' => { |
| 221 | self.input.next(); |
| 222 | Some((SyntaxKind::DOLLAR, "$".to_string())) |
| 223 | } |
| 224 | ',' => { |
| 225 | self.input.next(); |
| 226 | Some((SyntaxKind::COMMA, ",".to_string())) |
| 227 | } |
| 228 | '\\' => { |
| 229 | self.input.next(); |
| 230 | // A backslash-newline is a continuation only if this |
| 231 | // backslash is not escaped by a preceding one. |
| 232 | if !escaped && self.input.peek().is_some_and(|&c| Self::is_newline(c)) { |
| 233 | self.continuation = true; |
| 234 | } |
| 235 | self.pending_backslash_escape = !escaped; |
| 236 | Some((SyntaxKind::BACKSLASH, "\\".to_string())) |
| 237 | } |
| 238 | _ => { |
| 239 | self.input.next(); |
| 240 | Some((SyntaxKind::ERROR, c.to_string())) |
| 241 | } |
| 242 | }, |
| 243 | } |
| 244 | } else { |
| 245 | None |
| 246 | } |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | impl Iterator for Lexer<'_> { |
| 251 | type Item = (crate::SyntaxKind, String); |
| 252 | |
| 253 | fn next(&mut self) -> Option<Self::Item> { |
| 254 | self.next_token() |
| 255 | } |
| 256 | } |
| 257 | |
| 258 | pub(crate) fn lex(input: &str) -> Vec<(SyntaxKind, String)> { |
| 259 | Lexer::new(input).collect() |
| 260 | } |
| 261 | |
| 262 | #[cfg(test)] |
| 263 | mod tests { |
| 264 | use super::*; |
| 265 | |
| 266 | use crate::SyntaxKind::*; |
| 267 | |
| 268 | #[test] |
| 269 | fn test_empty() { |
| 270 | assert_eq!(lex(""), vec![]); |
| 271 | } |
| 272 | |
| 273 | #[test] |
| 274 | fn test_simple() { |
| 275 | assert_eq!( |
| 276 | lex(r#"VARIABLE = value |
| 277 | |
| 278 | rule: prerequisite |
| 279 | recipe |
| 280 | "#) |
| 281 | .iter() |
| 282 | .map(|(kind, text)| (*kind, text.as_str())) |
| 283 | .collect::<Vec<_>>(), |
| 284 | vec![ |
| 285 | (IDENTIFIER, "VARIABLE"), |
| 286 | (WHITESPACE, " "), |
| 287 | (OPERATOR, "="), |
| 288 | (WHITESPACE, " "), |
| 289 | (IDENTIFIER, "value"), |
| 290 | (NEWLINE, "\n"), |
| 291 | (NEWLINE, "\n"), |
| 292 | (IDENTIFIER, "rule"), |
| 293 | (OPERATOR, ":"), |
| 294 | (WHITESPACE, " "), |
| 295 | (IDENTIFIER, "prerequisite"), |
| 296 | (NEWLINE, "\n"), |
| 297 | (INDENT, "\t"), |
| 298 | (TEXT, "recipe"), |
| 299 | (NEWLINE, "\n"), |
| 300 | ] |
| 301 | ); |
| 302 | } |
| 303 | |
| 304 | #[test] |
| 305 | fn test_bare_export() { |
| 306 | assert_eq!( |
| 307 | lex(r#"export |
| 308 | "#) |
| 309 | .iter() |
| 310 | .map(|(kind, text)| (*kind, text.as_str())) |
| 311 | .collect::<Vec<_>>(), |
| 312 | vec![(IDENTIFIER, "export"), (NEWLINE, "\n"),] |
| 313 | ); |
| 314 | } |
| 315 | |
| 316 | #[test] |
| 317 | fn test_export() { |
| 318 | assert_eq!( |
| 319 | lex(r#"export VARIABLE |
| 320 | "#) |
| 321 | .iter() |
| 322 | .map(|(kind, text)| (*kind, text.as_str())) |
| 323 | .collect::<Vec<_>>(), |
| 324 | vec![ |
| 325 | (IDENTIFIER, "export"), |
| 326 | (WHITESPACE, " "), |
| 327 | (IDENTIFIER, "VARIABLE"), |
| 328 | (NEWLINE, "\n"), |
| 329 | ] |
| 330 | ); |
| 331 | } |
| 332 | |
| 333 | #[test] |
| 334 | fn test_export_assignment() { |
| 335 | assert_eq!( |
| 336 | lex(r#"export VARIABLE := value |
| 337 | "#) |
| 338 | .iter() |
| 339 | .map(|(kind, text)| (*kind, text.as_str())) |
| 340 | .collect::<Vec<_>>(), |
| 341 | vec![ |
| 342 | (IDENTIFIER, "export"), |
| 343 | (WHITESPACE, " "), |
| 344 | (IDENTIFIER, "VARIABLE"), |
| 345 | (WHITESPACE, " "), |
| 346 | (OPERATOR, ":="), |
| 347 | (WHITESPACE, " "), |
| 348 | (IDENTIFIER, "value"), |
| 349 | (NEWLINE, "\n"), |
| 350 | ] |
| 351 | ); |
| 352 | } |
| 353 | |
| 354 | #[test] |
| 355 | fn test_multiple_prerequisites() { |
| 356 | assert_eq!( |
| 357 | lex(r#"rule: prerequisite1 prerequisite2 |
| 358 | recipe |
| 359 | |
| 360 | "#) |
| 361 | .iter() |
| 362 | .map(|(kind, text)| (*kind, text.as_str())) |
| 363 | .collect::<Vec<_>>(), |
| 364 | vec![ |
| 365 | (IDENTIFIER, "rule"), |
| 366 | (OPERATOR, ":"), |
| 367 | (WHITESPACE, " "), |
| 368 | (IDENTIFIER, "prerequisite1"), |
| 369 | (WHITESPACE, " "), |
| 370 | (IDENTIFIER, "prerequisite2"), |
| 371 | (NEWLINE, "\n"), |
| 372 | (INDENT, "\t"), |
| 373 | (TEXT, "recipe"), |
| 374 | (NEWLINE, "\n"), |
| 375 | (NEWLINE, "\n"), |
| 376 | ] |
| 377 | ); |
| 378 | } |
| 379 | |
| 380 | #[test] |
| 381 | fn test_variable_question() { |
| 382 | assert_eq!( |
| 383 | lex("VARIABLE ?= value\n") |
| 384 | .iter() |
| 385 | .map(|(kind, text)| (*kind, text.as_str())) |
| 386 | .collect::<Vec<_>>(), |
| 387 | vec![ |
| 388 | (IDENTIFIER, "VARIABLE"), |
| 389 | (WHITESPACE, " "), |
| 390 | (OPERATOR, "?="), |
| 391 | (WHITESPACE, " "), |
| 392 | (IDENTIFIER, "value"), |
| 393 | (NEWLINE, "\n"), |
| 394 | ] |
| 395 | ); |
| 396 | } |
| 397 | |
| 398 | #[test] |
| 399 | fn test_conditional() { |
| 400 | assert_eq!( |
| 401 | lex(r#"ifneq (a, b) |
| 402 | endif |
| 403 | "#) |
| 404 | .iter() |
| 405 | .map(|(kind, text)| (*kind, text.as_str())) |
| 406 | .collect::<Vec<_>>(), |
| 407 | vec![ |
| 408 | (IDENTIFIER, "ifneq"), |
| 409 | (WHITESPACE, " "), |
| 410 | (LPAREN, "("), |
| 411 | (IDENTIFIER, "a"), |
| 412 | (COMMA, ","), |
| 413 | (WHITESPACE, " "), |
| 414 | (IDENTIFIER, "b"), |
| 415 | (RPAREN, ")"), |
| 416 | (NEWLINE, "\n"), |
| 417 | (IDENTIFIER, "endif"), |
| 418 | (NEWLINE, "\n"), |
| 419 | ] |
| 420 | ); |
| 421 | } |
| 422 | |
| 423 | #[test] |
| 424 | fn test_variable_paren() { |
| 425 | assert_eq!( |
| 426 | lex("VARIABLE = $(value)\n") |
| 427 | .iter() |
| 428 | .map(|(kind, text)| (*kind, text.as_str())) |
| 429 | .collect::<Vec<_>>(), |
| 430 | vec![ |
| 431 | (IDENTIFIER, "VARIABLE"), |
| 432 | (WHITESPACE, " "), |
| 433 | (OPERATOR, "="), |
| 434 | (WHITESPACE, " "), |
| 435 | (DOLLAR, "$"), |
| 436 | (LPAREN, "("), |
| 437 | (IDENTIFIER, "value"), |
| 438 | (RPAREN, ")"), |
| 439 | (NEWLINE, "\n"), |
| 440 | ] |
| 441 | ); |
| 442 | } |
| 443 | |
| 444 | #[test] |
| 445 | fn test_variable_paren2() { |
| 446 | assert_eq!( |
| 447 | lex("VARIABLE = $(value)$(value2)\n") |
| 448 | .iter() |
| 449 | .map(|(kind, text)| (*kind, text.as_str())) |
| 450 | .collect::<Vec<_>>(), |
| 451 | vec![ |
| 452 | (IDENTIFIER, "VARIABLE"), |
| 453 | (WHITESPACE, " "), |
| 454 | (OPERATOR, "="), |
| 455 | (WHITESPACE, " "), |
| 456 | (DOLLAR, "$"), |
| 457 | (LPAREN, "("), |
| 458 | (IDENTIFIER, "value"), |
| 459 | (RPAREN, ")"), |
| 460 | (DOLLAR, "$"), |
| 461 | (LPAREN, "("), |
| 462 | (IDENTIFIER, "value2"), |
| 463 | (RPAREN, ")"), |
| 464 | (NEWLINE, "\n"), |
| 465 | ] |
| 466 | ); |
| 467 | } |
| 468 | |
| 469 | #[test] |
| 470 | fn test_oom() { |
| 471 | let text = r#" |
| 472 | #!/usr/bin/make -f |
| 473 | # |
| 474 | # debhelper-7 [debian/rules] for cups-pdf |
| 475 | # |
| 476 | # COPYRIGHT © 2003-2021 Martin-Éric Racine <[email protected]> |
| 477 | # |
| 478 | # LICENSE |
| 479 | # GPLv2+: GNU GPL version 2 or later <http://gnu.org/licenses/gpl.html> |
| 480 | # |
| 481 | export CC := $(shell dpkg-architecture --query DEB_HOST_GNU_TYPE)-gcc |
| 482 | export CPPFLAGS := $(shell dpkg-buildflags --get CPPFLAGS) |
| 483 | export CFLAGS := $(shell dpkg-buildflags --get CFLAGS) |
| 484 | export LDFLAGS := $(shell dpkg-buildflags --get LDFLAGS) |
| 485 | #export DEB_BUILD_MAINT_OPTIONS = hardening=+all,-bindnow,-pie |
| 486 | # Append flags for Long File Support (LFS) |
| 487 | # LFS_CPPFLAGS does not exist |
| 488 | export DEB_CFLAGS_MAINT_APPEND +=$(shell getconf LFS_CFLAGS) $(HARDENING_CFLAGS) |
| 489 | export DEB_LDFLAGS_MAINT_APPEND +=$(shell getconf LFS_LDFLAGS) $(HARDENING_LDFLAGS) |
| 490 | |
| 491 | override_dh_auto_build-arch: |
| 492 | $(CC) $(CPPFLAGS) $(CFLAGS) $(LDFLAGS) -o src/cups-pdf src/cups-pdf.c -lcups |
| 493 | |
| 494 | override_dh_auto_clean: |
| 495 | rm -f src/cups-pdf src/*.o |
| 496 | |
| 497 | %: |
| 498 | dh $@ |
| 499 | #EOF |
| 500 | "#; |
| 501 | |
| 502 | let _lexed = lex(text); |
| 503 | } |
| 504 | |
| 505 | #[test] |
| 506 | fn test_pattern_rule() { |
| 507 | assert_eq!( |
| 508 | lex("%.o: %.c\n") |
| 509 | .iter() |
| 510 | .map(|(kind, text)| (*kind, text.as_str())) |
| 511 | .collect::<Vec<_>>(), |
| 512 | vec![ |
| 513 | (IDENTIFIER, "%.o"), |
| 514 | (OPERATOR, ":"), |
| 515 | (WHITESPACE, " "), |
| 516 | (IDENTIFIER, "%.c"), |
| 517 | (NEWLINE, "\n"), |
| 518 | ] |
| 519 | ); |
| 520 | } |
| 521 | |
| 522 | #[test] |
| 523 | fn test_include_directive() { |
| 524 | assert_eq!( |
| 525 | lex("-include .env\n") |
| 526 | .iter() |
| 527 | .map(|(kind, text)| (*kind, text.as_str())) |
| 528 | .collect::<Vec<_>>(), |
| 529 | vec![ |
| 530 | (IDENTIFIER, "-include"), |
| 531 | (WHITESPACE, " "), |
| 532 | (IDENTIFIER, ".env"), |
| 533 | (NEWLINE, "\n"), |
| 534 | ] |
| 535 | ); |
| 536 | } |
| 537 | |
| 538 | #[test] |
| 539 | fn test_slash_in_identifier() { |
| 540 | assert_eq!( |
| 541 | lex("usr/bin/foo: src/main.o\n") |
| 542 | .iter() |
| 543 | .map(|(kind, text)| (*kind, text.as_str())) |
| 544 | .collect::<Vec<_>>(), |
| 545 | vec![ |
| 546 | (IDENTIFIER, "usr/bin/foo"), |
| 547 | (OPERATOR, ":"), |
| 548 | (WHITESPACE, " "), |
| 549 | (IDENTIFIER, "src/main.o"), |
| 550 | (NEWLINE, "\n"), |
| 551 | ] |
| 552 | ); |
| 553 | } |
| 554 | |
| 555 | #[test] |
| 556 | fn test_backslash_in_variable_continuation() { |
| 557 | let input = "VAR ?= $(shell cmd | \\\n\t\tsed -rne 's,^V: ([^-]+).*,\\1,p')\n"; |
| 558 | let tokens = lex(input); |
| 559 | // Check that the backslash before '1' is preserved |
| 560 | let text: String = tokens.iter().map(|(_, t)| t.as_str()).collect(); |
| 561 | assert_eq!(input, text, "Token text reconstruction differs from input"); |
| 562 | } |
| 563 | } |