linthis 0.19.3

A fast, cross-platform multi-language linter and formatter
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
// Copyright 2024 zhlinh and linthis Project Authors. All rights reserved.
// Use of this source code is governed by a MIT-style
// license that can be found at
//
// https://opensource.org/license/MIT
//
// The above copyright notice and this permission
// notice shall be included in all copies or
// substantial portions of the Software.

//! C/C++ language formatter using clang-format, clang-tidy --fix, and cpplint fixer.

use crate::fixers::cpplint::{CpplintFixer, CpplintFixerConfig, HeaderGuardMode};
use crate::fixers::source::SourceFixer;
use crate::formatters::Formatter;
use crate::utils::types::FormatResult;
use crate::{Language, Result};
use std::fs;
use std::path::{Path, PathBuf};
use std::process::Command;
use std::sync::Mutex;

/// C/C++ formatter using clang-format, clang-tidy --fix, and cpplint fixer.
pub struct CppFormatter {
    /// Enable clang-tidy --fix for auto-fixing lint issues
    use_clang_tidy_fix: bool,
    /// Enable cpplint fixer for header guards, TODOs, etc.
    use_cpplint_fix: bool,
    /// Custom compile_commands.json directory path
    compile_commands_dir: Option<PathBuf>,
    /// Cpplint fixer instance (wrapped in Mutex for interior mutability)
    cpplint_fixer: Mutex<CpplintFixer>,
}

impl CppFormatter {
    pub fn new() -> Self {
        Self {
            use_clang_tidy_fix: true, // Enable by default
            use_cpplint_fix: true,    // Enable by default
            compile_commands_dir: None,
            cpplint_fixer: Mutex::new(CpplintFixer::new()),
        }
    }

    /// Enable or disable clang-tidy --fix
    pub fn with_clang_tidy_fix(mut self, enable: bool) -> Self {
        self.use_clang_tidy_fix = enable;
        self
    }

    /// Enable or disable cpplint fixer
    pub fn with_cpplint_fix(mut self, enable: bool) -> Self {
        self.use_cpplint_fix = enable;
        self
    }

    /// Set custom compile_commands.json directory
    pub fn with_compile_commands_dir(mut self, path: PathBuf) -> Self {
        self.compile_commands_dir = Some(path);
        self
    }

    /// Configure cpplint fixer
    pub fn with_cpplint_config(self, config: CpplintFixerConfig) -> Self {
        *self.cpplint_fixer.lock().unwrap() = CpplintFixer::with_config(config);
        self
    }

    /// Set header guard mode
    pub fn with_header_guard_mode(self, mode: HeaderGuardMode) -> Self {
        {
            let mut fixer = self.cpplint_fixer.lock().unwrap();
            let config = CpplintFixerConfig {
                header_guard_mode: mode,
                ..Default::default()
            };
            *fixer = CpplintFixer::with_config(config);
        }
        self
    }

    /// Check if clang-tidy is available
    fn has_clang_tidy() -> bool {
        Command::new("clang-tidy")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }

    /// Find .clang-tidy config file by walking up from file path
    fn find_clang_tidy_config(start_path: &Path) -> Option<PathBuf> {
        let mut current = if start_path.is_file() {
            start_path.parent()?.to_path_buf()
        } else {
            start_path.to_path_buf()
        };

        loop {
            let config_path = current.join(".clang-tidy");
            if config_path.exists() {
                return Some(config_path);
            }
            if !current.pop() {
                break;
            }
        }
        None
    }

    /// Find .clang-format config file for a specific language.
    /// First checks .linthis/configs/{language}/.clang-format, then walks up directories.
    fn find_clang_format_config(start_path: &Path, language: &str) -> Option<PathBuf> {
        // First, check .linthis/configs/{language}/.clang-format
        let mut current = if start_path.is_file() {
            start_path.parent()?.to_path_buf()
        } else {
            start_path.to_path_buf()
        };

        // Walk up to find .linthis directory
        let mut search_dir = current.clone();
        loop {
            let linthis_config = search_dir
                .join(".linthis")
                .join("configs")
                .join(language)
                .join(".clang-format");
            if linthis_config.exists() {
                return Some(linthis_config);
            }
            if !search_dir.pop() {
                break;
            }
        }

        // Fall back to traditional .clang-format search in parent directories
        loop {
            let config_path = current.join(".clang-format");
            if config_path.exists() {
                return Some(config_path);
            }
            if !current.pop() {
                break;
            }
        }
        None
    }

