1use std::sync::OnceLock;
17
18use bynk_check::firstparty::{self, FIRSTPARTY_SOURCES, Stability, UNITS, UnitKind};
19use bynk_check::kernel_methods as km;
20use bynk_ide::completion::{BUILTIN_STATICS, capability_op_signature, free_fn_signature};
21use bynk_syntax::ast::{CommonsItem, Doc, FnName, SourceUnit};
22use bynk_syntax::{lexer, parser};
23use serde::Serialize;
24
25#[derive(Serialize)]
27pub struct Member {
28 pub name: String,
29 pub signature: String,
30 #[serde(skip_serializing_if = "Option::is_none")]
33 pub doc: Option<String>,
34 #[serde(skip_serializing_if = "std::ops::Not::not")]
36 pub experimental: bool,
37 #[serde(skip_serializing_if = "Option::is_none")]
39 pub deprecated: Option<String>,
40}
41
42#[derive(Serialize)]
44pub struct TypeEntry {
45 pub name: String,
46 pub statics: Vec<Member>,
47 pub methods: Vec<Member>,
48}
49
50#[derive(Serialize)]
52pub struct CapabilityEntry {
53 pub name: String,
54 pub unit: String,
56 #[serde(skip_serializing_if = "Option::is_none")]
57 pub doc: Option<String>,
58 pub experimental: bool,
60 pub operations: Vec<Member>,
61}
62
63#[derive(Serialize)]
65pub struct ModuleEntry {
66 pub name: String,
67 #[serde(skip_serializing_if = "Option::is_none")]
68 pub doc: Option<String>,
69 pub experimental: bool,
70 pub functions: Vec<Member>,
71}
72
73#[derive(Serialize)]
74pub struct Reference {
75 pub types: Vec<TypeEntry>,
76 pub capabilities: Vec<CapabilityEntry>,
77 pub modules: Vec<ModuleEntry>,
78}
79
80fn plain(name: &str, signature: &str) -> Member {
81 Member {
82 name: name.to_string(),
83 signature: signature.to_string(),
84 doc: None,
85 experimental: false,
86 deprecated: None,
87 }
88}
89
90fn types() -> Vec<TypeEntry> {
91 let mut out: Vec<TypeEntry> = km::ALL_METHODS
92 .iter()
93 .map(|&(name, table)| TypeEntry {
94 name: name.to_string(),
95 statics: Vec::new(),
96 methods: table.iter().map(|m| plain(m.name, m.signature)).collect(),
97 })
98 .collect();
99 for &(name, statics) in BUILTIN_STATICS {
100 let members: Vec<Member> = statics.iter().map(|&(n, sig)| plain(n, sig)).collect();
101 match out.iter_mut().find(|t| t.name == name) {
102 Some(t) => t.statics = members,
103 None => out.push(TypeEntry {
105 name: name.to_string(),
106 statics: members,
107 methods: Vec::new(),
108 }),
109 }
110 }
111 out
112}
113
114fn doc_text(d: &Option<Doc>) -> Option<String> {
115 d.as_ref().map(|d| d.text.clone())
116}
117
118fn parse(src: &str) -> Option<SourceUnit> {
119 let tokens = lexer::tokenize(src).ok()?;
120 let (unit, errors) = parser::parse_unit_with_recovery(&tokens, src);
121 debug_assert!(errors.is_empty(), "first-party source has parse errors");
123 unit
124}
125
126fn is_experimental(path: &str) -> bool {
127 firstparty::stability_of(path) == Some(Stability::Experimental)
128}
129
130fn units() -> (Vec<CapabilityEntry>, Vec<ModuleEntry>) {
131 let mut caps = Vec::new();
132 let mut mods = Vec::new();
133 for (unit_name, src) in FIRSTPARTY_SOURCES {
134 let Some(kind) = UNITS.iter().find(|u| u.name == *unit_name).map(|u| u.kind) else {
135 debug_assert!(false, "{unit_name} is in FIRSTPARTY_SOURCES but not UNITS");
136 continue;
137 };
138 let Some(unit) = parse(src) else {
139 debug_assert!(false, "first-party unit {unit_name} failed to parse");
140 continue;
141 };
142 match (kind, &unit) {
143 (UnitKind::Adapter, SourceUnit::Adapter(a)) => {
144 for item in &a.items {
145 let CommonsItem::Capability(c) = item else {
146 continue;
147 };
148 if c.derived.is_some() {
151 continue;
152 }
153 let cap_path = format!("{unit_name}.{}", c.name.name);
154 caps.push(CapabilityEntry {
155 name: c.name.name.clone(),
156 unit: unit_name.to_string(),
157 doc: doc_text(&c.documentation),
158 experimental: is_experimental(&cap_path),
159 operations: c
160 .ops
161 .iter()
162 .map(|op| Member {
163 name: op.name.name.clone(),
164 signature: capability_op_signature(op),
165 doc: doc_text(&op.documentation),
166 experimental: is_experimental(&format!(
167 "{cap_path}.{}",
168 op.name.name
169 )),
170 deprecated: None,
171 })
172 .collect(),
173 });
174 }
175 }
176 (UnitKind::Commons, SourceUnit::Commons(c)) => {
177 let functions: Vec<Member> = c
178 .items
179 .iter()
180 .filter_map(|item| {
181 let CommonsItem::Fn(f) = item else {
182 return None;
183 };
184 let FnName::Free(id) = &f.name else {
185 return None;
186 };
187 if f.private.is_some() {
188 return None;
189 }
190 let deprecated = if *unit_name == "bynk.list" {
191 bynk_check::checker::BYNK_LIST_DEPRECATED
192 .iter()
193 .find(|(n, _)| *n == id.name)
194 .map(|(_, form)| format!("use the `List` method form `{form}`"))
195 } else {
196 bynk_check::checker::BYNK_COLLECTION_DEPRECATED
197 .iter()
198 .find(|(m, n, _, _)| m == unit_name && *n == id.name)
199 .map(|(_, _, method, _)| {
200 format!("use the method form `.{method}(…)`")
201 })
202 };
203 Some(Member {
204 name: id.name.clone(),
205 signature: free_fn_signature(&id.name, f),
206 doc: doc_text(&f.documentation),
207 experimental: is_experimental(&format!("{unit_name}.{}", id.name)),
208 deprecated,
209 })
210 })
211 .collect();
212 if !functions.is_empty() {
214 mods.push(ModuleEntry {
215 name: unit_name.to_string(),
216 doc: doc_text(&c.documentation),
217 experimental: is_experimental(unit_name),
218 functions,
219 });
220 }
221 }
222 _ => debug_assert!(false, "{unit_name}: unit kind does not match its source"),
223 }
224 }
225 (caps, mods)
226}
227
228pub fn build() -> Reference {
230 let (capabilities, modules) = units();
231 Reference {
232 types: types(),
233 capabilities,
234 modules,
235 }
236}
237
238pub fn reference_to_json() -> String {
241 static JSON: OnceLock<String> = OnceLock::new();
242 JSON.get_or_init(|| {
243 serde_json::to_string(&build())
244 .unwrap_or_else(|_| "{\"types\":[],\"capabilities\":[],\"modules\":[]}".to_string())
245 })
246 .clone()
247}
248
249#[cfg(test)]
250mod tests {
251 use super::*;
252
253 fn json() -> serde_json::Value {
254 serde_json::from_str(&reference_to_json()).expect("valid JSON")
255 }
256
257 fn find<'a>(v: &'a serde_json::Value, key: &str, name: &str) -> &'a serde_json::Value {
258 member(v, key, name)
259 }
260
261 fn member<'a>(entry: &'a serde_json::Value, key: &str, name: &str) -> &'a serde_json::Value {
262 entry[key]
263 .as_array()
264 .unwrap()
265 .iter()
266 .find(|e| e["name"] == name)
267 .unwrap_or_else(|| panic!("{key} `{name}` missing"))
268 }
269
270 #[test]
271 fn value_methods_are_listed_with_signatures() {
272 let v = json();
273 for &(name, table) in km::ALL_METHODS {
274 let t = find(&v, "types", name);
275 assert_eq!(
276 t["methods"].as_array().unwrap().len(),
277 table.len(),
278 "{name}"
279 );
280 }
281 let len = member(find(&v, "types", "List"), "methods", "length");
282 assert_eq!(len["signature"], "length() -> Int");
283 }
284
285 #[test]
286 fn statics_include_instant_duration_bytes_and_json() {
287 let v = json();
288 member(find(&v, "types", "Instant"), "statics", "fromEpochMillis");
289 member(find(&v, "types", "Instant"), "statics", "fromIso");
290 member(find(&v, "types", "Duration"), "statics", "millis");
291 member(find(&v, "types", "Bytes"), "statics", "fromUtf8");
292 member(find(&v, "types", "Json"), "statics", "decode");
293 member(find(&v, "types", "Yaml"), "statics", "decode");
294 member(find(&v, "types", "Form"), "statics", "decode");
295 member(find(&v, "types", "Form"), "statics", "encode");
296 let n = v["types"]
298 .as_array()
299 .unwrap()
300 .iter()
301 .filter(|t| t["name"] == "Instant")
302 .count();
303 assert_eq!(n, 1);
304 }
305
306 #[test]
307 fn capabilities_carry_docs_and_signatures() {
308 let v = json();
309 let clock = find(&v, "capabilities", "Clock");
310 assert_eq!(clock["unit"], "bynk");
311 assert_eq!(clock["experimental"], false);
312 assert!(clock["doc"].as_str().is_some_and(|d| !d.is_empty()));
313 let now = member(clock, "operations", "now");
314 assert!(now["signature"].as_str().unwrap().starts_with("now()"));
315 let list = find(&v, "modules", "bynk.list");
317 assert!(member(list, "functions", "reverse")["doc"].is_string());
318 }
319
320 #[test]
321 fn crypto_is_marked_experimental() {
322 let v = json();
323 let crypto: Vec<_> = v["capabilities"]
324 .as_array()
325 .unwrap()
326 .iter()
327 .filter(|c| c["unit"] == "bynk.crypto")
328 .collect();
329 assert!(!crypto.is_empty());
330 assert!(crypto.iter().all(|c| c["experimental"] == true));
331 }
332
333 #[test]
334 fn deprecated_list_functions_say_what_to_use() {
335 let v = json();
336 let list = find(&v, "modules", "bynk.list");
337 let map = member(list, "functions", "map");
338 assert_eq!(map["deprecated"], "use the `List` method form `xs.map(f)`");
339 assert!(map["doc"].is_string());
340 assert_eq!(
342 member(list, "functions", "reverse")["deprecated"],
343 "use the `List` method form `xs.reverse()`"
344 );
345 }
346
347 #[test]
348 fn every_first_party_unit_with_functions_appears() {
349 let v = json();
350 for name in [
351 "bynk.list",
352 "bynk.map",
353 "bynk.string",
354 "bynk.set",
355 "bynk.url",
356 ] {
357 assert!(
358 !find(&v, "modules", name)["functions"]
359 .as_array()
360 .unwrap()
361 .is_empty(),
362 "{name}"
363 );
364 }
365 }
366
367 const NOTHING_TO_LIST: &[&str] = &["bynk.locale.types"];
369
370 #[test]
371 fn every_first_party_unit_is_listed_or_allowlisted() {
372 let v = json();
373 for (name, src) in FIRSTPARTY_SOURCES {
374 let tokens = lexer::tokenize(src).expect("lexes");
375 let (unit, errors) = parser::parse_unit_with_recovery(&tokens, src);
376 assert!(errors.is_empty(), "{name}: {errors:?}");
377 let unit = unit.expect("parses");
378 let listed = match &unit {
379 SourceUnit::Adapter(_) => v["capabilities"]
380 .as_array()
381 .unwrap()
382 .iter()
383 .any(|c| c["unit"] == *name),
384 SourceUnit::Commons(_) => v["modules"]
385 .as_array()
386 .unwrap()
387 .iter()
388 .any(|m| m["name"] == *name),
389 _ => false,
390 };
391 assert!(
392 listed || NOTHING_TO_LIST.contains(name),
393 "{name} is neither in the reference nor allowlisted"
394 );
395 }
396 }
397
398 #[test]
399 fn no_first_party_derived_capability() {
400 for (name, src) in FIRSTPARTY_SOURCES {
403 if let Some(SourceUnit::Adapter(a)) = parse(src) {
404 for item in &a.items {
405 if let CommonsItem::Capability(c) = item {
406 assert!(c.derived.is_none(), "{name}.{} is derived", c.name.name);
407 }
408 }
409 }
410 }
411 }
412
413 #[test]
414 fn the_catalogue_stays_a_bounded_size() {
415 let n = reference_to_json().len();
418 assert!(n < 200_000, "bynk_reference is {n} bytes");
419 }
420}