Skip to main content

bynk/
book.rs

1//! `bynk book` — the Bynk Book as this toolchain documents it (#2463).
2//!
3//! The editor's `bynk_search_book` language-model tool (and `bynk mcp`) need Book
4//! text that matches the `bynk` the user runs, not the live site (which may
5//! describe features this build lacks) and not the extension's own version. The
6//! driver embeds the whole Book at build time (`build.rs`: the `llms-full.txt`
7//! bundle, every page in sidebar order) and serves it two ways:
8//!
9//! - `bynk book` prints the whole Book under a first line naming the toolchain
10//!   version;
11//! - `bynk book --search <query>` returns the best-matching sections, as
12//!   Markdown or (`--format json`) as data. [`search`] is the ranking, shared
13//!   by every caller inside the driver.
14//!
15//! A build made without the bundle (a plain `cargo build`) carries none: both
16//! forms then say "no Book bundled in this build" and exit non-zero, so a source
17//! build never silently returns nothing. The editor falls back to the hosted
18//! Book, ranked by a small TypeScript copy of [`search`].
19
20use bynk_driver::emsg;
21use std::io::Write;
22use std::process::ExitCode;
23
24use bynk_syntax::diagnostics::BOOK_BASE_URL;
25
26/// The Book bundle embedded at build time; empty when the build had none.
27const BUNDLE: &str = include_str!(concat!(env!("OUT_DIR"), "/book.txt"));
28
29/// How many sections a search returns.
30pub const RESULTS: usize = 5;
31
32/// The longest excerpt of one section, in characters.
33const EXCERPT_CHARS: usize = 1_800;
34
35/// One heading's worth of a Book page.
36#[derive(Debug, PartialEq)]
37pub struct Section {
38    /// The page's hosted URL.
39    pub url: String,
40    /// The page title, then the headings down to this section.
41    pub trail: Vec<String>,
42    /// The section's text, headings excluded.
43    pub text: String,
44}
45
46/// A Book text, split for searching.
47#[derive(Debug, PartialEq)]
48pub struct Book {
49    pub sections: Vec<Section>,
50}
51
52/// The trees `llms-full.txt` bundles, each served under a path of the same
53/// name: the Book, then the Reference (web presence slice 5).
54const TREES: [&str; 2] = ["book", "reference"];
55
56/// The tree and page of a bundle marker's source, `reference/types.md` →
57/// `("reference", "types.md")`, or `None` for a source in no known tree.
58fn split_source(source: &str) -> Option<(&str, &str)> {
59    let (tree, page) = source.split_once('/')?;
60    TREES.contains(&tree).then_some((tree, page))
61}
62
63/// The hosted URL of a bundled source page: `book/guides/agents/index.md` →
64/// `/book/guides/agents/`, `reference/types.md` → `/reference/types/`.
65fn 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
83/// An ATX heading (`#` to `####`) line's depth and text, with a trailing
84/// `{#anchor}` dropped.
85fn 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
97/// Split a Book text (the layout `site/scripts/build-llms-full.mjs` writes: each
98/// page between `# ──` rules, headed `# Source: book/<page>`) into sections.
99pub 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    // The open headings, shallowest first, each with its depth.
104    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                // A heading closes every open one at its depth or deeper, so a
151                // skipped level (`##` then `####`) nests under what is open.
152                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
163/// The query's words, lower-cased and de-duplicated.
164fn 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
175/// The best `limit` sections for `query`: a word in a heading counts more than
176/// one in the body, a section holding every word beats one holding some, and a
177/// verbatim phrase beats both. Ties keep the Book's reading order.
178pub 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
213/// At most `max` characters of `text`, from the first line holding one of
214/// `terms` when the section is longer, with any code fence it cut left closed.
215fn 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        // One enormous line still gets shown, cut.
235        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
253/// A section's page title and own heading; the headings between are noise.
254fn 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
262/// The line that labels a result with the Book's version.
263fn source_note() -> String {
264    format!(
265        "Source: the Bynk Book v{}, from the installed toolchain.",
266        env!("CARGO_PKG_VERSION")
267    )
268}
269
270/// `bynk book --search` as Markdown. Also what the MCP server's
271/// `bynk_search_book` returns, so both surfaces print one text.
272pub 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
302/// `bynk book --search --format json`.
303fn 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/// How `bynk book --search` prints.
324#[derive(Clone, Copy, Debug, PartialEq, Eq)]
325pub enum Format {
326    Text,
327    Json,
328}
329
330/// The embedded Book, or `None` for a build made without the bundle.
331pub fn embedded() -> Option<Book> {
332    (!BUNDLE.trim().is_empty()).then(|| parse(BUNDLE))
333}
334
335/// Run `bynk book`: print the whole Book, or with a `query` the matching
336/// sections. Exits `0` on success (including a search with no match) and `1`
337/// when this build carries no Book.
338pub 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    // A closed pipe (`bynk book | head`) is the reader's choice.
357    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        // Slice 5: a Reference page is served under /reference/, a Book page
390        // under /book/.
391        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}