1 //! This module contains utilities for turning SyntaxNodes and HIR types
2 //! into types that may be used to render in a UI.
5 ast::{self, AstNode, AttrsOwner, GenericParamsOwner, NameOwner},
6 SyntaxKind::{ATTR, COMMENT},
9 use ast::VisibilityOwner;
12 pub fn function_declaration(node: &ast::Fn) -> String {
13 let mut buf = String::new();
14 if let Some(vis) = node.visibility() {
15 format_to!(buf, "{} ", vis);
17 if node.async_token().is_some() {
18 format_to!(buf, "async ");
20 if node.const_token().is_some() {
21 format_to!(buf, "const ");
23 if node.unsafe_token().is_some() {
24 format_to!(buf, "unsafe ");
26 if let Some(abi) = node.abi() {
27 // Keyword `extern` is included in the string.
28 format_to!(buf, "{} ", abi);
30 if let Some(name) = node.name() {
31 format_to!(buf, "fn {}", name)
33 if let Some(type_params) = node.generic_param_list() {
34 format_to!(buf, "{}", type_params);
36 if let Some(param_list) = node.param_list() {
37 let params: Vec<String> = param_list
40 .map(|self_param| self_param.to_string())
41 .chain(param_list.params().map(|param| param.to_string()))
43 // Useful to inline parameters
44 format_to!(buf, "({})", params.join(", "));
46 if let Some(ret_type) = node.ret_type() {
47 if ret_type.ty().is_some() {
48 format_to!(buf, " {}", ret_type);
51 if let Some(where_clause) = node.where_clause() {
52 format_to!(buf, "\n{}", where_clause);
57 pub fn const_label(node: &ast::Const) -> String {
58 let label: String = node
60 .children_with_tokens()
61 .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR))
62 .map(|node| node.to_string())
65 label.trim().to_owned()
68 pub fn type_label(node: &ast::TypeAlias) -> String {
69 let label: String = node
71 .children_with_tokens()
72 .filter(|child| !(child.kind() == COMMENT || child.kind() == ATTR))
73 .map(|node| node.to_string())
76 label.trim().to_owned()
79 pub fn macro_label(node: &ast::Macro) -> String {
80 let name = node.name().map(|name| name.syntax().text().to_string()).unwrap_or_default();
82 ast::Macro::MacroRules(node) => {
83 let vis = if node.has_atom_attr("macro_export") { "#[macro_export]\n" } else { "" };
84 format!("{}macro_rules! {}", vis, name)
86 ast::Macro::MacroDef(node) => {
87 let mut s = String::new();
88 if let Some(vis) = node.visibility() {
89 format_to!(s, "{} ", vis);
91 format_to!(s, "macro {}", name);