Skip to main content

bynk_lsp/
fill_arms.rs

1//! #2100 slice 3: the fill-match-arms quick fix. It adds an arm for every
2//! variant (or `Bool` value, or the `_` an unbounded literal match or an
3//! extensible enum needs) that a non-exhaustive `match` leaves uncovered.
4//!
5//! The checker raises one `bynk.types.non_exhaustive_match` per missing
6//! witness, and one `bynk.types.extensible_match_needs_wildcard` when the
7//! enum may gain variants (its witness is the wildcard, `_` or `Some(_)`,
8//! that covers them). Each carries a `HasPlaceholders` suggestion inserting
9//! `\n<witness> => <default>` after the last arm, where `<default>` is a
10//! typed default of the arm result type (`0`, `""`, `None`, `[]`, …). The
11//! suggestion is never a one-click quick fix or a fix-all candidate (both take
12//! only `MachineApplicable`). This module collects every suggestion on one
13//! `match` into one action and lays the arms out the way `bynk-fmt` prints
14//! them: one per line at the last arm's indentation, each ending in `,`.
15//!
16//! The action is offered only when **every** witness of the match has a
17//! suggestion. A result type with no default (a record, a user sum, a refined
18//! type) or a `let … else match` means no action, and so does a match with more
19//! missing cases than the checker lists (it reports the first eight and a count,
20//! with no suggestions). Filling only some of the arms would still leave the
21//! match non-exhaustive.
22//!
23//! Fill-arms rides the unfiltered lightbulb request, so it's listed without
24//! an edit (`data` names the match) and the edit is computed, and re-checked
25//! (DECISION B), in `codeAction/resolve`.
26
27use bynk_syntax::error::Applicability;
28use bynk_syntax::span::Span;
29use tower_lsp::lsp_types::*;
30
31/// The categories a missing arm is reported under: a missing variant (or
32/// value), and the wildcard an extensible enum's future variants need.
33const CATEGORIES: [&str; 2] = [
34    "bynk.types.non_exhaustive_match",
35    "bynk.types.extensible_match_needs_wildcard",
36];
37const MESSAGE_PREFIX: &str = "add a match arm for ";
38const DATA_TAG: &str = "bynk.fillMatchArms";
39
40/// The `match` spans (the non-exhaustive diagnostics' span) that intersect
41/// `requested` and have an arm suggestion for every missing witness, in
42/// source order.
43pub fn fillable(diagnostics: &[bynk_ide::Diagnostic], requested: Span) -> Vec<Span> {
44    let mut spans: Vec<Span> = diagnostics
45        .iter()
46        .filter(|d| CATEGORIES.contains(&d.error.category))
47        .map(|d| d.error.span)
48        .filter(|s| s.start <= requested.end && requested.start <= s.end)
49        .collect();
50    spans.sort_by_key(|s| (s.start, s.end));
51    spans.dedup_by(|a, b| same_span(*a, *b));
52    spans.retain(|s| arms(diagnostics, *s).is_some());
53    spans
54}
55
56/// Spans compare by offsets: a span rebuilt from an action's `data` has no
57/// file id.
58fn same_span(a: Span, b: Span) -> bool {
59    (a.start, a.end) == (b.start, b.end)
60}
61
62/// The `(anchor, arm text)` for every missing witness of the match at
63/// `match_span`, or `None` unless every one of them has a suggestion and they
64/// share one anchor.
65fn arms(diagnostics: &[bynk_ide::Diagnostic], match_span: Span) -> Option<(usize, Vec<String>)> {
66    let mut anchor = None;
67    let mut out = Vec::new();
68    for d in diagnostics
69        .iter()
70        .filter(|d| CATEGORIES.contains(&d.error.category) && same_span(d.error.span, match_span))
71    {
72        let s = d.error.suggestions.iter().find(|s| {
73            s.applicability == Applicability::HasPlaceholders
74                && s.message.starts_with(MESSAGE_PREFIX)
75        })?;
76        let [(span, text)] = s.edits.as_slice() else {
77            return None;
78        };
79        if *anchor.get_or_insert(span.start) != span.start || span.start != span.end {
80            return None;
81        }
82        let arm = text.trim_start_matches('\n').to_string();
83        if !out.contains(&arm) {
84            out.push(arm);
85        }
86    }
87    Some((anchor?, out))
88}
89
90/// The edits that fill the match at `match_span` in `text`, laid out as
91/// `bynk-fmt` prints arms. `None` when there is nothing to fill or the last
92/// arm's line doesn't allow it: the match closes on that line, or the arm
93/// shares it with other code. A `bynk-fmt`-canonical file stays canonical.
94pub fn edits(
95    text: &str,
96    diagnostics: &[bynk_ide::Diagnostic],
97    match_span: Span,
98) -> Option<Vec<(Span, String)>> {
99    let (anchor, arms) = arms(diagnostics, match_span)?;
100    let line_start = text[..anchor].rfind('\n').map_or(0, |i| i + 1);
101    let line_end = text[anchor..].find('\n').map_or(text.len(), |i| anchor + i);
102    let indent: String = text[line_start..]
103        .chars()
104        .take_while(|c| *c == ' ' || *c == '\t')
105        .collect();
106    let rest = text[anchor..line_end].trim_start();
107    let (has_comma, after) = match rest.strip_prefix(',') {
108        Some(after) => (true, after.trim_start()),
109        None => (false, rest),
110    };
111    if !after.is_empty() && !after.starts_with("//") {
112        return None;
113    }
114    let mut out = Vec::new();
115    if !has_comma {
116        out.push((Span::new(anchor, anchor), ",".to_string()));
117    }
118    let inserted: String = arms.iter().map(|a| format!("\n{indent}{a},")).collect();
119    out.push((Span::new(line_end, line_end), inserted));
120
121    let filled = crate::fix_all::apply(text, &out);
122    let opts = bynk_fmt::FormatOptions::default();
123    let canonical = |s: &str| bynk_fmt::format_source(s, &opts).is_ok_and(|f| f == s);
124    if canonical(text) && !canonical(&filled) {
125        return None;
126    }
127    Some(out)
128}
129
130/// The listed (unresolved) action for the match at `match_span`: a quick fix
131/// on its diagnostics, with no edit yet. `data` carries what
132/// `codeAction/resolve` needs.
133pub fn listed(
134    diagnostics: &[bynk_ide::Diagnostic],
135    match_span: Span,
136    uri: &Url,
137    version: Option<i32>,
138) -> CodeActionOrCommand {
139    // The arms actually inserted, so the title matches the edit.
140    let count = arms(diagnostics, match_span).map_or(0, |(_, arms)| arms.len());
141    CodeActionOrCommand::CodeAction(CodeAction {
142        title: if count == 1 {
143            "Fill the missing match arm".to_string()
144        } else {
145            format!("Fill {count} missing match arms")
146        },
147        kind: Some(CodeActionKind::QUICKFIX),
148        data: Some(serde_json::json!({
149            "kind": DATA_TAG,
150            "uri": uri.as_str(),
151            "version": version,
152            "start": match_span.start,
153            "end": match_span.end,
154        })),
155        ..Default::default()
156    })
157}
158
159/// What a listed fill-arms action's `data` names, or `None` when the action
160/// is not one of ours.
161pub struct Target {
162    pub uri: Url,
163    pub version: Option<i32>,
164    pub match_span: Span,
165}
166
167impl Target {
168    pub fn of(action: &CodeAction) -> Option<Self> {
169        let data = action.data.as_ref()?;
170        if data.get("kind")?.as_str()? != DATA_TAG {
171            return None;
172        }
173        Some(Target {
174            uri: Url::parse(data.get("uri")?.as_str()?).ok()?,
175            version: data
176                .get("version")
177                .and_then(serde_json::Value::as_i64)
178                .and_then(|v| i32::try_from(v).ok()),
179            match_span: Span::new(
180                usize::try_from(data.get("start")?.as_u64()?).ok()?,
181                usize::try_from(data.get("end")?.as_u64()?).ok()?,
182            ),
183        })
184    }
185}
186
187/// `action` with its versioned edit filled in.
188pub fn resolve(
189    mut action: CodeAction,
190    text: &str,
191    edits: &[(Span, String)],
192    uri: &Url,
193    version: Option<i32>,
194) -> CodeAction {
195    action.edit = Some(WorkspaceEdit {
196        changes: None,
197        document_changes: Some(DocumentChanges::Edits(vec![TextDocumentEdit {
198            text_document: OptionalVersionedTextDocumentIdentifier {
199                uri: uri.clone(),
200                version,
201            },
202            edits: edits
203                .iter()
204                .map(|(span, new_text)| {
205                    OneOf::Left(TextEdit {
206                        range: crate::position::span_to_range(text, *span),
207                        new_text: new_text.clone(),
208                    })
209                })
210                .collect(),
211        }])),
212        change_annotations: None,
213    });
214    action
215}