Skip to main content

normalize_languages/
vhdl.rs

1//! VHDL support.
2
3use crate::external_packages::ResolvedPackage;
4use crate::{Export, Import, Language, Symbol, SymbolKind, Visibility, VisibilityMechanism};
5use std::path::{Path, PathBuf};
6use tree_sitter::Node;
7
8/// VHDL language support.
9pub struct Vhdl;
10
11impl Language for Vhdl {
12    fn name(&self) -> &'static str {
13        "VHDL"
14    }
15    fn extensions(&self) -> &'static [&'static str] {
16        &["vhd", "vhdl"]
17    }
18    fn grammar_name(&self) -> &'static str {
19        "vhdl"
20    }
21
22    fn has_symbols(&self) -> bool {
23        true
24    }
25
26    fn container_kinds(&self) -> &'static [&'static str] {
27        &[
28            "entity_declaration",
29            "architecture_body",
30            "package_declaration",
31        ]
32    }
33
34    fn function_kinds(&self) -> &'static [&'static str] {
35        &["function_body", "procedure_body"]
36    }
37
38    fn type_kinds(&self) -> &'static [&'static str] {
39        &["full_type_declaration"]
40    }
41
42    fn import_kinds(&self) -> &'static [&'static str] {
43        &["use_clause"]
44    }
45
46    fn public_symbol_kinds(&self) -> &'static [&'static str] {
47        &["entity_declaration", "package_declaration"]
48    }
49
50    fn visibility_mechanism(&self) -> VisibilityMechanism {
51        VisibilityMechanism::AllPublic
52    }
53
54    fn extract_public_symbols(&self, node: &Node, content: &str) -> Vec<Export> {
55        let kind = match node.kind() {
56            "entity_declaration" => SymbolKind::Module,
57            "package_declaration" => SymbolKind::Module,
58            _ => return Vec::new(),
59        };
60
61        if let Some(name) = self.node_name(node, content) {
62            return vec![Export {
63                name: name.to_string(),
64                kind,
65                line: node.start_position().row + 1,
66            }];
67        }
68        Vec::new()
69    }
70
71    fn scope_creating_kinds(&self) -> &'static [&'static str] {
72        &[
73            "entity_declaration",
74            "architecture_body",
75            "function_body",
76            "procedure_body",
77        ]
78    }
79
80    fn control_flow_kinds(&self) -> &'static [&'static str] {
81        &["if_statement", "case_statement", "loop_statement"]
82    }
83
84    fn complexity_nodes(&self) -> &'static [&'static str] {
85        &["if_statement", "case_statement", "loop_statement"]
86    }
87
88    fn nesting_nodes(&self) -> &'static [&'static str] {
89        &["entity_declaration", "architecture_body"]
90    }
91
92    fn signature_suffix(&self) -> &'static str {
93        ""
94    }
95
96    fn extract_function(&self, node: &Node, content: &str, _in_container: bool) -> Option<Symbol> {
97        if node.kind() != "function_body" && node.kind() != "procedure_body" {
98            return None;
99        }
100
101        let name = self.node_name(node, content)?;
102        let text = &content[node.byte_range()];
103        let first_line = text.lines().next().unwrap_or(text);
104
105        Some(Symbol {
106            name: name.to_string(),
107            kind: SymbolKind::Function,
108            signature: first_line.trim().to_string(),
109            docstring: None,
110            attributes: Vec::new(),
111            start_line: node.start_position().row + 1,
112            end_line: node.end_position().row + 1,
113            visibility: Visibility::Public,
114            children: Vec::new(),
115            is_interface_impl: false,
116            implements: Vec::new(),
117        })
118    }
119
120    fn extract_container(&self, node: &Node, content: &str) -> Option<Symbol> {
121        if node.kind() != "entity_declaration"
122            && node.kind() != "architecture_body"
123            && node.kind() != "package_declaration"
124        {
125            return None;
126        }
127
128        let name = self.node_name(node, content)?;
129        let text = &content[node.byte_range()];
130        let first_line = text.lines().next().unwrap_or(text);
131
132        Some(Symbol {
133            name: name.to_string(),
134            kind: SymbolKind::Module,
135            signature: first_line.trim().to_string(),
136            docstring: None,
137            attributes: Vec::new(),
138            start_line: node.start_position().row + 1,
139            end_line: node.end_position().row + 1,
140            visibility: Visibility::Public,
141            children: Vec::new(),
142            is_interface_impl: false,
143            implements: Vec::new(),
144        })
145    }
146
147    fn extract_type(&self, node: &Node, content: &str) -> Option<Symbol> {
148        if node.kind() != "full_type_declaration" {
149            return None;
150        }
151
152        let name = self.node_name(node, content)?;
153        let text = &content[node.byte_range()];
154
155        Some(Symbol {
156            name: name.to_string(),
157            kind: SymbolKind::Type,
158            signature: text.trim().to_string(),
159            docstring: None,
160            attributes: Vec::new(),
161            start_line: node.start_position().row + 1,
162            end_line: node.end_position().row + 1,
163            visibility: Visibility::Public,
164            children: Vec::new(),
165            is_interface_impl: false,
166            implements: Vec::new(),
167        })
168    }
169
170    fn extract_docstring(&self, _node: &Node, _content: &str) -> Option<String> {
171        None
172    }
173
174    fn extract_attributes(&self, _node: &Node, _content: &str) -> Vec<String> {
175        Vec::new()
176    }
177
178    fn extract_imports(&self, node: &Node, content: &str) -> Vec<Import> {
179        if node.kind() != "use_clause" {
180            return Vec::new();
181        }
182
183        let text = &content[node.byte_range()];
184        vec![Import {
185            module: text.trim().to_string(),
186            names: Vec::new(),
187            alias: None,
188            is_wildcard: text.contains(".all"),
189            is_relative: false,
190            line: node.start_position().row + 1,
191        }]
192    }
193
194    fn format_import(&self, import: &Import, names: Option<&[&str]>) -> String {
195        // VHDL: use library.package.all; or use library.package.item;
196        let names_to_use: Vec<&str> = names
197            .map(|n| n.to_vec())
198            .unwrap_or_else(|| import.names.iter().map(|s| s.as_str()).collect());
199        if import.is_wildcard || names_to_use.is_empty() {
200            format!("use {}.all;", import.module)
201        } else if names_to_use.len() == 1 {
202            format!("use {}.{};", import.module, names_to_use[0])
203        } else {
204            names_to_use
205                .iter()
206                .map(|n| format!("use {}.{};", import.module, n))
207                .collect::<Vec<_>>()
208                .join("\n")
209        }
210    }
211
212    fn is_public(&self, _node: &Node, _content: &str) -> bool {
213        true
214    }
215    fn get_visibility(&self, _node: &Node, _content: &str) -> Visibility {
216        Visibility::Public
217    }
218
219    fn is_test_symbol(&self, _symbol: &crate::Symbol) -> bool {
220        false
221    }
222
223    fn embedded_content(&self, _node: &Node, _content: &str) -> Option<crate::EmbeddedBlock> {
224        None
225    }
226
227    fn container_body<'a>(&self, node: &'a Node<'a>) -> Option<Node<'a>> {
228        node.child_by_field_name("body")
229    }
230
231    fn body_has_docstring(&self, _body: &Node, _content: &str) -> bool {
232        false
233    }
234
235    fn node_name<'a>(&self, node: &Node, content: &'a str) -> Option<&'a str> {
236        node.child_by_field_name("name")
237            .map(|n| &content[n.byte_range()])
238    }
239
240    fn file_path_to_module_name(&self, path: &Path) -> Option<String> {
241        let ext = path.extension()?.to_str()?;
242        if !["vhd", "vhdl"].contains(&ext) {
243            return None;
244        }
245        let stem = path.file_stem()?.to_str()?;
246        Some(stem.to_string())
247    }
248
249    fn module_name_to_paths(&self, module: &str) -> Vec<String> {
250        vec![format!("{}.vhd", module), format!("{}.vhdl", module)]
251    }
252
253    fn lang_key(&self) -> &'static str {
254        "vhdl"
255    }
256
257    fn is_stdlib_import(&self, _: &str, _: &Path) -> bool {
258        false
259    }
260    fn find_stdlib(&self, _: &Path) -> Option<PathBuf> {
261        None
262    }
263    fn resolve_local_import(&self, _: &str, _: &Path, _: &Path) -> Option<PathBuf> {
264        None
265    }
266    fn resolve_external_import(&self, _: &str, _: &Path) -> Option<ResolvedPackage> {
267        None
268    }
269    fn get_version(&self, _: &Path) -> Option<String> {
270        None
271    }
272    fn find_package_cache(&self, _: &Path) -> Option<PathBuf> {
273        None
274    }
275    fn indexable_extensions(&self) -> &'static [&'static str] {
276        &["vhd", "vhdl"]
277    }
278    fn package_sources(&self, _: &Path) -> Vec<crate::PackageSource> {
279        Vec::new()
280    }
281
282    fn should_skip_package_entry(&self, name: &str, is_dir: bool) -> bool {
283        use crate::traits::{has_extension, skip_dotfiles};
284        if skip_dotfiles(name) {
285            return true;
286        }
287        !is_dir && !has_extension(name, self.indexable_extensions())
288    }
289
290    fn discover_packages(&self, _: &crate::PackageSource) -> Vec<(String, PathBuf)> {
291        Vec::new()
292    }
293
294    fn package_module_name(&self, entry_name: &str) -> String {
295        entry_name
296            .strip_suffix(".vhd")
297            .or_else(|| entry_name.strip_suffix(".vhdl"))
298            .unwrap_or(entry_name)
299            .to_string()
300    }
301
302    fn find_package_entry(&self, path: &Path) -> Option<PathBuf> {
303        if path.is_file() {
304            Some(path.to_path_buf())
305        } else {
306            None
307        }
308    }
309}
310
311#[cfg(test)]
312mod tests {
313    use super::*;
314    use crate::validate_unused_kinds_audit;
315
316    #[test]
317    fn unused_node_kinds_audit() {
318        #[rustfmt::skip]
319        let documented_unused: &[&str] = &[
320            // Declarations
321            "constant_declaration", "signal_declaration", "variable_declaration",
322            "shared_variable_declaration", "file_declaration", "alias_declaration",
323            "attribute_declaration", "attribute_specification", "component_declaration",
324            "group_template_declaration", "group_declaration", "subtype_declaration",
325            "incomplete_type_declaration", "disconnection_specification",
326            "configuration_specification", "configuration_declaration",
327            // Type definitions
328            "enumeration_type_definition", "physical_type_definition",
329            "primary_unit_declaration", "secondary_unit_declaration", "record_type_definition",
330            "element_declaration", "access_type_definition", "file_type_definition",
331            "constrained_array_definition", "unbounded_array_definition",
332            "index_subtype_definition", "numeric_type_definition",
333            // Protected type
334            "protected_type_declaration", "protected_type_body",
335            // Procedures/functions
336            "procedure_declaration", "function_declaration",
337            "procedure_instantiation_declaration", "function_instantiation_declaration",
338            "procedure_parameter_clause", "function_parameter_clause",
339            "procedure_call_statement",
340            // Interface declarations
341            "constant_interface_declaration", "signal_interface_declaration",
342            "variable_interface_declaration", "file_interface_declaration",
343            "type_interface_declaration", "procedure_interface_declaration",
344            "function_interface_declaration", "package_interface_declaration",
345            "interface_subprogram_default",
346            // Process/statements
347            "process_statement", "concurrent_statement_part", "sequence_of_statements",
348            "wait_statement", "assertion_statement", "report_statement",
349            "next_statement", "exit_statement", "return_statement", "null_statement",
350            // Assignments
351            "simple_waveform_assignment", "conditional_waveform_assignment",
352            "selected_waveform_assignment", "simple_force_assignment",
353            "conditional_force_assignment", "selected_force_assignment",
354            "simple_variable_assignment", "conditional_variable_assignment",
355            "selected_variable_assignment", "simple_release_assignment",
356            // Waveforms
357            "waveforms", "waveform_element", "conditional_waveforms",
358            "selected_waveforms", "alternative_selected_waveforms",
359            "alternative_conditional_waveforms",
360            // Expressions
361            "expression", "simple_expression", "shift_expression", "logical_expression",
362            "conditional_expression", "parenthesized_expression", "qualified_expression",
363            "alternative_conditional_expressions", "alternative_selected_expressions",
364            "conditional_expressions", "selected_expressions", "expression_list",
365            "string_expression", "time_expression", "severity_expression",
366            "inertial_expression", "default_expression", "relation",
367            "exponentiation", "concatenation", "reduction", "condition",
368            // Generate
369            "for_generate_statement", "if_generate_statement", "case_generate_statement",
370            "if_generate", "elsif_generate", "else_generate", "case_generate_alternative",
371            "generate_statement_body", "generate_statement_element",
372            // Block
373            "block_statement", "block_header", "block_configuration", "block_specification",
374            // Component/instantiation
375            "component_instantiation_statement", "verification_unit_binding_indication",
376            "verification_unit_list", "component_configuration", "binding_indication",
377            "port_map_aspect", "generic_map_aspect",
378            "entity_instantiation", "configuration_instantiation", "component_instantiation",
379            "instantiation_list", "all", "component_header", "component_map_aspect",
380            // Clauses
381            "context_clause", "library_clause", "generic_clause", "port_clause",
382            // File
383            "file_open_information", "file_open_kind",
384            // Identifiers
385            "identifier", "extended_identifier", "identifier_list", "operator_symbol",
386            "label", "simple_name", "extended_simple_name",
387            "external_signal_name", "external_constant_name", "external_variable_name",
388            "pathname_element", "relative_pathname", "package_pathname", "absolute_pathname",
389            // Control flow helpers
390            "if", "elsif", "else", "return", "for_loop", "while_loop",
391            // Case
392            "case_statement_alternative",
393            // Packages
394            "package_body", "package_instantiation_declaration", "context_declaration",
395            "package_header", "package_map_aspect",
396            // Entity
397            "entity_specification", "entity_class", "entity_class_entry",
398            "entity_class_entry_list", "entity_header", "entity_name_list",
399            "entity_designator",
400            // Type/subtype
401            "type_mark", "subtype_indication", "resolution_function",
402            "range_constraint", "array_constraint", "record_constraint",
403            "record_element_constraint", "index_constraint", "array_element_constraint",
404            "parenthesized_resolution", "record_resolution", "record_element_resolution",
405            // Signal specification
406            "guarded_signal_specification", "signal_list", "signal_kind",
407            // Function
408            "function_call",
409            // Parameter
410            "parameter_specification",
411            // Associations
412            "association_list", "positional_association_element", "named_association_element",
413            "default",
414            // Names
415            "attribute_name", "slice_name", "selected_name", "ambiguous_name",
416            "predefined_designator",
417            // Targets
418            "aggregate", "positional_element_association", "named_element_association",
419            "choices", "others",
420            // Ranges
421            "ascending_range", "descending_range",
422            // Literals
423            "physical_literal", "string_literal", "bit_string_literal",
424            "character_literal", "integer_decimal", "real_decimal", "based_integer",
425            "based_real", "allocator", "null",
426            // Operators
427            "sign", "factor", "term",
428            // Signatures
429            "signature", "tool_directive",
430            // Library
431            "design_unit", "design_file", "logical_name_list",
432            "context_reference", "context_list",
433            // Subprogram
434            "subprogram_header", "subprogram_map_aspect",
435            // Concurrent statements
436            "conditional_concurrent_signal_assignment",
437            "selected_concurrent_signal_assignment", "simple_concurrent_signal_assignment",
438            // Group
439            "group_constituent_list",
440            // Misc syntax elements
441            "force_mode", "declarative_part", "open", "semicolon",
442            "transport", "inertial", "unaffected", "delay_mechanism",
443            "sensitivity_list", "same", "any", "boolean", "comment",
444            // PSL (Property Specification Language)
445            "PSL_Verification_Unit_Body", "PSL_Property_Declaration",
446            "PSL_Sequence_Declaration", "PSL_Clock_Declaration",
447            "PSL_Built_In_Function_Call", "PSL_Union_Expression",
448            "PSL_Expression", "PSL_Identifier", "PSL_HDL_Type", "PSL_Any_Type",
449            "PSL_Type_Class", "PSL_Formal_Parameter", "PSL_Formal_Parameter_List",
450            "PSL_Parameters_Definition", "PSL_Parameter_Specification",
451            "PSL_Constant_Parameter_Specification", "PSL_Temporal_Parameter_Specification",
452            "PSL_Assert_Directive", "PSL_Assume_Directive", "PSL_Assume_Guarantee_Directive",
453            "PSL_Cover_Directive", "PSL_Restrict_Directive", "PSL_Restrict_Guarantee_Directive",
454            "PSL_Fairness_Directive", "PSL_Strong_Fairness_Directive",
455            "PSL_Property_Instance", "PSL_Sequence_Instance", "PSL_Actual_Parameter_List",
456            "PSL_Property_Replicator", "PSL_Count", "PSL_Number",
457            "PSL_Boolean", "PSL_Value_Set",
458            "PSL_Compound_SERE", "PSL_Repeated_SERE",
459            "PSL_Braced_SERE", "PSL_Clocked_SERE", "PSL_Simple_SERE",
460            "PSL_Parameterized_SERE", "PSL_Ambiguous_Instance",
461            "PSL_Parameterized_Property", "PSL_Index_Range",
462            "PSL_Actual_Parameter",
463            "PSL_Parenthesized_FL_Property", "PSL_Sequential_FL_Property",
464            "PSL_Clocked_FL_Property", "PSL_Invariant_FL_Property",
465            "PSL_Ocurrence_FL_Property", "PSL_Implication_FL_Property",
466            "PSL_Logical_FL_Property", "PSL_Factor_FL_Property",
467            "PSL_Extended_Ocurrence_FL_Property", "PSL_Termination_FL_Property",
468            "PSL_Bounding_FL_Property", "PSL_Suffix_Implication_FL_Property",
469            "PSL_VUnit", "PSL_VProp", "PSL_VMode",
470            "PSL_Hierarchical_HDL_Name", "PSL_Inherit_Spec",
471        ];
472        validate_unused_kinds_audit(&Vhdl, documented_unused)
473            .expect("VHDL unused node kinds audit failed");
474    }
475}