    /// Find compile_commands.json recursively
    fn find_compile_commands(start_path: &Path) -> Option<PathBuf> {
        let mut current = if start_path.is_file() {
            start_path.parent()?.to_path_buf()
        } else {
            start_path.to_path_buf()
        };

        loop {
            // Check current directory
            if current.join("compile_commands.json").exists() {
                return Some(current.clone());
            }

            // Check common build directories
            for build_dir in &[
                "build",
                "Build",
                "out",
                "cmake-build-debug",
                "cmake-build-release",
            ] {
                let compile_db = current.join(build_dir).join("compile_commands.json");
                if compile_db.exists() {
                    return Some(current.join(build_dir));
                }
            }

            // Recursively search build-like directories (up to 6 levels)
            if let Some(found) = Self::find_compile_commands_recursive(&current, 0, 6) {
                return Some(found);
            }

            if !current.pop() {
                break;
            }
        }
        None
    }

    fn find_compile_commands_recursive(
        dir: &Path,
        depth: usize,
        max_depth: usize,
    ) -> Option<PathBuf> {
        if depth >= max_depth {
            return None;
        }

        let entries = std::fs::read_dir(dir).ok()?;

        for entry in entries.flatten() {
            let path = entry.path();
            if !path.is_dir() {
                continue;
            }

            let name = path.file_name().and_then(|n| n.to_str())?;
            let name_lower = name.to_lowercase();

            if is_build_directory(&name_lower, depth) {
                if path.join("compile_commands.json").exists() {
                    return Some(path);
                }
                if let Some(found) =
                    Self::find_compile_commands_recursive(&path, depth + 1, max_depth)
                {
                    return Some(found);
                }
            }
        }
        None
    }

    /// Run clang-tidy --fix on a file
    fn run_clang_tidy_fix(&self, path: &Path) -> Result<bool> {
        if !Self::has_clang_tidy() {
            return Ok(false);
        }

        // Respect LINTHIS_SKIP_CLANG_TIDY env var (same as checker)
        if std::env::var("LINTHIS_SKIP_CLANG_TIDY").is_ok() {
            return Ok(false);
        }

        // Find compile_commands.json - required for clang-tidy to work correctly.
        // Without it, clang-tidy treats .h files as C (not C++), causing it to
        // misidentify C++ keywords like "namespace" and corrupt the code.
        let build_path = if let Some(ref build_path) = self.compile_commands_dir {
            Some(build_path.clone())
        } else {
            Self::find_compile_commands(path)
        };

        if build_path.is_none() {
            // Skip clang-tidy without compilation database to avoid miscompilation
            return Ok(false);
        }

        let mut cmd = Command::new("clang-tidy");
        cmd.arg(path);
        cmd.arg("--fix");
        // Note: do NOT use --fix-errors here. It applies "fixes" for compilation
        // errors which can corrupt valid C++ code (e.g. inserting semicolons after
        // "namespace foo" because it doesn't recognize "namespace" without proper
        // compilation context).

        // Add config file if found
        if let Some(config) = Self::find_clang_tidy_config(path) {
            cmd.arg(format!("--config-file={}", config.display()));
        }

        cmd.arg(format!("-p={}", build_path.unwrap().display()));

        let output = cmd.output().map_err(|e| {
            crate::LintisError::formatter("clang-tidy", path, format!("Failed to run --fix: {}", e))
        })?;

        // clang-tidy returns non-zero if there are unfixable issues, but fix still works
        Ok(output.status.success() || !output.stdout.is_empty())
    }

    /// Run pre-format fixers (cpplint fixer and clang-tidy --fix)
    fn run_pre_format_fixers(&self, path: &Path, language: &str) {
        // Run cpplint fixer (fixes header guards, TODOs, copyright)
        if self.use_cpplint_fix {
            if let Ok(mut fixer) = self.cpplint_fixer.lock() {
                fixer.set_is_objc(language == "oc");
                let _ = fixer.fix_file(path);
            }
        }

        // Run clang-tidy --fix (skip for OC files)
        if self.use_clang_tidy_fix && language != "oc" {
            let _ = self.run_clang_tidy_fix(path);
        }
    }

    /// Run clang-format on a file, returning an error FormatResult if it fails
    fn run_clang_format(&self, path: &Path, language: &str) -> Result<Option<FormatResult>> {
        let mut cmd = Command::new("clang-format");
        cmd.arg("-i");

        if let Some(config_path) = Self::find_clang_format_config(path, language) {
            cmd.arg(format!("-style=file:{}", config_path.display()));
        } else {
            cmd.arg("-style=Google");
        }

        cmd.arg(path);
        let output = cmd.output().map_err(|e| {
            crate::LintisError::formatter("clang-format", path, format!("Failed to run: {}", e))
        })?;

        if !output.status.success() {
            let stderr = String::from_utf8_lossy(&output.stderr);
            return Ok(Some(FormatResult::error(
                path.to_path_buf(),
                format!("clang-format failed: {}", stderr),
            )));
        }

        Ok(None)
    }

