1use crate::{ContainerBody, Import, Language, LanguageSymbols, Visibility};
4use tree_sitter::Node;
5
6pub struct Cpp;
8
9impl Language for Cpp {
10 fn name(&self) -> &'static str {
11 "C++"
12 }
13 fn extensions(&self) -> &'static [&'static str] {
14 &["cpp", "cc", "cxx", "hpp", "hh", "hxx"]
15 }
16 fn grammar_name(&self) -> &'static str {
17 "cpp"
18 }
19
20 fn as_symbols(&self) -> Option<&dyn LanguageSymbols> {
21 Some(self)
22 }
23
24 fn signature_suffix(&self) -> &'static str {
25 " {}"
26 }
27
28 fn extract_docstring(&self, node: &Node, content: &str) -> Option<String> {
29 let mut prev = node.prev_sibling();
30 while let Some(sibling) = prev {
31 if sibling.kind() == "comment" {
32 let text = &content[sibling.byte_range()];
33 if text.starts_with("/**") {
34 let lines: Vec<&str> = text
35 .strip_prefix("/**")
36 .unwrap_or(text)
37 .strip_suffix("*/")
38 .unwrap_or(text)
39 .lines()
40 .map(|l| l.trim().strip_prefix('*').unwrap_or(l).trim())
41 .filter(|l| !l.is_empty())
42 .collect();
43 if !lines.is_empty() {
44 return Some(lines.join(" "));
45 }
46 }
47 return None;
48 }
49 if sibling.kind() == "template_declaration" {
50 prev = sibling.prev_sibling();
51 continue;
52 }
53 return None;
54 }
55 None
56 }
57
58 fn extract_attributes(&self, node: &Node, content: &str) -> Vec<String> {
59 let mut attrs = Vec::new();
60 let mut cursor = node.walk();
61 for child in node.children(&mut cursor) {
62 match child.kind() {
63 "attribute_declaration" => {
64 let text = content[child.byte_range()].trim();
66 attrs.push(text.to_string());
67 }
68 "attribute_specifier" => {
69 let text = content[child.byte_range()].trim();
71 attrs.push(text.to_string());
72 }
73 "ms_declspec_modifier" => {
74 let text = content[child.byte_range()].trim();
76 attrs.push(text.to_string());
77 }
78 _ => {}
79 }
80 }
81 attrs
82 }
83
84 fn refine_kind(
85 &self,
86 node: &Node,
87 _content: &str,
88 tag_kind: crate::SymbolKind,
89 ) -> crate::SymbolKind {
90 match node.kind() {
91 "struct_specifier" => crate::SymbolKind::Struct,
92 "enum_specifier" => crate::SymbolKind::Enum,
93 _ => tag_kind,
94 }
95 }
96
97 fn extract_implements(&self, node: &Node, content: &str) -> crate::ImplementsInfo {
98 let mut implements = Vec::new();
99 let mut cursor = node.walk();
100 for child in node.children(&mut cursor) {
101 if child.kind() == "base_class_clause" {
102 let mut bc = child.walk();
103 for base in child.children(&mut bc) {
104 if base.kind() == "type_identifier" {
105 implements.push(content[base.byte_range()].to_string());
106 }
107 }
108 }
109 }
110 crate::ImplementsInfo {
111 is_interface: false,
112 implements,
113 }
114 }
115
116 fn build_signature(&self, node: &Node, content: &str) -> String {
117 match node.kind() {
118 "function_definition" => {
119 if let Some(declarator) = node.child_by_field_name("declarator")
120 && let Some(name) = find_identifier(&declarator, content)
121 {
122 return name.to_string();
123 }
124 let text = &content[node.byte_range()];
125 text.lines().next().unwrap_or(text).trim().to_string()
126 }
127 "class_specifier" => {
128 let name = self.node_name(node, content).unwrap_or("");
129 format!("class {}", name)
130 }
131 "struct_specifier" => {
132 let name = self.node_name(node, content).unwrap_or("");
133 format!("struct {}", name)
134 }
135 _ => {
136 let text = &content[node.byte_range()];
137 text.lines().next().unwrap_or(text).trim().to_string()
138 }
139 }
140 }
141
142 fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
143 if node.kind() != "preproc_include" {
144 return Vec::new();
145 }
146
147 let line = node.start_position().row + 1;
148 let mut cursor = node.walk();
149 for child in node.children(&mut cursor) {
150 if child.kind() == "string_literal" || child.kind() == "system_lib_string" {
151 let text = &content[child.byte_range()];
152 let module = text
153 .trim_matches(|c| c == '"' || c == '<' || c == '>')
154 .to_string();
155 let is_relative = text.starts_with('"');
156 return vec![Import {
157 module,
158 names: Vec::new(),
159 alias: None,
160 is_wildcard: false,
161 is_relative,
162 line,
163 }];
164 }
165 }
166 Vec::new()
167 }
168
169 fn format_import(&self, import: &Import, _names: Option<&[&str]>) -> String {
170 if import.module.starts_with('<') || import.module.ends_with('>') {
172 format!("#include {}", import.module)
173 } else {
174 format!("#include \"{}\"", import.module)
175 }
176 }
177
178 fn is_test_symbol(&self, symbol: &crate::Symbol) -> bool {
179 let name = symbol.name.as_str();
180 match symbol.kind {
181 crate::SymbolKind::Function | crate::SymbolKind::Method => name.starts_with("test_"),
182 crate::SymbolKind::Module => name == "tests" || name == "test",
183 _ => false,
184 }
185 }
186
187 fn test_file_globs(&self) -> &'static [&'static str] {
188 &[
189 "**/test_*.cpp",
190 "**/*_test.cpp",
191 "**/test_*.cc",
192 "**/*_test.cc",
193 "**/tests/**/*.cpp",
194 "**/tests/**/*.cc",
195 ]
196 }
197
198 fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
199 node.child_by_field_name("body")
200 }
201
202 fn analyze_container_body(
203 &self,
204 body_node: &Node,
205 content: &str,
206 inner_indent: &str,
207 ) -> Option<ContainerBody> {
208 crate::body::analyze_brace_body(body_node, content, inner_indent)
209 }
210
211 fn get_visibility(&self, node: &Node, content: &str) -> Visibility {
212 let mut prev = node.prev_sibling();
216 while let Some(sibling) = prev {
217 if sibling.kind() == "access_specifier" {
218 let spec = content[sibling.byte_range()].trim().trim_end_matches(':');
219 return match spec {
220 "public" => Visibility::Public,
221 "protected" => Visibility::Protected,
222 "private" => Visibility::Private,
223 _ => Visibility::Public,
224 };
225 }
226 prev = sibling.prev_sibling();
227 }
228 if node
231 .parent()
232 .and_then(|p| p.parent())
233 .map(|g| g.kind() == "class_specifier")
234 .unwrap_or(false)
235 {
236 return Visibility::Private;
237 }
238 Visibility::Public
239 }
240
241 fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
242 if let Some(name_node) = node.child_by_field_name("name") {
243 return Some(&content[name_node.byte_range()]);
244 }
245 if let Some(declarator) = node.child_by_field_name("declarator") {
246 return find_identifier(&declarator, content);
247 }
248 None
249 }
250}
251
252impl LanguageSymbols for Cpp {}
253
254fn find_identifier<'a>(node: &Node, content: &'a str) -> Option<&'a str> {
255 if node.kind() == "identifier" || node.kind() == "field_identifier" {
256 return Some(&content[node.byte_range()]);
257 }
258 let mut cursor = node.walk();
259 for child in node.children(&mut cursor) {
260 if let Some(id) = find_identifier(&child, content) {
261 return Some(id);
262 }
263 }
264 None
265}
266
267#[cfg(test)]
268mod tests {
269 use super::*;
270 use crate::validate_unused_kinds_audit;
271
272 #[test]
275 fn unused_node_kinds_audit() {
276 #[rustfmt::skip]
277 let documented_unused: &[&str] = &[
278 "access_specifier", "base_class_clause", "bitfield_clause", "condition_clause", "declaration_list", "default_method_clause", "delete_method_clause", "dependent_type", "destructor_name", "enumerator", "enumerator_list", "field_declaration", "field_declaration_list", "field_expression", "field_identifier", "identifier", "init_statement", "linkage_specification", "module_name", "module_partition", "namespace_identifier", "nested_namespace_specifier", "operator_name", "parameter_declaration", "primitive_type", "pure_virtual_clause", "ref_qualifier", "sized_type_specifier", "statement_identifier", "static_assert_declaration", "storage_class_specifier", "structured_binding_declarator", "type_descriptor", "type_identifier", "type_parameter_declaration", "type_qualifier", "union_specifier", "using_declaration", "variadic_parameter_declaration", "variadic_type_parameter_declaration", "virtual_specifier", "else_clause", "noexcept", "alignof_expression", "assignment_expression", "binary_expression", "call_expression", "cast_expression", "co_await_expression", "co_return_statement", "co_yield_statement", "comma_expression", "compound_literal_expression", "delete_expression", "extension_expression", "fold_expression", "generic_expression", "gnu_asm_expression", "new_expression", "offsetof_expression", "parenthesized_expression","pointer_expression", "reflect_expression", "sizeof_expression", "splice_expression", "subscript_expression", "unary_expression", "update_expression", "template_declaration", "template_function", "template_method", "template_template_parameter_declaration", "template_type", "lambda_capture_initializer", "lambda_capture_specifier", "lambda_declarator", "lambda_default_capture", "lambda_specifier", "abstract_function_declarator", "explicit_function_specifier", "explicit_object_parameter_declaration", "operator_cast", "optional_parameter_declaration", "optional_type_parameter_declaration", "placeholder_type_specifier", "pointer_type_declarator", "trailing_return_type", "concept_definition", "requires_clause", "requires_expression", "type_requirement", "export_declaration", "global_module_fragment_declaration", "import_declaration", "module_declaration", "private_module_fragment_declaration", "preproc_elif", "preproc_elifdef", "preproc_else", "preproc_function_def", "preproc_if", "preproc_ifdef", "splice_specifier", "splice_type_specifier", "alias_declaration", "alignas_qualifier", "attribute_declaration", "attribute_specifier", "attributed_statement", "consteval_block_declaration", "decltype", "expansion_statement", "expression_statement", "friend_declaration", "gnu_asm_qualifier", "labeled_statement", "namespace_alias_definition", "qualified_identifier", "throw_specifier", "ms_based_modifier", "ms_call_modifier", "ms_declspec_modifier", "ms_pointer_modifier", "ms_restrict_modifier", "ms_signed_ptr_modifier", "ms_unaligned_ptr_modifier", "ms_unsigned_ptr_modifier", "seh_except_clause", "seh_finally_clause", "seh_leave_statement", "seh_try_statement", "function_definition",
436 "case_statement",
437 "for_range_loop",
438 "conditional_expression",
439 "do_statement",
440 "if_statement",
441 "catch_clause",
442 "while_statement",
443 "lambda_expression",
444 "continue_statement",
445 "switch_statement",
446 "throw_statement",
447 "try_statement",
448 "return_statement",
449 "break_statement",
450 "compound_statement",
451 "namespace_definition",
452 "goto_statement",
453 "for_statement",
454 ];
455
456 validate_unused_kinds_audit(&Cpp, documented_unused)
457 .expect("C++ unused node kinds audit failed");
458 }
459}