sway_lsp/capabilities/
inlay_hints.rs

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
use crate::{
    config::InlayHintsConfig,
    core::{
        session::Session,
        token::{get_range_from_span, TypedAstToken},
    },
};
use lsp_types::{self, Range, Url};
use std::sync::Arc;
use sway_core::{
    language::ty::{TyDecl, TyExpression, TyExpressionVariant},
    type_system::TypeInfo,
};
use sway_types::{Ident, Spanned};

#[derive(Clone, Debug, PartialEq, Eq)]
pub enum InlayKind {
    TypeHint,
    Parameter,
}

#[derive(Debug)]
pub struct InlayHint {
    pub range: Range,
    pub kind: InlayKind,
    pub label: String,
}

/// Generates inlay hints for the provided range.
pub fn inlay_hints(
    session: Arc<Session>,
    uri: &Url,
    range: &Range,
    config: &InlayHintsConfig,
) -> Option<Vec<lsp_types::InlayHint>> {
    let _span = tracing::trace_span!("inlay_hints").entered();

    if !config.type_hints {
        return None;
    }

    // 1. Iterate through all tokens in the file
    // 2. Filter for TypedVariableDeclaration tokens within the provided range
    // 3. For each variable declaration:
    //    a. If it's a function application, generate parameter hints
    //    b. If it doesn't have a type ascription and its type is known:
    //       - Look up the type information
    //       - Generate a type hint
    // 4. Collect all generated hints into a single vector
    let hints: Vec<lsp_types::InlayHint> = session
        .token_map()
        .tokens_for_file(uri)
        .filter_map(|item| {
            let token = item.value();
            token.typed.as_ref().and_then(|t| match t {
                TypedAstToken::TypedDeclaration(TyDecl::VariableDecl(var_decl)) => {
                    let var_range = get_range_from_span(&var_decl.name.span());
                    if var_range.start >= range.start && var_range.end <= range.end {
                        Some(var_decl.clone())
                    } else {
                        None
                    }
                }
                _ => None,
            })
        })
        .flat_map(|var| {
            let mut hints = Vec::new();

            // Function parameter hints
            if let TyExpressionVariant::FunctionApplication { arguments, .. } = &var.body.expression
            {
                hints.extend(handle_function_parameters(arguments, config));
            }

            // Variable declaration hints
            if var.type_ascription.call_path_tree.is_none() {
                let type_info = session.engines.read().te().get(var.type_ascription.type_id);
                if !matches!(
                    *type_info,
                    TypeInfo::Unknown | TypeInfo::UnknownGeneric { .. }
                ) {
                    let range = get_range_from_span(&var.name.span());
                    let kind = InlayKind::TypeHint;
                    let label = format!("{}", session.engines.read().help_out(var.type_ascription));
                    let inlay_hint = InlayHint { range, kind, label };
                    hints.push(self::inlay_hint(config, inlay_hint));
                }
            }
            hints
        })
        .collect();

    Some(hints)
}

fn handle_function_parameters(
    arguments: &[(Ident, TyExpression)],
    config: &InlayHintsConfig,
) -> Vec<lsp_types::InlayHint> {
    arguments
        .iter()
        .flat_map(|(name, exp)| {
            let mut hints = Vec::new();
            let (should_create_hint, span) = match &exp.expression {
                TyExpressionVariant::Literal(_)
                | TyExpressionVariant::ConstantExpression { .. }
                | TyExpressionVariant::Tuple { .. }
                | TyExpressionVariant::Array { .. }
                | TyExpressionVariant::ArrayIndex { .. }
                | TyExpressionVariant::FunctionApplication { .. }
                | TyExpressionVariant::StructFieldAccess { .. }
                | TyExpressionVariant::TupleElemAccess { .. } => (true, &exp.span),
                TyExpressionVariant::EnumInstantiation {
                    call_path_binding, ..
                } => (true, &call_path_binding.span),
                _ => (false, &exp.span),
            };
            if should_create_hint {
                let range = get_range_from_span(span);
                let kind = InlayKind::Parameter;
                let label = name.as_str().to_string();
                let inlay_hint = InlayHint { range, kind, label };
                hints.push(self::inlay_hint(config, inlay_hint));
            }
            // Handle nested function applications
            if let TyExpressionVariant::FunctionApplication {
                arguments: nested_args,
                ..
            } = &exp.expression
            {
                hints.extend(handle_function_parameters(nested_args, config));
            }
            hints
        })
        .collect::<Vec<_>>()
}

fn inlay_hint(config: &InlayHintsConfig, inlay_hint: InlayHint) -> lsp_types::InlayHint {
    let truncate_label = |label: String| -> String {
        if let Some(max_length) = config.max_length {
            if label.len() > max_length {
                format!("{}...", &label[..max_length.saturating_sub(3)])
            } else {
                label
            }
        } else {
            label
        }
    };

    let label = match inlay_hint.kind {
        InlayKind::TypeHint if config.render_colons => format!(": {}", inlay_hint.label),
        InlayKind::Parameter if config.render_colons => format!("{}: ", inlay_hint.label),
        _ => inlay_hint.label,
    };

    lsp_types::InlayHint {
        position: match inlay_hint.kind {
            // after annotated thing
            InlayKind::TypeHint => inlay_hint.range.end,
            InlayKind::Parameter => inlay_hint.range.start,
        },
        label: lsp_types::InlayHintLabel::String(truncate_label(label)),
        kind: match inlay_hint.kind {
            InlayKind::TypeHint => Some(lsp_types::InlayHintKind::TYPE),
            InlayKind::Parameter => Some(lsp_types::InlayHintKind::PARAMETER),
        },
        tooltip: None,
        padding_left: Some(match inlay_hint.kind {
            InlayKind::TypeHint => !config.render_colons,
            InlayKind::Parameter => false,
        }),
        padding_right: Some(match inlay_hint.kind {
            InlayKind::TypeHint => false,
            InlayKind::Parameter => !config.render_colons,
        }),
        text_edits: None,
        data: None,
    }
}