1use bynk_driver::emsg;
21use std::io::Write;
22use std::process::ExitCode;
23
24use bynk_syntax::diagnostics::BOOK_BASE_URL;
25
26const BUNDLE: &str = include_str!(concat!(env!("OUT_DIR"), "/book.txt"));
28
29pub const RESULTS: usize = 5;
31
32const EXCERPT_CHARS: usize = 1_800;
34
35#[derive(Debug, PartialEq)]
37pub struct Section {
38 pub url: String,
40 pub trail: Vec<String>,
42 pub text: String,
44}
45
46#[derive(Debug, PartialEq)]
48pub struct Book {
49 pub sections: Vec<Section>,
50}
51
52const TREES: [&str; 2] = ["book", "reference"];
55
56fn split_source(source: &str) -> Option<(&str, &str)> {
59 let (tree, page) = source.split_once('/')?;
60 TREES.contains(&tree).then_some((tree, page))
61}
62
63fn page_url(source: &str) -> String {
66 let (tree, source) = split_source(source).unwrap_or(("book", source));
67 let slug = source
68 .strip_suffix(".mdx")
69 .or_else(|| source.strip_suffix(".md"))
70 .unwrap_or(source);
71 let slug = if slug == "index" {
72 ""
73 } else {
74 slug.strip_suffix("/index").unwrap_or(slug)
75 };
76 if slug.is_empty() {
77 format!("{BOOK_BASE_URL}/{tree}/")
78 } else {
79 format!("{BOOK_BASE_URL}/{tree}/{slug}/")
80 }
81}
82
83fn heading(line: &str) -> Option<(usize, String)> {
86 let depth = line.bytes().take_while(|b| *b == b'#').count();
87 if !(1..=4).contains(&depth) || !line[depth..].starts_with(' ') {
88 return None;
89 }
90 let mut text = line[depth..].trim();
91 if let Some(at) = text.rfind(" {#").filter(|_| text.ends_with('}')) {
92 text = text[..at].trim_end();
93 }
94 (!text.is_empty()).then(|| (depth, text.to_string()))
95}
96
97pub fn parse(text: &str) -> Book {
100 let lines: Vec<&str> = text.lines().collect();
101 let mut sections = Vec::new();
102 let mut url: Option<String> = None;
103 let mut trail: Vec<(usize, String)> = Vec::new();
105 let mut body: Vec<&str> = Vec::new();
106 let mut in_fence = false;
107 let flush = |url: &Option<String>,
108 trail: &[(usize, String)],
109 body: &mut Vec<&str>,
110 out: &mut Vec<Section>| {
111 let joined = body.join("\n");
112 let joined = joined.trim();
113 if let (Some(url), false) = (url, joined.is_empty()) {
114 out.push(Section {
115 url: url.clone(),
116 trail: trail.iter().map(|(_, t)| t.clone()).collect(),
117 text: joined.to_string(),
118 });
119 }
120 body.clear();
121 };
122 let mut i = 0;
123 while i < lines.len() {
124 let line = lines[i];
125 let is_marker = line.starts_with("# ─")
126 && lines
127 .get(i + 1)
128 .and_then(|l| l.strip_prefix("# Source: "))
129 .is_some_and(|source| split_source(source).is_some())
130 && lines.get(i + 2).is_some_and(|l| l.starts_with("# ─"));
131 if is_marker {
132 flush(&url, &trail, &mut body, &mut sections);
133 url = Some(page_url(&lines[i + 1]["# Source: ".len()..]));
134 trail.clear();
135 in_fence = false;
136 i += 3;
137 continue;
138 }
139 i += 1;
140 if url.is_none() {
141 continue;
142 }
143 if line.trim_start().starts_with("```") {
144 in_fence = !in_fence;
145 }
146 match if in_fence { None } else { heading(line) } {
147 None => body.push(line),
148 Some((depth, title)) => {
149 flush(&url, &trail, &mut body, &mut sections);
150 while trail.last().is_some_and(|(d, _)| *d >= depth) {
153 trail.pop();
154 }
155 trail.push((depth, title));
156 }
157 }
158 }
159 flush(&url, &trail, &mut body, &mut sections);
160 Book { sections }
161}
162
163fn terms(query: &str) -> Vec<String> {
165 let mut out: Vec<String> = Vec::new();
166 let lower = query.to_lowercase();
167 for word in lower.split(|c: char| !(c.is_alphanumeric() || c == '_')) {
168 if word.chars().count() > 1 && !out.iter().any(|t| t == word) {
169 out.push(word.to_string());
170 }
171 }
172 out
173}
174
175pub fn search<'a>(book: &'a Book, query: &str, limit: usize) -> Vec<&'a Section> {
179 let terms = terms(query);
180 if terms.is_empty() {
181 return Vec::new();
182 }
183 let phrase = query.trim().to_lowercase();
184 let mut scored: Vec<(f64, usize, &Section)> = Vec::new();
185 for (order, section) in book.sections.iter().enumerate() {
186 let head = section.trail.join(" ").to_lowercase();
187 let body = section.text.to_lowercase();
188 let mut matched = 0usize;
189 let mut score = 0f64;
190 for t in &terms {
191 let in_head = head.matches(t.as_str()).count();
192 let in_body = body.matches(t.as_str()).count();
193 if in_head + in_body == 0 {
194 continue;
195 }
196 matched += 1;
197 score += (in_head.min(2) * 6 + in_body.min(5)) as f64;
198 }
199 if matched == 0 {
200 continue;
201 }
202 let coverage = matched as f64 / terms.len() as f64;
203 score *= coverage * coverage;
204 if terms.len() > 1 && (head.contains(&phrase) || body.contains(&phrase)) {
205 score += 10.0;
206 }
207 scored.push((score, order, section));
208 }
209 scored.sort_by(|a, b| b.0.total_cmp(&a.0).then(a.1.cmp(&b.1)));
210 scored.into_iter().take(limit).map(|s| s.2).collect()
211}
212
213fn excerpt(text: &str, terms: &[String], max: usize) -> String {
216 if text.chars().count() <= max {
217 return text.to_string();
218 }
219 let lines: Vec<&str> = text.lines().collect();
220 let from = lines
221 .iter()
222 .position(|l| {
223 let l = l.to_lowercase();
224 terms.iter().any(|t| l.contains(t.as_str()))
225 })
226 .unwrap_or(0);
227 let mut taken: Vec<String> = Vec::new();
228 let mut used = 0;
229 for line in &lines[from..] {
230 let len = line.chars().count() + 1;
231 if used + len > max && !taken.is_empty() {
232 break;
233 }
234 taken.push(line.chars().take(max).collect());
236 used += len;
237 }
238 let cut_after = from + taken.len() < lines.len();
239 if taken
240 .iter()
241 .filter(|l| l.trim_start().starts_with("```"))
242 .count()
243 % 2
244 == 1
245 {
246 taken.push("```".to_string());
247 }
248 let lead = if from > 0 { "…\n" } else { "" };
249 let tail = if cut_after { "\n…" } else { "" };
250 format!("{lead}{}{tail}", taken.join("\n"))
251}
252
253fn short_trail(trail: &[String]) -> String {
255 match trail {
256 [] => "(untitled)".to_string(),
257 [only] => only.clone(),
258 [first, .., last] => format!("{first} › {last}"),
259 }
260}
261
262fn source_note() -> String {
264 format!(
265 "Source: the Bynk Book v{}, from the installed toolchain.",
266 env!("CARGO_PKG_VERSION")
267 )
268}
269
270pub fn render_markdown(book: &Book, query: &str) -> String {
273 let note = source_note();
274 let hits = search(book, query, RESULTS);
275 if hits.is_empty() {
276 return format!(
277 "# Bynk Book: no match for \"{query}\"\n\n{note}\n\n\
278 Try other words, or browse {BOOK_BASE_URL}/book/.\n"
279 );
280 }
281 let terms = terms(query);
282 let parts: Vec<String> = hits
283 .iter()
284 .enumerate()
285 .map(|(i, h)| {
286 format!(
287 "**{}. {}** — {}\n\n{}\n",
288 i + 1,
289 short_trail(&h.trail),
290 h.url,
291 excerpt(&h.text, &terms, EXCERPT_CHARS)
292 )
293 })
294 .collect();
295 format!(
296 "# Bynk Book: {} result(s) for \"{query}\"\n\n{note}\n\n{}",
297 hits.len(),
298 parts.join("\n---\n\n")
299 )
300}
301
302fn render_json(book: &Book, query: &str) -> String {
304 let terms = terms(query);
305 let results: Vec<serde_json::Value> = search(book, query, RESULTS)
306 .into_iter()
307 .map(|h| {
308 serde_json::json!({
309 "trail": h.trail,
310 "url": h.url,
311 "text": excerpt(&h.text, &terms, EXCERPT_CHARS),
312 })
313 })
314 .collect();
315 let doc = serde_json::json!({
316 "version": env!("CARGO_PKG_VERSION"),
317 "query": query,
318 "results": results,
319 });
320 format!("{doc}\n")
321}
322
323#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325pub enum Format {
326 Text,
327 Json,
328}
329
330pub fn embedded() -> Option<Book> {
332 (!BUNDLE.trim().is_empty()).then(|| parse(BUNDLE))
333}
334
335pub fn run(query: Option<&str>, format: Format) -> ExitCode {
339 if BUNDLE.trim().is_empty() {
340 emsg!(
341 "error: no Book bundled in this build of `bynk`. Read it at \
342 {BOOK_BASE_URL}/book/ (or {BOOK_BASE_URL}/llms-full.txt)."
343 );
344 return ExitCode::FAILURE;
345 }
346 let text = match query {
347 None => format!("Bynk Book v{}\n\n{BUNDLE}", env!("CARGO_PKG_VERSION")),
348 Some(q) => {
349 let book = parse(BUNDLE);
350 match format {
351 Format::Text => render_markdown(&book, q),
352 Format::Json => render_json(&book, q),
353 }
354 }
355 };
356 let _ = std::io::stdout().write_all(text.as_bytes());
358 ExitCode::SUCCESS
359}
360
361#[cfg(test)]
362mod tests {
363 use super::*;
364
365 const RULE: &str = "# ────────────────────────────────────────────────────────────";
366
367 fn page(source: &str, body: &str) -> String {
368 format!("{RULE}\n# Source: {source}\n{RULE}\n\n{body}\n")
369 }
370
371 fn bundle() -> String {
372 let types = "# Types\n\nEvery value has a type.\n\n## Refined types\n\nA refined type adds a `where` predicate.\n\n\
373 ```bynk\n# not a heading\ntype Qty = Int where Positive\n```\n\n## Aliases\n\nA name for a type.";
374 let agents = "# Agents\n\nAn agent holds state per key.\n\n## Handlers {#handlers}\n\nHandlers mutate state.";
375 format!(
376 "# Bynk — Full Documentation\n\nintro\n\n{}\n{}\n{}",
377 page("reference/types.md", types),
378 page("book/guides/agents/index.md", agents),
379 page("book/index.md", "# The Bynk Book\n\nWelcome."),
380 )
381 }
382
383 fn trails(sections: &[&Section]) -> Vec<String> {
384 sections.iter().map(|s| s.trail.join(" > ")).collect()
385 }
386
387 #[test]
388 fn maps_a_source_page_to_its_hosted_url() {
389 assert_eq!(
392 page_url("reference/types.md"),
393 "https://bynk-lang.org/reference/types/"
394 );
395 assert_eq!(
396 page_url("reference/index.md"),
397 "https://bynk-lang.org/reference/"
398 );
399 assert_eq!(
400 page_url("book/guides/agents/index.mdx"),
401 "https://bynk-lang.org/book/guides/agents/"
402 );
403 assert_eq!(page_url("book/index.md"), "https://bynk-lang.org/book/");
404 }
405
406 #[test]
407 fn a_marker_outside_both_trees_does_not_start_a_page() {
408 assert_eq!(split_source("blog/post.md"), None);
409 let book = parse(&format!(
410 "{}{RULE}\n# Source: blog/post.md\n{RULE}\n\n# Not a page\n",
411 page("book/a.md", "# A\n\ntext\n")
412 ));
413 assert_eq!(book.sections.len(), 1);
414 }
415
416 #[test]
417 fn splits_pages_by_heading_leaving_code_fences_whole() {
418 let book = parse(&bundle());
419 let all: Vec<&Section> = book.sections.iter().collect();
420 assert_eq!(
421 trails(&all),
422 [
423 "Types",
424 "Types > Refined types",
425 "Types > Aliases",
426 "Agents",
427 "Agents > Handlers",
428 "The Bynk Book"
429 ]
430 );
431 assert!(book.sections[1].text.contains("# not a heading"));
432 assert_eq!(
433 book.sections[1].url,
434 "https://bynk-lang.org/reference/types/"
435 );
436 }
437
438 #[test]
439 fn a_skipped_heading_level_nests_under_what_is_open() {
440 let book = parse(&page(
441 "book/a.md",
442 "# A\n\ntop\n\n### C\n\nc\n\n#### E\n\ne\n\n### F\n\nf",
443 ));
444 let all: Vec<&Section> = book.sections.iter().collect();
445 assert_eq!(trails(&all), ["A", "A > C", "A > C > E", "A > F"]);
446 }
447
448 #[test]
449 fn ranks_a_heading_match_above_a_body_mention() {
450 let book = parse(&bundle());
451 assert_eq!(
452 trails(&search(&book, "refined types", 5))[0],
453 "Types > Refined types"
454 );
455 }
456
457 #[test]
458 fn prefers_a_section_holding_every_word() {
459 let book = parse(&bundle());
460 assert_eq!(
461 trails(&search(&book, "agent handlers", 5))[0],
462 "Agents > Handlers"
463 );
464 }
465
466 #[test]
467 fn finds_nothing_for_words_the_book_lacks_or_an_empty_query() {
468 let book = parse(&bundle());
469 assert!(search(&book, "zebra", 5).is_empty());
470 assert!(search(&book, " ", 5).is_empty());
471 }
472
473 #[test]
474 fn labels_results_with_the_toolchain_version() {
475 let book = parse(&bundle());
476 let out = render_markdown(&book, "refined types");
477 assert!(out.starts_with("# Bynk Book: "), "{out}");
478 assert!(out.contains(&format!(
479 "Source: the Bynk Book v{}, from the installed toolchain.",
480 env!("CARGO_PKG_VERSION")
481 )));
482 assert!(
483 out.contains("**1. Types › Refined types** — https://bynk-lang.org/reference/types/")
484 );
485 let none = render_markdown(&book, "zebra");
486 assert!(none.starts_with("# Bynk Book: no match for \"zebra\""));
487 assert!(none.contains(env!("CARGO_PKG_VERSION")));
488 }
489
490 #[test]
491 fn json_carries_the_version_and_results() {
492 let book = parse(&bundle());
493 let doc: serde_json::Value =
494 serde_json::from_str(&render_json(&book, "refined types")).unwrap();
495 assert_eq!(doc["version"], env!("CARGO_PKG_VERSION"));
496 assert_eq!(doc["results"][0]["trail"][1], "Refined types");
497 }
498
499 #[test]
500 fn cuts_a_long_section_near_the_match_and_closes_a_cut_fence() {
501 let body = format!(
502 "# A\n\n## Big\n\n{}needle here\n\n```bynk\n{}```\n",
503 "filler line\n".repeat(400),
504 "x\n".repeat(900)
505 );
506 let book = parse(&page("book/a.md", &body));
507 let out = render_markdown_with(&book, "needle", 300);
508 assert!(out.contains("needle here"), "{out}");
509 assert!(out.chars().count() < 1_200, "{}", out.chars().count());
510 assert_eq!(
511 out.lines().filter(|l| l.starts_with("```")).count() % 2,
512 0,
513 "{out}"
514 );
515 }
516
517 fn render_markdown_with(book: &Book, query: &str, max: usize) -> String {
518 let terms = terms(query);
519 search(book, query, 1)
520 .iter()
521 .map(|h| excerpt(&h.text, &terms, max))
522 .collect()
523 }
524}