    /// Run post-format source fixers (comment spacing, TODOs, etc.)
    fn run_post_format_fixers(path: &Path, language: &str) -> Result<()> {
        SourceFixer::fix_comment_spacing(path)?;
        SourceFixer::fix_todo_comments(path)?;
        SourceFixer::fix_lone_semicolon(path)?;

        let max_line_length = if language == "oc" { 150 } else { 120 };
        SourceFixer::fix_long_comments(path, max_line_length)?;

        if language == "oc" {
            SourceFixer::fix_pragma_separators(path)?;
        }

        Ok(())
    }
}

/// Check if a directory name matches build-related patterns
fn is_build_directory(name_lower: &str, depth: usize) -> bool {
    if name_lower.starts_with("cmake")
        || name_lower.starts_with("build")
        || name_lower.starts_with("out")
        || name_lower.ends_with("-build")
        || name_lower.ends_with("_build")
    {
        return true;
    }

    if depth > 0 {
        return is_platform_subdirectory(name_lower);
    }

    false
}

/// Check if a directory name matches platform/architecture patterns
fn is_platform_subdirectory(name_lower: &str) -> bool {
    const PLATFORM_KEYWORDS: &[&str] = &[
        "android", "ios", "linux", "windows", "arm", "x86", "static", "shared", "debug", "release",
    ];
    PLATFORM_KEYWORDS.iter().any(|kw| name_lower.contains(kw))
}

impl Default for CppFormatter {
    fn default() -> Self {
        Self::new()
    }
}

impl Formatter for CppFormatter {
    fn name(&self) -> &str {
        match (
            self.use_clang_tidy_fix && Self::has_clang_tidy(),
            self.use_cpplint_fix,
        ) {
            (true, true) => "clang-format + clang-tidy + cpplint-fix",
            (true, false) => "clang-format + clang-tidy",
            (false, true) => "clang-format + cpplint-fix",
            (false, false) => "clang-format",
        }
    }

    fn supported_languages(&self) -> &[Language] {
        &[Language::Cpp, Language::ObjectiveC]
    }

    fn format(&self, path: &Path) -> Result<FormatResult> {
        // Detect language from file extension
        let language = Self::detect_language(path);

        // Read original content for comparison
        let original = fs::read_to_string(path).map_err(|e| {
            crate::LintisError::formatter(
                "clang-format",
                path,
                format!("Failed to read file: {}", e),
            )
        })?;

        // Run pre-format fixers (cpplint, clang-tidy)
        self.run_pre_format_fixers(path, language);

        // Run clang-format (-i modifies in place)
        let format_result = self.run_clang_format(path, language)?;
        if let Some(err_result) = format_result {
            return Ok(err_result);
        }

        // Run post-format source fixers
        Self::run_post_format_fixers(path, language)?;

        // Read new content and compare
        let new_content = fs::read_to_string(path).map_err(|e| {
            crate::LintisError::formatter(
                "clang-format",
                path,
                format!("Failed to read formatted file: {}", e),
            )
        })?;

        if original == new_content {
            Ok(FormatResult::unchanged(path.to_path_buf()))
        } else {
            Ok(FormatResult::changed(path.to_path_buf()))
        }
    }

    fn check(&self, path: &Path) -> Result<bool> {
        // Detect language from file extension
        let language = Self::detect_language(path);

        // Read current content
        let current = fs::read_to_string(path).map_err(|e| {
            crate::LintisError::formatter(
                "clang-format",
                path,
                format!("Failed to read file: {}", e),
            )
        })?;

        // Run clang-format to get formatted output (without -i)
        let mut cmd = Command::new("clang-format");

        // Use language-specific config if found, otherwise fall back to Google style
        if let Some(config_path) = Self::find_clang_format_config(path, language) {
            cmd.arg(format!("-style=file:{}", config_path.display()));
        } else {
            cmd.arg("-style=Google");
        }

        let output = cmd.arg(path).output().map_err(|e| {
            crate::LintisError::formatter("clang-format", path, format!("Failed to run: {}", e))
        })?;

        let formatted = String::from_utf8_lossy(&output.stdout);

        // If they differ, file needs formatting
        Ok(current != formatted.as_ref())
    }

