1use crate::attributes::{collect_attrs_for_path, AttrValue, MacroTable};
13use crate::config::ConfigSet;
14use regex::{Regex, RegexBuilder};
15use std::collections::BTreeMap;
16use std::sync::{Arc, OnceLock};
17
18const BUILTIN_PATTERN_DEFS: &[(&str, &str, bool)] = &[
20 (
21 "ada",
22 r"!^(.*[ ])?(is[ ]+new|renames|is[ ]+separate)([ ].*)?$
23!^[ ]*with[ ].*$
24^[ ]*((procedure|function)[ ]+.*)$
25^[ ]*((package|protected|task)[ ]+.*)$",
26 true,
27 ),
28 (
29 "bash",
30 r"^[ ]*((([a-zA-Z_][a-zA-Z0-9_]*[ ]*\([ ]*\))|(function[ ]+[a-zA-Z_][a-zA-Z0-9_]*(([ ]*\([ ]*\))|([ ]+)))).*$)",
31 false,
32 ),
33 (
34 "bibtex",
35 r#"(@[a-zA-Z]{1,}[ ]*\{{0,1}[ ]*[^ "@',\#}{~%]*).*$"#,
36 false,
37 ),
38 (
39 "cpp",
40 r"!^[ ]*[A-Za-z_][A-Za-z_0-9]*:[[:space:]]*($|/[/*])
41^((::[[:space:]]*)?[A-Za-z_].*)$",
42 false,
43 ),
44 (
45 "csharp",
46 r"!(^|[ ]+)(do|while|for|foreach|if|else|new|default|return|switch|case|throw|catch|using|lock|fixed)([ (]+|$)
47^[ ]*(([][[:alnum:]@_.](<[][[:alnum:]@_, <>]+>)?)+([ ]+([][[:alnum:]@_.](<[][[:alnum:]@_, <>]+>)?)+)+[ ]*\([^;]*)$
48^[ ]*(([][[:alnum:]@_.](<[][[:alnum:]@_, <>]+>)?)+([ ]+([][[:alnum:]@_.](<[][[:alnum:]@_, <>]+>)?)+)+[^;=:,()]*)$
49^[ ]*(((static|public|internal|private|protected|new|unsafe|sealed|abstract|partial)[ ]+)*(class|enum|interface|struct|record)[ ]+.*)$
50^[ ]*(namespace[ ]+.*)$",
51 false,
52 ),
53 (
54 "css",
55 r"![:;][[:space:]]*$
56^[:[@.#]?[_a-z0-9].*$",
57 true,
58 ),
59 (
60 "dts",
61 r"!;
62!=
63^[ ]*((/[ ]*\{|&?[a-zA-Z_]).*)",
64 false,
65 ),
66 (
67 "elixir",
68 r"^[ ]*((def(macro|module|impl|protocol|p)?|test)[ ].*)$",
69 false,
70 ),
71 (
72 "fortran",
73 r#"!^([C*]|[ ]*!)
74!^[ ]*MODULE[ ]+PROCEDURE[ ]
75^[ ]*((END[ ]+)?(PROGRAM|MODULE|BLOCK[ ]+DATA|([^!'" ]+[ ]+)*(SUBROUTINE|FUNCTION))[ ]+[A-Z].*)$"#,
76 true,
77 ),
78 (
79 "fountain",
80 r"^((\.[^.]|(int|ext|est|int\.?/ext|i/e)[. ]).*)$",
81 true,
82 ),
83 (
84 "golang",
85 r"^[ ]*(func[ ]*.*(\{[ ]*)?)
86^[ ]*(type[ ].*(struct|interface)[ ]*(\{[ ]*)?)",
87 false,
88 ),
89 ("html", r"^[ ]*(<[Hh][1-6]([ ].*)?>.*)$", false),
90 ("ini", r"^[ ]*\[[^]]+\]", false),
91 (
92 "java",
93 r"!^[ ]*(catch|do|for|if|instanceof|new|return|switch|throw|while)
94^[ ]*(([a-z-]+[ ]+)*(class|enum|interface|record)[ ]+.*)$
95^[ ]*(([A-Za-z_<>&][][?&<>.,A-Za-z_0-9]*[ ]+)+[A-Za-z_][A-Za-z_0-9]*[ ]*\([^;]*)$",
96 false,
97 ),
98 (
99 "kotlin",
100 r"^[ ]*(([a-z]+[ ]+)*(fun|class|interface)[ ]+.*)$",
101 false,
102 ),
103 ("markdown", r"^ {0,3}#{1,6}[ ].*", false),
104 (
105 "matlab",
106 r"^[[:space:]]*((classdef|function)[[:space:]].*)$|^(%%%?|##)[[:space:]].*$",
107 false,
108 ),
109 (
110 "objc",
111 r"!^[ ]*(do|for|if|else|return|switch|while)
112^[ ]*([-+][ ]*\([ ]*[A-Za-z_][A-Za-z_0-9* ]*\)[ ]*[A-Za-z_].*)$
113^[ ]*(([A-Za-z_][A-Za-z_0-9]*[ ]+)+[A-Za-z_][A-Za-z_0-9]*[ ]*\([^;]*)$
114^(@(implementation|interface|protocol)[ ].*)$",
115 false,
116 ),
117 (
118 "pascal",
119 r"^(((class[ ]+)?(procedure|function)|constructor|destructor|interface|implementation|initialization|finalization)[ ]*.*)$
120^(.*=[ ]*(class|record).*)$",
121 false,
122 ),
123 (
124 "perl",
125 r"^package .*
126^sub [[:alnum:]_':]+[ ]*(\([^)]*\)[ ]*)?(:[^;#]*)?(\{[ ]*)?(#.*)?$
127^(BEGIN|END|INIT|CHECK|UNITCHECK|AUTOLOAD|DESTROY)[ ]*(\{[ ]*)?(#.*)?$
128^=head[0-9] .*",
129 false,
130 ),
131 (
132 "php",
133 r"^[ ]*(((public|protected|private|static|abstract|final)[ ]+)*function.*)$
134^[ ]*((((final|abstract)[ ]+)?class|enum|interface|trait).*)$",
135 false,
136 ),
137 ("python", r"^[ ]*((class|(async[ ]+)?def)[ ].*)$", false),
138 (
139 "r",
140 r"^[ ]*([a-zA-z][a-zA-Z0-9_.]*[ ]*(<-|=)[ ]*function.*)$",
141 false,
142 ),
143 ("ruby", r"^[ ]*((class|module|def)[ ].*)$", false),
144 (
145 "rust",
146 r#"^[ ]*((pub(\([^\)]+\))?[ ]+)?((async|const|unsafe|extern([ ]+"[^"]+"))[ ]+)?(struct|enum|union|mod|trait|fn|impl|macro_rules!)[< ]+[^;]*)$"#,
147 false,
148 ),
149 (
150 "scheme",
151 r"^[ ]*(\(((define|def(struct|syntax|class|method|rules|record|proto|alias)?)[-*/ ]|(library|module|struct|class)[*+ ]).*)$",
152 false,
153 ),
154 (
155 "tex",
156 r"^(\\((sub)*section|chapter|part)\*{0,1}\{.*)$",
157 false,
158 ),
159];
160
161#[derive(Debug, Clone)]
162struct FuncRule {
163 matcher: RuleMatcher,
164 negate: bool,
165}
166
167#[derive(Debug, Clone)]
168enum RuleMatcher {
169 Rust(Regex),
170}
171
172#[derive(Debug, Clone)]
173struct BuiltinPattern {
174 pattern: String,
175 ignore_case: bool,
176}
177
178static BUILTIN_FUNCNAME_MATCHERS: OnceLock<BTreeMap<String, Arc<FuncnameMatcher>>> =
180 OnceLock::new();
181
182#[derive(Debug, Clone)]
184pub struct FuncnameMatcher {
185 rules: Vec<FuncRule>,
186}
187
188impl FuncnameMatcher {
189 #[must_use]
193 pub fn match_line(&self, line: &str) -> Option<String> {
194 let mut text = line;
195 if let Some(stripped) = text.strip_suffix('\n') {
196 text = stripped;
197 if let Some(stripped_cr) = text.strip_suffix('\r') {
198 text = stripped_cr;
199 }
200 }
201
202 for rule in &self.rules {
203 let RuleMatcher::Rust(regex) = &rule.matcher;
204 let Some(caps) = regex.captures(text) else {
205 continue;
206 };
207 if rule.negate {
208 return None;
209 }
210 let matched = caps
211 .get(1)
212 .or_else(|| caps.get(0))
213 .map_or("", |m| m.as_str());
214 return Some(matched.trim_end().to_owned());
215 }
216 None
217 }
218}
219
220#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
222#[non_exhaustive]
223pub enum FuncnamePatternError {
224 #[error("last expression must not be negated: {line}")]
226 NegatedLastLine {
227 line: String,
229 },
230 #[error("invalid regexp to look for hunk header: {line}")]
232 InvalidRegex {
233 line: String,
235 },
236}
237
238pub fn matcher_for_path_parsed(
246 config: &ConfigSet,
247 rules: &[crate::attributes::AttrRule],
248 macros: &MacroTable,
249 rel_path: &str,
250 ignore_case: bool,
251) -> Result<Option<FuncnameMatcher>, FuncnamePatternError> {
252 let map = collect_attrs_for_path(rules, macros, rel_path, ignore_case);
253 let Some(AttrValue::Value(driver)) = map.get("diff") else {
254 return Ok(None);
255 };
256 matcher_for_driver(config, driver.as_str())
257}
258
259pub fn matcher_for_driver(
268 config: &ConfigSet,
269 driver: &str,
270) -> Result<Option<FuncnameMatcher>, FuncnamePatternError> {
271 if let Some(pattern) = config.value(&format!("diff.{driver}.xfuncname")) {
272 return compile_matcher(&pattern, true, false).map(Some);
273 }
274 if let Some(pattern) = config.value(&format!("diff.{driver}.funcname")) {
275 return compile_matcher(&pattern, false, false).map(Some);
276 }
277 if let Some(matcher) = cached_builtin_matcher(driver) {
278 return Ok(Some((*matcher).clone()));
279 }
280 Ok(None)
281}
282
283fn cached_builtin_matcher(driver: &str) -> Option<Arc<FuncnameMatcher>> {
284 let map = BUILTIN_FUNCNAME_MATCHERS.get_or_init(|| {
285 builtin_patterns()
286 .clone()
287 .into_iter()
288 .map(|(name, builtin)| {
289 let matcher = compile_matcher(&builtin.pattern, true, builtin.ignore_case)
290 .unwrap_or_else(|e| panic!("built-in userdiff driver {name}: {e}"));
291 (name, Arc::new(matcher))
292 })
293 .collect()
294 });
295 map.get(driver).cloned()
296}
297
298fn compile_matcher(
299 pattern: &str,
300 extended: bool,
301 ignore_case: bool,
302) -> Result<FuncnameMatcher, FuncnamePatternError> {
303 let lines: Vec<&str> = pattern.split('\n').collect();
304 if lines.is_empty() {
305 return Ok(FuncnameMatcher { rules: Vec::new() });
306 }
307
308 let mut rules = Vec::with_capacity(lines.len());
309 for (idx, raw) in lines.iter().enumerate() {
310 let mut line = *raw;
311 let negate = line.starts_with('!');
312 if negate {
313 if idx == lines.len() - 1 {
314 return Err(FuncnamePatternError::NegatedLastLine {
315 line: line.to_owned(),
316 });
317 }
318 line = &line[1..];
319 }
320
321 let posix_pattern = if extended {
322 line.to_owned()
323 } else {
324 bre_to_ere(line)
325 };
326
327 let matcher = compile_posix_ere_rule(&posix_pattern, ignore_case, line)?;
328 rules.push(FuncRule { matcher, negate });
329 }
330
331 Ok(FuncnameMatcher { rules })
332}
333
334fn builtin_patterns() -> &'static BTreeMap<String, BuiltinPattern> {
335 static BUILTIN_PATTERNS: OnceLock<BTreeMap<String, BuiltinPattern>> = OnceLock::new();
337 BUILTIN_PATTERNS.get_or_init(parse_builtin_patterns)
338}
339
340fn parse_builtin_patterns() -> BTreeMap<String, BuiltinPattern> {
341 BUILTIN_PATTERN_DEFS
342 .iter()
343 .filter(|(name, _, _)| !name.is_empty() && *name != "default")
344 .map(|(name, pattern, ignore_case)| {
345 (
346 (*name).to_owned(),
347 BuiltinPattern {
348 pattern: (*pattern).to_owned(),
349 ignore_case: *ignore_case,
350 },
351 )
352 })
353 .collect()
354}
355
356fn bre_to_ere(pattern: &str) -> String {
357 let mut result = String::with_capacity(pattern.len());
358 let chars: Vec<char> = pattern.chars().collect();
359 let mut i = 0usize;
360 let mut in_bracket = false;
361
362 while i < chars.len() {
363 if in_bracket {
364 if chars[i] == ']' && i > 0 {
365 result.push(']');
366 in_bracket = false;
367 i += 1;
368 } else if chars[i] == '[' {
369 result.push('[');
370 i += 1;
371 } else if chars[i] == '\\' {
372 if i + 1 < chars.len() {
376 let next = chars[i + 1];
377 if next.is_ascii_alphabetic() {
378 result.push('\\');
379 result.push('\\');
380 result.push(next);
381 i += 2;
382 } else {
383 result.push('\\');
384 result.push(next);
385 i += 2;
386 }
387 } else {
388 result.push('\\');
389 i += 1;
390 }
391 } else {
392 result.push(chars[i]);
393 i += 1;
394 }
395 } else if chars[i] == '[' {
396 result.push('[');
397 in_bracket = true;
398 i += 1;
399 if i < chars.len() && (chars[i] == '^' || chars[i] == '!') {
400 result.push(chars[i]);
401 i += 1;
402 }
403 if i < chars.len() && chars[i] == ']' {
404 result.push(']');
405 i += 1;
406 }
407 } else if chars[i] == '\\' && i + 1 < chars.len() {
408 match chars[i + 1] {
409 '+' | '?' | '{' | '}' | '(' | ')' | '|' => {
410 result.push(chars[i + 1]);
411 i += 2;
412 }
413 _ => {
414 result.push(chars[i]);
415 result.push(chars[i + 1]);
416 i += 2;
417 }
418 }
419 } else if matches!(chars[i], '+' | '?' | '{' | '}' | '(' | ')' | '|') {
420 result.push('\\');
421 result.push(chars[i]);
422 i += 1;
423 } else {
424 result.push(chars[i]);
425 i += 1;
426 }
427 }
428
429 result
430}
431
432fn posix_ere_to_rust_regex(pattern: &str) -> Option<String> {
436 let mut out = String::with_capacity(pattern.len() + 16);
437 let chars: Vec<char> = pattern.chars().collect();
438 let mut i = 0usize;
439 while i < chars.len() {
440 if chars[i] == '[' {
441 let (translated, consumed) = translate_posix_bracket(&chars[i..])?;
442 out.push_str(&translated);
443 i += consumed;
444 } else if chars[i] == '\\' && i + 1 < chars.len() {
445 out.push(chars[i]);
446 out.push(chars[i + 1]);
447 i += 2;
448 } else {
449 out.push(chars[i]);
450 i += 1;
451 }
452 }
453 Some(out)
454}
455
456fn translate_posix_bracket(src: &[char]) -> Option<(String, usize)> {
458 debug_assert!(src.first() == Some(&'['));
459 let mut out = String::from("[");
460 let mut i = 1usize;
461 if i < src.len() && (src[i] == '^' || src[i] == '!') {
462 out.push(src[i]);
463 i += 1;
464 }
465 if i < src.len() && src[i] == ']' {
466 out.push(']');
467 i += 1;
468 }
469 while i < src.len() {
470 if src[i] == ']' {
471 out.push(']');
472 return Some((out, i + 1));
473 }
474 if src[i] == '[' && i + 2 < src.len() && src[i + 1] == ':' {
475 let start = i;
476 i += 2;
477 while i + 1 < src.len() {
478 if src[i] == ':' && src[i + 1] == ']' {
479 i += 2;
480 break;
481 }
482 i += 1;
483 }
484 for ch in &src[start..i] {
485 out.push(*ch);
486 }
487 continue;
488 }
489 if src[i] == '\\' && i + 1 < src.len() {
490 out.push('\\');
491 out.push(src[i + 1]);
492 i += 2;
493 continue;
494 }
495 let ch = src[i];
496 if matches!(ch, '[' | ']' | '\\') {
497 out.push('\\');
498 }
499 out.push(ch);
500 i += 1;
501 }
502 None
503}
504
505fn validate_posix_ere(pattern: &str, ignore_case: bool) -> Result<(), regex::Error> {
507 let Some(rust_pattern) = posix_ere_to_rust_regex(pattern) else {
508 return Err(regex::Error::Syntax(
509 "unterminated bracket expression".into(),
510 ));
511 };
512 RegexBuilder::new(&rust_pattern)
513 .case_insensitive(ignore_case)
514 .build()
515 .map(|_| ())
516}
517
518fn compile_posix_ere_rule(
520 pattern: &str,
521 ignore_case: bool,
522 line: &str,
523) -> Result<RuleMatcher, FuncnamePatternError> {
524 let invalid = || FuncnamePatternError::InvalidRegex {
525 line: line.to_owned(),
526 };
527 validate_posix_ere(pattern, ignore_case).map_err(|_| invalid())?;
528 let rust_pattern = posix_ere_to_rust_regex(pattern).ok_or_else(invalid)?;
529 RegexBuilder::new(&rust_pattern)
530 .case_insensitive(ignore_case)
531 .build()
532 .map_err(|_| invalid())
533 .map(RuleMatcher::Rust)
534}
535
536#[cfg(test)]
537mod tests {
538 use super::*;
539 use std::path::Path;
540
541 use crate::config::{ConfigFile, ConfigScope, ConfigSet};
542
543 fn config_with_xfuncname(driver: &str, pattern: &str) -> ConfigSet {
544 let snippet = format!("[diff \"{driver}\"]\n\txfuncname = {pattern}\n");
545 let file = ConfigFile::parse(Path::new(".git/config"), &snippet, ConfigScope::Local)
546 .expect("parse config snippet");
547 let mut set = ConfigSet::new();
548 set.merge(&file);
549 set
550 }
551
552 #[test]
553 fn unterminated_posix_bracket_class_is_rejected() {
554 let err = compile_matcher("[a", true, false).unwrap_err();
555 assert!(matches!(err, FuncnamePatternError::InvalidRegex { ref line } if line == "[a"));
556 let cfg = config_with_xfuncname("probe", "[a");
557 let err = matcher_for_driver(&cfg, "probe").unwrap_err();
558 assert!(matches!(err, FuncnamePatternError::InvalidRegex { ref line } if line == "[a"));
559 }
560
561 #[test]
562 fn all_builtin_userdiff_drivers_compile_and_cache() {
563 let config = ConfigSet::default();
564 for (name, _, _) in BUILTIN_PATTERN_DEFS {
565 if name.is_empty() || *name == "default" {
566 continue;
567 }
568 let matcher = matcher_for_driver(&config, name)
569 .unwrap_or_else(|e| panic!("driver {name}: {e}"))
570 .unwrap_or_else(|| panic!("driver {name} missing builtin matcher"));
571 assert!(
572 cached_builtin_matcher(name).is_some(),
573 "driver {name} must be cached"
574 );
575 let _ = matcher.match_line(" \n");
576 }
577 }
578}