Skip to main content

lang_parsing_substrate/
cpp_header.rs

1//! Best-effort content-based disambiguation for `.h` files between C and
2//! C++.
3//!
4//! `.h` is inherently ambiguous by extension alone — `language_for_file`
5//! resolves it to the C grammar unconditionally (see this crate's
6//! `CLAUDE.md`), which is correct for the overwhelming majority of `.h`
7//! files but wrong for a C++ header that happens to use the `.h` extension
8//! instead of `.hpp`/`.hxx`. [`looks_like_cpp`] gives callers that already
9//! have the file's bytes (e.g. after reading it to parse) a way to catch
10//! the common case: a header using unambiguous C++ syntax.
11//!
12//! Consistent with the rest of this crate's "never fabricate" stance
13//! ([`crate::detect_min_c_standard`] is the other example), this only
14//! returns `true` for syntax that has **no meaning in C at all** — a
15//! header written entirely in the C-compatible subset of C++ (no classes,
16//! templates, namespaces, `::`, references, `try`/`catch`, …) is
17//! indistinguishable from C by syntax alone and is intentionally left
18//! classified as C rather than guessed at. `false` means "consistent with
19//! C", not "confirmed C".
20//!
21//! Deliberately excluded from the marker set: `static_assert_declaration`
22//! (tree-sitter-cpp's dedicated node for the `static_assert` keyword) —
23//! a C11 header that uses the `static_assert` macro from `<assert.h>`
24//! (which expands to `_Static_assert`, but tree-sitter has no preprocessor
25//! and sees the literal, unexpanded `static_assert` spelling) would parse
26//! identically under the C++ grammar and produce a false positive. This
27//! mirrors `c_standard`'s exclusion of the same identifier for the same
28//! reason.
29//!
30//! Three markers are also what tree-sitter-cpp makes of valid C:
31//! `new_expression` from a pointer named `new` (`new->next = head`),
32//! `delete_expression` from a parameter named `delete` (`return delete * 2;`),
33//! and `reference_declarator` from the statement `a & b;`. A `new` or
34//! `delete` expression counts only when it parsed without error, has no
35//! `ERROR` or `MISSING` node beside it, and the file never uses `new` or
36//! `delete` as a name outside a `#define` or `#ifdef` (MFC's
37//! `#define new DEBUG_NEW` is C++). A deleted function
38//! (`void f(double) = delete;`) always counts, though the grammar leaves a
39//! `MISSING` operand in it. A reference declarator counts under the same
40//! error rule, unless it is a bare `a & b;`: a reference declared with no
41//! initializer and without `extern`, which C++ rejects.
42//!
43//! Two more things count for nothing, whatever the marker:
44//!
45//! - A marker whose subtree holds a `MISSING` token. Error recovery inserts
46//!   tokens, and for `MA_API T f(void);` with `MA_API` defined elsewhere it
47//!   can build the qualified name `T::f` around a `MISSING` `::`. Whether it
48//!   does depends on the code around the declaration, so one such header
49//!   reads as C++ and a reduction of it does not.
50//! - A marker inside an arm only a C++ compiler reads: `#ifdef __cplusplus`,
51//!   `#if defined(__cplusplus) [&& ...]`, and the `#else` of
52//!   `#ifndef __cplusplus` / `#if !defined(__cplusplus)`. That is how a C
53//!   header offers C++ callers operator overloads or a wrapper class. A
54//!   header whose only C++ is in such arms is C when compiled as C.
55//!
56//! - A marker inside a brace block passed directly as a call argument, which
57//!   neither C nor C++ allows (a GNU statement expression is parenthesized):
58//!   it is a macro's argument text, such as the JavaScript in Emscripten's
59//!   `EM_ASM({ ... })`, where `new`, `delete` and `catch` are JavaScript.
60//! - A lambda whose capture list does not parse. That is how tree-sitter-cpp
61//!   reads an Objective-C message send, `[obj sel:x]`, in an Apple-only arm.
62//!
63//! The error rule costs some real C++: in `API_EXPORT int& counter();` the
64//! grammar cannot place the unknown macro and leaves an `ERROR` beside the
65//! reference, so a header whose only marker is that shape reads as C.
66//!
67//! [`sniff_header`] runs that parse within a [`ParseBudget`]: tree-sitter's
68//! error recovery is quadratic on some malformed inputs, and a header that
69//! reaches the budget is [`HeaderSniff::Undecided`], an answer the caller can
70//! report, rather than a guess either way. [`looks_like_cpp`] is the same
71//! check unbounded.
72//!
73//! Parses `source` with the C++ grammar internally, rather than taking an
74//! already-parsed `Tree` like [`crate::detect_min_c_standard`] does —
75//! there's no way to know which grammar to parse a `.h` file with *before*
76//! this check runs. tree-sitter-cpp accepts nearly all valid C as a subset,
77//! so parsing as C++ first and then looking for C++-exclusive node kinds is
78//! the only order that works: parsing as C first would reject genuine C++
79//! syntax outright rather than surface it as a queryable node.
80
81use tree_sitter::{Node, Parser, TreeCursor};
82
83use crate::parse_budget::{parse_within_budget, BudgetExceeded, ParseBudget};
84
85/// Returns `true` if `source`'s syntax contains a construct with no meaning
86/// in C — i.e. the file can only be C++. See the module documentation for
87/// what is and isn't treated as a marker, and why `false` doesn't mean
88/// "confirmed C".
89///
90/// The parse is **unbounded**: on a malformed input whose error recovery is
91/// quadratic it can run for minutes. Prefer [`sniff_header`], which stops at
92/// a [`ParseBudget`] and says so.
93pub fn looks_like_cpp(source: &[u8]) -> bool {
94    sniff_header_with_budget(source, ParseBudget::UNLIMITED) == HeaderSniff::Cpp
95}
96
97/// What [`sniff_header`] found in a `.h` file's content.
98#[derive(Debug, Clone, Copy, PartialEq, Eq)]
99#[non_exhaustive]
100pub enum HeaderSniff {
101    /// Consistent with C: no construct that only C++ has. Not "confirmed C";
102    /// see the module documentation.
103    C,
104    /// A construct with no meaning in C, so the file can only be C++.
105    Cpp,
106    /// The C++ parse reached its budget, so the content was not read. A
107    /// caller should report the file as refused rather than pick an answer.
108    Undecided(BudgetExceeded),
109}
110
111/// [`looks_like_cpp`]'s answer within [`ParseBudget::default`]: `C` or `Cpp`
112/// as that function would say, or `Undecided` when the parse is stopped.
113pub fn sniff_header(source: &[u8]) -> HeaderSniff {
114    sniff_header_with_budget(source, ParseBudget::default())
115}
116
117/// [`sniff_header`] with a caller's budget. [`ParseBudget::UNLIMITED`] never
118/// answers `Undecided`.
119pub 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
142/// The 1-based inclusive line ranges of the arms only a C++ compiler reads:
143/// `#ifdef __cplusplus`, `#if defined(__cplusplus) [&& ...]`, and the `#else`
144/// of `#ifndef __cplusplus` / `#if !defined(__cplusplus)`. C++ there is how a
145/// C header serves C++ callers, so it is no evidence about the header itself.
146/// The scan is the line-based one in [`crate::dead_code`], which the
147/// unbalanced brace of an `extern "C"` guard cannot mis-nest.
148fn 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
156/// Whether `node` is a lambda whose capture list did not parse: how
157/// tree-sitter-cpp reads an Objective-C message send such as
158/// `[session setActive:true error:nil]`, where `setActive:true` is no capture.
159fn 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
166/// Whether `node`'s subtree holds a token that error recovery inserted. For
167/// `MA_API T f(void);`, where `MA_API` is a macro defined elsewhere,
168/// tree-sitter-cpp can read `T f` as the qualified name `T::f` with a
169/// `MISSING` `::`; the C++ syntax there is the parser's, not the file's.
170/// Only subtrees that hold an error are entered.
171fn 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
189/// State for the single walk in [`looks_like_cpp`].
190///
191/// `new_expression`, `delete_expression` and `reference_declarator` also come
192/// out of valid C: a pointer named `new` (`new->next = head`), a parameter
193/// named `delete`, or an expression statement `a & b;`. So these three are
194/// judged from their parent, where the walk can see their siblings without a
195/// `Node::parent` call per node (that walks down from the root each time).
196struct Scan<'a> {
197    /// An unambiguous marker, or a reference declarator in a C++-only position.
198    found: bool,
199    /// A `new` or `delete` expression parsed cleanly.
200    new_or_delete: bool,
201    /// `new` or `delete` is used as a name somewhere, which C++ never allows
202    /// outside the preprocessor.
203    keyword_as_name: bool,
204    /// Start byte of the name in the last `#define` or `#ifdef` seen. A
205    /// macro may be named `new` in C++ too (MFC's `#define new DEBUG_NEW`).
206    macro_name_start: Option<usize>,
207    /// End byte of the furthest `ERROR` node seen. In pre-order, a node that
208    /// starts before it lies inside that `ERROR`.
209    error_end: usize,
210    /// Reused for every node's children, rather than a new cursor per node.
211    cursor: TreeCursor<'a>,
212    /// From [`cpp_only_lines`]; a marker starting in one counts for nothing.
213    cpp_only: Vec<(usize, usize)>,
214    /// Byte range of the outermost brace block seen passed directly as a call
215    /// argument (`EM_ASM({ ... })`). Neither C nor C++ allows one there (a GNU
216    /// statement expression is parenthesized), so it is a macro's argument
217    /// text, often in another language. In pre-order, a node starting inside
218    /// the range lies inside the block.
219    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    /// Whether `node` starts inside [`Scan::macro_block`].
237    fn in_macro_block(&self, node: Node) -> bool {
238        (self.macro_block.0..self.macro_block.1).contains(&node.start_byte())
239    }
240
241    /// Records a brace block among `arguments`' children, unless it lies in
242    /// the block already recorded.
243    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    /// Whether `node` starts in an arm only a C++ compiler reads.
256    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    /// Judges the ambiguous markers among `parent`'s children. A marker beside
295    /// an `ERROR` or `MISSING` sibling, or with one inside it, is error
296    /// recovery and counts for nothing, except the `delete` of a deleted
297    /// function.
298    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
340/// Whether `child` of `parent` is the `= delete` of a deleted function
341/// (`void f(double) = delete;`). tree-sitter-cpp reads it as a
342/// `delete_expression` whose operand is `MISSING`, under an `init_declarator`
343/// that declares a function. C cannot initialize a function at all, so the
344/// operand is not checked.
345fn 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
353/// Whether `declarator`, a `reference_declarator` directly under the
354/// declaration `parent`, is how tree-sitter-cpp reads the C statement
355/// `a & b;`. As C++ that declares a reference with no initializer, which is
356/// only legal when `extern`; a reference to a function (`const T& g();`) has
357/// a function declarator inside instead of a bare name.
358fn is_bitwise_and_statement(parent: Node, declarator: Node) -> bool {
359    if parent.kind() != "declaration" {
360        return false;
361    }
362    // tree-sitter-cpp gives the inner declarator no field name.
363    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
373/// Node kinds that tree-sitter-cpp 0.23 only produces for constructs with no
374/// C meaning whatsoever. Verified against that version's `node-types.json`/
375/// `grammar.json` — not assumed from general knowledge of C++ syntax, since
376/// what matters is whether *this pinned grammar* actually emits a distinct,
377/// queryable node for it. The ambiguous `new_expression`,
378/// `delete_expression` and `reference_declarator` are judged in
379/// [`Scan::judge_children`] instead.
380fn 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    /// Wraps `body` in the usual `extern "C"` guard, which tree-sitter-cpp
489    /// can only half-parse: the brace opens and closes in different
490    /// `#ifdef` branches.
491    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        // `new` is declared in another header, so only error recovery is left.
533        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        // Known gap: the grammar leaves an ERROR beside the reference.
574        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    /// An include guard, the `extern "C"` guard, a typedef'd struct and one
609    /// declaration behind an export macro defined elsewhere. tree-sitter-cpp
610    /// reads `ma_log_callback ma_log_callback_init` as a qualified name with a
611    /// `MISSING` `::` here. The recovery is that sensitive: shorter names or
612    /// the declaration alone parse without it.
613    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        // Guards the fixture: the grammar must still build the false marker.
641        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            // operator overloads for C++ callers
661            "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        // A Qt header: `Q_OBJECT` is a macro tree-sitter-cpp cannot place.
686        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    /// `/* x...` then `lines` lines of ` */`: tree-sitter's error recovery on
751    /// it is quadratic in `lines`.
752    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        // Unbounded, this sniff takes about 8 s; within the default budget it
763        // stops in well under a second and says it could not decide.
764        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        // 5,000 declarations, about 200 KB of clean declarations: linear to
814        // parse, and well inside the budget's per-byte allowance.
815        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}