1use serde_json::{json, Value};
4use vibe::catalog::{
5 canonical_id, describe, families, family_of, methods_for_family, ALL_INVOKE_IDS,
6};
7
8const KEYWORDS: &[(&str, &str)] = &[
9 ("cell", "Reactive cell declaration (`cell name := expr;`)"),
10 ("fn", "Function declaration"),
11 ("pure", "Pure effect modifier"),
12 ("effect", "External effect modifier"),
13 ("hot", "Hot zero-heap performance modifier"),
14 ("cold", "Cold construction modifier"),
15 ("using", "Lease a catalog family (`using Animation;`)"),
16 ("requires", "Capability requirements clause"),
17 ("import", "import \"vibe:0.1/math\" as math;"),
18 ("prefix", "prefix p: <iri>;"),
19 ("locale", "Opt-in keyword locale (`locale zh;`)"),
20 ("present", "Presentation sheaf surface"),
21 ("graph", "Embedded graph pattern"),
22 (
23 "graph?",
24 "Embedded SPARQL ASK (fail-closed without GraphDatabase)",
25 ),
26 ("law", "law Name when expr => consequence;"),
27 ("material", "material Name { ... }"),
28 ("field", "field name: Type { ... }"),
29 (
30 "obligate",
31 "Deontic obligation — lowers to DeonticLogic.evaluate when leased",
32 ),
33 (
34 "permit",
35 "Deontic permission — lowers to DeonticLogic.evaluate when leased",
36 ),
37 (
38 "forbid",
39 "Deontic prohibition — lowers to DeonticLogic.evaluate when leased",
40 ),
41 (
42 "knows",
43 "Epistemic knowledge — lowers to EpistemicLogic.evaluate when leased",
44 ),
45 (
46 "believes",
47 "Epistemic belief — lowers to EpistemicLogic.evaluate when leased",
48 ),
49 (
50 "always",
51 "LTL G(φ) — lowers to TemporalAndDescriptionLogic.ltl.globally when leased",
52 ),
53 (
54 "eventually",
55 "LTL F(φ) — lowers to TemporalAndDescriptionLogic.ltl.finally when leased",
56 ),
57 ("until", "LTL until"),
58];
59
60pub fn completions_at(src: &str, line: usize, character: usize) -> Vec<Value> {
62 let offset = position_to_offset(src, line, character);
63 let prefix = &src[..offset.min(src.len())];
64 if let Some(family) = family_before_dot(prefix) {
65 let methods = methods_for_family(family);
66 if !methods.is_empty() {
67 return methods
68 .into_iter()
69 .map(|id| {
70 let method = id.rsplit('.').next().unwrap_or(id);
71 json!({
72 "label": method,
73 "kind": 3,
74 "detail": describe(id),
75 "insertText": method,
76 "documentation": format!("`using {family};` leases this invoke"),
77 })
78 })
79 .collect();
80 }
81 }
82 let mut out = Vec::new();
83 for (label, detail) in KEYWORDS {
84 out.push(json!({
85 "label": label,
86 "kind": 14,
87 "detail": detail,
88 }));
89 }
90 for fam in families() {
91 out.push(json!({
92 "label": fam,
93 "kind": 9,
94 "detail": format!("Catalog family — `using {fam};` then `{fam}.method(...)`"),
95 "insertText": fam,
96 }));
97 }
98 for id in ALL_INVOKE_IDS.iter().copied().take(32) {
99 out.push(json!({
100 "label": id,
101 "kind": 3,
102 "detail": describe(id),
103 }));
104 }
105 out
106}
107
108pub fn hover_at(src: &str, line: usize, character: usize) -> String {
110 let offset = position_to_offset(src, line, character);
111 let token = ident_path_at(src, offset);
112 if token.is_empty() {
113 return "**VibeScript** (`vibe-0.1`)\n\nWorkshop dialect: `using Family;` then `Family.method(...)`. Modal verbs stay terms unless the engine family is leased.".into();
114 }
115 if let Some(id) = canonical_id(&token) {
116 let lease = family_of(id)
117 .map(|f| format!("\n\nLease: `using {f};`"))
118 .unwrap_or_default();
119 return format!(
120 "**`{id}`**\n\n{}\n\nType: host invoke (fail-closed).{lease}",
121 describe(&token)
122 );
123 }
124 for (kw, detail) in KEYWORDS {
125 if *kw == token {
126 return format!("**`{kw}`**\n\n{detail}");
127 }
128 }
129 format!("**`{token}`**\n\n{}", describe(&token))
130}
131
132pub fn workspace_edit_for_fix(uri: &str, diagnostic: &Value, src: &str) -> Option<Value> {
134 let fix = diagnostic
135 .pointer("/data/suggested_fix")
136 .and_then(|v| v.as_str())?;
137 let range = diagnostic.get("range").cloned().unwrap_or_else(|| {
138 json!({
139 "start": { "line": 0, "character": 0 },
140 "end": { "line": 0, "character": 0 }
141 })
142 });
143 let insert = if fix.starts_with("add `using") || fix.contains("using Family") {
144 let fam = family_from_source_diagnostic(src).unwrap_or("Animation");
145 format!("using {fam};\n")
146 } else if fix.starts_with("add requires") {
147 format!("{fix}\n")
148 } else {
149 format!("/* {fix} */\n")
150 };
151 let insert_range = if insert.starts_with("using ")
152 || insert.starts_with("add requires")
153 || insert.starts_with("requires")
154 {
155 json!({ "start": { "line": 0, "character": 0 }, "end": { "line": 0, "character": 0 } })
156 } else {
157 range
158 };
159 Some(json!({
160 "changes": {
161 uri: [{
162 "range": insert_range,
163 "newText": insert,
164 }]
165 }
166 }))
167}
168
169fn family_from_source_diagnostic(src: &str) -> Option<&'static str> {
170 for fam in families() {
171 if src.contains(fam) {
172 return Some(fam);
173 }
174 }
175 None
176}
177
178fn family_before_dot(prefix: &str) -> Option<&str> {
179 let trimmed = prefix.trim_end();
180 let trimmed = trimmed.strip_suffix('.')?;
181 let start = trimmed
182 .rfind(|c: char| !(c.is_ascii_alphanumeric() || c == '_'))
183 .map(|i| i + 1)
184 .unwrap_or(0);
185 let fam = &trimmed[start..];
186 if fam.is_empty() {
187 return None;
188 }
189 Some(fam)
190}
191
192fn ident_path_at(src: &str, offset: usize) -> String {
193 let bytes = src.as_bytes();
194 if bytes.is_empty() {
195 return String::new();
196 }
197 let mut i = offset.min(bytes.len().saturating_sub(1));
198 while i > 0 {
199 let c = bytes[i] as char;
200 if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
201 break;
202 }
203 i = i.saturating_sub(1);
204 }
205 let mut start = i;
206 while start > 0 {
207 let c = bytes[start - 1] as char;
208 if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
209 start -= 1;
210 } else {
211 break;
212 }
213 }
214 let mut end = i;
215 while end < bytes.len() {
216 let c = bytes[end] as char;
217 if c.is_ascii_alphanumeric() || c == '_' || c == '.' {
218 end += 1;
219 } else {
220 break;
221 }
222 }
223 src[start..end].to_string()
224}
225
226pub fn position_to_offset(src: &str, line: usize, character: usize) -> usize {
228 let mut cur_line = 0;
229 let mut cur_char = 0;
230 for (i, ch) in src.char_indices() {
231 if cur_line == line && cur_char >= character {
232 return i;
233 }
234 if ch == '\n' {
235 cur_line += 1;
236 cur_char = 0;
237 if cur_line > line {
238 return i;
239 }
240 } else {
241 cur_char += ch.len_utf16();
242 }
243 }
244 src.len()
245}
246
247#[cfg(test)]
248mod tests {
249 use super::*;
250
251 #[test]
252 fn family_dot_completes_methods() {
253 let items = completions_at("using Render;\nRender.", 1, 7);
254 let labels: Vec<String> = items
255 .iter()
256 .filter_map(|v| v.get("label").and_then(|l| l.as_str()).map(str::to_string))
257 .collect();
258 assert!(
259 labels
260 .iter()
261 .any(|l| l.contains("gpu_init") || l == "gpu_init"),
262 "expected Render.gpu_* methods, got {labels:?}"
263 );
264 assert!(!labels.iter().any(|l| l == "cell"));
265 }
266
267 #[test]
268 fn hover_catalog_path() {
269 let src = "using Animation;\nAnimation.orbit_spin(t)";
270 let text = hover_at(src, 1, 12);
271 assert!(text.contains("orbit_spin") || text.contains("evaluate_preset"));
272 assert!(text.contains("using"));
273 }
274}