    fn is_available(&self) -> bool {
        Command::new("clang-format")
            .arg("--version")
            .output()
            .map(|o| o.status.success())
            .unwrap_or(false)
    }
}

impl CppFormatter {
    /// Detect language from file extension and content.
    /// For .h files, checks content for OC syntax to determine if it's OC or C++.
    fn detect_language(path: &Path) -> &'static str {
        let debug = std::env::var("LINTHIS_DEBUG").is_ok();

        match path.extension().and_then(|e| e.to_str()) {
            Some("m") | Some("mm") | Some("M") | Some("MM") => {
                if debug {
                    eprintln!(
                        "[cpp-formatter] {} detected as OC (by extension)",
                        path.display()
                    );
                }
                "oc"
            }
            Some("h") | Some("H") => {
                // For header files, check content for OC-specific syntax
                if Self::contains_objc_syntax(path) {
                    if debug {
                        eprintln!(
                            "[cpp-formatter] {} detected as OC (by content)",
                            path.display()
                        );
                    }
                    "oc"
                } else {
                    if debug {
                        eprintln!(
                            "[cpp-formatter] {} detected as C++ (no OC syntax found)",
                            path.display()
                        );
                    }
                    "cpp"
                }
            }
            _ => {
                if debug {
                    eprintln!(
                        "[cpp-formatter] {} detected as C++ (by extension)",
                        path.display()
                    );
                }
                "cpp"
            }
        }
    }

    /// Check if a file contains Objective-C specific syntax.
    fn contains_objc_syntax(path: &Path) -> bool {
        let content = match fs::read_to_string(path) {
            Ok(c) => c,
            Err(_) => return false,
        };

        // OC-specific patterns (exact string matches)
        let oc_patterns = [
            "@import", // OC module import: @import UIKit;
            "@interface",
            "@implementation",
            "@protocol",
            "@property",
            "@synthesize",
            "@dynamic",
            "@selector",
            "@class",
            "@end",
            "NS_ASSUME_NONNULL_BEGIN",
            "NS_ENUM",
            "NS_OPTIONS",
            "nullable",
            "nonnull",
            "+ (",  // OC class method
            "- (",  // OC instance method
            " @\"", // OC string literal: @"string"
            " @[",  // OC array literal: @[@"a", @"b"]
        ];

        for pattern in oc_patterns {
            if content.contains(pattern) {
                return true;
            }
        }

        // Check for Foundation types: NS followed by uppercase letter (e.g., NSString, NSArray)
        // This follows Apple's naming convention and won't match C++ namespaces (which are lowercase)
        if Self::contains_ns_type(&content) {
            return true;
        }

        false
    }

    /// Check if content contains Foundation types (NS followed by uppercase letter).
    /// Examples: NSString, NSArray, NSDictionary, NSObject, NSURL, etc.
    fn contains_ns_type(content: &str) -> bool {
        let bytes = content.as_bytes();
        let len = bytes.len();

        // Look for "NS" followed by an uppercase letter A-Z
        for i in 0..len.saturating_sub(2) {
            if bytes[i] == b'N' && bytes[i + 1] == b'S' {
                let next_char = bytes[i + 2];
                // Check if next char is uppercase A-Z (ASCII 65-90)
                if next_char.is_ascii_uppercase() {
                    // Make sure it's not part of a longer identifier before "NS"
                    // (i.e., NS should be at word boundary)
                    if i == 0 || !is_identifier_char(bytes[i - 1]) {
                        return true;
                    }
                }
            }
        }
        false
    }
}

/// Check if a byte is a valid identifier character (alphanumeric or underscore)
fn is_identifier_char(b: u8) -> bool {
    b.is_ascii_alphanumeric() || b == b'_'
}

#[cfg(test)]
mod tests {
    use super::*;
    use std::io::Write;
    use tempfile::NamedTempFile;

    fn create_temp_header(content: &str) -> NamedTempFile {
        let mut file = tempfile::Builder::new().suffix(".h").tempfile().unwrap();
        file.write_all(content.as_bytes()).unwrap();
        file
    }

    // ==================== detect_language tests ====================

    #[test]
    fn test_detect_language_m_file() {
        let path = std::path::Path::new("test.m");
        assert_eq!(CppFormatter::detect_language(path), "oc");
    }

    #[test]
    fn test_detect_language_mm_file() {
        let path = std::path::Path::new("test.mm");
        assert_eq!(CppFormatter::detect_language(path), "oc");
    }

    #[test]
    fn test_detect_language_cpp_file() {
        let path = std::path::Path::new("test.cpp");
        assert_eq!(CppFormatter::detect_language(path), "cpp");
    }

