Skip to main content

bynk_lsp/
provider_stub.rs

1//! #2100 slice 4: generate a provider stub. For a capability declared in this
2//! file that nothing in its context provides, the action scaffolds
3//! `provides Cap = CapImpl { … }` right below the declaration, with every
4//! operation's signature copied and its body a typed default.
5//!
6//! It is offered as a quick fix on `bynk.exports.capability_not_provided`
7//! (an exported capability with no provider) and on
8//! `bynk.capability.not_provided` (a required capability with no provider),
9//! and as a `refactor` with the cursor on the capability's name. The editor's
10//! analysis runs as the bundle target, so it raises
11//! `bynk.capability.not_provided` only in a bundle with a composition root
12//! (`compose.ts`), as `bynk check` does; the Workers form, raised for every
13//! context on `--target workers`, never reaches the editor. So the refactor is
14//! what covers a required capability elsewhere.
15//!
16//! The language has no placeholder expression, so a stub body must be a value
17//! that type-checks (DECISION B re-checks the edit). Each body is a default of
18//! the operation's return type: the unrefined scalars, `()`, `None`, `[]`, or
19//! one of those inside an `Effect`. A capability with an operation returning
20//! anything else (a record, a user sum, a `Result`) gets no action. So does a
21//! derived capability, one declared outside a context, or one with generic
22//! operations (whose type parameters the stub would have to repeat).
23//!
24//! Whether a capability already has a provider is read from the committed
25//! index's implementation edges, so a provider in a sibling file counts. Like
26//! fill-arms, the action is listed without an edit, and `codeAction/resolve`
27//! computes and re-checks it. A `bynk-fmt`-canonical file is re-formatted and
28//! the edit narrowed to the changed region.
29
30use bynk_check::index::{ProjectIndex, SymbolKey, SymbolKind};
31use bynk_syntax::ast::{BaseType, CapabilityDecl, CommonsItem, SourceUnit, TypeRef};
32use bynk_syntax::lexer::tokenize;
33use bynk_syntax::parser::parse_unit_with_recovery;
34use bynk_syntax::span::Span;
35use tower_lsp::lsp_types::*;
36
37const DATA_TAG: &str = "bynk.generateProvider";
38const CATEGORIES: [&str; 2] = [
39    "bynk.exports.capability_not_provided",
40    "bynk.capability.not_provided",
41];
42
43/// A planned stub: the capability, the provider's name, and the edits.
44pub struct Plan {
45    pub capability: String,
46    pub provider: String,
47    pub edits: Vec<(Span, String)>,
48}
49
50/// One capability the request points at, and how: through a "no provider"
51/// diagnostic (a quick fix) or its declaration's name (a refactor).
52pub struct Request {
53    pub capability: String,
54    pub quick_fix: bool,
55}
56
57/// The capabilities at `requested`, by diagnostic first, each named once.
58pub fn requested(
59    text: &str,
60    diagnostics: &[bynk_ide::Diagnostic],
61    requested: Span,
62) -> Vec<Request> {
63    let mut out: Vec<Request> = Vec::new();
64    let touches = |s: Span| s.start <= requested.end && requested.start <= s.end;
65    for d in diagnostics {
66        if CATEGORIES.contains(&d.error.category) && touches(d.error.span) {
67            let name = text
68                .get(d.error.span.start..d.error.span.end)
69                .unwrap_or_default()
70                .trim()
71                .to_string();
72            if !name.is_empty() && !out.iter().any(|r| r.capability == name) {
73                out.push(Request {
74                    capability: name,
75                    quick_fix: true,
76                });
77            }
78        }
79    }
80    if let Some(unit) = parse(text) {
81        for cap in capabilities(&unit) {
82            if touches(cap.name.span) && !out.iter().any(|r| r.capability == cap.name.name) {
83                out.push(Request {
84                    capability: cap.name.name.clone(),
85                    quick_fix: false,
86                });
87            }
88        }
89    }
90    out
91}
92
93/// The stub for `capability` in `text`, or `None` when there is none to offer
94/// (see the module docs).
95pub fn plan(text: &str, capability: &str, index: &ProjectIndex) -> Option<Plan> {
96    let unit = parse(text)?;
97    let SourceUnit::Context(ctx) = &unit else {
98        return None;
99    };
100    let cap = capabilities(&unit)
101        .into_iter()
102        .find(|c| c.name.name == capability)?;
103    if cap.derived.is_some() || cap.ops.is_empty() {
104        return None;
105    }
106    let key = SymbolKey {
107        unit: ctx.name.joined(),
108        kind: SymbolKind::Capability,
109        name: capability.to_string(),
110    };
111    if index.impls_of(&key).next().is_some() {
112        return None;
113    }
114    // Names the context already declares anywhere (a sibling file's too,
115    // from the committed index) are taken, as well as words in this file.
116    let unit = ctx.name.joined();
117    let declared: Vec<&str> = index
118        .symbols
119        .keys()
120        .filter(|k| k.unit == unit)
121        .map(|k| k.name.as_str())
122        .collect();
123    let provider = fresh_name(text, &declared, &format!("{capability}Impl"));
124
125    let mut ops = Vec::new();
126    for op in &cap.ops {
127        if !op.type_params.is_empty() {
128            return None;
129        }
130        let body = default_of(&op.return_type)?;
131        let signature = text.get(op.span.start..op.return_type.span().end)?;
132        if signature.contains("//") || !signature.trim_start().starts_with("fn") {
133            return None;
134        }
135        ops.push(format!("  {} {{\n    {body}\n  }}", signature.trim()));
136    }
137    let stub = format!(
138        "\n\nprovides {capability} = {provider} {{\n{}\n}}",
139        ops.join("\n\n")
140    );
141    let mut edits = vec![(Span::new(cap.span.end, cap.span.end), stub)];
142
143    let opts = bynk_fmt::FormatOptions::default();
144    if bynk_fmt::format_source(text, &opts).is_ok_and(|f| f == text) {
145        let stubbed = crate::fix_all::apply(text, &edits);
146        let formatted = bynk_fmt::format_source(&stubbed, &opts).ok()?;
147        edits = vec![crate::inline::changed_region(text, &formatted)];
148    }
149    Some(Plan {
150        capability: capability.to_string(),
151        provider,
152        edits,
153    })
154}
155
156fn parse(text: &str) -> Option<SourceUnit> {
157    let tokens = tokenize(text).ok()?;
158    match parse_unit_with_recovery(&tokens, text) {
159        (Some(unit), errs) if errs.is_empty() => Some(unit),
160        _ => None,
161    }
162}
163
164fn capabilities(unit: &SourceUnit) -> Vec<&CapabilityDecl> {
165    let SourceUnit::Context(ctx) = unit else {
166        return Vec::new();
167    };
168    ctx.items
169        .iter()
170        .filter_map(|i| match i {
171            CommonsItem::Capability(c) => Some(c),
172            _ => None,
173        })
174        .collect()
175}
176
177/// A body sure to type-check as `ty` (the #852 `field_default_init` set plus
178/// unit), looking through one `Effect` (an op body auto-lifts).
179fn default_of(ty: &TypeRef) -> Option<&'static str> {
180    let ty = match ty {
181        TypeRef::Effect(inner, _) => inner,
182        other => other,
183    };
184    Some(match ty {
185        TypeRef::Base(BaseType::Int, _) => "0",
186        TypeRef::Base(BaseType::Float, _) => "0.0",
187        TypeRef::Base(BaseType::Decimal, _) => "0d",
188        TypeRef::Base(BaseType::String, _) => "\"\"",
189        TypeRef::Base(BaseType::Bool, _) => "false",
190        TypeRef::Unit(_) => "()",
191        TypeRef::Option(..) => "None",
192        TypeRef::List(..) => "[]",
193        _ => return None,
194    })
195}
196
197/// `base`, or `base2`, `base3`, … — the first that is neither a word of
198/// `text` nor one of the context's `declared` names.
199fn fresh_name(text: &str, declared: &[&str], base: &str) -> String {
200    let taken = |name: &str| {
201        declared.contains(&name)
202            || text.match_indices(name).any(|(i, _)| {
203                let before = text[..i].chars().next_back();
204                let after = text[i + name.len()..].chars().next();
205                !before.is_some_and(|c| c.is_alphanumeric() || c == '_')
206                    && !after.is_some_and(|c| c.is_alphanumeric() || c == '_')
207            })
208    };
209    if !taken(base) {
210        return base.to_string();
211    }
212    (2..)
213        .map(|n| format!("{base}{n}"))
214        .find(|name| !taken(name))
215        .expect("an unused name")
216}
217
218/// The listed (unresolved) action for `plan`.
219pub fn listed(
220    plan: &Plan,
221    quick_fix: bool,
222    uri: &Url,
223    version: Option<i32>,
224) -> CodeActionOrCommand {
225    CodeActionOrCommand::CodeAction(CodeAction {
226        title: format!(
227            "Generate provider `{}` for `{}`",
228            plan.provider, plan.capability
229        ),
230        kind: Some(if quick_fix {
231            CodeActionKind::QUICKFIX
232        } else {
233            CodeActionKind::REFACTOR
234        }),
235        data: Some(serde_json::json!({
236            "kind": DATA_TAG,
237            "uri": uri.as_str(),
238            "version": version,
239            "capability": plan.capability,
240        })),
241        ..Default::default()
242    })
243}
244
245/// What a listed stub action's `data` names.
246pub struct Target {
247    pub uri: Url,
248    pub version: Option<i32>,
249    pub capability: String,
250}
251
252impl Target {
253    pub fn of(action: &CodeAction) -> Option<Self> {
254        let data = action.data.as_ref()?;
255        if data.get("kind")?.as_str()? != DATA_TAG {
256            return None;
257        }
258        Some(Target {
259            uri: Url::parse(data.get("uri")?.as_str()?).ok()?,
260            version: data
261                .get("version")
262                .and_then(serde_json::Value::as_i64)
263                .and_then(|v| i32::try_from(v).ok()),
264            capability: data.get("capability")?.as_str()?.to_string(),
265        })
266    }
267}