1use tree_sitter::{Node, Parser, TreeCursor};
82
83use crate::parse_budget::{parse_within_budget, BudgetExceeded, ParseBudget};
84
85pub fn looks_like_cpp(source: &[u8]) -> bool {
94 sniff_header_with_budget(source, ParseBudget::UNLIMITED) == HeaderSniff::Cpp
95}
96
97#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum HeaderSniff {
101 C,
104 Cpp,
106 Undecided(BudgetExceeded),
109}
110
111pub fn sniff_header(source: &[u8]) -> HeaderSniff {
114 sniff_header_with_budget(source, ParseBudget::default())
115}
116
117pub fn sniff_header_with_budget(source: &[u8], budget: ParseBudget) -> HeaderSniff {
120 let mut parser = Parser::new();
121 if parser
122 .set_language(&tree_sitter_cpp::LANGUAGE.into())
123 .is_err()
124 {
125 return HeaderSniff::C;
126 }
127 let tree = match parse_within_budget(&mut parser, source, budget) {
128 Ok(Some(tree)) => tree,
129 Ok(None) => return HeaderSniff::C,
130 Err(exceeded) => return HeaderSniff::Undecided(exceeded),
131 };
132
133 let mut scan = Scan::new(tree.walk(), cpp_only_lines(source));
134 crate::query::walk_preorder(tree.root_node(), |node| scan.visit(node, source));
135 if scan.verdict() {
136 HeaderSniff::Cpp
137 } else {
138 HeaderSniff::C
139 }
140}
141
142fn cpp_only_lines(source: &[u8]) -> Vec<(usize, usize)> {
149 crate::dead_code::dead_code_ranges(&String::from_utf8_lossy(source))
150 .into_iter()
151 .filter(|region| region.reason == crate::dead_code::DeadCodeReason::CppOnly)
152 .map(|region| (region.start_line, region.end_line))
153 .collect()
154}
155
156fn is_message_send(node: Node) -> bool {
160 node.kind() == "lambda_expression"
161 && node
162 .child_by_field_name("captures")
163 .is_some_and(|captures| captures.has_error())
164}
165
166fn has_missing_token(node: Node) -> bool {
172 if !node.has_error() {
173 return false;
174 }
175 let mut found = false;
176 crate::query::walk_preorder(node, |n| {
177 if n.is_missing() {
178 found = true;
179 crate::query::Walk::Stop
180 } else if n.has_error() {
181 crate::query::Walk::Continue
182 } else {
183 crate::query::Walk::SkipChildren
184 }
185 });
186 found
187}
188
189struct Scan<'a> {
197 found: bool,
199 new_or_delete: bool,
201 keyword_as_name: bool,
204 macro_name_start: Option<usize>,
207 error_end: usize,
210 cursor: TreeCursor<'a>,
212 cpp_only: Vec<(usize, usize)>,
214 macro_block: (usize, usize),
220}
221
222impl<'a> Scan<'a> {
223 fn new(cursor: TreeCursor<'a>, cpp_only: Vec<(usize, usize)>) -> Self {
224 Self {
225 found: false,
226 new_or_delete: false,
227 keyword_as_name: false,
228 macro_name_start: None,
229 error_end: 0,
230 cursor,
231 cpp_only,
232 macro_block: (0, 0),
233 }
234 }
235
236 fn in_macro_block(&self, node: Node) -> bool {
238 (self.macro_block.0..self.macro_block.1).contains(&node.start_byte())
239 }
240
241 fn note_macro_block(&mut self, arguments: Node<'a>) {
244 if self.in_macro_block(arguments) {
245 return;
246 }
247 if let Some(block) = arguments
248 .children(&mut self.cursor)
249 .find(|child| child.kind() == "compound_statement")
250 {
251 self.macro_block = (block.start_byte(), block.end_byte());
252 }
253 }
254
255 fn in_cpp_only_arm(&self, node: Node) -> bool {
257 let line = node.start_position().row + 1;
258 self.cpp_only
259 .iter()
260 .any(|&(start, end)| (start..=end).contains(&line))
261 }
262
263 fn visit(&mut self, node: Node<'a>, source: &[u8]) -> crate::query::Walk {
264 match node.kind() {
265 "ERROR" => self.error_end = self.error_end.max(node.end_byte()),
266 "argument_list" => self.note_macro_block(node),
267 "preproc_def" | "preproc_function_def" | "preproc_ifdef" => {
268 self.macro_name_start = node.child_by_field_name("name").map(|n| n.start_byte());
269 }
270 "identifier" | "field_identifier"
271 if matches!(&source[node.byte_range()], b"new" | b"delete")
272 && self.macro_name_start != Some(node.start_byte()) =>
273 {
274 self.keyword_as_name = true;
275 }
276 _ => {}
277 }
278 if is_cpp_only_marker(node) {
279 self.found = !has_missing_token(node)
280 && !self.in_cpp_only_arm(node)
281 && !self.in_macro_block(node)
282 && !is_message_send(node);
283 } else if node.child_count() > 0 && node.start_byte() >= self.error_end && !node.is_error()
284 {
285 self.judge_children(node);
286 }
287 if self.found {
288 crate::query::Walk::Stop
289 } else {
290 crate::query::Walk::Continue
291 }
292 }
293
294 fn judge_children(&mut self, parent: Node<'a>) {
299 let mut candidate = false;
300 for child in parent.children(&mut self.cursor) {
301 if child.is_error() || child.is_missing() {
302 return;
303 }
304 candidate |= matches!(
305 child.kind(),
306 "new_expression" | "delete_expression" | "reference_declarator"
307 );
308 }
309 if !candidate {
310 return;
311 }
312 let children: Vec<Node<'a>> = parent.children(&mut self.cursor).collect();
313 for child in children {
314 if self.in_cpp_only_arm(child) || self.in_macro_block(child) {
315 continue;
316 }
317 if is_deleted_function(parent, child) {
318 self.found = true;
319 return;
320 }
321 if child.has_error() {
322 continue;
323 }
324 match child.kind() {
325 "new_expression" | "delete_expression" => self.new_or_delete = true,
326 "reference_declarator" if !is_bitwise_and_statement(parent, child) => {
327 self.found = true;
328 return;
329 }
330 _ => {}
331 }
332 }
333 }
334
335 fn verdict(&self) -> bool {
336 self.found || (self.new_or_delete && !self.keyword_as_name)
337 }
338}
339
340fn is_deleted_function(parent: Node, child: Node) -> bool {
346 parent.kind() == "init_declarator"
347 && child.kind() == "delete_expression"
348 && parent
349 .child_by_field_name("declarator")
350 .is_some_and(|d| d.kind() == "function_declarator")
351}
352
353fn is_bitwise_and_statement(parent: Node, declarator: Node) -> bool {
359 if parent.kind() != "declaration" {
360 return false;
361 }
362 let names_a_variable = declarator
364 .named_child(0)
365 .is_some_and(|inner| inner.kind() == "identifier");
366 let mut cursor = parent.walk();
367 let is_extern = parent.children(&mut cursor).any(|c| {
368 c.kind() == "storage_class_specifier" && c.child(0).is_some_and(|k| k.kind() == "extern")
369 });
370 names_a_variable && !is_extern
371}
372
373fn is_cpp_only_marker(node: Node) -> bool {
381 matches!(
382 node.kind(),
383 "class_specifier"
384 | "namespace_definition"
385 | "namespace_alias_definition"
386 | "template_declaration"
387 | "template_instantiation"
388 | "using_declaration"
389 | "access_specifier"
390 | "qualified_identifier"
391 | "try_statement"
392 | "catch_clause"
393 | "throw_statement"
394 | "friend_declaration"
395 | "operator_cast"
396 | "operator_name"
397 | "lambda_expression"
398 | "destructor_name"
399 | "field_initializer_list"
400 | "base_class_clause"
401 | "noexcept"
402 | "concept_definition"
403 | "requires_clause"
404 )
405}
406
407#[cfg(test)]
408mod tests {
409 use super::*;
410
411 #[test]
412 fn plain_c_header_is_not_cpp() {
413 let src = br#"
414#ifndef FOO_H
415#define FOO_H
416
417typedef struct Point {
418 int x;
419 int y;
420} Point;
421
422int point_distance(const Point *a, const Point *b);
423
424#endif
425"#;
426 assert!(!looks_like_cpp(src));
427 }
428
429 #[test]
430 fn c11_static_assert_macro_is_not_cpp() {
431 let src = br#"
432#include <assert.h>
433static_assert(sizeof(int) == 4, "unexpected int size");
434"#;
435 assert!(!looks_like_cpp(src));
436 }
437
438 #[test]
439 fn class_is_cpp() {
440 let src = br#"
441class Widget {
442public:
443 Widget();
444 int value() const;
445private:
446 int value_;
447};
448"#;
449 assert!(looks_like_cpp(src));
450 }
451
452 #[test]
453 fn namespace_is_cpp() {
454 let src = b"namespace app { int helper(); }";
455 assert!(looks_like_cpp(src));
456 }
457
458 #[test]
459 fn template_is_cpp() {
460 let src = b"template<typename T> T max(T a, T b) { return a > b ? a : b; }";
461 assert!(looks_like_cpp(src));
462 }
463
464 #[test]
465 fn scope_resolution_is_cpp() {
466 let src = b"int Widget::value() const { return 0; }";
467 assert!(looks_like_cpp(src));
468 }
469
470 #[test]
471 fn reference_parameter_is_cpp() {
472 let src = b"void increment(int &x);";
473 assert!(looks_like_cpp(src));
474 }
475
476 #[test]
477 fn try_catch_is_cpp() {
478 let src = b"void f() { try { g(); } catch (...) { } }";
479 assert!(looks_like_cpp(src));
480 }
481
482 #[test]
483 fn using_namespace_is_cpp() {
484 let src = b"using namespace std;";
485 assert!(looks_like_cpp(src));
486 }
487
488 fn guarded(body: &str) -> Vec<u8> {
492 format!(
493 "#ifdef __cplusplus\nextern \"C\" {{\n#endif\n\n{body}\n\n#ifdef __cplusplus\n}}\n#endif\n"
494 )
495 .into_bytes()
496 }
497
498 const POINTER_NAMED_NEW: &str = "static inline void list_add(struct list_head *new, struct list_head *head) { new->next = head->next; head->next = new; }";
499 const PARAMETER_NAMED_DELETE: &str = "int f(int delete) { return delete * 2; }";
500 const BITWISE_AND_STATEMENT: &str = "void g(int a, int b) { a & b; }";
501 const KR_DEFINITION: &str =
502 "int old_style(a, b)\nint a;\nchar *b;\n{\n return a & 1;\n}\n\nstatic void h(struct node *new) { struct node *p = new; new = p; free(new); }";
503
504 #[test]
505 fn pointer_named_new_is_not_cpp() {
506 assert!(!looks_like_cpp(POINTER_NAMED_NEW.as_bytes()));
507 assert!(!looks_like_cpp(&guarded(POINTER_NAMED_NEW)));
508 }
509
510 #[test]
511 fn parameter_named_delete_is_not_cpp() {
512 assert!(!looks_like_cpp(PARAMETER_NAMED_DELETE.as_bytes()));
513 assert!(!looks_like_cpp(&guarded(PARAMETER_NAMED_DELETE)));
514 let initialized = b"int f(int delete) { int x = delete * 2; return x; }";
515 assert!(!looks_like_cpp(initialized));
516 }
517
518 #[test]
519 fn bitwise_and_statement_is_not_cpp() {
520 assert!(!looks_like_cpp(BITWISE_AND_STATEMENT.as_bytes()));
521 assert!(!looks_like_cpp(&guarded(BITWISE_AND_STATEMENT)));
522 }
523
524 #[test]
525 fn kr_definition_after_extern_c_guard_is_not_cpp() {
526 assert!(!looks_like_cpp(KR_DEFINITION.as_bytes()));
527 assert!(!looks_like_cpp(&guarded(KR_DEFINITION)));
528 }
529
530 #[test]
531 fn new_declared_elsewhere_is_not_cpp() {
532 for body in [
534 "void f(void) { new->next = 0; }",
535 "void f(void) { list = new; }",
536 ] {
537 assert!(!looks_like_cpp(body.as_bytes()), "{body}");
538 }
539 }
540
541 #[test]
542 fn new_beside_a_parse_error_is_not_cpp() {
543 assert!(!looks_like_cpp(b"void f(void) { new T $ }"));
544 }
545
546 #[test]
547 fn delete_inside_a_parse_error_is_not_cpp() {
548 assert!(!looks_like_cpp(b"void f( { delete p; }"));
549 }
550
551 #[test]
552 fn new_beside_a_missing_node_is_not_cpp() {
553 assert!(!looks_like_cpp(b"void f(void) { return new T }"));
554 }
555
556 #[test]
557 fn new_defined_as_a_macro_is_still_cpp() {
558 let src = b"#define new DEBUG_NEW\nvoid f(void) { T *p = new T; }";
559 assert!(looks_like_cpp(src));
560 assert!(looks_like_cpp(
561 b"#ifdef new\n#endif\nvoid f(void) { delete p; }"
562 ));
563 }
564
565 #[test]
566 fn deleted_function_is_cpp() {
567 assert!(looks_like_cpp(b"void f(double) = delete;"));
568 assert!(looks_like_cpp(&guarded("void f(double) = delete;")));
569 }
570
571 #[test]
572 fn reference_beside_an_unknown_macro_is_not_detected() {
573 assert!(!looks_like_cpp(b"API_EXPORT int& counter();"));
575 }
576
577 #[test]
578 fn new_and_delete_expressions_are_cpp() {
579 for body in [
580 "void f() { T *p = new T; }",
581 "void f(int n) { int *a = new int[n]; }",
582 "void f(T *p) { delete p; }",
583 "void f(T *p) { delete[] p; }",
584 ] {
585 assert!(looks_like_cpp(body.as_bytes()), "{body}");
586 assert!(looks_like_cpp(&guarded(body)), "guarded: {body}");
587 }
588 }
589
590 #[test]
591 fn reference_declarators_are_cpp() {
592 for body in [
593 "void f() { T& r = x; }",
594 "void f(T& x);",
595 "const T& g();",
596 "extern T& r;",
597 ] {
598 assert!(looks_like_cpp(body.as_bytes()), "{body}");
599 assert!(looks_like_cpp(&guarded(body)), "guarded: {body}");
600 }
601 }
602
603 #[test]
604 fn class_inside_extern_c_guard_is_cpp() {
605 assert!(looks_like_cpp(&guarded("class Widget { int v; };")));
606 }
607
608 const EXPORT_MACRO_HEADER: &[u8] = b"#ifndef X_H
614#define X_H
615#ifdef __cplusplus
616extern \"C\" {
617#endif
618typedef unsigned int ma_uint32;
619typedef struct
620{
621 void* pUserData;
622} ma_log_callback;
623
624MA_API ma_log_callback ma_log_callback_init(void* pUserData);
625#ifdef __cplusplus
626}
627#endif
628#endif
629";
630
631 #[test]
632 fn inserted_scope_operator_is_not_cpp() {
633 let tree = {
634 let mut parser = Parser::new();
635 parser
636 .set_language(&tree_sitter_cpp::LANGUAGE.into())
637 .unwrap();
638 parser.parse(EXPORT_MACRO_HEADER, None).unwrap()
639 };
640 let mut inserted = false;
642 crate::query::walk_preorder(tree.root_node(), |n| {
643 inserted |= n.kind() == "qualified_identifier" && has_missing_token(n);
644 crate::query::Walk::Continue
645 });
646 assert!(inserted, "fixture no longer yields a MISSING `::`");
647 assert!(!looks_like_cpp(EXPORT_MACRO_HEADER));
648 }
649
650 #[test]
651 fn written_scope_operator_beside_an_export_macro_is_cpp() {
652 let mut src = EXPORT_MACRO_HEADER.to_vec();
653 src.extend_from_slice(b"int Widget::value() const { return 0; }\n");
654 assert!(looks_like_cpp(&src));
655 }
656
657 #[test]
658 fn cpp_only_arms_of_a_c_header_are_not_cpp() {
659 for src in [
660 "typedef struct { float x, y; } Vec2;\n#if defined(__cplusplus) && !defined(NO_CPP_OPERATORS)\ninline Vec2 operator+(Vec2 a, Vec2 b) { return a; }\ninline Vec2& operator+=(Vec2& a, Vec2 b) { return a; }\n#endif\n",
662 "#ifdef __cplusplus\n# include <cstring>\nusing namespace std;\n#else\n# include <string.h>\n#endif\n",
663 "#ifndef __cplusplus\nint f(void);\n#else\nnamespace m { class Model { public: Model(); ~Model(); }; }\n#endif\n",
664 "#if !defined(__cplusplus)\nint f(void);\n#else\ntemplate<typename T> T id(T t) { return t; }\n#endif\n",
665 "#ifdef __cplusplus\nvoid f(T& x);\nvoid g(T *p) { delete p; }\n#endif\n",
666 ] {
667 assert!(!looks_like_cpp(src.as_bytes()), "{src}");
668 }
669 }
670
671 #[test]
672 fn cpp_outside_a_cpp_only_arm_is_cpp() {
673 for src in [
674 "#ifndef __cplusplus\nnamespace m { int f(); }\n#endif\n",
675 "#ifdef __cplusplus\nextern \"C\" {\n#endif\nint f(void);\n#ifdef __cplusplus\n}\n#endif\nclass Widget { int v; };\n",
676 "#ifdef __cplusplus\nusing namespace std;\n#endif\nvoid f(T& x);\n",
677 "#if defined(__cplusplus) || defined(WANT_CPP)\nusing namespace std;\n#endif\n",
678 ] {
679 assert!(looks_like_cpp(src.as_bytes()), "{src}");
680 }
681 }
682
683 #[test]
684 fn cpp_header_with_an_unknown_class_macro_is_cpp() {
685 let src = b"#ifndef SIGNALBAR_H
687#define SIGNALBAR_H
688#include <QObject>
689class SignalBar : public QStyledItemDelegate
690{
691\tQ_OBJECT
692
693public:
694\tSignalBar(QObject *parent = 0);
695\t~SignalBar();
696\tvirtual void paint(QPainter *painter, const QStyleOptionViewItem &option, const QModelIndex &index) const;
697};
698#endif
699";
700 assert!(looks_like_cpp(src));
701 }
702
703 #[test]
704 fn javascript_in_a_macro_argument_is_not_cpp() {
705 for src in [
706 "void f(void) { EM_ASM({ var a = new Uint8Array(data); }); }",
707 "void f(void) { EM_ASM({ delete window.miniaudio; }); }",
708 "int f(void) { return EM_ASM_INT({ try { return g(); } catch(e) { return 0; } }); }",
709 "void f(void) { EM_ASM({ var h = function(e) { var r = new FileReader(); }; }, 0); }",
710 ] {
711 assert!(!looks_like_cpp(src.as_bytes()), "{src}");
712 }
713 }
714
715 #[test]
716 fn cpp_in_a_call_argument_is_cpp() {
717 for src in [
718 "void f() { g(new T); }",
719 "void f() { g([](int x) { return x + 1; }); }",
720 "void f() { g([&](int x) { T *p = new T; return x; }); }",
721 "void f() { g(({ int y = 1; y; }), [=] { return 0; }); }",
722 "void f() { g({1, 2}); class Local { int v; }; }",
723 ] {
724 assert!(looks_like_cpp(src.as_bytes()), "{src}");
725 }
726 }
727
728 #[test]
729 fn objective_c_message_send_is_not_cpp() {
730 for src in [
731 "void f(void) { if ([pAudioSession setActive:true error:nil]) { g(); } }",
732 "void f(void) { if (![[AVAudioSession sharedInstance] setActive:false error:nil]) { g(); } }",
733 "void f(void) { if (a) { g(); } else if ([session setCategory: AVAudioSessionCategoryPlayback withOptions:options error:nil]) { h(); } }",
734 ] {
735 assert!(!looks_like_cpp(src.as_bytes()), "{src}");
736 }
737 }
738
739 #[test]
740 fn lambdas_are_cpp() {
741 for src in [
742 "auto add = [](int a, int b) { return a + b; };",
743 "void f() { int n = 0; auto inc = [&n]() { ++n; }; }",
744 "void f() { auto g = [this, x = 2]() mutable { return x; }; }",
745 ] {
746 assert!(looks_like_cpp(src.as_bytes()), "{src}");
747 }
748 }
749
750 fn unclosed_comment_header(lines: usize) -> Vec<u8> {
753 let mut src = format!("/* {}\n", "x".repeat(40)).into_bytes();
754 for _ in 0..lines {
755 src.extend_from_slice(b" */\n");
756 }
757 src
758 }
759
760 #[test]
761 fn quadratic_recovery_is_undecided_not_guessed() {
762 let src = unclosed_comment_header(4_000);
765 let start = std::time::Instant::now();
766 match sniff_header(&src) {
767 HeaderSniff::Undecided(exceeded) => {
768 assert_eq!(exceeded.source_len, src.len());
769 assert_eq!(
770 exceeded.budget_steps,
771 ParseBudget::DEFAULT.steps_for(src.len())
772 );
773 }
774 other => panic!("expected Undecided, got {other:?}"),
775 }
776 assert!(start.elapsed().as_secs() < 5, "{:?}", start.elapsed());
777 }
778
779 #[test]
780 fn a_small_malformed_header_still_decides() {
781 assert_eq!(sniff_header(&unclosed_comment_header(50)), HeaderSniff::C);
782 }
783
784 #[test]
785 fn unlimited_budget_keeps_the_unbounded_answer() {
786 let src = unclosed_comment_header(300);
787 assert_eq!(
788 sniff_header_with_budget(&src, ParseBudget::UNLIMITED),
789 HeaderSniff::C
790 );
791 assert!(!looks_like_cpp(&src));
792 }
793
794 #[test]
795 fn sniff_header_agrees_with_looks_like_cpp() {
796 for src in [
797 EXPORT_MACRO_HEADER.to_vec(),
798 b"namespace app { int helper(); }".to_vec(),
799 guarded(POINTER_NAMED_NEW),
800 b"void f(double) = delete;".to_vec(),
801 ] {
802 let expected = if looks_like_cpp(&src) {
803 HeaderSniff::Cpp
804 } else {
805 HeaderSniff::C
806 };
807 assert_eq!(sniff_header(&src), expected);
808 }
809 }
810
811 #[test]
812 fn a_large_ordinary_header_decides_within_the_default() {
813 let mut src = guarded("").to_vec();
816 for i in 0..5_000 {
817 src.extend_from_slice(format!("int function_{i}(int a, const char *b);\n").as_bytes());
818 }
819 assert_eq!(sniff_header(&src), HeaderSniff::C);
820 src.extend_from_slice(b"class Widget { int v; };\n");
821 assert_eq!(sniff_header(&src), HeaderSniff::Cpp);
822 }
823
824 #[test]
825 fn empty_source_is_not_cpp() {
826 assert!(!looks_like_cpp(b""));
827 }
828}