    #[test]
    fn test_detect_language_h_file_cpp() {
        let file = create_temp_header("#include <iostream>\nvoid foo();\n");
        assert_eq!(CppFormatter::detect_language(file.path()), "cpp");
    }

    #[test]
    fn test_detect_language_h_file_oc_interface() {
        let file = create_temp_header("@interface MyClass : NSObject\n@end\n");
        assert_eq!(CppFormatter::detect_language(file.path()), "oc");
    }

    #[test]
    fn test_detect_language_h_file_oc_property() {
        let file = create_temp_header("@property (nonatomic) NSString *name;\n");
        assert_eq!(CppFormatter::detect_language(file.path()), "oc");
    }

    // ==================== contains_objc_syntax tests ====================

    #[test]
    fn test_contains_objc_syntax_interface() {
        let file = create_temp_header("@interface Test\n@end\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_implementation() {
        let file = create_temp_header("@implementation Test\n@end\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_protocol() {
        let file = create_temp_header("@protocol MyProtocol\n@end\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_ns_enum() {
        let file = create_temp_header("typedef NS_ENUM(NSUInteger, MyEnum) {\n};\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_ns_options() {
        let file = create_temp_header("typedef NS_OPTIONS(NSUInteger, MyOptions) {\n};\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nsinteger() {
        let file = create_temp_header("- (NSInteger)count;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nsuinteger() {
        let file = create_temp_header("NSUInteger value = 0;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nsstring() {
        let file = create_temp_header("NSString *name;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nsarray() {
        let file = create_temp_header("NSArray *items;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nsdictionary() {
        let file = create_temp_header("NSDictionary *dict;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nsobject() {
        let file = create_temp_header("@interface MyClass : NSObject\n@end\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nsurl() {
        let file = create_temp_header("NSURL *url;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nserror() {
        let file = create_temp_header("NSError *error;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_string_literal() {
        let file = create_temp_header("NSString *s = @\"hello\";\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    // ==================== contains_ns_type tests ====================

    #[test]
    fn test_contains_ns_type_nsstring() {
        assert!(CppFormatter::contains_ns_type("NSString *name;"));
    }

    #[test]
    fn test_contains_ns_type_nsarray() {
        assert!(CppFormatter::contains_ns_type(
            "NSArray<NSString *> *items;"
        ));
    }

    #[test]
    fn test_contains_ns_type_at_line_start() {
        assert!(CppFormatter::contains_ns_type("NSObject *obj;"));
    }

    #[test]
    fn test_contains_ns_type_after_space() {
        assert!(CppFormatter::contains_ns_type("id<NSCopying> obj;"));
    }

    #[test]
    fn test_contains_ns_type_after_paren() {
        assert!(CppFormatter::contains_ns_type("(NSString *)value"));
    }

    #[test]
    fn test_contains_ns_type_no_false_positive_dns() {
        // "DNS" should not match because D is before NS
        assert!(!CppFormatter::contains_ns_type("DNSResolver resolver;"));
    }

    #[test]
    fn test_contains_ns_type_no_false_positive_lowercase() {
        // "NSfoo" where next char is lowercase should not match
        // But actually NS followed by lowercase is rare, let's test NS alone
        assert!(!CppFormatter::contains_ns_type("namespace ns { }"));
    }

    #[test]
    fn test_contains_ns_type_no_false_positive_part_of_word() {
        // "AwesomeNSString" - NS is part of larger identifier
        assert!(!CppFormatter::contains_ns_type("AwesomeNSString x;"));
    }

    #[test]
    fn test_contains_ns_type_pure_cpp() {
        assert!(!CppFormatter::contains_ns_type(
            "#include <vector>\nstd::vector<int> v;"
        ));
    }

    #[test]
    fn test_contains_objc_syntax_array_literal() {
        let file = create_temp_header("NSArray *arr = @[@\"a\", @\"b\"];\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_class_method() {
        let file = create_temp_header("+ (instancetype)sharedInstance;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_instance_method() {
        let file = create_temp_header("- (void)doSomething;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nullable() {
        let file = create_temp_header("nullable NSString *name;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_nonnull() {
        let file = create_temp_header("nonnull NSString *name;\n");
        assert!(CppFormatter::contains_objc_syntax(file.path()));
    }

    #[test]
    fn test_contains_objc_syntax_pure_cpp() {
        let file = create_temp_header("#include <vector>\nstd::vector<int> v;\n");
        assert!(!CppFormatter::contains_objc_syntax(file.path()));
    }
}