Local code intelligence for developers and AI agents. Connect code, docs and infrastructure in a persistent graph, with CBM Lens, MCP tools, agent integrations and change-aware test selection.
C aiderastclaude-codecode-analysiscode-intelligencecodexcursorcypherdeveloper-toolsgemini-cligraph-visualizationkilocodeknowledge-graphmcpmcp-servermodel-context-protocolopencodesqlitetree-sitterwindsurf
doc-links(rust): intra-doc links become MENTIONS edges, held until their audit
Martin Vogel3af25b432fd4
diff --git a/Makefile.cbm b/Makefile.cbmindex 29f5896d0..43999c35c 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -388,6 +388,7 @@ EXTRACTION_SRCS = \$(CBM_DIR)/pdf/pdf_unicode.c \$(CBM_DIR)/doclink_go.c \$(CBM_DIR)/doclink_jvm.c \+ $(CBM_DIR)/doclink_rs.c \$(CBM_DIR)/sql_values.c \$(CBM_DIR)/helpers.c \$(CBM_DIR)/cpp_branch_views.c \@@ -516,6 +517,7 @@ PIPELINE_SRCS = \src/pipeline/doc_links_adoc.c \src/pipeline/doc_links_go.c \src/pipeline/doc_links_jvm.c \+ src/pipeline/doc_links_rs.c \src/pipeline/doc_links_msbuild.c \src/pipeline/pass_route_nodes.c \src/pipeline/pass_enrichment.c \@@ -778,7 +780,7 @@ TEST_DISCOVER_SRCS = \TEST_GRAPH_BUFFER_SRCS = tests/test_graph_buffer.c-TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.c+TEST_PIPELINE_SRCS = tests/test_registry.c tests/test_pipeline.c tests/test_pipeline_conventions.c tests/test_pipeline_frozen.c tests/test_importance.c tests/test_cross_repo.c tests/test_fqn.c tests/test_route_canon.c tests/test_path_alias.c tests/test_configlink.c tests/test_doclinks.c tests/test_doc_mentions.c tests/test_doc_links_md.c tests/test_doc_links_pdf.c tests/test_doc_links_rst.c tests/test_doc_links_adoc.c tests/test_doc_mentions_go.c tests/test_doc_mentions_jvm.c tests/test_doc_mentions_rs.c tests/test_infrascan.c tests/test_worker_pool.c tests/test_parallel.c tests/test_index_resilience.c tests/test_index_format.c tests/test_call_reference_contract.c tests/repro/repro_call_scope_usages.c tests/repro/repro_call_argument_usages.c tests/repro/repro_reference_precision.c tests/repro/repro_lexical_binding_precision.c tests/repro/repro_call_argument_matrix_a.c tests/repro/repro_call_argument_matrix_b.c tests/repro/repro_call_node_behaviors.c tests/repro/repro_language_registry.c tests/repro/repro_call_node_manifest.c tests/repro/repro_lsp_ordered_signatures.c tests/repro/repro_lsp_ordered_local.c tests/repro/repro_ts_overload_return_chains.c tests/repro/repro_harness_cleanup.c tests/repro/repro_runner_filter.cTEST_WATCHER_SRCS = tests/test_watcher.cdiff --git a/internal/cbm/doclink.c b/internal/cbm/doclink.cindex 6e58f34c2..92892d6e3 100644--- a/internal/cbm/doclink.c+++ b/internal/cbm/doclink.c@@ -200,6 +200,17 @@ static const doclink_lang_t DOCLINK_LANGS[] = {.scan_scope = cbm_doclink_kotlin_scan_scope,.scope_tag = CBM_DOCLINK_JVM_SCOPE_TAG,.portable_scope = cbm_doclink_jvm_portable_scope},+ {.lang = CBM_LANG_RUST,+ .parse_doc = cbm_doclink_rs_parse_doc,+ .scan_scope = cbm_doclink_rs_scan_scope,+ .scope_tag = CBM_DOCLINK_RS_SCOPE_TAG,+ .portable_scope = cbm_doclink_rs_portable_scope},+ /* Cargo.toml: the Rust resolver's crate facts come from its scope blob */+ {.lang = CBM_LANG_TOML,+ .parse_doc = cbm_doclink_rs_manifest_parse_doc,+ .scan_scope = cbm_doclink_rs_manifest_scan_scope,+ .scope_tag = CBM_DOCLINK_RS_SCOPE_TAG,+ .portable_scope = cbm_doclink_rs_portable_scope},};static const doclink_lang_t *doclink_lang(CBMLanguage lang) {diff --git a/internal/cbm/doclink.h b/internal/cbm/doclink.hindex c3a94cca3..4a5127437 100644--- a/internal/cbm/doclink.h+++ b/internal/cbm/doclink.h@@ -95,6 +95,9 @@X(CBM_DOCLINK_KT_SEE, CBM_LANG_KOTLIN, "see", false, false, "MENTIONS") \X(CBM_DOCLINK_KT_THROWS, CBM_LANG_KOTLIN, "throws", false, false, "MENTIONS") \X(CBM_DOCLINK_KT_SAMPLE, CBM_LANG_KOTLIN, "sample", false, false, "MENTIONS") \+ /* rust (doclink_rs.c): intra-doc links; held until their audit passes */ \+ X(CBM_DOCLINK_RS_INTRA_DOC, CBM_LANG_RUST, "intra_doc", false, false, "MENTIONS") \+ X(CBM_DOCLINK_RS_LINK_DEF, CBM_LANG_RUST, "link_def", false, false, "MENTIONS") \/* markdown (doclink_md.c): what a document's text names explicitly */ \X(CBM_DOCLINK_MD_LINK, CBM_LANG_MARKDOWN, "link", false, true, "MENTIONS") \X(CBM_DOCLINK_MD_PATH, CBM_LANG_MARKDOWN, "path", false, true, "MENTIONS") \@@ -461,5 +464,76 @@ size_t cbm_doclink_java_norm_type(const char *in, size_t len, char *out, size_t/* The longest reference a Java or Kotlin token may carry: a longer one is cut* just past this length at extraction and reported as unparseable. */#define CBM_DOCLINK_JVM_REF_MAX 1000+/* ── Rust (doclink_rs.c) ───────────────────────────────────────────── */++void cbm_doclink_rs_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def, const char *doc,+ uint32_t doc_line);+const char *cbm_doclink_rs_scan_scope(CBMExtractCtx *ctx);+char *cbm_doclink_rs_portable_scope(const char *scope);++/* A Cargo manifest is a TOML file the indexer extracts anyway: its scope blob+ * (package, targets, dependencies) is what the Rust resolver knows of crates,+ * so nothing is read from disk when references are resolved. Any other TOML+ * file has no scope, and no TOML file has references. */+void cbm_doclink_rs_manifest_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def,+ const char *doc, uint32_t doc_line);+const char *cbm_doclink_rs_manifest_scan_scope(CBMExtractCtx *ctx);++/* The Rust scope blob (a source file's and a manifest's) starts with this tag+ * line. */+#define CBM_DOCLINK_RS_SCOPE_TAG "rs1"++enum {+ CBM_DOCLINK_RS_MAX_SEGS = 16, /* path segments of one reference */+ CBM_DOCLINK_RS_SEG_CAP = 96, /* bytes of one segment, NUL included */+ CBM_DOCLINK_RS_RAW_CAP = 512, /* bytes of a reference as stored, NUL included */+};++/* What a rustdoc disambiguator (`struct@`, `fn@` ...) or suffix (`()`, `!`)+ * asks of the entity a path names. */+typedef enum {+ CBM_DOCLINK_RS_DIS_NONE = 0,+ CBM_DOCLINK_RS_DIS_STRUCT,+ CBM_DOCLINK_RS_DIS_ENUM,+ CBM_DOCLINK_RS_DIS_TRAIT,+ CBM_DOCLINK_RS_DIS_UNION,+ CBM_DOCLINK_RS_DIS_TYALIAS,+ CBM_DOCLINK_RS_DIS_MOD,+ CBM_DOCLINK_RS_DIS_CONST,+ CBM_DOCLINK_RS_DIS_STATIC,+ CBM_DOCLINK_RS_DIS_FN, /* `fn@`, `function@`, `method@`, and the `()` suffix */+ CBM_DOCLINK_RS_DIS_DERIVE, /* a derive macro */+ CBM_DOCLINK_RS_DIS_FIELD, /* a struct or union field */+ CBM_DOCLINK_RS_DIS_VARIANT, /* an enum variant */+ CBM_DOCLINK_RS_DIS_MACRO_BANG, /* the `!` suffix: a function-like macro */+ CBM_DOCLINK_RS_DIS_TYPE_NS, /* `type@`: anything of the type namespace */+ CBM_DOCLINK_RS_DIS_VALUE_NS, /* `value@` */+ CBM_DOCLINK_RS_DIS_MACRO_NS, /* `macro@` */+ CBM_DOCLINK_RS_DIS_PRIM, /* `prim@`, `primitive@` */+} CBMDocLinkRsDis;++/* One intra-doc link destination, taken apart. */+typedef struct {+ char segs[CBM_DOCLINK_RS_MAX_SEGS][CBM_DOCLINK_RS_SEG_CAP];+ int nsegs;+ bool global; /* a leading `::`: the first segment names a crate */+ int dis; /* CBMDocLinkRsDis */+} CBMDocLinkRsPath;++typedef enum {+ CBM_DOCLINK_RS_PATH_OK = 0,+ CBM_DOCLINK_RS_PATH_NOT_LINK, /* rustdoc does not treat this text as an intra-doc link */+ CBM_DOCLINK_RS_PATH_MALFORMED /* a link rustdoc reports as broken syntax */+} CBMDocLinkRsPathStatus;++/* Take a link destination apart the way rustdoc's `preprocess_link` does+ * (backticks and `#fragment` already removed): disambiguator or suffix,+ * generics stripped, `::` segments. `lenient` is rustdoc's rule for text that+ * may be an ordinary link or plain brackets (an inline or defined+ * destination, or an undefined shortcut without backticks): there a character+ * no path can hold means NOT_LINK instead of MALFORMED. `len` bytes of `raw`+ * are read. */+CBMDocLinkRsPathStatus cbm_doclink_rs_parse_path(const char *raw, size_t len, bool lenient,+ CBMDocLinkRsPath *out);#endif /* CBM_DOCLINK_H */diff --git a/internal/cbm/doclink_rs.c b/internal/cbm/doclink_rs.cnew file mode 100644index 000000000..c1da55f89--- /dev/null+++ b/internal/cbm/doclink_rs.c@@ -0,0 +1,4135 @@+/*+ * doclink_rs.c — Rust intra-doc links and the Rust doc-link scope.+ *+ * Tokens. Only what rustdoc itself documents is read: `///` (not `////`),+ * a block opened by slash-star-star (not by three stars), `//!` and the bang+ * block. The Markdown is read the way pulldown-cmark reads it for rustdoc:+ * fenced and indented code blocks, HTML blocks, code spans, inline HTML and+ * autolinks hold no links; link reference definitions are collected first;+ * inline `[text](dest)`, full `[text][label]`, collapsed `[label][]` and+ * shortcut `[label]` links are found, images, footnotes and task markers are+ * not links. A link is a reference when rustdoc's `preprocess_link` keeps it.+ * Families:+ * intra_doc the destination is written at the link: `[text](path)`, and+ * `[path]`, `[path][]`, `[text][path]` whose label has no+ * definition+ * link_def the destination comes from a link reference definition+ * href (the core's) an inline or defined destination that is a URL+ * A relative file destination and a page anchor are not harvested.+ *+ * Scope blob: one record per line, tab-separated, first line "rs1". Records+ * marked (fresh) exist only in the blob of the extraction itself and are+ * dropped by the persisted form, which also zeroes every line number:+ * B the tree has a parse error, or holds+ * something this scan cannot represent:+ * a name the file's modules do not show+ * may still be declared there+ * E line (fresh) first line that is not trusted: a+ * definition from there on has no scope+ * N id parent start end flags name inline module (the file itself is+ * module 0)+ * D mod flags name path `mod name;` declared in module `mod`;+ * path is the `#[path]` literal or '-'+ * U mod vis kind local path b named import, s `self` import (type+ * namespace only), g glob, x extern crate+ * T mod start end flags kind name node extra+ * item. kind: S struct E enum U union+ * R trait A alias F fn C const G static+ * M macro_rules V derive macro+ * B attribute macro P function-like+ * proc macro. extra: an alias's target+ * path; the derive names of a struct,+ * enum or union ("Clone,Debug", '*' for+ * names that were not read); '-'+ * otherwise+ * M start kind name node member of the preceding T (trait,+ * struct, union, enum) or I record:+ * f function, c constant, t type,+ * d field, v variant+ * I mod start end self trait impl block; self '?' when it is not a+ * path, trait '-' when inherent+ * Q mod name a name a macro invocation may declare+ * in module `mod`; '*': somewhere in the+ * file (it follows a parse error)+ * V mod name module `mod` invokes the macro `name`+ * among its items+ * W name names the `macro_rules!` macro `name` declares+ * these names (comma-joined) wherever it+ * is invoked+ * P line names (fresh) parameter and type parameter names of+ * the documented definition at `line`+ * Z line suffix (fresh) a documented definition that does not+ * own its node+ * flags: visibility (p pub, c crate, s super, i in-path, - private), then+ * 't' for `#[cfg(test)]` / `#[test]`, 'e' for `#[macro_export]`, 'c' for a+ * `mod` whose file cannot be told from the tree (a conditional path+ * attribute; an inline module with a path attribute, which moves the files of+ * the `mod x;` inside it).+ * node: '!' when the definition has no graph node of its own, else a label+ * code (S Struct, E Enum, C Class, I Interface, T Type, F Function,+ * V Variable, M Method, D Field) followed by '=' when the node's qualified+ * name is <module>.<name>, or by ':' and the part after "<module>.".+ *+ * Every item is matched to its definition in ctx->result->defs, so a node's+ * qualified name is the extractor's own (cfg suffixes, impl self-type text).+ * The graph keeps one node per qualified name: a definition owns it only when+ * it is the survivor among the file's definitions of that name (largest start+ * line, then name, then label -- cbm_gbuf_upsert_node's rule).+ *+ * Everything is derived from the tree and the definitions extracted from it,+ * so the blob is a pure function of the file's bytes.+ */+#include "doclink.h"++#include "arena.h"+#include "foundation/constants.h"+#include "foundation/mem_core.h"+#include "helpers.h" /* cbm_fqn_compute: the qualified names the extractor gives */+#include "tree_sitter/api.h"++#include <ctype.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++/* ── Small arena string builder ──────────────────────────────────── */++typedef struct {+ CBMArena *a;+ char *buf;+ size_t len;+ size_t cap;+ bool failed;+} rs_sb_t;++enum { RS_SB_INIT = 1024, RS_UINT_DIGITS = 16 };++static void rs_sb_reserve(rs_sb_t *sb, size_t extra) {+ if (sb->failed || sb->len + extra + SKIP_ONE <= sb->cap) {+ return;+ }+ size_t ncap = sb->cap ? sb->cap : RS_SB_INIT;+ while (ncap < sb->len + extra + SKIP_ONE) {+ ncap *= PAIR_LEN;+ }+ char *grown = (char *)cbm_arena_alloc(sb->a, ncap);+ if (!grown) {+ sb->failed = true;+ return;+ }+ if (sb->len > 0) {+ memcpy(grown, sb->buf, sb->len);+ }+ sb->buf = grown;+ sb->cap = ncap;+}++static void rs_sb_putn(rs_sb_t *sb, const char *s, size_t n) {+ rs_sb_reserve(sb, n);+ if (sb->failed) {+ return;+ }+ memcpy(sb->buf + sb->len, s, n);+ sb->len += n;+ sb->buf[sb->len] = '\0';+}++static void rs_sb_puts(rs_sb_t *sb, const char *s) {+ rs_sb_putn(sb, s, strlen(s));+}++static void rs_sb_putc(rs_sb_t *sb, char c) {+ rs_sb_putn(sb, &c, SKIP_ONE);+}++static void rs_sb_putu(rs_sb_t *sb, uint32_t v) {+ char tmp[RS_UINT_DIGITS];+ int n = snprintf(tmp, sizeof(tmp), "%u", v);+ if (n > 0) {+ rs_sb_putn(sb, tmp, (size_t)n);+ }+}++/* ── Characters ──────────────────────────────────────────────────── */++/* UTF-8 lead bytes and the code-point ranges that are neither letters nor+ * digits (rustdoc asks char::is_alphanumeric; this is that test without the+ * Unicode tables: every non-ASCII code point counts as a letter except the+ * punctuation, symbol and private-use blocks below). */+enum {+ RS_U8_ASCII_END = 0x80,+ RS_U8_LEAD2 = 0xC0,+ RS_U8_LEAD3 = 0xE0,+ RS_U8_LEAD4 = 0xF0,+ RS_U8_LEAD_END = 0xF8,+ RS_U8_CONT_MASK = 0xC0,+ RS_U8_CONT = 0x80,+ RS_U8_CONT_BITS = 6,+ RS_U8_CONT_VALUE = 0x3F,+ RS_U8_LEN2 = 2,+ RS_U8_LEN3 = 3,+ RS_U8_LEN4 = 4,+ RS_U8_MASK2 = 0x1F,+ RS_U8_MASK3 = 0x0F,+ RS_U8_MASK4 = 0x07,+ RS_CP_LATIN1_LETTERS = 0xC0, /* below: Latin-1 punctuation and symbols */+ RS_CP_FEMININE = 0xAA,+ RS_CP_MICRO = 0xB5,+ RS_CP_MASCULINE = 0xBA,+ RS_CP_TIMES = 0xD7,+ RS_CP_DIVIDE = 0xF7,+ RS_CP_PUNCT_FIRST = 0x2000, /* general punctuation .. misc symbols and arrows */+ RS_CP_PUNCT_LAST = 0x2BFF,+ RS_CP_CJK_PUNCT_FIRST = 0x3000,+ RS_CP_CJK_PUNCT_LAST = 0x303F,+ RS_CP_PRIVATE_FIRST = 0xE000,+ RS_CP_PRIVATE_LAST = 0xF8FF,+ RS_CP_VARIATION_FIRST = 0xFE00,+ RS_CP_VARIATION_LAST = 0xFE6F,+ RS_CP_SPECIALS_FIRST = 0xFFF0,+ RS_CP_SPECIALS_LAST = 0xFFFF,+ RS_CP_PICTO_FIRST = 0x1F000, /* emoji and pictographs */+ RS_CP_PICTO_LAST = 0x1FFFF,+ RS_CP_TAGS_FIRST = 0xE0000,+};++/* One code point at s[0..n): its value, or -1 for a byte that starts none;+ * *adv is the number of bytes to step over (at least 1). */+static int32_t rs_u8_decode(const unsigned char *s, size_t n, size_t *adv) {+ *adv = SKIP_ONE;+ if (n == 0) {+ return CBM_NOT_FOUND;+ }+ unsigned char b = s[0];+ if (b < RS_U8_ASCII_END) {+ return b;+ }+ size_t want = 0;+ int32_t cp = 0;+ if (b >= RS_U8_LEAD4 && b < RS_U8_LEAD_END) {+ want = RS_U8_LEN4;+ cp = b & RS_U8_MASK4;+ } else if (b >= RS_U8_LEAD3 && b < RS_U8_LEAD4) {+ want = RS_U8_LEN3;+ cp = b & RS_U8_MASK3;+ } else if (b >= RS_U8_LEAD2 && b < RS_U8_LEAD3) {+ want = RS_U8_LEN2;+ cp = b & RS_U8_MASK2;+ } else {+ return CBM_NOT_FOUND;+ }+ if (want > n) {+ return CBM_NOT_FOUND;+ }+ for (size_t i = SKIP_ONE; i < want; i++) {+ if ((s[i] & RS_U8_CONT_MASK) != RS_U8_CONT) {+ return CBM_NOT_FOUND;+ }+ cp = (cp << RS_U8_CONT_BITS) | (s[i] & RS_U8_CONT_VALUE);+ }+ *adv = want;+ return cp;+}++static bool rs_cp_in(int32_t cp, int32_t first, int32_t last) {+ return cp >= first && cp <= last;+}++static bool rs_cp_alnum(int32_t cp) {+ if (cp < 0) {+ return false;+ }+ if (cp < RS_U8_ASCII_END) {+ return isalnum(cp) != 0;+ }+ if (cp < RS_CP_LATIN1_LETTERS) {+ return cp == RS_CP_FEMININE || cp == RS_CP_MICRO || cp == RS_CP_MASCULINE;+ }+ if (cp == RS_CP_TIMES || cp == RS_CP_DIVIDE) {+ return false;+ }+ return !(rs_cp_in(cp, RS_CP_PUNCT_FIRST, RS_CP_PUNCT_LAST) ||+ rs_cp_in(cp, RS_CP_CJK_PUNCT_FIRST, RS_CP_CJK_PUNCT_LAST) ||+ rs_cp_in(cp, RS_CP_PRIVATE_FIRST, RS_CP_PRIVATE_LAST) ||+ rs_cp_in(cp, RS_CP_VARIATION_FIRST, RS_CP_VARIATION_LAST) ||+ rs_cp_in(cp, RS_CP_SPECIALS_FIRST, RS_CP_SPECIALS_LAST) ||+ rs_cp_in(cp, RS_CP_PICTO_FIRST, RS_CP_PICTO_LAST) || cp >= RS_CP_TAGS_FIRST);+}++/* True when every character of s[0..n) is a letter, a digit or one of+ * `extra`: rustdoc's test for text that can be a path. */+static bool rs_chars_ok(const char *s, size_t n, const char *extra) {+ const unsigned char *u = (const unsigned char *)s;+ for (size_t i = 0; i < n;) {+ size_t adv = SKIP_ONE;+ int32_t cp = rs_u8_decode(u + i, n - i, &adv);+ bool ok = rs_cp_alnum(cp) || (cp > 0 && cp < RS_U8_ASCII_END && strchr(extra, cp) != NULL);+ if (!ok) {+ return false;+ }+ i += adv;+ }+ return true;+}++/* A path segment: an identifier (optionally raw, `r#name`), or digits only (a+ * tuple field). */+static bool rs_is_segment(const char *s, size_t n) {+ static const char raw_prefix[] = "r#";+ const size_t rl = sizeof(raw_prefix) - SKIP_ONE;+ if (n > rl && memcmp(s, raw_prefix, rl) == 0) {+ s += rl;+ n -= rl;+ }+ if (n == 0) {+ return false;+ }+ bool digits = true;+ const unsigned char *u = (const unsigned char *)s;+ for (size_t i = 0; i < n;) {+ size_t adv = SKIP_ONE;+ int32_t cp = rs_u8_decode(u + i, n - i, &adv);+ if (!(rs_cp_alnum(cp) || cp == '_')) {+ return false;+ }+ digits = digits && cp < RS_U8_ASCII_END && isdigit(cp);+ i += adv;+ }+ return digits || !isdigit(u[0]);+}++/* ── The path grammar (rustdoc's preprocess_link) ────────────────── */++static const char RS_PATH_CHARS[] = ":_<>, !*&;"; /* should_ignore_link */+static const char RS_PATH_CHARS_DIS[] = ":_<>, !*&;@()"; /* ..._with_disambiguators */++static int rs_disambiguator(const char *word, size_t len) {+ static const struct {+ const char *word;+ int dis;+ } table[] = {+ {"struct", CBM_DOCLINK_RS_DIS_STRUCT}, {"enum", CBM_DOCLINK_RS_DIS_ENUM},+ {"trait", CBM_DOCLINK_RS_DIS_TRAIT}, {"union", CBM_DOCLINK_RS_DIS_UNION},+ {"module", CBM_DOCLINK_RS_DIS_MOD}, {"mod", CBM_DOCLINK_RS_DIS_MOD},+ {"const", CBM_DOCLINK_RS_DIS_CONST}, {"constant", CBM_DOCLINK_RS_DIS_CONST},+ {"static", CBM_DOCLINK_RS_DIS_STATIC}, {"function", CBM_DOCLINK_RS_DIS_FN},+ {"fn", CBM_DOCLINK_RS_DIS_FN}, {"method", CBM_DOCLINK_RS_DIS_FN},+ {"derive", CBM_DOCLINK_RS_DIS_DERIVE}, {"field", CBM_DOCLINK_RS_DIS_FIELD},+ {"variant", CBM_DOCLINK_RS_DIS_VARIANT}, {"type", CBM_DOCLINK_RS_DIS_TYPE_NS},+ {"value", CBM_DOCLINK_RS_DIS_VALUE_NS}, {"macro", CBM_DOCLINK_RS_DIS_MACRO_NS},+ {"prim", CBM_DOCLINK_RS_DIS_PRIM}, {"primitive", CBM_DOCLINK_RS_DIS_PRIM},+ {"tyalias", CBM_DOCLINK_RS_DIS_TYALIAS}, {"typealias", CBM_DOCLINK_RS_DIS_TYALIAS},+ };+ for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {+ if (strlen(table[i].word) == len && memcmp(table[i].word, word, len) == 0) {+ return table[i].dis;+ }+ }+ return CBM_DOCLINK_RS_DIS_NONE;+}++typedef struct {+ char *s;+ size_t n;+} rs_text_t;++static void rs_text_trim(rs_text_t *t) {+ while (t->n > 0 && isspace((unsigned char)t->s[0])) {+ t->s++;+ t->n--;+ }+ while (t->n > 0 && isspace((unsigned char)t->s[t->n - SKIP_ONE])) {+ t->n--;+ }+}++/* The `()`, `!` and `!()` suffixes: the kind they ask for, with the suffix+ * cut off. A suffix that would leave nothing is part of the path (`!` is the+ * never type, `()` the unit type). */+static int rs_cut_suffix(rs_text_t *t) {+ static const struct {+ const char *suffix;+ int dis;+ } table[] = {+ {"!()", CBM_DOCLINK_RS_DIS_MACRO_BANG}, {"!{}", CBM_DOCLINK_RS_DIS_MACRO_BANG},+ {"![]", CBM_DOCLINK_RS_DIS_MACRO_BANG}, {"()", CBM_DOCLINK_RS_DIS_FN},+ {"!", CBM_DOCLINK_RS_DIS_MACRO_BANG},+ };+ for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {+ size_t sl = strlen(table[i].suffix);+ if (t->n > sl && memcmp(t->s + t->n - sl, table[i].suffix, sl) == 0) {+ t->n -= sl;+ return table[i].dis;+ }+ }+ return CBM_DOCLINK_RS_DIS_NONE;+}++/* One `::`-separated piece with its generics removed, appended to `out`+ * (joined by `::`). false when the angle brackets do not balance or hold+ * fully-qualified syntax (`<T as Trait>`). */+static bool rs_strip_segment(const char *seg, size_t n, char *out, size_t *w) {+ static const char as_kw[] = " as ";+ const size_t as_len = sizeof(as_kw) - SKIP_ONE;+ int depth = 0;+ size_t start = *w;+ size_t chunk = 0; /* start of the innermost generics text read so far */+ if (start > 0) {+ out[(*w)++] = ':';+ out[(*w)++] = ':';+ }+ size_t body = *w;+ for (size_t i = 0; i < n; i++) {+ char c = seg[i];+ if (c == '<') {+ depth++;+ chunk = i + SKIP_ONE;+ } else if (c == '>') {+ depth--;+ for (size_t k = chunk; k + as_len <= i; k++) {+ if (memcmp(seg + k, as_kw, as_len) == 0) {+ return false;+ }+ }+ } else if (depth == 0) {+ out[(*w)++] = c;+ }+ }+ if (depth != 0) {+ return false;+ }+ if (*w == body) {+ *w = start; /* nothing left of it: no separator either */+ }+ return true;+}++/* rustdoc's strip_generics_from_path, in place: `Vec<T>::new` -> `Vec::new`.+ * false for malformed generics. A path without angle brackets is left as it+ * is. */+static bool rs_strip_generics(rs_text_t *t) {+ if (!memchr(t->s, '<', t->n) && !memchr(t->s, '>', t->n)) {+ return true;+ }+ char seg[CBM_DOCLINK_RS_RAW_CAP];+ char out[CBM_DOCLINK_RS_RAW_CAP + PAIR_LEN];+ size_t sn = 0;+ size_t w = 0;+ size_t i = 0;+ while (i < t->n) {+ char c = t->s[i++];+ if (c == ':') {+ if (i >= t->n || t->s[i] != ':') {+ return false; /* a single colon */+ }+ i++;+ if (!rs_strip_segment(seg, sn, out, &w)) {+ return false;+ }+ sn = 0;+ } else if (c == '<') {+ seg[sn++] = c;+ if (i >= t->n) {+ break;+ }+ char d = t->s[i++];+ if (d == '<' || d == '>') {+ return false; /* `<<` or `<>` */+ }+ seg[sn++] = d;+ while (i < t->n && t->s[i] != '>') {+ seg[sn++] = t->s[i++];+ }+ } else {+ seg[sn++] = c;+ }+ }+ if (sn > 0 && !rs_strip_segment(seg, sn, out, &w)) {+ return false;+ }+ if (w == 0) {+ return false;+ }+ memcpy(t->s, out, w);+ t->n = w;+ return true;+}++/* rustdoc's spellings of primitive types that are no identifiers. */+static bool rs_symbol_primitive(const char *s, size_t n) {+ static const char *const names[] = {"!", "&", "&mut", "&str", "*const", "*mut"};+ for (size_t i = 0; i < sizeof(names) / sizeof(names[0]); i++) {+ if (strlen(names[i]) == n && memcmp(names[i], s, n) == 0) {+ return true;+ }+ }+ return false;+}++/* Split a generics-free path at `::` into out->segs. */+static bool rs_split_segments(const char *s, size_t n, CBMDocLinkRsPath *out) {+ size_t i = 0;+ if (n >= PAIR_LEN && s[0] == ':' && s[1] == ':') {+ out->global = true;+ i = PAIR_LEN;+ }+ while (i <= n) {+ size_t e = i;+ while (e < n && !(s[e] == ':' && e + SKIP_ONE < n && s[e + SKIP_ONE] == ':')) {+ e++;+ }+ size_t len = e - i;+ if (out->nsegs >= CBM_DOCLINK_RS_MAX_SEGS || len >= CBM_DOCLINK_RS_SEG_CAP ||+ !rs_is_segment(s + i, len)) {+ return false;+ }+ memcpy(out->segs[out->nsegs], s + i, len);+ out->segs[out->nsegs][len] = '\0';+ out->nsegs++;+ if (e >= n) {+ break;+ }+ i = e + PAIR_LEN;+ }+ return out->nsegs > 0;+}++CBMDocLinkRsPathStatus cbm_doclink_rs_parse_path(const char *raw, size_t len, bool lenient,+ CBMDocLinkRsPath *out) {+ memset(out, 0, sizeof(*out));+ char buf[CBM_DOCLINK_RS_RAW_CAP];+ if (!raw || len >= sizeof(buf)) {+ return CBM_DOCLINK_RS_PATH_MALFORMED;+ }+ memcpy(buf, raw, len);+ buf[len] = '\0';+ rs_text_t t = {buf, len};+ rs_text_trim(&t);+ if (t.n == 0) {+ return CBM_DOCLINK_RS_PATH_NOT_LINK;+ }+ char *at = (char *)memchr(t.s, '@', t.n);+ if (at) {+ out->dis = rs_disambiguator(t.s, (size_t)(at - t.s));+ if (out->dis == CBM_DOCLINK_RS_DIS_NONE) {+ /* an unknown prefix: rustdoc reports it unless the text could not+ * be a link anyway */+ return rs_chars_ok(t.s, t.n, RS_PATH_CHARS_DIS) ? CBM_DOCLINK_RS_PATH_MALFORMED+ : CBM_DOCLINK_RS_PATH_NOT_LINK;+ }+ t.n -= (size_t)(at + SKIP_ONE - t.s);+ t.s = at + SKIP_ONE;+ rs_text_trim(&t);+ } else {+ out->dis = rs_cut_suffix(&t);+ }+ if (lenient && !rs_chars_ok(t.s, t.n, RS_PATH_CHARS)) {+ return CBM_DOCLINK_RS_PATH_NOT_LINK;+ }+ if (t.n > SKIP_ONE && t.s[0] == '!') {+ /* rustdoc: never a path (`!` alone is the never type). Admonitions+ * such as `[!NOTE]` are written this way. */+ return CBM_DOCLINK_RS_PATH_NOT_LINK;+ }+ if (rs_symbol_primitive(t.s, t.n)) {+ memcpy(out->segs[0], t.s, t.n);+ out->segs[0][t.n] = '\0';+ out->nsegs = SKIP_ONE;+ return CBM_DOCLINK_RS_PATH_OK;+ }+ if (!rs_strip_generics(&t)) {+ return CBM_DOCLINK_RS_PATH_MALFORMED;+ }+ if (memchr(t.s, ' ', t.n)) {+ return CBM_DOCLINK_RS_PATH_NOT_LINK; /* prose in brackets */+ }+ return rs_split_segments(t.s, t.n, out) ? CBM_DOCLINK_RS_PATH_OK+ : CBM_DOCLINK_RS_PATH_MALFORMED;+}++/* ── Doc text -> Markdown lines ──────────────────────────────────── */++enum { RS_L_BLANK = 0, RS_L_CODE, RS_L_TEXT, RS_L_DEF };+enum { RS_DOC_NONE = 0, RS_DOC_LINE, RS_DOC_BLOCK };+enum { RS_MARK_LEN = 3 }; /* `///`, `//!`, slash-star-star, slash-star-bang */++typedef struct {+ const char *p; /* content: after the comment marker, later after block markers */+ uint32_t len;+ uint32_t line; /* 1-based source line */+ uint32_t boff; /* offset of the content in its paragraph buffer */+ uint8_t kind; /* RS_L_* */+ bool para_start;+} rs_line_t;++static CBMArena *rs_scratch(CBMExtractCtx *ctx) {+ return ctx->scratch ? ctx->scratch : ctx->arena;+}++/* Which kind of rustdoc comment `doc` starts with (a plain `//`, a `////`+ * line and a three-star block are comments, not documentation). */+static int rs_doc_style(const char *doc) {+ if (doc[0] != '/') {+ return RS_DOC_NONE;+ }+ if (doc[1] == '/') {+ bool outer = doc[2] == '/' && doc[3] != '/';+ return (outer || doc[2] == '!') ? RS_DOC_LINE : RS_DOC_NONE;+ }+ if (doc[1] == '*') {+ bool outer = doc[2] == '*' && doc[3] != '*' && doc[3] != '/';+ return (outer || doc[2] == '!') ? RS_DOC_BLOCK : RS_DOC_NONE;+ }+ return RS_DOC_NONE;+}++static bool rs_blank(const char *p, uint32_t n) {+ for (uint32_t i = 0; i < n; i++) {+ if (p[i] != ' ' && p[i] != '\t' && p[i] != '\r') {+ return false;+ }+ }+ return true;+}++/* The number of spaces and tabs `p` (`n` bytes) starts with. */+static uint32_t rs_indent_len(const char *p, uint32_t n) {+ uint32_t i = 0;+ while (i < n && (p[i] == ' ' || p[i] == '\t')) {+ i++;+ }+ return i;+}++/* The content of one `///` or `//!` line; nothing for any other line. */+static void rs_line_content(rs_line_t *ln) {+ const char *p = ln->p;+ uint32_t n = ln->len;+ uint32_t i = rs_indent_len(p, n);+ const char *mark = p + i;+ uint32_t rest = n - i;+ if (rest < RS_MARK_LEN || mark[0] != '/' || mark[SKIP_ONE] != '/') {+ ln->len = 0;+ return;+ }+ /* `//!` is a doc line, `///` too unless a fourth slash makes it `////` */+ bool inner = mark[PAIR_LEN] == '!';+ bool outer = mark[PAIR_LEN] == '/' && !(rest > RS_MARK_LEN && mark[RS_MARK_LEN] == '/');+ if (!inner && !outer) {+ ln->len = 0;+ return;+ }+ ln->p = mark + RS_MARK_LEN;+ ln->len = rest - RS_MARK_LEN;+}++/* A block comment's decoration: when every line after the first that has text+ * starts with a star, the stars go (rustdoc's beautify_doc_string). */+static void rs_block_stars(rs_line_t *lines, int n) {+ bool any = false;+ for (int i = SKIP_ONE; i < n; i++) {+ const rs_line_t *ln = &lines[i];+ uint32_t k = 0;+ while (k < ln->len && (ln->p[k] == ' ' || ln->p[k] == '\t')) {+ k++;+ }+ if (k >= ln->len) {+ continue; /* blank */+ }+ if (ln->p[k] != '*') {+ return;+ }+ any = true;+ }+ for (int i = SKIP_ONE; any && i < n; i++) {+ rs_line_t *ln = &lines[i];+ uint32_t k = 0;+ while (k < ln->len && (ln->p[k] == ' ' || ln->p[k] == '\t')) {+ k++;+ }+ if (k < ln->len) {+ ln->p += k + SKIP_ONE;+ ln->len -= k + SKIP_ONE;+ }+ }+}++/* Remove the indentation every line with text shares (rustdoc's+ * unindent_doc_fragments). */+static void rs_unindent(rs_line_t *lines, int n) {+ uint32_t min = UINT32_MAX;+ for (int i = 0; i < n; i++) {+ const rs_line_t *ln = &lines[i];+ if (rs_blank(ln->p, ln->len)) {+ continue;+ }+ uint32_t k = 0;+ while (k < ln->len && (ln->p[k] == ' ' || ln->p[k] == '\t')) {+ k++;+ }+ min = k < min ? k : min;+ }+ if (min == UINT32_MAX || min == 0) {+ return;+ }+ for (int i = 0; i < n; i++) {+ rs_line_t *ln = &lines[i];+ if (ln->len >= min && !rs_blank(ln->p, ln->len)) {+ ln->p += min;+ ln->len -= min;+ }+ }+}++/* Split the stored doc text into Markdown lines. NULL (and *out_n 0) when it+ * is no rustdoc comment or memory ran out. */+static rs_line_t *rs_doc_lines(CBMArena *a, const char *doc, uint32_t doc_line, int *out_n) {+ *out_n = 0;+ int style = rs_doc_style(doc);+ if (style == RS_DOC_NONE) {+ return NULL;+ }+ size_t total = strlen(doc);+ const char *body = doc;+ if (style == RS_DOC_BLOCK) {+ while (total > 0 && isspace((unsigned char)doc[total - SKIP_ONE])) {+ total--;+ }+ if (total >= RS_MARK_LEN + PAIR_LEN && doc[total - PAIR_LEN] == '*' &&+ doc[total - SKIP_ONE] == '/') {+ total -= PAIR_LEN;+ }+ }+ int count = SKIP_ONE;+ for (size_t i = 0; i < total; i++) {+ count += doc[i] == '\n';+ }+ rs_line_t *lines = (rs_line_t *)cbm_arena_alloc(a, (size_t)count * sizeof(rs_line_t));+ if (!lines) {+ return NULL;+ }+ int n = 0;+ size_t start = 0;+ for (size_t i = 0; i <= total && n < count; i++) {+ if (i < total && body[i] != '\n') {+ continue;+ }+ size_t end = i;+ while (end > start && body[end - SKIP_ONE] == '\r') {+ end--;+ }+ lines[n] = (rs_line_t){.p = body + start,+ .len = (uint32_t)(end - start),+ .line = doc_line + (uint32_t)n,+ .kind = RS_L_BLANK};+ n++;+ start = i + SKIP_ONE;+ }+ if (style == RS_DOC_LINE) {+ for (int i = 0; i < n; i++) {+ rs_line_content(&lines[i]);+ }+ } else {+ lines[0].p += RS_MARK_LEN;+ lines[0].len = lines[0].len >= RS_MARK_LEN ? lines[0].len - RS_MARK_LEN : 0;+ rs_block_stars(lines, n);+ }+ rs_unindent(lines, n);+ *out_n = n;+ return lines;+}++/* text[0..*n) without the white space at both ends. */+static const char *rs_trimmed(const char *text, size_t *n) {+ while (*n > 0 && isspace((unsigned char)text[0])) {+ text++;+ (*n)--;+ }+ while (*n > 0 && isspace((unsigned char)text[*n - SKIP_ONE])) {+ (*n)--;+ }+ return text;+}++/* Give the lines of a file's own doc their real source lines.+ *+ * The inner docs of a file are every `//!` line and bang block before its+ * first item, joined: plain comments, blank lines and `#![..]` attributes+ * between them are not part of the text, so counting from the first line+ * drifts. Each doc line is looked up in the source instead, forward from the+ * line before it (a doc line equals its source line up to indentation).+ * Nothing changes unless every line is found. */+static void rs_lines_resync(CBMExtractCtx *ctx, rs_line_t *lines, int n, const char *doc,+ uint32_t doc_line) {+ const char *src = ctx->source;+ size_t src_len = ctx->source_len > 0 ? (size_t)ctx->source_len : 0;+ uint32_t *found = (uint32_t *)cbm_arena_alloc(rs_scratch(ctx), (size_t)n * sizeof(uint32_t));+ if (!src || !found || doc_line == 0) {+ return;+ }+ size_t pos = 0; /* start of source line `at` */+ uint32_t at = SKIP_ONE;+ while (at < doc_line && pos < src_len) {+ const char *nl = (const char *)memchr(src + pos, '\n', src_len - pos);+ pos = nl ? (size_t)(nl - src) + SKIP_ONE : src_len;+ at++;+ }+ const char *d = doc;+ for (int i = 0; i < n; i++) {+ const char *dnl = strchr(d, '\n');+ size_t dlen = dnl ? (size_t)(dnl - d) : strlen(d);+ const char *want = rs_trimmed(d, &dlen);+ bool matched = false;+ while (!matched && pos < src_len) {+ const char *nl = (const char *)memchr(src + pos, '\n', src_len - pos);+ size_t slen = nl ? (size_t)(nl - (src + pos)) : src_len - pos;+ const char *have = rs_trimmed(src + pos, &slen);+ matched = slen == dlen && memcmp(have, want, dlen) == 0;+ found[i] = at;+ pos = nl ? (size_t)(nl - src) + SKIP_ONE : src_len;+ at++;+ }+ if (!matched) {+ return;+ }+ d = dnl ? dnl + SKIP_ONE : d + strlen(d);+ }+ for (int i = 0; i < n; i++) {+ lines[i].line = found[i];+ }+}++/* ── Markdown blocks ─────────────────────────────────────────────── */++enum {+ RS_MD_CODE_INDENT = 4, /* columns that make an indented code block */+ RS_MD_TAB = 4,+ RS_MD_FENCE_MIN = 3,+ RS_MD_ATX_MAX = 6,+ RS_MD_ORDERED_DIGITS = 9,+ RS_MD_LIST_INIT = 8, /* open list items: the stack grows */+ RS_MD_LABEL_MAX = 999, /* CommonMark's limit for a link label */+ RS_MD_TAG_NAME_MAX = 16, /* longest HTML block tag name + 1 */+ RS_HTML_NONE = 0,+ RS_HTML_RAW = 1, /* pre, script, style, textarea: until the closing tag */+ RS_HTML_COMMENT = 2, /* until --> */+ RS_HTML_PI = 3, /* until ?> */+ RS_HTML_DECL = 4, /* until > */+ RS_HTML_CDATA = 5, /* until ]]> */+ RS_HTML_BLOCK = 6, /* a block tag: until a blank line */+ RS_HTML_ANY = 7, /* any single tag alone on its line: until a blank line */+};++typedef struct {+ const char *label; /* normalized: trimmed, whitespace collapsed, ASCII lower case */+ const char *dest;+ uint32_t dest_len;+ int order;+} rs_def_t;++typedef struct {+ CBMArena *a;+ rs_def_t *v;+ int n;+ int cap;+ bool failed;+} rs_defs_t;++typedef struct {+ bool fence;+ char fence_ch;+ uint32_t fence_len;+ int html; /* RS_HTML_* of the open HTML block */+ bool para;+ bool quoted; /* the open paragraph is inside a block quote */+ CBMArena *a;+ int *list; /* content column of every open list item */+ int nlist;+ int list_cap;+ bool failed; /* out of memory: the doc text gets no tokens */+} rs_md_t;++/* A cursor in one line: byte position and the column it stands at. */+typedef struct {+ const char *p;+ uint32_t n;+ uint32_t pos;+ int col;+} rs_cur_t;++static void rs_cur_skip_ws(rs_cur_t *c) {+ while (c->pos < c->n && (c->p[c->pos] == ' ' || c->p[c->pos] == '\t')) {+ c->col += c->p[c->pos] == '\t' ? RS_MD_TAB - (c->col % RS_MD_TAB) : SKIP_ONE;+ c->pos++;+ }+}++static bool rs_cur_eol(const rs_cur_t *c) {+ return rs_blank(c->p + c->pos, c->n - c->pos);+}++/* An opening code fence at the cursor: its character and length. */+static bool rs_md_fence_open(const rs_cur_t *c, char *ch, uint32_t *len) {+ if (c->pos >= c->n || (c->p[c->pos] != '`' && c->p[c->pos] != '~')) {+ return false;+ }+ char f = c->p[c->pos];+ uint32_t k = c->pos;+ while (k < c->n && c->p[k] == f) {+ k++;+ }+ if (k - c->pos < RS_MD_FENCE_MIN) {+ return false;+ }+ if (f == '`' && memchr(c->p + k, '`', c->n - k)) {+ return false; /* the info string of a backtick fence holds no backtick */+ }+ *ch = f;+ *len = k - c->pos;+ return true;+}++static bool rs_md_fence_close(const rs_line_t *ln, const rs_md_t *st) {+ rs_cur_t c = {ln->p, ln->len, 0, 0};+ rs_cur_skip_ws(&c);+ uint32_t k = c.pos;+ while (k < c.n && c.p[k] == st->fence_ch) {+ k++;+ }+ return k - c.pos >= st->fence_len && rs_blank(c.p + k, c.n - k);+}++/* `---`, `***`, `___` (three or more, spaces allowed between). */+static bool rs_md_thematic(const rs_cur_t *c) {+ if (c->pos >= c->n) {+ return false;+ }+ char m = c->p[c->pos];+ if (m != '-' && m != '*' && m != '_') {+ return false;+ }+ int count = 0;+ for (uint32_t k = c->pos; k < c->n; k++) {+ char ch = c->p[k];+ if (ch == m) {+ count++;+ } else if (ch != ' ' && ch != '\t' && ch != '\r') {+ return false;+ }+ }+ return count >= RS_MD_FENCE_MIN;+}++/* `# heading`: the cursor moves to the heading's text. */+static bool rs_md_atx(rs_cur_t *c) {+ uint32_t k = c->pos;+ while (k < c->n && c->p[k] == '#') {+ k++;+ }+ uint32_t hashes = k - c->pos;+ if (hashes == 0 || hashes > RS_MD_ATX_MAX || (k < c->n && c->p[k] != ' ' && c->p[k] != '\t')) {+ return false;+ }+ c->col += (int)hashes;+ c->pos = k;+ return true;+}++/* A list marker at the cursor: its width in bytes, 0 when there is none.+ * *first is false for an ordered marker other than `1`, which cannot+ * interrupt a paragraph. */+static uint32_t rs_md_list_marker(const rs_cur_t *c, bool *first) {+ *first = true;+ uint32_t k = c->pos;+ if (k >= c->n) {+ return 0;+ }+ char m = c->p[k];+ if (m == '-' || m == '+' || m == '*') {+ k++;+ } else if (isdigit((unsigned char)m)) {+ while (k < c->n && isdigit((unsigned char)c->p[k]) && k - c->pos < RS_MD_ORDERED_DIGITS) {+ k++;+ }+ if (k >= c->n || (c->p[k] != '.' && c->p[k] != ')')) {+ return 0;+ }+ *first = k - c->pos == SKIP_ONE && m == '1';+ k++;+ } else {+ return 0;+ }+ if (k < c->n && c->p[k] != ' ' && c->p[k] != '\t' && c->p[k] != '\r') {+ return 0;+ }+ return k - c->pos;+}++static bool rs_ci_prefix(const char *p, uint32_t n, const char *word) {+ size_t wl = strlen(word);+ if (n < wl) {+ return false;+ }+ for (size_t i = 0; i < wl; i++) {+ if (tolower((unsigned char)p[i]) != word[i]) {+ return false;+ }+ }+ return true;+}++static bool rs_ci_find(const char *p, uint32_t n, const char *word) {+ size_t wl = strlen(word);+ for (uint32_t i = 0; i + wl <= n; i++) {+ if (rs_ci_prefix(p + i, n - i, word)) {+ return true;+ }+ }+ return false;+}++static bool rs_html_block_tag(const char *name, size_t len) {+ static const char *const tags[] = {+ "address", "article", "aside", "base", "basefont", "blockquote", "body",+ "caption", "center", "col", "colgroup", "dd", "details", "dialog",+ "dir", "div", "dl", "dt", "fieldset", "figcaption", "figure",+ "footer", "form", "frame", "frameset", "h1", "h2", "h3",+ "h4", "h5", "h6", "head", "header", "hr", "html",+ "iframe", "legend", "li", "link", "main", "menu", "menuitem",+ "nav", "noframes", "ol", "optgroup", "option", "p", "param",+ "search", "section", "summary", "table", "tbody", "td", "tfoot",+ "th", "thead", "title", "tr", "track", "ul",+ };+ char low[RS_MD_TAG_NAME_MAX];+ if (len == 0 || len >= sizeof(low)) {+ return false;+ }+ for (size_t i = 0; i < len; i++) {+ low[i] = (char)tolower((unsigned char)name[i]);+ }+ low[len] = '\0';+ for (size_t i = 0; i < sizeof(tags) / sizeof(tags[0]); i++) {+ if (strcmp(tags[i], low) == 0) {+ return true;+ }+ }+ return false;+}++/* End of an HTML tag that starts at p[0] == '<' (a quoted attribute value may+ * hold '>'): index just past its '>', or 0 when the line has none. */+static uint32_t rs_html_tag_end(const char *p, uint32_t n) {+ char quote = 0;+ for (uint32_t i = SKIP_ONE; i < n; i++) {+ char c = p[i];+ if (quote) {+ quote = c == quote ? 0 : quote;+ } else if (c == '"' || c == '\'') {+ quote = c;+ } else if (c == '>') {+ return i + SKIP_ONE;+ } else if (c == '<') {+ return 0;+ }+ }+ return 0;+}++/* The HTML block that starts at the cursor (RS_HTML_*), none inside a+ * paragraph for the kind that cannot interrupt one. */+static int rs_md_html_start(const rs_cur_t *c, bool in_para) {+ const char *p = c->p + c->pos;+ uint32_t n = c->n - c->pos;+ if (n < PAIR_LEN || p[0] != '<') {+ return RS_HTML_NONE;+ }+ static const char *const raw[] = {"<pre", "<script", "<style", "<textarea"};+ for (size_t i = 0; i < sizeof(raw) / sizeof(raw[0]); i++) {+ size_t rl = strlen(raw[i]);+ if (rs_ci_prefix(p, n, raw[i]) &&+ (n == rl || p[rl] == ' ' || p[rl] == '\t' || p[rl] == '>' || p[rl] == '\r')) {+ return RS_HTML_RAW;+ }+ }+ if (rs_ci_prefix(p, n, "<!--")) {+ return RS_HTML_COMMENT;+ }+ if (p[1] == '?') {+ return RS_HTML_PI;+ }+ if (rs_ci_prefix(p, n, "<![cdata[")) {+ return RS_HTML_CDATA;+ }+ if (p[1] == '!' && n > PAIR_LEN && isalpha((unsigned char)p[PAIR_LEN])) {+ return RS_HTML_DECL;+ }+ uint32_t k = p[1] == '/' ? PAIR_LEN : SKIP_ONE;+ uint32_t name = k;+ while (k < n && (isalnum((unsigned char)p[k]) || p[k] == '-')) {+ k++;+ }+ if (k == name || !isalpha((unsigned char)p[name])) {+ return RS_HTML_NONE;+ }+ bool ends = k >= n || p[k] == ' ' || p[k] == '\t' || p[k] == '>' || p[k] == '\r' ||+ (p[k] == '/' && k + SKIP_ONE < n && p[k + SKIP_ONE] == '>');+ if (ends && rs_html_block_tag(p + name, k - name)) {+ return RS_HTML_BLOCK;+ }+ uint32_t end = rs_html_tag_end(p, n);+ return (!in_para && end > 0 && rs_blank(p + end, n - end)) ? RS_HTML_ANY : RS_HTML_NONE;+}++/* True when this line ends the open HTML block of kind `html`. */+static bool rs_md_html_end(const rs_line_t *ln, int html) {+ switch (html) {+ case RS_HTML_RAW:+ return rs_ci_find(ln->p, ln->len, "</pre>") || rs_ci_find(ln->p, ln->len, "</script>") ||+ rs_ci_find(ln->p, ln->len, "</style>") || rs_ci_find(ln->p, ln->len, "</textarea>");+ case RS_HTML_COMMENT:+ return rs_ci_find(ln->p, ln->len, "-->");+ case RS_HTML_PI:+ return rs_ci_find(ln->p, ln->len, "?>");+ case RS_HTML_DECL:+ return memchr(ln->p, '>', ln->len) != NULL;+ case RS_HTML_CDATA:+ return rs_ci_find(ln->p, ln->len, "]]>");+ default:+ return false;+ }+}++/* ── Link reference definitions ──────────────────────────────────── */++/* A link label, normalized into the arena: trimmed, inner whitespace+ * collapsed, ASCII letters lower-cased. NULL when it holds no text. */+static const char *rs_label_norm(CBMArena *a, const char *s, size_t n) {+ char *out = (char *)cbm_arena_alloc(a, n + SKIP_ONE);+ if (!out) {+ return NULL;+ }+ size_t w = 0;+ bool space = false;+ for (size_t i = 0; i < n; i++) {+ unsigned char c = (unsigned char)s[i];+ if (isspace(c)) {+ space = w > 0;+ continue;+ }+ if (space) {+ out[w++] = ' ';+ space = false;+ }+ out[w++] = (char)tolower(c);+ }+ out[w] = '\0';+ return w > 0 ? out : NULL;+}++/* End of the label that starts after the '[' at s[from - 1]: the index of its+ * closing ']', or UINT32_MAX when the text is no label (an unescaped bracket+ * inside, too long, or unclosed). */+static uint32_t rs_label_end(const char *s, uint32_t n, uint32_t from) {+ for (uint32_t i = from; i < n && i - from <= RS_MD_LABEL_MAX; i++) {+ char c = s[i];+ if (c == '\\' && i + SKIP_ONE < n) {+ i++;+ } else if (c == '[') {+ return UINT32_MAX;+ } else if (c == ']') {+ return i;+ }+ }+ return UINT32_MAX;+}++/* True when s[0..n) can be a link label: some text, no unescaped bracket, not+ * longer than CommonMark allows. */+static bool rs_label_clean(const char *s, uint32_t n) {+ if (n == 0 || n > RS_MD_LABEL_MAX || rs_blank(s, n)) {+ return false;+ }+ for (uint32_t i = 0; i < n; i++) {+ if (s[i] == '\\' && i + SKIP_ONE < n) {+ i++;+ } else if (s[i] == '[' || s[i] == ']') {+ return false;+ }+ }+ return true;+}++/* A link destination at s[*pos]: `<...>` or a run without spaces and with+ * balanced parentheses. On success *pos moves past it. */+static bool rs_link_dest(const char *s, uint32_t n, uint32_t *pos, const char **dest,+ uint32_t *dest_len) {+ uint32_t i = *pos;+ if (i < n && s[i] == '<') {+ uint32_t k = i + SKIP_ONE;+ while (k < n && s[k] != '>' && s[k] != '<' && s[k] != '\n') {+ k += (s[k] == '\\' && k + SKIP_ONE < n) ? PAIR_LEN : SKIP_ONE;+ }+ if (k >= n || s[k] != '>') {+ return false;+ }+ *dest = s + i + SKIP_ONE;+ *dest_len = k - i - SKIP_ONE;+ *pos = k + SKIP_ONE;+ return true;+ }+ int depth = 0;+ uint32_t k = i;+ while (k < n) {+ unsigned char c = (unsigned char)s[k];+ if (c == '\\' && k + SKIP_ONE < n) {+ k += PAIR_LEN;+ continue;+ }+ if (c <= ' ') {+ break;+ }+ if (c == '(') {+ depth++;+ } else if (c == ')') {+ if (depth == 0) {+ break;+ }+ depth--;+ }+ k++;+ }+ if (depth != 0) {+ return false;+ }+ *dest = s + i;+ *dest_len = k - i;+ *pos = k;+ return true;+}++/* An optional link title at s[*pos] (`"..."`, `'...'`, `(...)`): *pos moves+ * past it. false when a title starts and does not end. */+static bool rs_link_title(const char *s, uint32_t n, uint32_t *pos) {+ uint32_t i = *pos;+ if (i >= n || (s[i] != '"' && s[i] != '\'' && s[i] != '(')) {+ return true;+ }+ char close = s[i] == '(' ? ')' : s[i];+ for (uint32_t k = i + SKIP_ONE; k < n; k++) {+ if (s[k] == '\\' && k + SKIP_ONE < n) {+ k++;+ } else if (s[k] == close) {+ *pos = k + SKIP_ONE;+ return true;+ }+ }+ return false;+}++static void rs_defs_push(rs_defs_t *d, rs_def_t def) {+ if (d->n >= d->cap) {+ int ncap = d->cap ? d->cap * PAIR_LEN : CBM_SZ_8;+ rs_def_t *grown = (rs_def_t *)cbm_arena_alloc(d->a, (size_t)ncap * sizeof(rs_def_t));+ if (!grown) {+ d->failed = true;+ return;+ }+ if (d->n > 0) {+ memcpy(grown, d->v, (size_t)d->n * sizeof(rs_def_t));+ }+ d->v = grown;+ d->cap = ncap;+ }+ def.order = d->n;+ d->v[d->n++] = def;+}++static uint32_t rs_skip_spaces(const char *s, uint32_t n, uint32_t i) {+ while (i < n && (s[i] == ' ' || s[i] == '\t' || s[i] == '\r')) {+ i++;+ }+ return i;+}++/* A link reference definition `[label]: dest "title"` that starts at the+ * cursor of lines[i]; the destination may stand on the next line. Returns the+ * number of lines it takes (0: this is no definition). */+static int rs_md_definition(rs_line_t *lines, int n, int i, const rs_cur_t *c, rs_defs_t *defs) {+ const char *s = c->p;+ uint32_t len = c->n;+ uint32_t pos = c->pos;+ if (pos >= len || s[pos] != '[' || (pos + SKIP_ONE < len && s[pos + SKIP_ONE] == '^')) {+ return 0;+ }+ uint32_t close = rs_label_end(s, len, pos + SKIP_ONE);+ if (close == UINT32_MAX || close + SKIP_ONE >= len || s[close + SKIP_ONE] != ':') {+ return 0;+ }+ const char *label = rs_label_norm(defs->a, s + pos + SKIP_ONE, close - pos - SKIP_ONE);+ if (!label) {+ return 0;+ }+ int taken = SKIP_ONE;+ uint32_t k = rs_skip_spaces(s, len, close + PAIR_LEN);+ if (k >= len) {+ /* the destination is on the next line */+ if (i + SKIP_ONE >= n || rs_blank(lines[i + SKIP_ONE].p, lines[i + SKIP_ONE].len)) {+ return 0;+ }+ s = lines[i + SKIP_ONE].p;+ len = lines[i + SKIP_ONE].len;+ k = rs_skip_spaces(s, len, 0);+ taken = PAIR_LEN;+ }+ const char *dest = NULL;+ uint32_t dest_len = 0;+ if (!rs_link_dest(s, len, &k, &dest, &dest_len) || dest_len == 0) {+ return 0;+ }+ uint32_t after = rs_skip_spaces(s, len, k);+ if (after < len &&+ (after == k || !rs_link_title(s, len, &after) || rs_skip_spaces(s, len, after) < len)) {+ return 0; /* something that is no title follows the destination */+ }+ rs_defs_push(defs, (rs_def_t){.label = label, .dest = dest, .dest_len = dest_len});+ return taken;+}++static int rs_def_cmp(const void *a, const void *b) {+ const rs_def_t *x = (const rs_def_t *)a;+ const rs_def_t *y = (const rs_def_t *)b;+ int c = strcmp(x->label, y->label);+ return c ? c : (x->order > y->order) - (x->order < y->order);+}++/* The first definition of `label` (normalized), or NULL. */+static const rs_def_t *rs_def_find(const rs_defs_t *d, const char *label) {+ int lo = 0;+ int hi = d->n;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (strcmp(d->v[mid].label, label) < 0) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return (lo < d->n && strcmp(d->v[lo].label, label) == 0) ? &d->v[lo] : NULL;+}++/* ── Markdown blocks: one line ───────────────────────────────────── */++static void rs_md_pop_lists(rs_md_t *st, int col) {+ while (st->nlist > 0 && st->list[st->nlist - SKIP_ONE] > col) {+ st->nlist--;+ }+}++/* Column the text of a line is measured from: the content column of the+ * innermost open list item it reaches. The stack is strictly increasing (an+ * item opens to the right of everything still open), so this is a binary+ * search. */+static int rs_md_base(const rs_md_t *st, int col) {+ int lo = 0;+ int hi = st->nlist;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (st->list[mid] <= col) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo > 0 ? st->list[lo - SKIP_ONE] : 0;+}++static void rs_md_push_list(rs_md_t *st, int content) {+ if (st->nlist >= st->list_cap) {+ int ncap = st->list_cap ? st->list_cap * PAIR_LEN : RS_MD_LIST_INIT;+ int *grown = (int *)cbm_arena_alloc(st->a, (size_t)ncap * sizeof(int));+ if (!grown) {+ st->failed = true;+ return;+ }+ if (st->nlist > 0) {+ memcpy(grown, st->list, (size_t)st->nlist * sizeof(int));+ }+ st->list = grown;+ st->list_cap = ncap;+ }+ st->list[st->nlist++] = content;+}++/* Block-quote markers at the cursor; true when there was one. */+static bool rs_md_quote(rs_cur_t *c) {+ bool quoted = false;+ while (c->pos < c->n && c->p[c->pos] == '>') {+ quoted = true;+ c->pos++;+ c->col++;+ if (c->pos < c->n && c->p[c->pos] == ' ') {+ c->pos++;+ c->col++;+ }+ rs_cur_skip_ws(c);+ }+ return quoted;+}++/* Open a list item whose marker is `width` bytes at the cursor; the cursor+ * moves to the item's content (past a task marker). */+static void rs_md_open_item(rs_md_t *st, rs_cur_t *c, uint32_t width) {+ c->pos += width;+ c->col += (int)width;+ int marker_end = c->col;+ rs_cur_skip_ws(c);+ int content = c->col;+ if (rs_cur_eol(c) || content - marker_end > RS_MD_CODE_INDENT) {+ content = marker_end + SKIP_ONE;+ }+ rs_md_push_list(st, content);+ /* a task marker `[ ]` / `[x]` is no link */+ const char *p = c->p + c->pos;+ uint32_t left = c->n - c->pos;+ if (left > RS_MARK_LEN && p[0] == '[' && (p[1] == ' ' || p[1] == 'x' || p[1] == 'X') &&+ p[PAIR_LEN] == ']' && (p[RS_MARK_LEN] == ' ' || p[RS_MARK_LEN] == '\t')) {+ c->pos += RS_MARK_LEN;+ c->col += RS_MARK_LEN;+ }+}++/* What starts at the cursor. */+enum { RS_BLK_TEXT = 0, RS_BLK_FENCE, RS_BLK_HTML, RS_BLK_RULE, RS_BLK_HEADING, RS_BLK_ITEM };++typedef struct {+ int kind;+ char fence_ch;+ uint32_t fence_len;+ int html;+ uint32_t marker; /* width of a list marker */+ bool interrupts; /* may end an open paragraph */+} rs_blk_t;++static rs_blk_t rs_md_block_at(const rs_cur_t *c, bool in_para) {+ rs_blk_t b = {.kind = RS_BLK_TEXT, .interrupts = true};+ if (rs_md_fence_open(c, &b.fence_ch, &b.fence_len)) {+ b.kind = RS_BLK_FENCE;+ return b;+ }+ b.html = rs_md_html_start(c, in_para);+ if (b.html != RS_HTML_NONE) {+ b.kind = RS_BLK_HTML;+ return b;+ }+ if (rs_md_thematic(c)) {+ b.kind = RS_BLK_RULE;+ return b;+ }+ rs_cur_t probe = *c;+ if (rs_md_atx(&probe)) {+ b.kind = RS_BLK_HEADING;+ return b;+ }+ bool first = true;+ b.marker = rs_md_list_marker(c, &first);+ if (b.marker > 0) {+ b.kind = RS_BLK_ITEM;+ /* an empty item, or an ordered one not numbered 1, continues a paragraph */+ rs_cur_t rest = *c;+ rest.pos += b.marker;+ b.interrupts = first && !rs_cur_eol(&rest);+ }+ return b;+}++/* A line of an open fenced block or HTML block, or a blank line: classified+ * here. false for any other line. */+static bool rs_md_line_in_block(rs_md_t *st, rs_line_t *ln) {+ if (st->fence) {+ st->fence = !rs_md_fence_close(ln, st);+ return true;+ }+ bool blank = rs_blank(ln->p, ln->len);+ if (st->html != RS_HTML_NONE) {+ if (st->html >= RS_HTML_BLOCK ? blank : rs_md_html_end(ln, st->html)) {+ st->html = RS_HTML_NONE;+ }+ ln->kind = blank ? RS_L_BLANK : RS_L_CODE;+ return true;+ }+ if (blank) {+ ln->kind = RS_L_BLANK;+ st->para = false;+ }+ return blank;+}++/* The line is inline text from the cursor on. */+static void rs_md_text(rs_line_t *ln, const rs_cur_t *c, bool para_start) {+ ln->kind = RS_L_TEXT;+ ln->para_start = para_start;+ ln->len -= c->pos;+ ln->p += c->pos;+}++/* What is no list item starts at the cursor of lines[i]. Returns the lines it+ * takes, or 0 when the rest of the line is inline text (a heading's, or a+ * paragraph's first line). */+static int rs_md_start_block(rs_md_t *st, rs_line_t *lines, int n, int i, rs_cur_t *c,+ const rs_blk_t *b, bool quoted, rs_defs_t *defs) {+ rs_line_t *ln = &lines[i];+ if (b->kind == RS_BLK_FENCE) {+ st->fence = true;+ st->fence_ch = b->fence_ch;+ st->fence_len = b->fence_len;+ return SKIP_ONE;+ }+ if (b->kind == RS_BLK_HTML) {+ bool closed = b->html < RS_HTML_BLOCK && rs_md_html_end(ln, b->html);+ st->html = closed ? RS_HTML_NONE : b->html;+ return SKIP_ONE;+ }+ if (b->kind == RS_BLK_RULE) {+ ln->kind = RS_L_BLANK;+ return SKIP_ONE;+ }+ if (b->kind == RS_BLK_HEADING) {+ (void)rs_md_atx(c);+ return 0;+ }+ int taken = rs_md_definition(lines, n, i, c, defs);+ if (taken > 0) {+ ln->kind = RS_L_DEF;+ if (taken > SKIP_ONE) {+ lines[i + SKIP_ONE].kind = RS_L_DEF;+ }+ return taken;+ }+ st->para = true;+ st->quoted = quoted;+ return 0;+}++/* Classify lines[i] and strip its block markers. Returns how many lines were+ * consumed (2 when a link definition's destination is on the next line). */+static int rs_md_line(rs_md_t *st, rs_line_t *lines, int n, int i, rs_defs_t *defs) {+ rs_line_t *ln = &lines[i];+ ln->kind = RS_L_CODE;+ if (rs_md_line_in_block(st, ln)) {+ return SKIP_ONE;+ }+ rs_cur_t c = {ln->p, ln->len, 0, 0};+ rs_cur_skip_ws(&c);+ bool quoted = rs_md_quote(&c);+ if (quoted && !st->quoted) {+ st->para = false; /* a block quote interrupts a paragraph */+ }+ /* every round opens one list item, which moves the cursor on */+ for (;;) {+ rs_blk_t b = rs_md_block_at(&c, st->para);+ if (st->para) {+ bool breaks = b.kind != RS_BLK_TEXT && b.interrupts &&+ c.col - rs_md_base(st, c.col) < RS_MD_CODE_INDENT;+ if (!breaks) {+ rs_md_text(ln, &c, false); /* the paragraph goes on, however indented */+ return SKIP_ONE;+ }+ st->para = false;+ }+ rs_md_pop_lists(st, c.col);+ if (c.col - rs_md_base(st, c.col) >= RS_MD_CODE_INDENT) {+ return SKIP_ONE; /* an indented code block */+ }+ if (b.kind != RS_BLK_ITEM) {+ int taken = rs_md_start_block(st, lines, n, i, &c, &b, quoted, defs);+ if (taken > 0) {+ return taken;+ }+ break;+ }+ rs_md_open_item(st, &c, b.marker);+ if (rs_cur_eol(&c)) {+ ln->kind = RS_L_BLANK;+ return SKIP_ONE;+ }+ }+ rs_md_text(ln, &c, true);+ return SKIP_ONE;+}++/* ── Inline links ────────────────────────────────────────────────── */++enum { RS_LINK_INLINE = 0, RS_LINK_REFERENCE, RS_LINK_COLLAPSED, RS_LINK_SHORTCUT };++typedef struct {+ uint32_t pos;+ bool image;+} rs_opener_t;++/* A maximal run of backticks. */+typedef struct {+ uint32_t pos;+ uint32_t len;+} rs_run_t;++/* What a found link is handed to. */+typedef struct {+ CBMExtractCtx *ctx;+ const char *source_qn;+ uint32_t def_line;+ const rs_defs_t *defs;+ const rs_line_t *lines; /* the paragraph's lines */+ int nlines;+ int line_cursor;+} rs_sink_t;++/* Inline state of one paragraph. The arrays are allocated once per doc text,+ * large enough for any paragraph of it (one slot per '[' and per backtick), so+ * nothing here has a limit a long doc could hit. */+typedef struct {+ const char *s; /* the paragraph */+ uint32_t n;+ rs_opener_t *open; /* the '[' not yet closed */+ int nopen;+ int dead; /* openers below this index are inside a link: they open none */+ rs_run_t *runs; /* backtick runs in text order */+ rs_run_t *by_len; /* the same, sorted by (length, position) */+ int nruns;+ int run_cursor; /* first run that ends after the scan position */+ bool no_comment_end; /* no later `-->` / `]]>` / `?>`: searched once */+ bool no_cdata_end;+ bool no_pi_end;+ rs_sink_t *sink;+} rs_inline_t;++/* Source line of paragraph offset `off`. Links are reported in the order of+ * their opening brackets, so the cursor rarely moves back. */+static uint32_t rs_sink_line(rs_sink_t *k, uint32_t off) {+ if (k->lines[k->line_cursor].boff > off) {+ k->line_cursor = 0;+ }+ while (k->line_cursor + SKIP_ONE < k->nlines &&+ k->lines[k->line_cursor + SKIP_ONE].boff <= off) {+ k->line_cursor++;+ }+ return k->lines[k->line_cursor].line;+}++static bool rs_is_url(const char *s, size_t n) {+ static const char mailto[] = "mailto:";+ static const char sep[] = "://";+ if (rs_ci_prefix(s, (uint32_t)n, mailto)) {+ return true;+ }+ size_t i = 0;+ if (n == 0 || !isalpha((unsigned char)s[0])) {+ return false;+ }+ while (i < n && (isalnum((unsigned char)s[i]) || s[i] == '+' || s[i] == '.' || s[i] == '-')) {+ i++;+ }+ return i + sizeof(sep) - SKIP_ONE <= n && memcmp(s + i, sep, sizeof(sep) - SKIP_ONE) == 0;+}++static void rs_push_token(rs_sink_t *k, const char *raw, size_t n, int syntax, uint32_t line) {+ static const char cut[] = "...";+ char buf[CBM_DOCLINK_RS_RAW_CAP];+ if (n >= sizeof(buf) - sizeof(cut)) {+ /* oversized: a prefix that can never parse as a path */+ n = sizeof(buf) - sizeof(cut) - SKIP_ONE;+ memcpy(buf, raw, n);+ memcpy(buf + n, cut, sizeof(cut));+ n += sizeof(cut) - SKIP_ONE;+ } else {+ memcpy(buf, raw, n);+ buf[n] = '\0';+ }+ for (size_t i = 0; i < n; i++) {+ if (buf[i] == '\n' || buf[i] == '\t' || buf[i] == '\r' || buf[i] == '\0') {+ buf[i] = ' ';+ }+ }+ const char *copy = cbm_arena_strndup(k->ctx->arena, buf, n);+ if (!copy) {+ return;+ }+ CBMDocLink link = {+ .source_qn = k->source_qn,+ .raw = copy,+ .line = line,+ .def_line = k->def_line,+ .syntax = (uint16_t)syntax,+ };+ cbm_doclinks_push(&k->ctx->result->doc_links, k->ctx->arena, link);+}++/* A found link: decide whether rustdoc treats its destination as an intra-doc+ * link, and push the token. `defined`: the destination was written (inline)+ * or comes from a definition, so it may be an ordinary URL. */+static void rs_emit_link(rs_sink_t *k, int kind, const char *dest, uint32_t dest_len, bool from_def,+ uint32_t off) {+ while (dest_len > 0 && isspace((unsigned char)dest[0])) {+ dest++;+ dest_len--;+ }+ while (dest_len > 0 && isspace((unsigned char)dest[dest_len - SKIP_ONE])) {+ dest_len--;+ }+ if (dest_len == 0) {+ return;+ }+ uint32_t line = rs_sink_line(k, off);+ bool written = kind == RS_LINK_INLINE || from_def; /* rustdoc's can_be_url */+ int family = from_def ? CBM_DOCLINK_RS_LINK_DEF : CBM_DOCLINK_RS_INTRA_DOC;+ if (written && memchr(dest, '/', dest_len)) {+ if (rs_is_url(dest, dest_len)) {+ rs_push_token(k, dest, dest_len, CBM_DOCLINK_HREF, line);+ }+ return; /* a relative file is not harvested */+ }+ /* backticks go, the fragment is cut */+ char clean[CBM_DOCLINK_RS_RAW_CAP];+ size_t w = 0;+ int hashes = 0;+ bool backtick = false;+ for (uint32_t i = 0; i < dest_len; i++) {+ if (dest[i] == '`') {+ backtick = true;+ continue;+ }+ hashes += dest[i] == '#';+ if (w + SKIP_ONE < sizeof(clean)) {+ clean[w++] = dest[i];+ }+ }+ clean[w] = '\0';+ if (w + SKIP_ONE >= sizeof(clean)) {+ rs_push_token(k, clean, w, family, line); /* oversized */+ return;+ }+ /* rustdoc looks at the text before the first '#' first: empty means an+ * anchor of this page, whatever follows. A second '#' is then an error. */+ size_t path_len = hashes > 0 ? (size_t)((const char *)memchr(clean, '#', w) - clean) : w;+ while (path_len > 0 && isspace((unsigned char)clean[path_len - SKIP_ONE])) {+ path_len--;+ }+ if (path_len == 0) {+ return; /* an anchor of this page */+ }+ if (hashes > SKIP_ONE) {+ path_len = w; /* the row shows the whole destination */+ }+ bool lenient = written || (kind == RS_LINK_SHORTCUT && !backtick);+ CBMDocLinkRsPath path;+ CBMDocLinkRsPathStatus st = hashes > SKIP_ONE+ ? CBM_DOCLINK_RS_PATH_MALFORMED+ : cbm_doclink_rs_parse_path(clean, path_len, lenient, &path);+ if (st == CBM_DOCLINK_RS_PATH_NOT_LINK) {+ if (written && rs_is_url(dest, dest_len)) {+ rs_push_token(k, dest, dest_len, CBM_DOCLINK_HREF, line);+ }+ return;+ }+ rs_push_token(k, clean, path_len, family, line);+}++/* A reference-style link whose label is s[0..n): its destination is the+ * definition's, or (rustdoc's broken-link callback) the label itself. */+static void rs_emit_reference(rs_sink_t *k, int kind, const char *label, uint32_t n, uint32_t off) {+ const char *norm = rs_label_norm(rs_scratch(k->ctx), label, n);+ if (!norm || norm[0] == '^') {+ return; /* empty, or a footnote */+ }+ const rs_def_t *def = rs_def_find(k->defs, norm);+ if (def) {+ rs_emit_link(k, kind, def->dest, def->dest_len, true, off);+ } else {+ rs_emit_link(k, kind, label, n, false, off);+ }+}++static int rs_run_len_cmp(const void *a, const void *b) {+ const rs_run_t *x = (const rs_run_t *)a;+ const rs_run_t *y = (const rs_run_t *)b;+ if (x->len != y->len) {+ return x->len < y->len ? -1 : 1;+ }+ return (x->pos > y->pos) - (x->pos < y->pos);+}++/* Record the paragraph's backtick runs, in text order and by length: a code+ * span closes at the first later run of its opener's length, which is then a+ * binary search instead of a scan of the rest of the paragraph. */+static void rs_inline_runs(rs_inline_t *in) {+ in->nruns = 0;+ in->run_cursor = 0;+ for (uint32_t i = 0; i < in->n;) {+ if (in->s[i] != '`') {+ i++;+ continue;+ }+ uint32_t e = i;+ while (e < in->n && in->s[e] == '`') {+ e++;+ }+ in->runs[in->nruns++] = (rs_run_t){.pos = i, .len = e - i};+ i = e;+ }+ if (in->nruns > 0) {+ memcpy(in->by_len, in->runs, (size_t)in->nruns * sizeof(rs_run_t));+ qsort(in->by_len, (size_t)in->nruns, sizeof(rs_run_t), rs_run_len_cmp);+ }+}++/* Past the code span that opens at the backtick s[i], or past its run alone+ * when no later run has the opener's length. The opener is what is left of+ * its run from s[i] on (a backslash before the run takes its first backtick). */+static uint32_t rs_inline_backticks(rs_inline_t *in, uint32_t i) {+ while (in->run_cursor < in->nruns &&+ in->runs[in->run_cursor].pos + in->runs[in->run_cursor].len <= i) {+ in->run_cursor++;+ }+ if (in->run_cursor >= in->nruns) {+ return i + SKIP_ONE;+ }+ uint32_t run_end = in->runs[in->run_cursor].pos + in->runs[in->run_cursor].len;+ rs_run_t want = {.pos = run_end, .len = run_end - i};+ int lo = 0;+ int hi = in->nruns;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (rs_run_len_cmp(&in->by_len[mid], &want) < 0) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ if (lo < in->nruns && in->by_len[lo].len == want.len) {+ return in->by_len[lo].pos + want.len;+ }+ return run_end;+}++/* Index just past the first `mark` at or after s[from], or 0. */+static uint32_t rs_find_after(const rs_inline_t *in, uint32_t from, const char *mark) {+ size_t ml = strlen(mark);+ for (uint32_t k = from; k + ml <= in->n; k++) {+ if (memcmp(in->s + k, mark, ml) == 0) {+ return k + (uint32_t)ml;+ }+ }+ return 0;+}++/* Past the HTML comment, CDATA section or processing instruction that starts+ * at s[i]; 0 when s[i] starts none of them. One whose end marker is missing is+ * plain text, and so is every later one of its kind: the search for the marker+ * runs once per paragraph. */+static uint32_t rs_inline_raw_html(rs_inline_t *in, uint32_t i, bool *is_raw) {+ static const char comment[] = "<!--";+ static const char cdata[] = "<![CDATA[";+ static const char pi[] = "<?";+ const char *p = in->s + i;+ uint32_t n = in->n - i;+ const char *end_mark = NULL;+ bool *none = NULL;+ uint32_t skip = 0;+ if (n >= sizeof(comment) - SKIP_ONE && memcmp(p, comment, sizeof(comment) - SKIP_ONE) == 0) {+ end_mark = "-->";+ none = &in->no_comment_end;+ skip = sizeof(comment) - SKIP_ONE;+ } else if (n >= sizeof(cdata) - SKIP_ONE && memcmp(p, cdata, sizeof(cdata) - SKIP_ONE) == 0) {+ end_mark = "]]>";+ none = &in->no_cdata_end;+ skip = sizeof(cdata) - SKIP_ONE;+ } else if (n >= sizeof(pi) - SKIP_ONE && memcmp(p, pi, sizeof(pi) - SKIP_ONE) == 0) {+ end_mark = "?>";+ none = &in->no_pi_end;+ skip = sizeof(pi) - SKIP_ONE;+ }+ *is_raw = end_mark != NULL;+ if (!end_mark || *none) {+ return 0;+ }+ uint32_t end = rs_find_after(in, i + skip, end_mark);+ *none = end == 0;+ return end;+}++/* Past the autolink or HTML construct at s[i] == '<', or i + 1 when it is+ * neither. */+static uint32_t rs_inline_angle(rs_inline_t *in, uint32_t i) {+ const char *p = in->s + i;+ uint32_t n = in->n - i;+ if (n < PAIR_LEN) {+ return i + SKIP_ONE;+ }+ bool is_raw = false;+ uint32_t raw_end = rs_inline_raw_html(in, i, &is_raw);+ if (is_raw) {+ return raw_end ? raw_end : i + SKIP_ONE;+ }+ char c = p[1];+ if (!(isalpha((unsigned char)c) || c == '/' || c == '!')) {+ return i + SKIP_ONE;+ }+ uint32_t end = rs_html_tag_end(p, n);+ if (end == 0) {+ return i + SKIP_ONE;+ }+ if (isalpha((unsigned char)c)) {+ /* `<name ...>` is a tag; `<scheme:...>` and `<a@b>` are autolinks; text+ * with a space before any of that is neither */+ uint32_t k = SKIP_ONE;+ while (k < end &&+ (isalnum((unsigned char)p[k]) || p[k] == '-' || p[k] == '+' || p[k] == '.')) {+ k++;+ }+ bool tag = p[k] == '>' || p[k] == ' ' || p[k] == '\t' || p[k] == '\n' || p[k] == '/';+ bool autolink = (p[k] == ':' || p[k] == '@') && !memchr(p, ' ', end);+ if (!tag && !autolink) {+ return i + SKIP_ONE;+ }+ }+ return i + end;+}++/* The inline link `(dest "title")` at s[i] == '('. On success *end is past the+ * closing parenthesis. */+static bool rs_inline_dest(const rs_inline_t *in, uint32_t i, const char **dest, uint32_t *dest_len,+ uint32_t *end) {+ const char *s = in->s;+ uint32_t n = in->n;+ uint32_t k = i + SKIP_ONE;+ while (k < n && isspace((unsigned char)s[k])) {+ k++;+ }+ if (!rs_link_dest(s, n, &k, dest, dest_len)) {+ return false;+ }+ uint32_t after = k;+ while (after < n && isspace((unsigned char)s[after])) {+ after++;+ }+ if (after > k && !rs_link_title(s, n, &after)) {+ return false;+ }+ while (after < n && isspace((unsigned char)s[after])) {+ after++;+ }+ if (after >= n || s[after] != ')') {+ return false;+ }+ *end = after + SKIP_ONE;+ return true;+}++/* The reference-style link the ']' at s[i] ends, when the text after it or+ * the bracket text itself is a label: full `[text][label]`, collapsed+ * `[label][]`, shortcut `[label]`. *made is set when it is one; returns where+ * scanning continues. */+static uint32_t rs_inline_reference(rs_inline_t *in, const rs_opener_t *op, uint32_t i,+ bool *made) {+ const char *s = in->s;+ const char *text = s + op->pos + SKIP_ONE;+ uint32_t text_len = i - op->pos - SKIP_ONE;+ uint32_t after = i + SKIP_ONE;+ bool text_is_label = rs_label_clean(text, text_len);+ if (after < in->n && s[after] == '[') {+ uint32_t close = rs_label_end(s, in->n, after + SKIP_ONE);+ if (close != UINT32_MAX && close > after + SKIP_ONE) {+ *made = true;+ if (!op->image) {+ rs_emit_reference(in->sink, RS_LINK_REFERENCE, s + after + SKIP_ONE,+ close - after - SKIP_ONE, op->pos);+ }+ return close + SKIP_ONE;+ }+ if (close == after + SKIP_ONE && text_is_label) {+ *made = true;+ if (!op->image) {+ rs_emit_reference(in->sink, RS_LINK_COLLAPSED, text, text_len, op->pos);+ }+ return close + SKIP_ONE;+ }+ }+ if (text_is_label) {+ *made = true;+ if (!op->image) {+ rs_emit_reference(in->sink, RS_LINK_SHORTCUT, text, text_len, op->pos);+ }+ }+ return i + SKIP_ONE;+}++/* The ']' at s[i]: make a link of the bracket pair it closes, when it is one.+ * Returns where scanning continues. */+static uint32_t rs_inline_close(rs_inline_t *in, uint32_t i) {+ if (in->nopen == 0) {+ return i + SKIP_ONE;+ }+ int idx = --in->nopen;+ rs_opener_t op = in->open[idx];+ bool dead = idx < in->dead && !op.image; /* inside a link: links do not nest */+ if (in->dead > in->nopen) {+ in->dead = in->nopen;+ }+ if (dead) {+ return i + SKIP_ONE;+ }+ uint32_t after = i + SKIP_ONE;+ const char *dest = NULL;+ uint32_t dest_len = 0;+ uint32_t end = 0;+ bool made = false;+ if (after < in->n && in->s[after] == '(' && rs_inline_dest(in, after, &dest, &dest_len, &end)) {+ made = true;+ if (!op.image) {+ rs_emit_link(in->sink, RS_LINK_INLINE, dest, dest_len, false, op.pos);+ }+ } else {+ end = rs_inline_reference(in, &op, i, &made);+ }+ if (made && !op.image) {+ in->dead = in->nopen; /* every '[' still open encloses this link */+ }+ return end;+}++/* Find the links of one paragraph. */+static void rs_inline_scan(rs_inline_t *in) {+ uint32_t i = 0;+ while (i < in->n) {+ char c = in->s[i];+ if (c == '\\' && i + SKIP_ONE < in->n && ispunct((unsigned char)in->s[i + SKIP_ONE])) {+ i += PAIR_LEN;+ } else if (c == '`') {+ i = rs_inline_backticks(in, i);+ } else if (c == '<') {+ i = rs_inline_angle(in, i);+ } else if (c == '[') {+ bool image = i > 0 && in->s[i - SKIP_ONE] == '!' &&+ !(i > SKIP_ONE && in->s[i - PAIR_LEN] == '\\');+ in->open[in->nopen++] = (rs_opener_t){.pos = i, .image = image};+ i++;+ } else if (c == ']') {+ i = rs_inline_close(in, i);+ } else {+ i++;+ }+ }+}++/* ── Tokens of one doc text ──────────────────────────────────────── */++/* Scan the paragraph lines[first..last] (RS_L_TEXT lines): their contents are+ * joined by newlines in `buf`. */+static void rs_scan_paragraph(rs_inline_t *in, rs_sink_t *sink, rs_line_t *lines, int first,+ int last, char *buf) {+ uint32_t w = 0;+ for (int i = first; i <= last; i++) {+ lines[i].boff = w;+ memcpy(buf + w, lines[i].p, lines[i].len);+ w += lines[i].len;+ buf[w++] = '\n';+ }+ in->s = buf;+ in->n = w;+ in->nopen = 0;+ in->dead = 0;+ in->no_comment_end = false;+ in->no_cdata_end = false;+ in->no_pi_end = false;+ in->sink = sink;+ sink->lines = lines + first;+ sink->nlines = last - first + SKIP_ONE;+ sink->line_cursor = 0;+ rs_inline_runs(in);+ rs_inline_scan(in);+}++/* The inline state for a doc text whose inline lines are lines[0..n): arrays+ * with one slot per '[' and per backtick of the whole text, so no paragraph can+ * outgrow them. NULL when there is no inline text or memory ran out; *buf_out+ * is the paragraph buffer. */+static rs_inline_t *rs_inline_new(CBMArena *tmp, const rs_line_t *lines, int n, char **buf_out) {+ size_t text_bytes = 0;+ size_t brackets = 0;+ size_t backticks = 0;+ for (int i = 0; i < n; i++) {+ if (lines[i].kind != RS_L_TEXT) {+ continue;+ }+ text_bytes += (size_t)lines[i].len + SKIP_ONE;+ for (uint32_t k = 0; k < lines[i].len; k++) {+ brackets += lines[i].p[k] == '[';+ backticks += lines[i].p[k] == '`';+ }+ }+ if (text_bytes == 0 || brackets == 0) {+ return NULL; /* no bracket, no link */+ }+ rs_inline_t *in = (rs_inline_t *)cbm_arena_alloc(tmp, sizeof(*in));+ char *buf = (char *)cbm_arena_alloc(tmp, text_bytes + SKIP_ONE);+ if (!in || !buf) {+ return NULL;+ }+ memset(in, 0, sizeof(*in));+ in->open = (rs_opener_t *)cbm_arena_alloc(tmp, brackets * sizeof(rs_opener_t));+ in->runs = (rs_run_t *)cbm_arena_alloc(tmp, (backticks + SKIP_ONE) * sizeof(rs_run_t));+ in->by_len = (rs_run_t *)cbm_arena_alloc(tmp, (backticks + SKIP_ONE) * sizeof(rs_run_t));+ if (!in->open || !in->runs || !in->by_len) {+ return NULL;+ }+ *buf_out = buf;+ return in;+}++/* The references of one doc text, pushed as tokens of the node `source_qn`.+ * `file_doc`: it is the file's own doc, whose lines need not be contiguous. */+static void rs_parse_text(CBMExtractCtx *ctx, const char *source_qn, uint32_t def_line,+ const char *doc, uint32_t doc_line, bool file_doc) {+ if (!doc || !source_qn || !strchr(doc, '[')) {+ return; /* no bracket, no link */+ }+ CBMArena *tmp = rs_scratch(ctx);+ int n = 0;+ rs_line_t *lines = rs_doc_lines(tmp, doc, doc_line, &n);+ if (!lines || n == 0) {+ return;+ }+ if (file_doc) {+ rs_lines_resync(ctx, lines, n, doc, doc_line);+ }+ rs_defs_t defs = {.a = tmp};+ rs_md_t st;+ memset(&st, 0, sizeof(st));+ st.a = tmp;+ for (int i = 0; i < n;) {+ i += rs_md_line(&st, lines, n, i, &defs);+ }+ char *buf = NULL;+ rs_inline_t *in = (defs.failed || st.failed) ? NULL : rs_inline_new(tmp, lines, n, &buf);+ if (!in) {+ return;+ }+ if (defs.n > SKIP_ONE) {+ qsort(defs.v, (size_t)defs.n, sizeof(rs_def_t), rs_def_cmp);+ }+ rs_sink_t sink = {.ctx = ctx, .source_qn = source_qn, .def_line = def_line, .defs = &defs};+ int first = CBM_NOT_FOUND;+ for (int i = 0; i <= n; i++) {+ bool text = i < n && lines[i].kind == RS_L_TEXT;+ if (first >= 0 && (!text || lines[i].para_start)) {+ rs_scan_paragraph(in, &sink, lines, first, i - SKIP_ONE, buf);+ first = CBM_NOT_FOUND;+ }+ if (text && first < 0) {+ first = i;+ }+ }+}++void cbm_doclink_rs_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def, const char *doc,+ uint32_t doc_line) {+ if (!ctx || !ctx->result || !def) {+ return;+ }+ /* the driver's stand-in definition for the file's own doc is labelled File */+ bool file_doc = def->label && strcmp(def->label, "File") == 0;+ rs_parse_text(ctx, def->qualified_name, def->start_line, doc, doc_line, file_doc);+}++/* ── Scope scan: state ───────────────────────────────────────────── */++enum {+ RS_SCAN_NAME_CAP = 128, /* bytes of one identifier, NUL included */+ RS_SCAN_PATH_CAP = 512, /* bytes of one written path, NUL included */+ RS_SCAN_ATTR_CAP = 1024, /* bytes of an attribute that are read */+ RS_SCAN_DERIVES_CAP = 256, /* bytes of the derive names of one item, NUL included */+ RS_SCAN_INIT = 16,+};++/* A block whose items are still to be read: the file, an inline module's+ * body, an extern block's body. Blocks are queued, never recursed into. */+typedef struct {+ TSNode node;+ int mod; /* module the items belong to */+} rs_block_t;++/* A definition of the file, keyed for the items the scan meets. */+typedef struct {+ uint32_t line;+ const char *name;+ int def;+} rs_defkey_t;++/* What the attributes above an item say about it. */+typedef struct {+ bool test; /* #[cfg(test)], #[test], #[bench], #[tokio::test] ... */+ bool macro_export; /* #[macro_export] */+ bool cond_path; /* #[cfg_attr(.., path = ..)]: where the module file is depends on cfg */+ bool derives_more; /* derive names that did not fit, or were not read */+ char macro_kind; /* P #[proc_macro], B #[proc_macro_attribute], V #[proc_macro_derive] */+ char path[RS_SCAN_PATH_CAP]; /* #[path = "..."] */+ char derive[RS_SCAN_NAME_CAP]; /* the derive macro's name */+ char derives[RS_SCAN_DERIVES_CAP]; /* #[derive(A, b::C)] -> "A,C": impls not in the tree */+} rs_attrs_t;++typedef struct {+ CBMExtractCtx *ctx;+ CBMArena *tmp; /* nothing of it outlives the scan */+ const char *src;+ uint32_t src_len;+ rs_sb_t sb;+ bool failed; /* out of memory */+ bool broken; /* something the blob cannot represent, or a parse error */+ uint32_t err_byte; /* first byte that is not trusted; UINT32_MAX: none */+ int next_mod;+ rs_block_t *blocks;+ int nblocks;+ int blocks_cap;+ const char *item_prefix; /* "<qualified name of an item of this file minus its name>." */+ size_t item_prefix_len;+ rs_defkey_t *defkeys;+ int ndefkeys;+ unsigned char *owner; /* per definition: 1 when it owns its graph node */+ int *owner_of; /* per definition: the definition that owns its qualified name */+ int *def_mod; /* per definition: 1 + the module the scan met it in, 0: not met */+ uint32_t *ref_lines; /* start lines of the definitions that carry references, sorted */+ int nref_lines;+ int last_use_mod; /* the V record written last: a run of */+ char last_use[RS_SCAN_NAME_CAP]; /* invocations of one macro is written once */+} rs_scan_t;++static bool rs_kind(TSNode n, const char *kind) {+ return strcmp(ts_node_type(n), kind) == 0;+}++static TSNode rs_field(TSNode n, const char *field) {+ return ts_node_child_by_field_name(n, field, (uint32_t)strlen(field));+}++static uint32_t rs_line_of(TSNode n) {+ return ts_node_start_point(n).row + TS_LINE_OFFSET;+}++static uint32_t rs_end_line_of(TSNode n) {+ return ts_node_end_point(n).row + TS_LINE_OFFSET;+}++static void *rs_tmp_alloc(rs_scan_t *s, size_t n) {+ void *p = cbm_arena_alloc(s->tmp, n ? n : SKIP_ONE);+ s->failed = s->failed || !p;+ return p;+}++/* The node's text as a name: copied into `out` when it is an identifier that+ * fits (raw `r#name` keeps its marker, as the extractor's names do). false+ * for anything else -- error recovery can hand back a "name" spanning code. */+static bool rs_name_of(const rs_scan_t *s, TSNode n, char *out, size_t cap) {+ if (ts_node_is_null(n)) {+ return false;+ }+ uint32_t a = ts_node_start_byte(n);+ uint32_t b = ts_node_end_byte(n);+ if (b <= a || b > s->src_len || (size_t)(b - a) >= cap || !rs_is_segment(s->src + a, b - a)) {+ return false;+ }+ memcpy(out, s->src + a, b - a);+ out[b - a] = '\0';+ return true;+}++/* A written path (`a::b::C`, `crate::x`, `::std::fmt`) of the node's text,+ * whitespace removed: copied into `out` when it holds nothing but segments.+ * false for a type that is no path (a reference, a tuple, generics inside). */+static bool rs_path_of(const rs_scan_t *s, TSNode n, char *out, size_t cap) {+ if (ts_node_is_null(n)) {+ return false;+ }+ uint32_t a = ts_node_start_byte(n);+ uint32_t b = ts_node_end_byte(n);+ if (b <= a || b > s->src_len) {+ return false;+ }+ size_t w = 0;+ for (uint32_t i = a; i < b; i++) {+ char c = s->src[i];+ if (isspace((unsigned char)c)) {+ continue;+ }+ if (w + SKIP_ONE >= cap) {+ return false;+ }+ out[w++] = c;+ }+ out[w] = '\0';+ CBMDocLinkRsPath path;+ return w > 0 && !memchr(out, '<', w) && !memchr(out, '@', w) && !memchr(out, '!', w) &&+ !memchr(out, '(', w) &&+ cbm_doclink_rs_parse_path(out, w, false, &path) == CBM_DOCLINK_RS_PATH_OK;+}++/* ── Scope scan: definitions ─────────────────────────────────────── */++static int rs_defkey_cmp(const void *a, const void *b) {+ const rs_defkey_t *x = (const rs_defkey_t *)a;+ const rs_defkey_t *y = (const rs_defkey_t *)b;+ if (x->line != y->line) {+ return x->line < y->line ? -1 : 1;+ }+ int c = strcmp(x->name, y->name);+ return c ? c : (x->def > y->def) - (x->def < y->def);+}++/* The order in which the graph buffer lets definitions of one qualified name+ * replace each other (cbm_gbuf_upsert_node, same file): start line, then+ * name, then label; the last one owns the node. */+static int rs_defqn_cmp_ctx(const CBMDefinition *x, const CBMDefinition *y) {+ int c = strcmp(x->qualified_name, y->qualified_name);+ if (c) {+ return c;+ }+ if (x->start_line != y->start_line) {+ return x->start_line < y->start_line ? -1 : 1;+ }+ c = strcmp(x->name, y->name);+ return c ? c : strcmp(x->label ? x->label : "", y->label ? y->label : "");+}++typedef struct {+ const CBMDefinition *def;+ int idx;+} rs_defref_t;++static int rs_defref_cmp(const void *a, const void *b) {+ const rs_defref_t *x = (const rs_defref_t *)a;+ const rs_defref_t *y = (const rs_defref_t *)b;+ int c = rs_defqn_cmp_ctx(x->def, y->def);+ return c ? c : (x->idx > y->idx) - (x->idx < y->idx);+}++/* Index the file's definitions: by (line, name) for the items the scan meets,+ * and which definition of every qualified name owns the node. */+static void rs_scan_defs(rs_scan_t *s) {+ const CBMDefArray *defs = &s->ctx->result->defs;+ int n = defs->count;+ s->defkeys = (rs_defkey_t *)rs_tmp_alloc(s, (size_t)n * sizeof(rs_defkey_t));+ s->owner = (unsigned char *)rs_tmp_alloc(s, (size_t)n + SKIP_ONE);+ s->owner_of = (int *)rs_tmp_alloc(s, ((size_t)n + SKIP_ONE) * sizeof(int));+ s->def_mod = (int *)rs_tmp_alloc(s, ((size_t)n + SKIP_ONE) * sizeof(int));+ rs_defref_t *refs = (rs_defref_t *)rs_tmp_alloc(s, (size_t)n * sizeof(rs_defref_t));+ if (s->failed) {+ return;+ }+ memset(s->owner, 0, (size_t)n + SKIP_ONE);+ memset(s->def_mod, 0, ((size_t)n + SKIP_ONE) * sizeof(int));+ for (int i = 0; i <= n; i++) {+ s->owner_of[i] = CBM_NOT_FOUND;+ }+ int k = 0;+ for (int i = 0; i < n; i++) {+ const CBMDefinition *d = &defs->items[i];+ if (!d->name || !d->qualified_name) {+ continue;+ }+ s->defkeys[k] = (rs_defkey_t){.line = d->start_line, .name = d->name, .def = i};+ refs[k] = (rs_defref_t){.def = d, .idx = i};+ k++;+ }+ s->ndefkeys = k;+ if (k == 0) {+ return;+ }+ qsort(s->defkeys, (size_t)k, sizeof(rs_defkey_t), rs_defkey_cmp);+ qsort(refs, (size_t)k, sizeof(rs_defref_t), rs_defref_cmp);+ int owner = CBM_NOT_FOUND; /* of the run of equal qualified names being walked, last first */+ for (int i = k - SKIP_ONE; i >= 0; i--) {+ bool last = i + SKIP_ONE >= k || strcmp(refs[i + SKIP_ONE].def->qualified_name,+ refs[i].def->qualified_name) != 0;+ owner = last ? refs[i].idx : owner;+ s->owner[refs[i].idx] = last ? SKIP_ONE : 0;+ s->owner_of[refs[i].idx] = owner;+ }+}++/* The definition the extractor made of an item of module `mod`: same start+ * line, name and label, declared by `parent` (the qualified name of its type,+ * NULL for a module-level item). CBM_NOT_FOUND when there is none. The module+ * of a definition that is found is remembered. */+static int rs_scan_def(rs_scan_t *s, int mod, uint32_t line, const char *name, const char *label,+ const char *parent) {+ const CBMDefArray *defs = &s->ctx->result->defs;+ int lo = 0;+ int hi = s->ndefkeys;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ const rs_defkey_t *key = &s->defkeys[mid];+ bool less = key->line < line || (key->line == line && strcmp(key->name, name) < 0);+ if (less) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ for (int i = lo; i < s->ndefkeys; i++) {+ const rs_defkey_t *key = &s->defkeys[i];+ if (key->line != line || strcmp(key->name, name) != 0) {+ break;+ }+ const CBMDefinition *d = &defs->items[key->def];+ bool same_parent = parent ? (d->parent_class && strcmp(d->parent_class, parent) == 0)+ : d->parent_class == NULL;+ if (d->label && strcmp(d->label, label) == 0 && same_parent) {+ s->def_mod[key->def] = mod + SKIP_ONE;+ return key->def;+ }+ }+ return CBM_NOT_FOUND;+}++static char rs_label_code(const char *label) {+ static const struct {+ const char *label;+ char code;+ } table[] = {+ {"Struct", 'S'}, {"Enum", 'E'}, {"Class", 'C'}, {"Interface", 'I'}, {"Type", 'T'},+ {"Function", 'F'}, {"Variable", 'V'}, {"Method", 'M'}, {"Field", 'D'},+ };+ for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {+ if (strcmp(table[i].label, label) == 0) {+ return table[i].code;+ }+ }+ return 0;+}++/* Write an item's node field: '!' when definition `def` does not exist, does+ * not own its node, or has a qualified name the blob cannot carry; else the+ * label code and the qualified name's part after the file's item prefix. */+static void rs_put_node(rs_scan_t *s, int def, const char *name) {+ if (def < 0) {+ rs_sb_putc(&s->sb, '!');+ return;+ }+ const CBMDefinition *d = &s->ctx->result->defs.items[def];+ char code = rs_label_code(d->label);+ const char *qn = d->qualified_name;+ bool ok = code && qn && s->owner[def] && strlen(qn) > s->item_prefix_len &&+ memcmp(qn, s->item_prefix, s->item_prefix_len) == 0;+ const char *suffix = ok ? qn + s->item_prefix_len : "";+ if (!ok || strpbrk(suffix, "\t\n\r")) {+ rs_sb_putc(&s->sb, '!');+ return;+ }+ rs_sb_putc(&s->sb, code);+ if (strcmp(suffix, name) == 0) {+ rs_sb_putc(&s->sb, '=');+ } else {+ rs_sb_putc(&s->sb, ':');+ rs_sb_puts(&s->sb, suffix);+ }+}++/* The qualified name the extractor gives the type `owner` of this file: the+ * parent_class of its members' definitions. */+static const char *rs_owner_qn(rs_scan_t *s, const char *owner, size_t owner_len) {+ char *out = (char *)rs_tmp_alloc(s, s->item_prefix_len + owner_len + SKIP_ONE);+ if (!out) {+ return NULL;+ }+ memcpy(out, s->item_prefix, s->item_prefix_len);+ memcpy(out + s->item_prefix_len, owner, owner_len);+ out[s->item_prefix_len + owner_len] = '\0';+ return out;+}++/* ── Scope scan: records ─────────────────────────────────────────── */++static void rs_rec(rs_scan_t *s, char tag) {+ rs_sb_putc(&s->sb, tag);+}++static void rs_rec_u(rs_scan_t *s, uint32_t v) {+ rs_sb_putc(&s->sb, '\t');+ rs_sb_putu(&s->sb, v);+}++static void rs_rec_s(rs_scan_t *s, const char *v) {+ rs_sb_putc(&s->sb, '\t');+ rs_sb_puts(&s->sb, v);+}++static void rs_rec_end(rs_scan_t *s) {+ rs_sb_putc(&s->sb, '\n');+}++/* A name some macro invocation may declare in module `mod` (-1: somewhere in+ * the file). */+static void rs_rec_maybe(rs_scan_t *s, int mod, const char *name) {+ rs_rec(s, 'Q');+ if (mod < 0) {+ rs_rec_s(s, "*");+ } else {+ rs_rec_u(s, (uint32_t)mod);+ }+ rs_rec_s(s, name);+ rs_rec_end(s);+}++/* The visibility of an item and what its attributes add: the flags field. */+static void rs_rec_flags(rs_scan_t *s, TSNode item, const rs_attrs_t *at) {+ char vis = '-';+ TSTreeCursor cur = ts_tree_cursor_new(item);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ do {+ TSNode ch = ts_tree_cursor_current_node(&cur);+ if (!rs_kind(ch, "visibility_modifier")) {+ continue;+ }+ vis = 'p';+ uint32_t nc = ts_node_named_child_count(ch);+ if (nc > 0) {+ const char *k = ts_node_type(ts_node_named_child(ch, 0));+ vis = strcmp(k, "crate") == 0+ ? 'c'+ : (strcmp(k, "super") == 0 ? 's' : (strcmp(k, "self") == 0 ? '-' : 'i'));+ }+ break;+ } while (ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+ rs_sb_putc(&s->sb, '\t');+ rs_sb_putc(&s->sb, vis);+ if (at && at->test) {+ rs_sb_putc(&s->sb, 't');+ }+ if (at && at->macro_export) {+ rs_sb_putc(&s->sb, 'e');+ }+ if (at && at->cond_path) {+ rs_sb_putc(&s->sb, 'c');+ }+}++/* ── Scope scan: attributes ──────────────────────────────────────── */++static bool rs_word_is(const char *p, size_t n, const char *word) {+ return strlen(word) == n && memcmp(p, word, n) == 0;+}++/* True when the identifier `word` stands in text[0..n). */+static bool rs_has_word(const char *text, size_t n, const char *word) {+ size_t wl = strlen(word);+ for (size_t i = 0; i + wl <= n; i++) {+ bool starts =+ i == 0 || !(isalnum((unsigned char)text[i - SKIP_ONE]) || text[i - SKIP_ONE] == '_');+ bool ends = i + wl == n || !(isalnum((unsigned char)text[i + wl]) || text[i + wl] == '_');+ if (starts && ends && memcmp(text + i, word, wl) == 0) {+ return true;+ }+ }+ return false;+}++/* The string literal that follows `key =` in text[0..n), copied into `out`.+ * false when there is none, it holds an escape, or it does not fit. */+static bool rs_attr_string(const char *text, size_t n, char *out, size_t cap) {+ const char *eq = (const char *)memchr(text, '=', n);+ if (!eq) {+ return false;+ }+ size_t i = (size_t)(eq - text) + SKIP_ONE;+ while (i < n && isspace((unsigned char)text[i])) {+ i++;+ }+ if (i >= n || text[i] != '"') {+ return false;+ }+ size_t start = ++i;+ while (i < n && text[i] != '"' && text[i] != '\\' && (unsigned char)text[i] >= ' ') {+ i++;+ }+ if (i >= n || text[i] != '"' || i - start >= cap || i == start) {+ return false;+ }+ memcpy(out, text + start, i - start);+ out[i - start] = '\0';+ return true;+}++/* The first identifier inside the parentheses of text[0..n). */+static void rs_attr_first_arg(const char *text, size_t n, char *out, size_t cap) {+ out[0] = '\0';+ const char *open = (const char *)memchr(text, '(', n);+ if (!open) {+ return;+ }+ size_t i = (size_t)(open - text) + SKIP_ONE;+ while (i < n && isspace((unsigned char)text[i])) {+ i++;+ }+ size_t start = i;+ while (i < n && (isalnum((unsigned char)text[i]) || text[i] == '_')) {+ i++;+ }+ if (i > start && i - start < cap) {+ memcpy(out, text + start, i - start);+ out[i - start] = '\0';+ }+}++/* Append a derive name to the list of `at` (comma-joined). */+static void rs_derive_put(rs_attrs_t *at, const char *name, size_t n) {+ size_t have = strlen(at->derives);+ if (n == 0) {+ return;+ }+ if (have + n + PAIR_LEN >= sizeof(at->derives)) {+ at->derives_more = true;+ return;+ }+ if (have > 0) {+ at->derives[have++] = ',';+ }+ memcpy(at->derives + have, name, n);+ at->derives[have + n] = '\0';+}++/* The names inside every `derive(..)` of an attribute's text (also inside+ * `cfg_attr(x, derive(..))`): the last segment of each path. */+static void rs_attr_derives(const char *text, size_t n, rs_attrs_t *at) {+ static const char word[] = "derive";+ const size_t wl = sizeof(word) - SKIP_ONE;+ for (size_t i = 0; i + wl < n; i++) {+ bool starts =+ i == 0 || !(isalnum((unsigned char)text[i - SKIP_ONE]) || text[i - SKIP_ONE] == '_');+ size_t j = i + wl;+ if (!starts || memcmp(text + i, word, wl) != 0) {+ continue;+ }+ while (j < n && isspace((unsigned char)text[j])) {+ j++;+ }+ if (j >= n || text[j] != '(') {+ continue;+ }+ size_t id = 0; /* the identifier read last, and its length */+ size_t idlen = 0;+ bool in_id = false;+ for (j++; j < n && text[j] != ')'; j++) {+ unsigned char c = (unsigned char)text[j];+ if (isalnum(c) || c == '_') {+ id = in_id ? id : j;+ idlen = in_id ? idlen + SKIP_ONE : SKIP_ONE;+ in_id = true;+ continue;+ }+ in_id = false;+ if (c == ',') {+ rs_derive_put(at, text + id, idlen);+ }+ idlen = (c == ',' || c == ':') ? 0 : idlen;+ }+ rs_derive_put(at, text + id, idlen);+ at->derives_more = at->derives_more || j >= n; /* cut off before its `)` */+ i = j;+ }+}++/* Read one `#[...]` above an item into `at`. */+static void rs_attr_read(const rs_scan_t *s, TSNode attr_item, rs_attrs_t *at) {+ uint32_t a = ts_node_start_byte(attr_item);+ uint32_t b = ts_node_end_byte(attr_item);+ if (b <= a || b > s->src_len) {+ return;+ }+ const char *text = s->src + a;+ size_t n = b - a;+ bool long_attr = n > RS_SCAN_ATTR_CAP;+ n = long_attr ? RS_SCAN_ATTR_CAP : n;+ /* the attribute's own name: the path after `#[` up to `(`, `=` or `]` */+ size_t i = 0;+ while (i < n && (text[i] == '#' || text[i] == '[' || isspace((unsigned char)text[i]))) {+ i++;+ }+ size_t name = i;+ while (i < n && (isalnum((unsigned char)text[i]) || text[i] == '_' || text[i] == ':')) {+ i++;+ }+ size_t nl = i - name;+ const char *p = text + name;+ static const char test_suffix[] = "::test";+ const size_t tsl = sizeof(test_suffix) - SKIP_ONE;+ if (rs_word_is(p, nl, "test") || rs_word_is(p, nl, "bench") ||+ (nl > tsl && memcmp(p + nl - tsl, test_suffix, tsl) == 0)) {+ at->test = true;+ } else if (rs_word_is(p, nl, "cfg")) {+ at->test = at->test || (rs_has_word(text, n, "test") && !rs_has_word(text, n, "not"));+ } else if (rs_word_is(p, nl, "path")) {+ if (long_attr || !rs_attr_string(text, n, at->path, sizeof(at->path))) {+ at->cond_path = true; /* a path this scan cannot read */+ }+ } else if (rs_word_is(p, nl, "cfg_attr")) {+ at->cond_path = at->cond_path || long_attr || rs_has_word(text, n, "path");+ at->derives_more = at->derives_more || long_attr;+ rs_attr_derives(text, n, at);+ } else if (rs_word_is(p, nl, "derive")) {+ at->derives_more = at->derives_more || long_attr;+ rs_attr_derives(text, n, at);+ } else if (rs_word_is(p, nl, "macro_export")) {+ at->macro_export = true;+ } else if (rs_word_is(p, nl, "proc_macro")) {+ at->macro_kind = 'P';+ } else if (rs_word_is(p, nl, "proc_macro_attribute")) {+ at->macro_kind = 'B';+ } else if (rs_word_is(p, nl, "proc_macro_derive")) {+ at->macro_kind = 'V';+ rs_attr_first_arg(text, n, at->derive, sizeof(at->derive));+ }+}++/* ── Scope scan: names local to a documented item ────────────────── */++/* True when a definition that starts at `line` carries references. */+static bool rs_has_refs(const rs_scan_t *s, uint32_t line) {+ int lo = 0;+ int hi = s->nref_lines;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (s->ref_lines[mid] < line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo < s->nref_lines && s->ref_lines[lo] == line;+}++static void rs_put_local(rs_scan_t *s, TSNode name, bool *first) {+ char buf[RS_SCAN_NAME_CAP];+ if (!rs_name_of(s, name, buf, sizeof(buf))) {+ return;+ }+ if (!*first) {+ rs_sb_putc(&s->sb, ',');+ }+ rs_sb_puts(&s->sb, buf);+ *first = false;+}++/* The type and const parameters of a `type_parameters` list. */+static void rs_put_generics(rs_scan_t *s, TSNode tparams, bool *first) {+ if (ts_node_is_null(tparams)) {+ return;+ }+ uint32_t nc = ts_node_named_child_count(tparams);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode p = ts_node_named_child(tparams, i);+ if (rs_kind(p, "type_parameter") || rs_kind(p, "const_parameter")) {+ rs_put_local(s, rs_field(p, "name"), first);+ } else if (rs_kind(p, "type_identifier")) {+ rs_put_local(s, p, first);+ }+ }+}++/* Every name the patterns of a `parameters` list bind. The walk is a cursor+ * walk of the list's subtree: no recursion. */+static void rs_put_params(rs_scan_t *s, TSNode params, bool *first) {+ if (ts_node_is_null(params)) {+ return;+ }+ TSTreeCursor cur = ts_tree_cursor_new(params);+ for (;;) {+ TSNode n = ts_tree_cursor_current_node(&cur);+ const char *field = ts_tree_cursor_current_field_name(&cur);+ bool in_type = field && strcmp(field, "type") == 0;+ if (rs_kind(n, "identifier") || rs_kind(n, "shorthand_field_identifier")) {+ rs_put_local(s, n, first);+ }+ if (!in_type && ts_tree_cursor_goto_first_child(&cur)) {+ continue;+ }+ bool moved = ts_tree_cursor_goto_next_sibling(&cur);+ while (!moved && ts_tree_cursor_goto_parent(&cur)) {+ moved = ts_tree_cursor_goto_next_sibling(&cur);+ }+ if (!moved) {+ break;+ }+ }+ ts_tree_cursor_delete(&cur);+}++/* The P record of the definition at `line`: the type parameters of its owner+ * (`outer`, may be null) and, for `item`, its own type parameters and+ * parameter names. Written only for a definition with references that has+ * such names. */+static void rs_rec_locals(rs_scan_t *s, uint32_t line, TSNode outer, TSNode item) {+ if (!rs_has_refs(s, line) || s->sb.failed) {+ return;+ }+ size_t mark = s->sb.len;+ rs_rec(s, 'P');+ rs_rec_u(s, line);+ rs_sb_putc(&s->sb, '\t');+ size_t names_at = s->sb.len;+ bool first = true;+ rs_put_generics(s, outer, &first);+ if (!ts_node_is_null(item)) {+ rs_put_generics(s, rs_field(item, "type_parameters"), &first);+ rs_put_params(s, rs_field(item, "parameters"), &first);+ }+ if (s->sb.failed) {+ return;+ }+ if (s->sb.len == names_at) {+ s->sb.len = mark; /* nothing local: no record */+ s->sb.buf[mark] = '\0';+ return;+ }+ rs_rec_end(s);+}++/* ── Scope scan: members ─────────────────────────────────────────── */++static void rs_rec_member(rs_scan_t *s, uint32_t line, char kind, const char *name, int def) {+ rs_rec(s, 'M');+ rs_rec_u(s, line);+ rs_sb_putc(&s->sb, '\t');+ rs_sb_putc(&s->sb, kind);+ rs_rec_s(s, name);+ rs_sb_putc(&s->sb, '\t');+ rs_put_node(s, def, name);+ rs_rec_end(s);+}++/* The members a type's or an impl's body declares. `owner_qn` is the+ * qualified name their definitions carry as parent (NULL: no definition is+ * looked up). `callable_label` is the label of the functions' definitions. */+static void rs_scan_members(rs_scan_t *s, int mod, TSNode body, const char *owner_qn, TSNode outer,+ bool in_trait) {+ if (ts_node_is_null(body)) {+ return;+ }+ TSTreeCursor cur = ts_tree_cursor_new(body);+ bool more = ts_tree_cursor_goto_first_child(&cur);+ for (; more && !s->failed; more = ts_tree_cursor_goto_next_sibling(&cur)) {+ TSNode m = ts_tree_cursor_current_node(&cur);+ const char *k = ts_node_type(m);+ char kind = 0;+ const char *label = NULL;+ if (strcmp(k, "function_item") == 0 || strcmp(k, "function_signature_item") == 0) {+ kind = 'f';+ label = "Method";+ } else if (strcmp(k, "const_item") == 0) {+ kind = 'c';+ label = in_trait ? "Variable" : NULL; /* an impl's constant has no definition */+ } else if (strcmp(k, "type_item") == 0 || strcmp(k, "associated_type") == 0) {+ kind = 't';+ } else if (strcmp(k, "field_declaration") == 0) {+ kind = 'd';+ label = "Field";+ } else if (strcmp(k, "enum_variant") == 0) {+ kind = 'v';+ }+ if (!kind) {+ continue;+ }+ char name[RS_SCAN_NAME_CAP];+ if (ts_node_start_byte(m) >= s->err_byte ||+ !rs_name_of(s, rs_field(m, "name"), name, sizeof(name))) {+ s->broken = true; /* a member this scan cannot show */+ continue;+ }+ uint32_t line = rs_line_of(m);+ int def =+ (label && owner_qn) ? rs_scan_def(s, mod, line, name, label, owner_qn) : CBM_NOT_FOUND;+ rs_rec_member(s, line, kind, name, def);+ TSNode none = {0};+ rs_rec_locals(s, line, outer, kind == 'f' ? m : none);+ }+ ts_tree_cursor_delete(&cur);+}++/* The positional fields of a tuple struct: members `0`, `1` ... without a+ * node. */+static void rs_scan_tuple_fields(rs_scan_t *s, TSNode body) {+ TSTreeCursor cur = ts_tree_cursor_new(body);+ uint32_t index = 0;+ bool more = ts_tree_cursor_goto_first_child(&cur);+ for (; more && !s->failed; more = ts_tree_cursor_goto_next_sibling(&cur)) {+ const char *field = ts_tree_cursor_current_field_name(&cur);+ if (!field || strcmp(field, "type") != 0) {+ continue;+ }+ char name[RS_UINT_DIGITS];+ snprintf(name, sizeof(name), "%u", index++);+ rs_rec_member(s, 0, 'd', name, CBM_NOT_FOUND);+ }+ ts_tree_cursor_delete(&cur);+}++/* ── Scope scan: `use` ───────────────────────────────────────────── */++typedef struct {+ TSNode node;+ const char *prefix; /* the path written before this part of the tree, "" at the top */+} rs_use_frame_t;++typedef struct {+ rs_use_frame_t *v;+ int n;+ int cap;+} rs_use_stack_t;++static void rs_use_push(rs_scan_t *s, rs_use_stack_t *st, TSNode node, const char *prefix) {+ if (ts_node_is_null(node) || s->failed) {+ return;+ }+ if (st->n >= st->cap) {+ int ncap = st->cap ? st->cap * PAIR_LEN : RS_SCAN_INIT;+ rs_use_frame_t *grown =+ (rs_use_frame_t *)rs_tmp_alloc(s, (size_t)ncap * sizeof(rs_use_frame_t));+ if (!grown) {+ return;+ }+ if (st->n > 0) {+ memcpy(grown, st->v, (size_t)st->n * sizeof(rs_use_frame_t));+ }+ st->v = grown;+ st->cap = ncap;+ }+ st->v[st->n++] = (rs_use_frame_t){.node = node, .prefix = prefix};+}++/* `prefix::path` in the scratch arena. NULL (and the file is marked) when+ * `node` is no plain path or the result is too long to carry. */+static const char *rs_use_join(rs_scan_t *s, const char *prefix, TSNode node) {+ char path[RS_SCAN_PATH_CAP];+ path[0] = '\0';+ if (!ts_node_is_null(node) && !rs_path_of(s, node, path, sizeof(path))) {+ s->broken = true;+ return NULL;+ }+ size_t pl = strlen(prefix);+ size_t nl = strlen(path);+ if (pl + nl + PAIR_LEN >= RS_SCAN_PATH_CAP) {+ s->broken = true;+ return NULL;+ }+ char *out = (char *)rs_tmp_alloc(s, pl + nl + PAIR_LEN + SKIP_ONE);+ if (!out) {+ return NULL;+ }+ snprintf(out, pl + nl + PAIR_LEN + SKIP_ONE, "%s%s%s", prefix, (pl && nl) ? "::" : "", path);+ return out;+}++static void rs_rec_use(rs_scan_t *s, int mod, TSNode decl, char kind, const char *local,+ const char *path) {+ rs_rec(s, 'U');+ rs_rec_u(s, (uint32_t)mod);+ rs_rec_flags(s, decl, NULL);+ rs_sb_putc(&s->sb, '\t');+ rs_sb_putc(&s->sb, kind);+ rs_rec_s(s, local);+ rs_rec_s(s, path);+ rs_rec_end(s);+}++/* A leaf of a use tree: `full` is the whole path, `alias` the name after+ * `as` (NULL when there is none). `a::b::self` imports `b` itself, in the type+ * namespace only. */+static void rs_use_leaf(rs_scan_t *s, int mod, TSNode decl, const char *full, const char *alias) {+ static const char self_seg[] = "::self";+ const size_t sl = sizeof(self_seg) - SKIP_ONE;+ char path[RS_SCAN_PATH_CAP];+ snprintf(path, sizeof(path), "%s", full);+ size_t n = strlen(path);+ char kind = 'b';+ if (n > sl && strcmp(path + n - sl, self_seg) == 0) {+ path[n - sl] = '\0';+ kind = 's';+ }+ const char *last = strrchr(path, ':');+ const char *local = alias ? alias : (last ? last + SKIP_ONE : path);+ bool keyword =+ strcmp(local, "crate") == 0 || strcmp(local, "super") == 0 || strcmp(local, "self") == 0;+ if (!local[0] || (keyword && !alias)) {+ return; /* `use crate;` binds nothing */+ }+ rs_rec_use(s, mod, decl, kind, local, path);+}++/* The bindings of one `use` declaration: its tree is walked with a stack. */+static void rs_item_use(rs_scan_t *s, TSNode decl, int mod) {+ rs_use_stack_t st = {0};+ rs_use_push(s, &st, rs_field(decl, "argument"), "");+ while (st.n > 0 && !s->failed) {+ rs_use_frame_t f = st.v[--st.n];+ const char *k = ts_node_type(f.node);+ if (strcmp(k, "use_list") == 0) {+ for (uint32_t i = ts_node_named_child_count(f.node); i > 0; i--) {+ rs_use_push(s, &st, ts_node_named_child(f.node, i - SKIP_ONE), f.prefix);+ }+ } else if (strcmp(k, "scoped_use_list") == 0) {+ const char *prefix = rs_use_join(s, f.prefix, rs_field(f.node, "path"));+ if (prefix) {+ rs_use_push(s, &st, rs_field(f.node, "list"), prefix);+ }+ } else if (strcmp(k, "use_wildcard") == 0) {+ TSNode none = {0};+ TSNode inner =+ ts_node_named_child_count(f.node) > 0 ? ts_node_named_child(f.node, 0) : none;+ const char *path = rs_use_join(s, f.prefix, inner);+ if (path && path[0]) {+ rs_rec_use(s, mod, decl, 'g', "-", path);+ }+ } else if (strcmp(k, "use_as_clause") == 0) {+ char alias[RS_SCAN_NAME_CAP];+ const char *full = rs_use_join(s, f.prefix, rs_field(f.node, "path"));+ if (full && rs_name_of(s, rs_field(f.node, "alias"), alias, sizeof(alias))) {+ rs_use_leaf(s, mod, decl, full, alias);+ } else {+ s->broken = true;+ }+ } else if (strcmp(k, "line_comment") != 0 && strcmp(k, "block_comment") != 0) {+ const char *full = rs_use_join(s, f.prefix, f.node);+ if (full) {+ rs_use_leaf(s, mod, decl, full, NULL);+ }+ }+ }+}++static void rs_item_extern_crate(rs_scan_t *s, TSNode decl, int mod) {+ char name[RS_SCAN_NAME_CAP];+ char alias[RS_SCAN_NAME_CAP];+ if (!rs_name_of(s, rs_field(decl, "name"), name, sizeof(name))) {+ s->broken = true;+ return;+ }+ bool renamed = rs_name_of(s, rs_field(decl, "alias"), alias, sizeof(alias));+ rs_rec_use(s, mod, decl, 'x', renamed ? alias : name, name);+}++/* ── Scope scan: macro invocations ───────────────────────────────── */++typedef struct {+ TSNode *v;+ int n;+ int cap;+} rs_node_stack_t;++static void rs_node_push(rs_scan_t *s, rs_node_stack_t *st, TSNode node) {+ if (s->failed) {+ return;+ }+ if (st->n >= st->cap) {+ int ncap = st->cap ? st->cap * PAIR_LEN : RS_SCAN_INIT;+ TSNode *grown = (TSNode *)rs_tmp_alloc(s, (size_t)ncap * sizeof(TSNode));+ if (!grown) {+ return;+ }+ if (st->n > 0) {+ memcpy(grown, st->v, (size_t)st->n * sizeof(TSNode));+ }+ st->v = grown;+ st->cap = ncap;+ }+ st->v[st->n++] = node;+}++/* A keyword after which a name is declared. */+static bool rs_item_keyword(const char *t) {+ static const char *const words[] = {"struct", "enum", "union", "trait", "fn",+ "mod", "type", "const", "static"};+ for (size_t i = 0; i < sizeof(words) / sizeof(words[0]); i++) {+ if (strcmp(words[i], t) == 0) {+ return true;+ }+ }+ return false;+}++/* A word that may stand between such a keyword and the name (`static ref X`,+ * `const unsafe fn f`). */+static bool rs_item_modifier(const char *t) {+ static const char *const words[] = {"ref", "mut", "unsafe", "async", "extern"};+ for (size_t i = 0; i < sizeof(words) / sizeof(words[0]); i++) {+ if (strcmp(words[i], t) == 0) {+ return true;+ }+ }+ return false;+}++static bool rs_delimiter(const char *t, bool open) {+ return open ? (strcmp(t, "(") == 0 || strcmp(t, "[") == 0 || strcmp(t, "{") == 0)+ : (strcmp(t, ")") == 0 || strcmp(t, "]") == 0 || strcmp(t, "}") == 0);+}++/* A name a token tree may declare: a Q record for module `mod`, or (reading a+ * macro definition) one more name of the list `names`. */+static void rs_macro_name(rs_scan_t *s, int mod, const char *name, rs_sb_t *names) {+ if (!names) {+ rs_rec_maybe(s, mod, name);+ return;+ }+ rs_sb_puts(names, name);+ rs_sb_putc(names, ',');+ s->failed = s->failed || names->failed;+}++/* The names one token tree may declare: an identifier after an item keyword+ * (at any depth), and at the top a whole argument that is one identifier+ * (`define_label!(AppLabel, ..)`). Nested trees are pushed, not recursed.+ * A metavariable (`struct $name`) is no identifier and is not recorded. */+static void rs_macro_tree(rs_scan_t *s, rs_node_stack_t *st, TSNode tree, bool top, int mod,+ rs_sb_t *names) {+ bool after_keyword = false;+ bool arg_start = false;+ TSNode candidate = {0};+ TSTreeCursor cur = ts_tree_cursor_new(tree);+ bool more = ts_tree_cursor_goto_first_child(&cur);+ for (; more && !s->failed; more = ts_tree_cursor_goto_next_sibling(&cur)) {+ TSNode c = ts_tree_cursor_current_node(&cur);+ const char *t = ts_node_type(c);+ bool ends_arg = strcmp(t, ",") == 0 || rs_delimiter(t, false);+ if (!ts_node_is_null(candidate) && ends_arg) {+ char name[RS_SCAN_NAME_CAP];+ if (rs_name_of(s, candidate, name, sizeof(name))) {+ rs_macro_name(s, mod, name, names);+ }+ }+ candidate = (TSNode){0};+ if (strcmp(t, "identifier") == 0) {+ /* inside a token tree a contextual keyword (`union`) and a+ * modifier (`ref` of `static ref X`) are plain identifiers */+ char name[RS_SCAN_NAME_CAP];+ bool named = rs_name_of(s, c, name, sizeof(name));+ if (named && after_keyword && rs_item_modifier(name)) {+ arg_start = false;+ continue;+ }+ if (named && after_keyword) {+ rs_macro_name(s, mod, name, names);+ } else if (top && arg_start) {+ candidate = c;+ }+ after_keyword = named && !after_keyword && rs_item_keyword(name);+ } else if (strcmp(t, "token_tree") == 0) {+ rs_node_push(s, st, c);+ after_keyword = false;+ } else if (rs_item_keyword(t)) {+ after_keyword = true;+ } else if (!rs_item_modifier(t)) {+ after_keyword = false;+ }+ arg_start = strcmp(t, ",") == 0 || rs_delimiter(t, true);+ }+ ts_tree_cursor_delete(&cur);+}++/* A macro invocation among a module's items: what it expands to is not in+ * the tree. The names written at the invocation that it may declare are+ * recorded (Q), and so is the invocation itself (V): the macro's own body may+ * declare names too (W records, of this file or another). */+static void rs_item_macro(rs_scan_t *s, TSNode invocation, int mod) {+ rs_node_stack_t st = {0};+ char name[RS_SCAN_NAME_CAP];+ TSNode macro = rs_field(invocation, "macro");+ if (!ts_node_is_null(macro) && rs_kind(macro, "scoped_identifier")) {+ macro = rs_field(macro, "name");+ }+ if (rs_name_of(s, macro, name, sizeof(name)) &&+ !(s->last_use_mod == mod && strcmp(s->last_use, name) == 0)) {+ rs_rec(s, 'V');+ rs_rec_u(s, (uint32_t)mod);+ rs_rec_s(s, name);+ rs_rec_end(s);+ s->last_use_mod = mod;+ snprintf(s->last_use, sizeof(s->last_use), "%s", name);+ }+ uint32_t nc = ts_node_named_child_count(invocation);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(invocation, i);+ if (rs_kind(c, "token_tree")) {+ rs_macro_tree(s, &st, c, true, mod, NULL);+ }+ }+ while (st.n > 0 && !s->failed) {+ TSNode tree = st.v[--st.n];+ rs_macro_tree(s, &st, tree, false, mod, NULL);+ }+}++/* What the body of a `macro_rules!` definition declares by a written name+ * (`pub struct Options { .. }` in a transcriber): a W record. A module that+ * invokes the macro may then hold those names. */+static void rs_macro_declares(rs_scan_t *s, TSNode def, const char *name) {+ rs_node_stack_t st = {0};+ rs_sb_t names = {.a = s->tmp};+ uint32_t nc = ts_node_named_child_count(def);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode rule = ts_node_named_child(def, i);+ if (rs_kind(rule, "macro_rule")) {+ rs_node_push(s, &st, rs_field(rule, "right"));+ }+ }+ while (st.n > 0 && !s->failed) {+ TSNode tree = st.v[--st.n];+ if (!ts_node_is_null(tree)) {+ rs_macro_tree(s, &st, tree, false, 0, &names);+ }+ }+ if (names.len > SKIP_ONE && !s->failed) {+ rs_rec(s, 'W');+ rs_rec_s(s, name);+ rs_sb_putc(&s->sb, '\t');+ rs_sb_putn(&s->sb, names.buf, names.len - SKIP_ONE); /* without the last comma */+ rs_rec_end(s);+ }+}++/* ── Scope scan: items ───────────────────────────────────────────── */++static void rs_block_push(rs_scan_t *s, TSNode node, int mod) {+ if (ts_node_is_null(node) || s->failed) {+ return;+ }+ if (s->nblocks >= s->blocks_cap) {+ int ncap = s->blocks_cap ? s->blocks_cap * PAIR_LEN : RS_SCAN_INIT;+ rs_block_t *grown = (rs_block_t *)rs_tmp_alloc(s, (size_t)ncap * sizeof(rs_block_t));+ if (!grown) {+ return;+ }+ if (s->nblocks > 0) {+ memcpy(grown, s->blocks, (size_t)s->nblocks * sizeof(rs_block_t));+ }+ s->blocks = grown;+ s->blocks_cap = ncap;+ }+ s->blocks[s->nblocks++] = (rs_block_t){.node = node, .mod = mod};+}++/* The first fields of a T record: T mod start end flags kind name, then the+ * tab before the node field. */+static void rs_rec_item(rs_scan_t *s, int mod, TSNode item, const rs_attrs_t *at, char kind,+ const char *name) {+ rs_rec(s, 'T');+ rs_rec_u(s, (uint32_t)mod);+ rs_rec_u(s, rs_line_of(item));+ rs_rec_u(s, rs_end_line_of(item));+ rs_rec_flags(s, item, at);+ rs_sb_putc(&s->sb, '\t');+ rs_sb_putc(&s->sb, kind);+ rs_rec_s(s, name);+ rs_sb_putc(&s->sb, '\t');+}++/* The path a type node names, generics dropped: `a::S<T>` -> `a::S`. false+ * for a type that is no path. */+static bool rs_type_path(const rs_scan_t *s, TSNode type, char *out, size_t cap) {+ if (!ts_node_is_null(type) && rs_kind(type, "generic_type")) {+ type = rs_field(type, "type");+ }+ if (ts_node_is_null(type) ||+ !(rs_kind(type, "type_identifier") || rs_kind(type, "scoped_type_identifier") ||+ rs_kind(type, "identifier") || rs_kind(type, "scoped_identifier"))) {+ return false;+ }+ return rs_path_of(s, type, out, cap);+}++/* True when `name` is one of the type parameters of `tparams`: `impl<T> Tr+ * for T` implements for every type, not for a type named T. */+static bool rs_is_generic(const rs_scan_t *s, TSNode tparams, const char *name) {+ if (ts_node_is_null(tparams)) {+ return false;+ }+ uint32_t nc = ts_node_named_child_count(tparams);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode p = ts_node_named_child(tparams, i);+ TSNode pn = rs_kind(p, "type_parameter") ? rs_field(p, "name") : p;+ char buf[RS_SCAN_NAME_CAP];+ if (rs_name_of(s, pn, buf, sizeof(buf)) && strcmp(buf, name) == 0) {+ return true;+ }+ }+ return false;+}++static void rs_item_impl(rs_scan_t *s, TSNode n, int mod) {+ TSNode type = rs_field(n, "type");+ TSNode trait = rs_field(n, "trait");+ TSNode tparams = rs_field(n, "type_parameters");+ char self_path[RS_SCAN_PATH_CAP];+ char trait_path[RS_SCAN_PATH_CAP];+ bool has_self = rs_type_path(s, type, self_path, sizeof(self_path)) &&+ !rs_is_generic(s, tparams, self_path);+ bool has_trait = !ts_node_is_null(trait);+ bool trait_ok = has_trait && rs_type_path(s, trait, trait_path, sizeof(trait_path));+ rs_rec(s, 'I');+ rs_rec_u(s, (uint32_t)mod);+ rs_rec_u(s, rs_line_of(n));+ rs_rec_u(s, rs_end_line_of(n));+ rs_rec_s(s, has_self ? self_path : "?");+ rs_rec_s(s, has_trait ? (trait_ok ? trait_path : "?") : "-");+ rs_rec_end(s);+ /* the extractor names a method <type text up to '<'>.<name> */+ const char *owner_qn = NULL;+ if (has_self && !ts_node_is_null(type)) {+ uint32_t a = ts_node_start_byte(type);+ uint32_t b = ts_node_end_byte(type);+ const char *lt = b > a ? (const char *)memchr(s->src + a, '<', b - a) : NULL;+ size_t len = lt ? (size_t)(lt - (s->src + a)) : (size_t)(b - a);+ owner_qn = rs_owner_qn(s, s->src + a, len);+ }+ rs_scan_members(s, mod, rs_field(n, "body"), owner_qn, tparams, false);+}++/* What the scan does with a module-level item of one node kind. */+typedef struct {+ const char *node_kind;+ char kind;+ const char *label; /* of its definition; NULL: the extractor makes none */+} rs_item_kind_t;++static const rs_item_kind_t *rs_item_kind(const char *k) {+ static const rs_item_kind_t kinds[] = {+ {"struct_item", 'S', "Struct"},+ {"enum_item", 'E', "Enum"},+ {"union_item", 'U', "Class"},+ {"trait_item", 'R', "Interface"},+ {"type_item", 'A', "Type"},+ {"function_item", 'F', "Function"},+ {"function_signature_item", 'F', "Function"},+ {"const_item", 'C', "Variable"},+ {"static_item", 'G', "Variable"},+ {"macro_definition", 'M', NULL},+ };+ for (size_t i = 0; i < sizeof(kinds) / sizeof(kinds[0]); i++) {+ if (strcmp(kinds[i].node_kind, k) == 0) {+ return &kinds[i];+ }+ }+ return NULL;+}++/* The members of a struct, union, enum or trait. */+static void rs_item_members(rs_scan_t *s, int mod, TSNode n, char kind, const char *name) {+ TSNode body = rs_field(n, "body");+ TSNode tparams = rs_field(n, "type_parameters");+ if (ts_node_is_null(body)) {+ return;+ }+ if (rs_kind(body, "ordered_field_declaration_list")) {+ rs_scan_tuple_fields(s, body);+ return;+ }+ rs_scan_members(s, mod, body, rs_owner_qn(s, name, strlen(name)), tparams, kind == 'R');+}++/* A named item: its T record, its members, its local names. */+static void rs_item_named(rs_scan_t *s, TSNode n, const rs_item_kind_t *ik, int mod,+ const rs_attrs_t *at) {+ char name[RS_SCAN_NAME_CAP];+ if (!rs_name_of(s, rs_field(n, "name"), name, sizeof(name))) {+ s->broken = true;+ return;+ }+ if (strcmp(name, "_") == 0) {+ return; /* `const _: () = ..` declares nothing */+ }+ char kind = ik->kind;+ const char *shown = name;+ if (kind == 'F' && at->macro_kind) {+ kind = at->macro_kind; /* the function IS a procedural macro */+ shown = (kind == 'V' && at->derive[0]) ? at->derive : name;+ }+ uint32_t line = rs_line_of(n);+ int def = ik->label ? rs_scan_def(s, mod, line, name, ik->label, NULL) : CBM_NOT_FOUND;+ rs_rec_item(s, mod, n, at, kind, shown);+ rs_put_node(s, def, shown);+ char alias[RS_SCAN_PATH_CAP];+ bool aliased = kind == 'A' && rs_type_path(s, rs_field(n, "type"), alias, sizeof(alias));+ bool derived =+ (kind == 'S' || kind == 'E' || kind == 'U') && (at->derives[0] || at->derives_more);+ if (derived) {+ rs_rec_s(s, at->derives);+ rs_sb_puts(&s->sb, at->derives_more ? (at->derives[0] ? ",*" : "*") : "");+ } else {+ rs_rec_s(s, aliased ? alias : "-");+ }+ rs_rec_end(s);+ if (rs_kind(n, "macro_definition")) {+ rs_macro_declares(s, n, name);+ }+ if (kind == 'S' || kind == 'U' || kind == 'E' || kind == 'R') {+ rs_item_members(s, mod, n, kind, name);+ }+ TSNode none = {0};+ rs_rec_locals(s, line, none, n);+}++static void rs_item_mod(rs_scan_t *s, TSNode n, int mod, const rs_attrs_t *at) {+ char name[RS_SCAN_NAME_CAP];+ if (!rs_name_of(s, rs_field(n, "name"), name, sizeof(name))) {+ s->broken = true;+ return;+ }+ TSNode body = rs_field(n, "body");+ if (ts_node_is_null(body)) {+ rs_rec(s, 'D');+ rs_rec_u(s, (uint32_t)mod);+ rs_rec_flags(s, n, at);+ rs_rec_s(s, name);+ rs_rec_s(s, at->path[0] ? at->path : "-");+ rs_rec_end(s);+ return;+ }+ int id = s->next_mod++;+ rs_rec(s, 'N');+ rs_rec_u(s, (uint32_t)id);+ rs_rec_u(s, (uint32_t)mod);+ rs_rec_u(s, rs_line_of(n));+ rs_rec_u(s, rs_end_line_of(n));+ rs_rec_flags(s, n, at);+ if (at->path[0] && !at->cond_path) {+ rs_sb_putc(&s->sb, 'c'); /* `#[path]` on an inline module moves its `mod x;` files */+ }+ rs_rec_s(s, name);+ rs_rec_end(s);+ rs_block_push(s, body, id);+}++/* An item that starts where the tree is no longer trusted: only its name is+ * kept, as one that may be declared somewhere in the file. */+static void rs_item_untrusted(rs_scan_t *s, TSNode n) {+ char name[RS_SCAN_NAME_CAP];+ s->broken = true;+ if (rs_name_of(s, rs_field(n, "name"), name, sizeof(name))) {+ rs_rec_maybe(s, CBM_NOT_FOUND, name);+ }+}++static void rs_scan_item(rs_scan_t *s, TSNode n, int mod, const rs_attrs_t *at) {+ const char *k = ts_node_type(n);+ if (ts_node_start_byte(n) >= s->err_byte || strcmp(k, "ERROR") == 0) {+ rs_item_untrusted(s, n);+ return;+ }+ const rs_item_kind_t *ik = rs_item_kind(k);+ if (ik) {+ rs_item_named(s, n, ik, mod, at);+ } else if (strcmp(k, "mod_item") == 0) {+ rs_item_mod(s, n, mod, at);+ } else if (strcmp(k, "use_declaration") == 0) {+ rs_item_use(s, n, mod);+ } else if (strcmp(k, "extern_crate_declaration") == 0) {+ rs_item_extern_crate(s, n, mod);+ } else if (strcmp(k, "impl_item") == 0) {+ rs_item_impl(s, n, mod);+ } else if (strcmp(k, "foreign_mod_item") == 0) {+ rs_block_push(s, rs_field(n, "body"), mod); /* its items are the module's */+ } else if (strcmp(k, "macro_invocation") == 0) {+ rs_item_macro(s, n, mod);+ } else if (strcmp(k, "expression_statement") == 0 && ts_node_named_child_count(n) > 0 &&+ rs_kind(ts_node_named_child(n, 0), "macro_invocation")) {+ rs_item_macro(s, ts_node_named_child(n, 0), mod);+ }+}++/* The items of one block, in order; attributes belong to the item after+ * them. */+static void rs_scan_block(rs_scan_t *s, rs_block_t block) {+ rs_attrs_t *at = (rs_attrs_t *)rs_tmp_alloc(s, sizeof(*at));+ if (!at) {+ return;+ }+ memset(at, 0, sizeof(*at));+ TSTreeCursor cur = ts_tree_cursor_new(block.node);+ bool more = ts_tree_cursor_goto_first_child(&cur);+ for (; more && !s->failed; more = ts_tree_cursor_goto_next_sibling(&cur)) {+ TSNode n = ts_tree_cursor_current_node(&cur);+ const char *k = ts_node_type(n);+ if (strcmp(k, "attribute_item") == 0) {+ rs_attr_read(s, n, at);+ continue;+ }+ if (!ts_node_is_named(n) || strcmp(k, "line_comment") == 0 ||+ strcmp(k, "block_comment") == 0 || strcmp(k, "inner_attribute_item") == 0) {+ continue;+ }+ rs_scan_item(s, n, block.mod, at);+ memset(at, 0, sizeof(*at));+ }+ ts_tree_cursor_delete(&cur);+}++/* ── Scope scan: the driver ──────────────────────────────────────── */++/* True when the delimiters in text[0..n) pair up. */+static bool rs_delims_balanced(const char *text, size_t n) {+ static const char open[] = "([{";+ static const char close[] = ")]}";+ enum { KINDS = 3 };+ long depth[KINDS] = {0, 0, 0};+ for (size_t i = 0; i < n; i++) {+ for (int k = 0; k < KINDS; k++) {+ depth[k] += text[i] == open[k];+ depth[k] -= text[i] == close[k];+ if (depth[k] < 0) {+ return false;+ }+ }+ }+ return depth[0] == 0 && depth[1] == 0 && depth[PAIR_LEN] == 0;+}++/* An error node that cannot have moved an item boundary: it lies inside a+ * block (a function body: nothing in there is scanned), and the parser+ * neither skipped unpaired delimiters nor made one up. Syntax the grammar+ * does not know yet parses this way; the items around the function are then+ * exactly where the tree puts them. */+static bool rs_error_contained(const rs_scan_t *s, TSNode n, bool in_block) {+ uint32_t a = ts_node_start_byte(n);+ uint32_t b = ts_node_end_byte(n);+ if (!in_block || b > s->src_len) {+ return false;+ }+ if (ts_node_is_missing(n)) {+ const char *t = ts_node_type(n);+ return !rs_delimiter(t, true) && !rs_delimiter(t, false);+ }+ return b <= a || rs_delims_balanced(s->src + a, b - a);+}++/* The first ERROR or MISSING node of the tree, in document order, that is not+ * contained (rs_error_contained); a null node when there is none. Walks only+ * the nodes that hold an error, with a cursor. */+static TSNode rs_first_error(const rs_scan_t *s, TSNode root) {+ TSNode found = {0};+ if (!ts_node_has_error(root)) {+ return found;+ }+ TSTreeCursor cur = ts_tree_cursor_new(root);+ int depth = 0;+ int block_depth = CBM_NOT_FOUND; /* depth of the outermost block around the cursor */+ for (bool more = true; more;) {+ TSNode n = ts_tree_cursor_current_node(&cur);+ bool error = ts_node_is_missing(n) || rs_kind(n, "ERROR");+ if (error && !rs_error_contained(s, n, block_depth >= 0)) {+ found = n;+ break;+ }+ if (block_depth < 0 && rs_kind(n, "block")) {+ block_depth = depth;+ }+ if (!error && ts_node_has_error(n) && ts_tree_cursor_goto_first_child(&cur)) {+ depth++;+ continue;+ }+ for (;;) { /* on to the next node: a sibling, or an ancestor's sibling */+ if (block_depth == depth) {+ block_depth = CBM_NOT_FOUND; /* leaving the block itself */+ }+ if (ts_tree_cursor_goto_next_sibling(&cur)) {+ break;+ }+ if (!ts_tree_cursor_goto_parent(&cur)) {+ more = false;+ break;+ }+ depth--;+ }+ }+ ts_tree_cursor_delete(&cur);+ return found;+}++static int rs_u32_cmp(const void *a, const void *b) {+ uint32_t x = *(const uint32_t *)a;+ uint32_t y = *(const uint32_t *)b;+ return (x > y) - (x < y);+}++/* The start lines of the definitions whose docs hold references (the file's+ * own doc is no definition), sorted. */+static void rs_scan_ref_lines(rs_scan_t *s) {+ const CBMDocLinkArray *links = &s->ctx->result->doc_links;+ s->ref_lines = (uint32_t *)rs_tmp_alloc(s, (size_t)links->count * sizeof(uint32_t));+ if (!s->ref_lines) {+ return;+ }+ int n = 0;+ for (int i = 0; i < links->count; i++) {+ if (!(links->items[i].flags & CBM_DOCLINK_FLAG_FILE)) {+ s->ref_lines[n++] = links->items[i].def_line;+ }+ }+ if (n > SKIP_ONE) {+ qsort(s->ref_lines, (size_t)n, sizeof(uint32_t), rs_u32_cmp);+ }+ s->nref_lines = n;+}++/* Two definitions of one qualified name that are one member name of one type+ * (a field and the method named like it), or one item name of one module+ * (declared twice under different cfg): the node stands for both, and a+ * reference in the doc of either may leave from it. Definitions of different+ * modules or parents only share a name the graph cannot tell apart. */+static bool rs_same_declared_name(const rs_scan_t *s, int a, int b) {+ const CBMDefArray *defs = &s->ctx->result->defs;+ const char *pa = defs->items[a].parent_class;+ const char *pb = defs->items[b].parent_class;+ bool same_parent = (!pa && !pb) || (pa && pb && strcmp(pa, pb) == 0);+ return same_parent && s->def_mod[a] != 0 && s->def_mod[a] == s->def_mod[b];+}++/* Z records: a documented definition with references that does not own its+ * node and shares it with an unrelated definition (rs_same_declared_name).+ * Its references would otherwise leave from that other definition's node. */+static void rs_scan_unowned(rs_scan_t *s) {+ const CBMDefArray *defs = &s->ctx->result->defs;+ for (int i = 0; i < defs->count && !s->failed; i++) {+ const CBMDefinition *d = &defs->items[i];+ if (s->owner[i] || !d->docstring || !d->qualified_name || !d->name ||+ !rs_has_refs(s, d->start_line) ||+ strncmp(d->qualified_name, s->item_prefix, s->item_prefix_len) != 0 ||+ (s->owner_of[i] >= 0 && rs_same_declared_name(s, i, s->owner_of[i]))) {+ continue;+ }+ const char *suffix = d->qualified_name + s->item_prefix_len;+ if (strpbrk(suffix, "\t\n\r")) {+ continue;+ }+ rs_rec(s, 'Z');+ rs_rec_u(s, d->start_line);+ rs_rec_s(s, suffix);+ rs_rec_end(s);+ }+}++const char *cbm_doclink_rs_scan_scope(CBMExtractCtx *ctx) {+ if (!ctx || !ctx->result || ts_node_is_null(ctx->root) || !ctx->source) {+ return NULL;+ }+ rs_scan_t s = {.ctx = ctx,+ .tmp = rs_scratch(ctx),+ .src = ctx->source,+ .src_len = ctx->source_len > 0 ? (uint32_t)ctx->source_len : 0,+ .sb = {.a = ctx->arena},+ .err_byte = UINT32_MAX,+ .next_mod = SKIP_ONE,+ .last_use_mod = CBM_NOT_FOUND};+ /* the qualified name of an item `x` of this file, minus the `x` */+ const char *probe = cbm_fqn_compute(s.tmp, ctx->project, ctx->rel_path, "x");+ if (!probe || strlen(probe) < PAIR_LEN) {+ return NULL;+ }+ s.item_prefix = probe;+ s.item_prefix_len = strlen(probe) - SKIP_ONE;+ rs_scan_defs(&s);+ rs_scan_ref_lines(&s);+ TSNode err = rs_first_error(&s, ctx->root);+ rs_sb_puts(&s.sb, CBM_DOCLINK_RS_SCOPE_TAG "\n");+ if (!ts_node_is_null(err)) {+ s.err_byte = ts_node_start_byte(err);+ s.broken = true;+ rs_rec(&s, 'E');+ rs_rec_u(&s, rs_line_of(err));+ rs_rec_end(&s);+ }+ rs_block_push(&s, ctx->root, 0);+ for (int b = 0; b < s.nblocks && !s.failed; b++) {+ rs_scan_block(&s, s.blocks[b]);+ }+ if (!s.failed) {+ rs_scan_unowned(&s);+ }+ if (s.broken) {+ rs_sb_puts(&s.sb, "B\n");+ }+ if (s.failed || s.sb.failed || !s.sb.buf) {+ return NULL;+ }+ return s.sb.buf;+}++/* ── Cargo manifest ──────────────────────────────────────────────────+ *+ * The scope blob of a `Cargo.toml` (tag line "rs1", then "C"): what the Rust+ * resolver knows of packages, targets and dependencies. The indexer extracts+ * the file anyway, so the resolver reads no file of its own.+ * K table key value a key of [package], [lib] or+ * [workspace.package] the resolver uses+ * A kind one [[bin]] / [[example]] / [[test]] /+ * [[bench]] target; its keys follow as+ * a key value `name` or `path` of that target+ * W the manifest has a [workspace] table+ * X kind name attr value a dependency. kind: d dependencies, v dev,+ * b build, w workspace.dependencies; attr '-'+ * when the entry is only named, else `path`,+ * `package` or `workspace`+ * B the TOML tree has a parse error+ * A value this scan cannot carry (an escape, a multi-line string, a tab) is+ * written as "?": the resolver then knows the key is set, not to what. */++enum { RS_TOML_SEGS = 8 };++typedef struct {+ char seg[RS_TOML_SEGS][RS_SCAN_NAME_CAP];+ int n;+ bool ok; /* false: more segments, a longer one, or an escape */+} rs_toml_key_t;++enum {+ RS_TABLE_OTHER = 0,+ RS_TABLE_PACKAGE,+ RS_TABLE_LIB,+ RS_TABLE_WORKSPACE_PACKAGE,+ RS_TABLE_TARGET, /* one element of a target array */+ RS_TABLE_DEPS, /* a dependency table: `dep` is its kind */+ RS_TABLE_DEP, /* the table of one dependency: `dep` and `name` */+};++typedef struct {+ int kind;+ char dep;+ const char *name; /* RS_TABLE_DEP: the dependency; else the table's dotted name */+ bool is_workspace; /* [workspace] or a table below it */+} rs_table_t;++void cbm_doclink_rs_manifest_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def,+ const char *doc, uint32_t doc_line) {+ (void)ctx;+ (void)def;+ (void)doc;+ (void)doc_line; /* a manifest holds no doc-comment references */+}++static bool rs_is_manifest(const char *rel_path) {+ static const char name[] = "Cargo.toml";+ const char *slash = strrchr(rel_path, '/');+ return strcmp(slash ? slash + SKIP_ONE : rel_path, name) == 0;+}++/* The dotted key written at text[0..n): `a.'b c'."d"` -> a, b c, d. */+static void rs_toml_key(const char *text, size_t n, rs_toml_key_t *out) {+ out->n = 0;+ out->ok = true;+ size_t i = 0;+ while (i < n && out->ok) {+ while (i < n && (text[i] == ' ' || text[i] == '\t')) {+ i++;+ }+ char quote = (i < n && (text[i] == '"' || text[i] == '\'')) ? text[i] : 0;+ size_t start = quote ? i + SKIP_ONE : i;+ size_t e = start;+ while (e < n &&+ (quote ? text[e] != quote : (text[e] != '.' && text[e] != ' ' && text[e] != '\t'))) {+ out->ok = out->ok && text[e] != '\\';+ e++;+ }+ if (out->n >= RS_TOML_SEGS || e - start >= RS_SCAN_NAME_CAP || e == start ||+ (quote && e >= n)) {+ out->ok = false;+ return;+ }+ memcpy(out->seg[out->n], text + start, e - start);+ out->seg[out->n][e - start] = '\0';+ out->n++;+ i = quote ? e + SKIP_ONE : e;+ while (i < n && (text[i] == ' ' || text[i] == '\t')) {+ i++;+ }+ if (i < n && text[i] != '.') {+ out->ok = false;+ return;+ }+ i++;+ }+}++static void rs_toml_key_of(const rs_scan_t *s, TSNode key, rs_toml_key_t *out) {+ uint32_t a = ts_node_start_byte(key);+ uint32_t b = ts_node_end_byte(key);+ if (ts_node_is_null(key) || b <= a || b > s->src_len) {+ out->n = 0;+ out->ok = false;+ return;+ }+ rs_toml_key(s->src + a, b - a, out);+}++static bool rs_toml_is_key(TSNode n) {+ return rs_kind(n, "bare_key") || rs_kind(n, "quoted_key") || rs_kind(n, "dotted_key");+}++/* A string or boolean value as text; "?" for one the blob cannot carry. NULL+ * for a value of another kind. */+static const char *rs_toml_scalar(rs_scan_t *s, TSNode v) {+ if (ts_node_is_null(v)) {+ return NULL;+ }+ uint32_t a = ts_node_start_byte(v);+ uint32_t b = ts_node_end_byte(v);+ if (b <= a || b > s->src_len) {+ return NULL;+ }+ const char *text = s->src + a;+ size_t n = b - a;+ if (rs_kind(v, "boolean")) {+ return rs_word_is(text, n, "true") ? "true" : "false";+ }+ if (!rs_kind(v, "string")) {+ return NULL;+ }+ char q = text[0];+ bool plain = n >= PAIR_LEN && (q == '"' || q == '\'') && text[n - SKIP_ONE] == q &&+ n - PAIR_LEN < RS_SCAN_PATH_CAP;+ for (size_t i = SKIP_ONE; plain && i + SKIP_ONE < n; i++) {+ unsigned char c = (unsigned char)text[i];+ plain = c != (unsigned char)q && c >= ' ' && !(q == '"' && c == '\\');+ }+ if (!plain || n == PAIR_LEN) {+ return "?";+ }+ char *out = (char *)rs_tmp_alloc(s, n);+ if (!out) {+ return NULL;+ }+ memcpy(out, text + SKIP_ONE, n - PAIR_LEN);+ out[n - PAIR_LEN] = '\0';+ return out;+}++static char rs_dep_kind(const char *seg) {+ static const struct {+ const char *name;+ char kind;+ } table[] = {+ {"dependencies", 'd'}, {"dev-dependencies", 'v'}, {"dev_dependencies", 'v'},+ {"build-dependencies", 'b'}, {"build_dependencies", 'b'},+ };+ for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {+ if (strcmp(table[i].name, seg) == 0) {+ return table[i].kind;+ }+ }+ return 0;+}++/* What the table named `key` is. `array`: it is written `[[key]]`. */+static rs_table_t rs_table_class(const rs_toml_key_t *key, bool array) {+ rs_table_t t = {.kind = RS_TABLE_OTHER};+ if (!key->ok || key->n == 0) {+ return t;+ }+ const char *first = key->seg[0];+ const char *last = key->seg[key->n - SKIP_ONE];+ t.is_workspace = strcmp(first, "workspace") == 0;+ static const char *const targets[] = {"bin", "example", "test", "bench"};+ for (size_t i = 0; array && key->n == SKIP_ONE && i < sizeof(targets) / sizeof(targets[0]);+ i++) {+ if (strcmp(first, targets[i]) == 0) {+ t.kind = RS_TABLE_TARGET;+ t.name = targets[i];+ return t;+ }+ }+ if (array) {+ return t;+ }+ if (key->n == SKIP_ONE && strcmp(first, "package") == 0) {+ t.kind = RS_TABLE_PACKAGE;+ t.name = "package";+ } else if (key->n == SKIP_ONE && strcmp(first, "lib") == 0) {+ t.kind = RS_TABLE_LIB;+ t.name = "lib";+ } else if (key->n == PAIR_LEN && t.is_workspace && strcmp(last, "package") == 0) {+ t.kind = RS_TABLE_WORKSPACE_PACKAGE;+ t.name = "workspace.package";+ } else if (rs_dep_kind(last)) {+ t.kind = RS_TABLE_DEPS;+ t.dep = t.is_workspace ? 'w' : rs_dep_kind(last);+ } else if (key->n >= PAIR_LEN && rs_dep_kind(key->seg[key->n - PAIR_LEN])) {+ t.kind = RS_TABLE_DEP;+ t.dep = t.is_workspace ? 'w' : rs_dep_kind(key->seg[key->n - PAIR_LEN]);+ t.name = last;+ }+ return t;+}++static void rs_rec_dep(rs_scan_t *s, char kind, const char *name, const char *attr,+ const char *value) {+ rs_rec(s, 'X');+ rs_sb_putc(&s->sb, '\t');+ rs_sb_putc(&s->sb, kind);+ rs_rec_s(s, name);+ rs_rec_s(s, attr);+ rs_rec_s(s, value);+ rs_rec_end(s);+}++static bool rs_dep_attr(const char *key) {+ return strcmp(key, "path") == 0 || strcmp(key, "package") == 0 || strcmp(key, "workspace") == 0;+}++/* The key and value node of a `pair`. */+static void rs_toml_pair(TSNode pair, TSNode *key, TSNode *value) {+ *key = (TSNode){0};+ *value = (TSNode){0};+ uint32_t nc = ts_node_named_child_count(pair);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(pair, i);+ if (rs_kind(c, "comment")) {+ continue;+ }+ if (ts_node_is_null(*key) && rs_toml_is_key(c)) {+ *key = c;+ } else if (!ts_node_is_null(*key)) {+ *value = c;+ }+ }+}++/* One entry of a dependency table: `name = "1"`, `name = { path = .. }`,+ * `name.workspace = true`. */+static void rs_manifest_dep(rs_scan_t *s, char kind, const rs_toml_key_t *key, TSNode value) {+ const char *name = key->seg[0];+ if (strpbrk(name, "\t\n\r")) {+ return;+ }+ rs_rec_dep(s, kind, name, "-", "-");+ if (key->n == PAIR_LEN && rs_dep_attr(key->seg[1])) {+ const char *v = rs_toml_scalar(s, value);+ rs_rec_dep(s, kind, name, key->seg[1], v ? v : "?");+ return;+ }+ if (key->n != SKIP_ONE || ts_node_is_null(value) || !rs_kind(value, "inline_table")) {+ return;+ }+ uint32_t nc = ts_node_named_child_count(value);+ for (uint32_t i = 0; i < nc && !s->failed; i++) {+ TSNode inner = ts_node_named_child(value, i);+ TSNode ik;+ TSNode iv;+ if (!rs_kind(inner, "pair")) {+ continue;+ }+ rs_toml_pair(inner, &ik, &iv);+ rs_toml_key_t in_key;+ rs_toml_key_of(s, ik, &in_key);+ if (in_key.ok && in_key.n == SKIP_ONE && rs_dep_attr(in_key.seg[0])) {+ const char *v = rs_toml_scalar(s, iv);+ rs_rec_dep(s, kind, name, in_key.seg[0], v ? v : "?");+ }+ }+}++/* True for the keys of [package], [lib], [workspace.package] and a target+ * that the resolver reads. */+static bool rs_manifest_key_used(const char *key) {+ static const char *const keys[] = {"name", "edition", "build", "path",+ "autobins", "autoexamples", "autotests", "autobenches",+ "proc-macro", "proc_macro"};+ for (size_t i = 0; i < sizeof(keys) / sizeof(keys[0]); i++) {+ if (strcmp(keys[i], key) == 0) {+ return true;+ }+ }+ return false;+}++/* `key = value` of [package], [lib], [workspace.package] or a target.+ * `edition.workspace = true` and `edition = { workspace = true }` are both+ * written as the key `edition.workspace`. */+static void rs_manifest_setting(rs_scan_t *s, const rs_table_t *t, const rs_toml_key_t *key,+ TSNode value) {+ if (!rs_manifest_key_used(key->seg[0])) {+ return;+ }+ const char *v = rs_toml_scalar(s, value);+ bool inherited = key->n == PAIR_LEN && strcmp(key->seg[1], "workspace") == 0;+ if (key->n == SKIP_ONE && !v && !ts_node_is_null(value) && rs_kind(value, "inline_table")) {+ uint32_t a = ts_node_start_byte(value);+ uint32_t b = ts_node_end_byte(value);+ inherited = b > a && b <= s->src_len && rs_has_word(s->src + a, b - a, "workspace");+ v = "true";+ }+ if (key->n > PAIR_LEN || (key->n == PAIR_LEN && !inherited)) {+ return;+ }+ if (t->kind == RS_TABLE_TARGET) {+ rs_rec(s, 'a');+ } else {+ rs_rec(s, 'K');+ rs_rec_s(s, t->name);+ }+ rs_sb_putc(&s->sb, '\t');+ rs_sb_puts(&s->sb, key->seg[0]);+ if (inherited) {+ rs_sb_puts(&s->sb, ".workspace");+ }+ rs_rec_s(s, v ? v : "?");+ rs_rec_end(s);+}++/* The pairs of one table (a `table` or `table_array_element` node). */+static void rs_manifest_table(rs_scan_t *s, TSNode table, bool array) {+ rs_toml_key_t name = {.n = 0, .ok = false};+ rs_table_t t = {.kind = RS_TABLE_OTHER};+ TSTreeCursor cur = ts_tree_cursor_new(table);+ bool more = ts_tree_cursor_goto_first_child(&cur);+ bool named = false;+ for (; more && !s->failed; more = ts_tree_cursor_goto_next_sibling(&cur)) {+ TSNode c = ts_tree_cursor_current_node(&cur);+ if (!named && rs_toml_is_key(c)) {+ named = true;+ rs_toml_key_of(s, c, &name);+ t = rs_table_class(&name, array);+ if (t.is_workspace) {+ rs_sb_puts(&s->sb, "W\n");+ }+ if (t.kind == RS_TABLE_TARGET) {+ rs_rec(s, 'A');+ rs_rec_s(s, t.name);+ rs_rec_end(s);+ } else if (t.kind == RS_TABLE_DEP && !strpbrk(t.name, "\t\n\r")) {+ rs_rec_dep(s, t.dep, t.name, "-", "-");+ }+ continue;+ }+ if (!rs_kind(c, "pair") || t.kind == RS_TABLE_OTHER) {+ continue;+ }+ TSNode k;+ TSNode v;+ rs_toml_pair(c, &k, &v);+ rs_toml_key_t key;+ rs_toml_key_of(s, k, &key);+ if (!key.ok || key.n == 0) {+ continue;+ }+ if (t.kind == RS_TABLE_DEPS) {+ rs_manifest_dep(s, t.dep, &key, v);+ } else if (t.kind == RS_TABLE_DEP) {+ if (key.n == SKIP_ONE && rs_dep_attr(key.seg[0])) {+ const char *val = rs_toml_scalar(s, v);+ rs_rec_dep(s, t.dep, t.name, key.seg[0], val ? val : "?");+ }+ } else {+ rs_manifest_setting(s, &t, &key, v);+ }+ }+ ts_tree_cursor_delete(&cur);+}++const char *cbm_doclink_rs_manifest_scan_scope(CBMExtractCtx *ctx) {+ if (!ctx || !ctx->result || !ctx->rel_path || !ctx->source || ts_node_is_null(ctx->root) ||+ !rs_is_manifest(ctx->rel_path)) {+ return NULL;+ }+ rs_scan_t s = {.ctx = ctx,+ .tmp = rs_scratch(ctx),+ .src = ctx->source,+ .src_len = ctx->source_len > 0 ? (uint32_t)ctx->source_len : 0,+ .sb = {.a = ctx->arena}};+ rs_sb_puts(&s.sb, CBM_DOCLINK_RS_SCOPE_TAG "\nC\n");+ TSTreeCursor cur = ts_tree_cursor_new(ctx->root);+ bool more = ts_tree_cursor_goto_first_child(&cur);+ for (; more && !s.failed; more = ts_tree_cursor_goto_next_sibling(&cur)) {+ TSNode c = ts_tree_cursor_current_node(&cur);+ if (rs_kind(c, "table")) {+ rs_manifest_table(&s, c, false);+ } else if (rs_kind(c, "table_array_element")) {+ rs_manifest_table(&s, c, true);+ }+ }+ ts_tree_cursor_delete(&cur);+ if (ts_node_has_error(ctx->root)) {+ rs_sb_puts(&s.sb, "B\n");+ }+ if (s.failed || s.sb.failed || !s.sb.buf) {+ return NULL;+ }+ return s.sb.buf;+}++/* ── Persisted form ──────────────────────────────────────────────── */++/* Field positions (0-based, the tag is field 0) that hold line numbers. */+static bool rs_line_field(char tag, int field) {+ enum { F1 = 1, F2 = 2, F3 = 3, F4 = 4 };+ switch (tag) {+ case 'N':+ return field == F3 || field == F4;+ case 'T':+ case 'I':+ return field == F2 || field == F3;+ case 'M':+ return field == F1;+ default:+ return false;+ }+}++/* Records only the file's own references need: never persisted. */+static bool rs_fresh_only(char tag) {+ return tag == 'P' || tag == 'Z' || tag == 'E';+}++char *cbm_doclink_rs_portable_scope(const char *scope) {+ size_t n = strlen(scope);+ char *out = (char *)cbm_alloc(CBM_MEM_CLASS_OTHER, n + SKIP_ONE);+ if (!out) {+ return NULL;+ }+ size_t w = 0;+ const char *p = scope;+ bool first = true;+ while (*p) {+ const char *nl = strchr(p, '\n');+ size_t len = nl ? (size_t)(nl - p) : strlen(p);+ char tag = first ? 0 : p[0];+ const char *next = nl ? nl + SKIP_ONE : p + len;+ if (rs_fresh_only(tag)) {+ p = next;+ first = false;+ continue;+ }+ int field = 0;+ size_t i = 0;+ while (i < len) {+ size_t fend = i;+ while (fend < len && p[fend] != '\t') {+ fend++;+ }+ if (rs_line_field(tag, field)) {+ out[w++] = '0';+ } else {+ memcpy(out + w, p + i, fend - i);+ w += fend - i;+ }+ i = fend;+ if (i < len) {+ out[w++] = '\t';+ i++;+ field++;+ }+ }+ if (nl) {+ out[w++] = '\n';+ }+ p = next;+ first = false;+ }+ out[w] = '\0';+ return out;+}diff --git a/src/pipeline/doc_links.c b/src/pipeline/doc_links.cindex b486d6267..a365ddf41 100644--- a/src/pipeline/doc_links.c+++ b/src/pipeline/doc_links.c@@ -47,7 +47,7 @@ const char *cbm_doclink_reason_name(int reason) {static const cbm_doclink_resolver_t *const DOCLINK_RESOLVERS[] = {&cbm_doclink_cs_resolver, &cbm_doclink_md_resolver, &cbm_doclink_pdf_resolver,&cbm_doclink_rst_resolver, &cbm_doclink_adoc_resolver, &cbm_doclink_go_resolver,- &cbm_doclink_jvm_resolver,+ &cbm_doclink_jvm_resolver, &cbm_doclink_rs_resolver,};enum { DOCLINK_RESOLVER_COUNT = sizeof(DOCLINK_RESOLVERS) / sizeof(DOCLINK_RESOLVERS[0]) };diff --git a/src/pipeline/doc_links.h b/src/pipeline/doc_links.hindex 5ea4e46af..a85e3d512 100644--- a/src/pipeline/doc_links.h+++ b/src/pipeline/doc_links.h@@ -297,6 +297,7 @@ void cbm_doclink_cs_test_unit_memo(bool on);bool cbm_doclinks_binds_lines(CBMLanguage lang);extern const cbm_doclink_resolver_t cbm_doclink_go_resolver;extern const cbm_doclink_resolver_t cbm_doclink_jvm_resolver;+extern const cbm_doclink_resolver_t cbm_doclink_rs_resolver;/* True when `rel_path` is a scope input of some language (scope_input). */bool cbm_doclinks_is_scope_input(const char *rel_path);diff --git a/src/pipeline/doc_links_rs.c b/src/pipeline/doc_links_rs.cnew file mode 100644index 000000000..0f6c02460--- /dev/null+++ b/src/pipeline/doc_links_rs.c@@ -0,0 +1,4447 @@+/*+ * doc_links_rs.c — Rust intra-doc link resolution for doc_links.h.+ *+ * The index is built from the scope blobs of the repository's Rust files and+ * Cargo manifests (internal/cbm/doclink_rs.c); nothing is read from disk.+ * Graph nodes are looked up by qualified name only, and a node is taken only+ * when its label and file are the declaration's, so the closure-repair route+ * (line-less proxy nodes) resolves exactly as a full build does.+ *+ * Model.+ * package a Cargo manifest with [package]: its directory, edition and+ * dependencies. A dependency names a crate of the repository+ * only through `path` (its own, or the workspace table's)+ * crate root a target root file of a package: the lib (src/lib.rs or+ * [lib] path), src/main.rs, src/bin/, tests/, benches/,+ * examples/, build.rs, and explicit target paths+ * module a file's root module or an inline `mod x { }`. A `mod x;`+ * attaches the file rustc would read: x.rs or x/mod.rs beside a+ * crate root, a mod.rs or a `#[path]` file, under <stem>/ beside+ * any other file, or the `#[path]` file. A file can be attached+ * more than once and belong to several crate roots; a file no+ * root reaches is an orphan+ * binding what a module declares under a name: an item, a child+ * module, a named import, a name a macro invocation may declare+ *+ * Lookup follows rustc's name resolution as rustdoc applies it to intra-doc+ * links, one namespace (type, value, macro) at a time:+ * first segment `crate` (every crate root of the file), `self`, `super`+ * (repeatable), `Self` (the impl's self type, the trait, or+ * the documented type), `::name` (extern prelude), else+ * 1. the module's own bindings+ * 2. its glob imports, through re-exporting globs, only+ * names visible to the importing module+ * 3. the extern prelude: std, core, alloc, proc_macro,+ * test, the package's dependencies, and the package's+ * own lib from its other targets+ * 4. the std prelude, primitive types, std macros+ * The first level with a binding in the namespace decides. A+ * level whose content is not known (a glob of an external+ * module) is not looked past.+ * later segments a module's levels 1 and 2; for a type: enum variant, items+ * of its inherent impls, then items of trait impls whose+ * trait is in scope of the documenting module, then (value+ * namespace) fields; for a trait its own items; type aliases+ * are followed+ * The candidates of the namespaces are united. One entity binds. A trait and+ * a derive macro of one name are the trait (rustdoc's rule). Anything else+ * with two or more is ambiguous. A disambiguator or suffix restricts the+ * namespace and the kind; an entity of another kind is no match.+ *+ * Nothing is resolved around what the scan could not place: in a file with a+ * parse error (or constructs the blob cannot carry) a name its modules do not+ * show is a graph gap, never looked up further out; so are a name a macro+ * invocation may declare, an import that cannot be followed, a `mod` whose+ * file is not indexed, and `crate::` or `super::` from an orphan file.+ */+#include "pipeline/doc_links.h"++#include "doclink.h"+#include "helpers.h" /* cbm_fqn_compute, cbm_fqn_module_source_lang, cbm_is_test_file */+#include "foundation/arena.h"+#include "foundation/constants.h"+#include "foundation/hash_table.h"+#include "foundation/log.h"+#include "foundation/mem_core.h"++#include <ctype.h>+#include <stdint.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++enum {+ RS_NS_TYPE = 1,+ RS_NS_VALUE = 2,+ RS_NS_MACRO = 4,+ RS_NS_ALL = 7,+ RS_NS_COUNT = 3,+};++static const int RS_NS_LIST[RS_NS_COUNT] = {RS_NS_TYPE, RS_NS_VALUE, RS_NS_MACRO};++/* What a path names. */+enum {+ RS_E_NONE = 0,+ RS_E_ITEM, /* idx: item */+ RS_E_MOD, /* idx: module */+ RS_E_MEMBER, /* idx: member */+ RS_E_IMPL, /* idx: impl whose self type is no item of the repository (`Self` only) */+ RS_E_EXTERNAL, /* outside the repository */+ RS_E_GAP, /* declared in the repository, but not placed or not followed */+};++enum {+ RS_SET_CAP = 8, /* distinct candidates kept; more is ambiguous either way */+ RS_ROOTS_KEPT = 4, /* crate roots kept per file; a file of more has no single crate */+ RS_IMPORT_PASSES = 32, /* an import behind a longer chain of imports is not followed */+ RS_ALIAS_HOPS = 8, /* a chain of type aliases; longer is not followed */+ RS_UP_STEPS = 256, /* module ancestors walked for one question; more is unknown */+ RS_GLOB_VISIT = 64, /* modules reached through globs for one name; more is unknown */+ RS_IMPL_SCAN = 256, /* trait impls of one type searched for a default item */+ RS_QN_BUF = 2048,+ RS_PATH_BUF = 1024,+ RS_PATH_DEPTH = RS_PATH_BUF / 2, /* inline modules around a `mod x;` */+ RS_FIELDS_MAX = 9,+ RS_TAIL = 4, /* path components read from the end */+ RS_EDITION_2015 = 2015,+ RS_EDITION_2018 = 2018,+ RS_EDITION_UNKNOWN = 0,+ RS_EDITION_INHERITED = -1,+ RS_EDITION_UNREADABLE = -2,+ RS_PKG_NONE = -1,+ RS_PKG_CONFLICT = -2,+ RS_VIEW_A = 1, /* out-of-line children are read beside the file */+ RS_VIEW_B = 2, /* ... from the directory named like the file */+ RS_RS_EXT = 3, /* strlen(".rs") */+};++enum { RS_FILE_OTHER = 0, RS_FILE_SOURCE, RS_FILE_MANIFEST };+enum { RS_BIND_ITEM = 0, RS_BIND_CHILD, RS_BIND_IMPORT, RS_BIND_MAYBE };+enum { RS_STATE_NEW = 0, RS_STATE_DONE };+enum {+ RS_TARGET_LIB = 0,+ RS_TARGET_BIN,+ RS_TARGET_EXAMPLE,+ RS_TARGET_TEST,+ RS_TARGET_BENCH,+ RS_TARGET_BUILD+};++typedef struct {+ uint8_t kind; /* RS_E_* */+ bool via_import; /* bound by a named import: an exact naming */+ bool weak; /* the name was not found, but is not known to be absent either (a gap+ * or an external glob could hold it): a binding found in another+ * namespace overrides it */+ int idx;+} rs_ent_t;++typedef struct {+ rs_ent_t v[RS_SET_CAP];+ int n;+ bool overflow;+} rs_set_t;++/* ── Index data ──────────────────────────────────────────────────── */++typedef struct {+ int file;+ int parent; /* the inline parent module; CBM_NOT_FOUND for a file's root module */+ const char *name;+ uint32_t start; /* lines: a re-extracted file's only */+ uint32_t end;+ char vis;+ bool cfg_test;+ bool path_attr; /* an inline module with `#[path]`: where its `mod x;` files are is not known */+ bool product; /* reachable as product code: not test-only */+ int bind_first;+ int bind_count;+ int glob_first;+ int glob_count;+ int named_first;+ int named_count;+ int attach_first; /* a file's root module: the `mod x;` declarations naming the file */+ int attach_count;+} rs_mod_t;++typedef struct {+ int mod; /* the declaring module */+ const char *name;+ const char *path; /* the #[path] literal, NULL when there is none */+ char vis;+ bool cfg_test;+ bool cond_path; /* its file depends on cfg: not followed */+ int child; /* the declared file's root module, CBM_NOT_FOUND when not known */+} rs_decl_t;++typedef struct {+ int child;+ int decl;+} rs_attach_t;++typedef struct {+ int file;+ int mod;+ const char *name;+ char kind; /* S E U R A F C G M V B P */+ char vis;+ bool test;+ bool macro_export;+ const char *derives; /* a type's derive names, comma-joined; NULL when it has none */+ uint32_t start;+ uint32_t end;+ char label; /* node label code, 0 when the item has no node */+ const char *suffix; /* the node's qualified name after the file's item prefix */+ const char *alias; /* A: the aliased path, NULL when it is no path */+ rs_ent_t alias_ent;+ int member_first;+ int member_count;+ int impl_first; /* into rs_index_t.item_impls */+ int impl_count;+} rs_item_t;++typedef struct {+ int file;+ int mod;+ int owner; /* the item it belongs to, or -(impl) - 1 */+ bool owner_test;+ const char *name;+ char kind; /* f c t d v */+ char label;+ const char *suffix;+ int seq;+} rs_member_t;++typedef struct {+ int file;+ int mod;+ uint32_t start;+ uint32_t end;+ const char *self_path; /* NULL when the self type is no path */+ const char *trait_path; /* NULL for an inherent impl, "?" when it is no path */+ rs_ent_t self_ent;+ rs_ent_t trait_ent;+ int member_first;+ int member_count;+} rs_impl_t;++typedef struct {+ int item;+ int impl;+} rs_item_impl_t;++/* An impl's member, by the type the impl is for. */+typedef struct {+ int item;+ const char *name;+ int impl;+ int member;+} rs_assoc_t;++typedef struct {+ int file;+ int mod;+ char vis;+ char kind; /* b named, s `self` (type namespace only), g glob, x extern crate */+ const char *local;+ const char **segs;+ int nsegs;+ bool global;+ bool spread; /* what it names has no known namespace (external, or a gap): res[] holds+ * it in all three, and a binding the module really has in one of them+ * takes precedence there */+ int state;+ int done_pass;+ int seq;+ rs_ent_t res[RS_NS_COUNT]; /* named: per namespace; the others: res[0] */+} rs_import_t;++typedef struct {+ int mod;+ const char *name;+ int kind; /* RS_BIND_* */+ int ref;+ int seq;+ char vis;+} rs_bind_t;++/* An index entry sorted by (mod, seq). */+typedef struct {+ int mod;+ int seq;+ int ref;+} rs_ref_t;++/* A name the body of the `macro_rules!` macro `macro` declares (W records). */+typedef struct {+ const char *name;+ const char *macro;+} rs_macdecl_t;++/* Module `mod` invokes a macro of this name among its items (V records). */+typedef struct {+ int mod;+ const char *macro;+} rs_macuse_t;++/* A range of a file in which `Self` means one type: a type item's own+ * extent, or an impl block. */+typedef struct {+ uint32_t start;+ uint32_t end;+ int item; /* CBM_NOT_FOUND for an impl */+ int impl;+} rs_scope_t;++typedef struct {+ uint32_t line;+ const char *text; /* P: comma-joined names; Z: the unowned definition's QN suffix */+} rs_note_t;++/* From line `from` on, the innermost module is `mod`. */+typedef struct {+ uint32_t from;+ int mod;+} rs_span_t;++typedef struct {+ const char *rel_path;+ const char *item_prefix; /* qualified name of an item of the file, minus its name */+ const char *module_qn;+ int kind;+ bool test_path;+ bool broken; /* its modules may declare names the blob does not show */+ bool fresh; /* re-extracted in this run: its blob has line numbers */+ bool crate_root;+ bool queued;+ bool roots_top; /* more crate roots than are kept */+ bool in_lib; /* some crate root of it is a package's lib target */+ uint8_t views; /* RS_VIEW_* its `mod x;` declarations are read under */+ uint8_t views_done;+ uint32_t err_line; /* first line whose definitions have no scope; 0: none */+ int mod_base; /* its root module */+ int nmods;+ int decl_first;+ int decl_count;+ int item_first;+ int item_count;+ int root_pkg; /* a crate root: its package (RS_PKG_*) */+ int pkg; /* the package of its crate roots (RS_PKG_*) */+ int roots[RS_ROOTS_KEPT];+ int nroots;+ int scope_first;+ int scope_count;+ int local_first; /* P records */+ int local_count;+ int unowned_first; /* Z records */+ int unowned_count;+ int span_first;+ int span_count;+ int test_first; /* start lines of the items marked as tests */+ int test_count;+} rs_file_t;++typedef struct {+ char kind; /* d dependencies, v dev, b build, w workspace.dependencies */+ const char *name;+ const char *attr; /* "-", "path", "package", "workspace" */+ const char *value;+ int seq;+} rs_rawdep_t;++typedef struct {+ const char *key; /* the crate's name in scope */+ rs_ent_t target;+} rs_dep_t;++typedef struct {+ int file;+ const char *dir; /* "" for the repository root */+ const char *name;+ const char *lib_name; /* the lib crate's name; NULL when it has none that is known */+ const char *lib_path;+ const char *build;+ bool has_package;+ bool is_workspace;+ bool broken;+ bool no_autobins;+ bool no_autoexamples;+ bool no_autotests;+ bool no_autobenches;+ int edition;+ int ws_edition;+ rs_rawdep_t *raw;+ int nraw;+ const char **targets; /* explicit target paths, as written */+ int ntargets;+ rs_dep_t *deps; /* sorted by key */+ int ndeps;+ int lib_root; /* the lib target's root module, CBM_NOT_FOUND when it has none */+ int ws; /* its workspace root's package, CBM_NOT_FOUND */+} rs_pkg_t;++typedef struct {+ CBMArena arena;+ bool oom;+ const char *project;+ rs_file_t *files;+ int nfiles;+ int nsources;+ int *run_to_file;+ int run_count;+ rs_mod_t *mods;+ int nmods;+ rs_decl_t *decls;+ int ndecls;+ rs_attach_t *attach;+ int nattach;+ rs_item_t *items;+ int nitems;+ rs_member_t *members;+ int nmembers;+ rs_impl_t *impls;+ int nimpls;+ rs_item_impl_t *item_impls;+ int nitem_impls;+ rs_assoc_t *assoc;+ int nassoc;+ rs_import_t *imports;+ int nimports;+ rs_ref_t *globs; /* the glob imports, by module */+ int nglobs;+ rs_ref_t *named; /* the named imports, by module */+ int nnamed;+ rs_bind_t *binds;+ int nbinds;+ rs_ref_t *maybes; /* Q records: ref indexes maybe_names */+ const char **maybe_names;+ int nmaybes;+ rs_macdecl_t *macdecls; /* sorted by (name, macro) */+ int nmacdecls;+ rs_macuse_t *macuses; /* sorted by (mod, macro) */+ int nmacuses;+ rs_scope_t *scopes;+ int nscopes;+ rs_note_t *locals;+ int nlocals;+ rs_note_t *unowned;+ int nunowned;+ rs_span_t *spans;+ int nspans;+ uint32_t *test_lines;+ int ntest_lines;+ rs_pkg_t *pkgs;+ int npkgs;+ CBMHashTable *file_by_path; /* rel_path -> file + 1 */+ CBMHashTable *pkg_by_dir; /* directory -> package + 1 */+ CBMHashTable *blanket; /* names of members of impls for no named type */+ int crate_roots;+ int orphans;+ int gap_imports;+} rs_index_t;++/* ── Small helpers ───────────────────────────────────────────────── */++static void *ix_alloc(rs_index_t *ix, size_t n) {+ void *p = cbm_arena_alloc(&ix->arena, n ? n : SKIP_ONE);+ ix->oom = ix->oom || !p;+ return p;+}++static void *ix_calloc(rs_index_t *ix, size_t count, size_t size) {+ size_t n = count * size;+ void *p = ix_alloc(ix, n);+ if (p) {+ memset(p, 0, n ? n : SKIP_ONE);+ }+ return p;+}++static char *ix_strdup(rs_index_t *ix, const char *s) {+ char *p = cbm_arena_strdup(&ix->arena, s ? s : "");+ ix->oom = ix->oom || !p;+ return p;+}++static char *ix_strndup(rs_index_t *ix, const char *s, size_t n) {+ char *p = cbm_arena_strndup(&ix->arena, s, n);+ ix->oom = ix->oom || !p;+ return p;+}++/* A name without the raw-identifier marker: `r#type` and `type` are one name. */+static const char *rs_plain(const char *name) {+ return (name[0] == 'r' && name[1] == '#' && name[PAIR_LEN]) ? name + PAIR_LEN : name;+}++/* Split `line` in place at tabs into at most `max` fields; the count. */+static int rs_fields(char *line, char **out, int max) {+ int n = 0;+ out[n++] = line;+ for (char *p = line; *p && n < max; p++) {+ if (*p == '\t') {+ *p = '\0';+ out[n++] = p + SKIP_ONE;+ }+ }+ return n;+}++static bool rs_ends_with(const char *s, const char *suffix) {+ size_t n = strlen(s);+ size_t sl = strlen(suffix);+ return n >= sl && strcmp(s + n - sl, suffix) == 0;+}++static const char *rs_basename(const char *rel) {+ const char *slash = strrchr(rel, '/');+ return slash ? slash + SKIP_ONE : rel;+}++/* Append "/" and s[0..n) to the path in out[0..*w); nothing when n is 0. false+ * when it does not fit. */+static bool rs_path_put(char *out, size_t cap, size_t *w, const char *s, size_t n) {+ if (n == 0) {+ return true;+ }+ if (*w + n + PAIR_LEN >= cap) {+ return false;+ }+ if (*w > 0) {+ out[(*w)++] = '/';+ }+ memcpy(out + *w, s, n);+ *w += n;+ out[*w] = '\0';+ return true;+}++/* Normalize `dir`/`path` (repository-relative): "." and ".." segments, doubled+ * and trailing slashes. false when it leaves the repository or does not fit. */+static bool rs_join_path(const char *dir, const char *path, char *out, size_t cap) {+ char tmp[RS_PATH_BUF];+ int k = (path[0] == '/') ? CBM_NOT_FOUND+ : snprintf(tmp, sizeof(tmp), "%s%s%s", dir, dir[0] ? "/" : "", path);+ if (k < 0 || (size_t)k >= sizeof(tmp)) {+ return false;+ }+ size_t w = 0;+ out[0] = '\0';+ for (const char *p = tmp; *p;) {+ const char *slash = strchr(p, '/');+ size_t len = slash ? (size_t)(slash - p) : strlen(p);+ const char *next = slash ? slash + SKIP_ONE : p + len;+ if (len == PAIR_LEN && p[0] == '.' && p[1] == '.') {+ if (w == 0) {+ return false;+ }+ while (w > 0 && out[w - SKIP_ONE] != '/') {+ w--;+ }+ w = w > 0 ? w - SKIP_ONE : 0;+ out[w] = '\0';+ } else if (len > 0 && !(len == SKIP_ONE && p[0] == '.')) {+ if (!rs_path_put(out, cap, &w, p, len)) {+ return false;+ }+ }+ p = next;+ }+ return true;+}++static bool rs_is_test_dir(const char *seg, size_t n) {+ static const char *const dirs[] = {"tests", "test", "benches", "examples", "fixtures"};+ for (size_t i = 0; i < sizeof(dirs) / sizeof(dirs[0]); i++) {+ if (strlen(dirs[i]) == n && memcmp(dirs[i], seg, n) == 0) {+ return true;+ }+ }+ return false;+}++/* Test, bench, example and fixture code by its place in the tree: Cargo's+ * target directories, plus the indexer's own test-file rule. */+static bool rs_is_test_path(const char *rel) {+ if (cbm_is_test_file(rel, CBM_LANG_RUST)) {+ return true;+ }+ for (const char *p = rel;;) {+ const char *slash = strchr(p, '/');+ if (!slash) {+ return false;+ }+ if (rs_is_test_dir(p, (size_t)(slash - p))) {+ return true;+ }+ p = slash + SKIP_ONE;+ }+}++static int rs_ns_index(int ns) {+ return ns == RS_NS_TYPE ? 0 : (ns == RS_NS_VALUE ? SKIP_ONE : PAIR_LEN);+}++static int rs_item_ns(char kind) {+ switch (kind) {+ case 'S':+ case 'E':+ case 'U':+ case 'R':+ case 'A':+ return RS_NS_TYPE;+ case 'F':+ case 'C':+ case 'G':+ return RS_NS_VALUE;+ default:+ return RS_NS_MACRO;+ }+}++/* A variant is a type-namespace name here: its constructor in the value+ * namespace is not what a link names (rustdoc drops it). */+static int rs_member_ns(char kind) {+ return (kind == 't' || kind == 'v') ? RS_NS_TYPE : RS_NS_VALUE;+}++static bool rs_item_is_type(char kind) {+ return kind == 'S' || kind == 'E' || kind == 'U' || kind == 'R' || kind == 'A';+}++static bool rs_in_list(const char *const *list, size_t n, const char *name) {+ for (size_t i = 0; i < n; i++) {+ if (strcmp(list[i], name) == 0) {+ return true;+ }+ }+ return false;+}++#define RS_IN(list, name) rs_in_list((list), sizeof(list) / sizeof((list)[0]), (name))++/* ── Candidate sets ──────────────────────────────────────────────── */++static rs_ent_t rs_ent(uint8_t kind, int idx) {+ return (rs_ent_t){.kind = kind, .idx = idx};+}++/* RS_E_GAP or RS_E_EXTERNAL for a name that was not found (rs_ent_t.weak). */+static rs_ent_t rs_weak(uint8_t kind) {+ return (rs_ent_t){.kind = kind, .weak = true};+}++static bool rs_ent_same(rs_ent_t a, rs_ent_t b) {+ return a.kind == b.kind && (a.kind == RS_E_EXTERNAL || a.kind == RS_E_GAP || a.idx == b.idx);+}++/* Add `e`. Every entity outside the repository counts as one candidate (the+ * outcome is `external` whichever it is), and so does every gap. */+static void rs_set_add(rs_set_t *s, rs_ent_t e) {+ if (e.kind == RS_E_NONE) {+ return;+ }+ for (int i = 0; i < s->n; i++) {+ if (rs_ent_same(s->v[i], e)) {+ s->v[i].via_import = s->v[i].via_import || e.via_import;+ s->v[i].weak = s->v[i].weak && e.weak;+ return;+ }+ }+ if (s->n >= RS_SET_CAP) {+ s->overflow = true;+ return;+ }+ s->v[s->n++] = e;+}++static void rs_set_merge(rs_set_t *dst, const rs_set_t *src) {+ for (int i = 0; i < src->n; i++) {+ rs_set_add(dst, src->v[i]);+ }+ dst->overflow = dst->overflow || src->overflow;+}++static bool rs_set_empty(const rs_set_t *s) {+ return s->n == 0 && !s->overflow;+}++static bool rs_set_has(const rs_set_t *s, rs_ent_t e) {+ for (int i = 0; i < s->n; i++) {+ if (rs_ent_same(s->v[i], e)) {+ return true;+ }+ }+ return false;+}++static bool rs_set_equal(const rs_set_t *a, const rs_set_t *b) {+ if (a->n != b->n || a->overflow || b->overflow) {+ return false;+ }+ for (int i = 0; i < a->n; i++) {+ if (!rs_set_has(b, a->v[i])) {+ return false;+ }+ }+ return true;+}++/* ── Scope blobs: counting ───────────────────────────────────────── */++typedef struct {+ int mods;+ int decls;+ int items;+ int members;+ int impls;+ int imports;+ int maybes;+ int locals;+ int unowned;+ int deps;+ int targets;+ int macuses;+ int macdecls;+} rs_counts_t;++/* The number of comma-separated names a W record carries. */+static int rs_count_names(const char *line, const char *end) {+ int n = SKIP_ONE;+ for (const char *p = line; p < end; p++) {+ n += *p == ',';+ }+ return n;+}++static void rs_count_blob(const char *blob, rs_counts_t *c) {+ for (const char *p = blob; p && *p;) {+ const char *eol = strchr(p, '\n');+ switch (p[0]) {+ case 'V':+ c->macuses++;+ break;+ case 'W':+ c->macdecls += rs_count_names(p, eol ? eol : p + strlen(p));+ break;+ case 'N':+ c->mods++;+ break;+ case 'D':+ c->decls++;+ break;+ case 'T':+ c->items++;+ break;+ case 'M':+ c->members++;+ break;+ case 'I':+ c->impls++;+ break;+ case 'U':+ c->imports++;+ break;+ case 'Q':+ c->maybes++;+ break;+ case 'P':+ c->locals++;+ break;+ case 'Z':+ c->unowned++;+ break;+ case 'X':+ c->deps++;+ break;+ case 'a':+ c->targets++;+ break;+ default:+ break;+ }+ p = eol ? eol + SKIP_ONE : NULL;+ }+}++/* True when `scope` is a manifest's blob: the line after the tag is "C". */+static bool rs_blob_is_manifest(const char *scope) {+ const char *nl = scope ? strchr(scope, '\n') : NULL;+ return nl && nl[SKIP_ONE] == 'C' && (nl[PAIR_LEN] == '\n' || nl[PAIR_LEN] == '\0');+}++/* ── Scope blobs: a source file ──────────────────────────────────── */++/* The node field of a T or M record: '!' for none, else a label code and '='+ * (the node's name is the record's name as written) or ':' and the node's+ * name after the item prefix. */+static void rs_parse_node(const char *field, const char *name, char *label, const char **suffix) {+ *label = 0;+ *suffix = NULL;+ if (!field[0] || field[0] == '!') {+ return;+ }+ if (field[SKIP_ONE] == '=') {+ *label = field[0];+ *suffix = name;+ } else if (field[SKIP_ONE] == ':' && field[PAIR_LEN]) {+ *label = field[0];+ *suffix = field + PAIR_LEN;+ }+}++/* A module field of a record of file `f`: the module, or CBM_NOT_FOUND when+ * the number is not one of the file's. */+static int rs_mod_field(const rs_file_t *f, const char *field) {+ char *end = NULL;+ long id = strtol(field, &end, CBM_DECIMAL_BASE);+ if (end == field || *end || id < 0 || id >= f->nmods) {+ return CBM_NOT_FOUND;+ }+ return f->mod_base + (int)id;+}++static uint32_t rs_u32_field(const char *field) {+ return (uint32_t)strtoul(field, NULL, CBM_DECIMAL_BASE);+}++/* What is being built while one source blob is read. */+typedef struct {+ rs_index_t *ix;+ rs_file_t *f;+ int file;+ int next_mod; /* the id the next N record must carry */+ int owner_item; /* the T or I record members belong to */+ int owner_impl;+ int owner_mod;+ bool owner_test;+} rs_reader_t;++static void rs_read_module(rs_reader_t *r, char **fld, int n) {+ enum { F_ID = 1, F_PARENT, F_START, F_END, F_FLAGS, F_NAME, F_COUNT };+ rs_index_t *ix = r->ix;+ int parent = n == F_COUNT ? rs_mod_field(r->f, fld[F_PARENT]) : CBM_NOT_FOUND;+ if (parent < 0 || (int)rs_u32_field(fld[F_ID]) != r->next_mod || r->next_mod >= r->f->nmods ||+ parent >= r->f->mod_base + r->next_mod || !fld[F_FLAGS][0]) {+ r->f->broken = true;+ return;+ }+ rs_mod_t *m = &ix->mods[r->f->mod_base + r->next_mod];+ r->next_mod++;+ m->parent = parent;+ m->start = rs_u32_field(fld[F_START]);+ m->end = rs_u32_field(fld[F_END]);+ m->vis = fld[F_FLAGS][0];+ m->cfg_test = strchr(fld[F_FLAGS] + SKIP_ONE, 't') != NULL;+ m->path_attr = strchr(fld[F_FLAGS] + SKIP_ONE, 'c') != NULL;+ m->name = rs_plain(fld[F_NAME]);+}++static void rs_read_decl(rs_reader_t *r, char **fld, int n) {+ enum { F_MOD = 1, F_FLAGS, F_NAME, F_PATH, F_COUNT };+ int mod = n == F_COUNT ? rs_mod_field(r->f, fld[F_MOD]) : CBM_NOT_FOUND;+ if (mod < 0 || !fld[F_FLAGS][0]) {+ r->f->broken = true;+ return;+ }+ rs_decl_t *d = &r->ix->decls[r->ix->ndecls++];+ r->f->decl_count++;+ d->mod = mod;+ d->vis = fld[F_FLAGS][0];+ d->cfg_test = strchr(fld[F_FLAGS] + SKIP_ONE, 't') != NULL;+ d->cond_path = strchr(fld[F_FLAGS] + SKIP_ONE, 'c') != NULL;+ d->name = rs_plain(fld[F_NAME]);+ d->path = strcmp(fld[F_PATH], "-") == 0 ? NULL : fld[F_PATH];+ d->child = CBM_NOT_FOUND;+}++static void rs_read_import(rs_reader_t *r, char **fld, int n) {+ enum { F_MOD = 1, F_VIS, F_KIND, F_LOCAL, F_PATH, F_COUNT };+ rs_index_t *ix = r->ix;+ int mod = n == F_COUNT ? rs_mod_field(r->f, fld[F_MOD]) : CBM_NOT_FOUND;+ if (mod < 0) {+ r->f->broken = true;+ return;+ }+ rs_import_t *imp = &ix->imports[ix->nimports];+ imp->file = r->file;+ imp->mod = mod;+ imp->vis = fld[F_VIS][0];+ imp->kind = fld[F_KIND][0];+ imp->local = rs_plain(fld[F_LOCAL]);+ imp->seq = ix->nimports++;+ CBMDocLinkRsPath path;+ if (cbm_doclink_rs_parse_path(fld[F_PATH], strlen(fld[F_PATH]), false, &path) !=+ CBM_DOCLINK_RS_PATH_OK) {+ return; /* no segments: an import that is not followed */+ }+ imp->segs = (const char **)ix_alloc(ix, (size_t)path.nsegs * sizeof(char *));+ imp->global = path.global;+ for (int i = 0; imp->segs && i < path.nsegs; i++) {+ imp->segs[i] = ix_strdup(ix, rs_plain(path.segs[i]));+ }+ imp->nsegs = imp->segs ? path.nsegs : 0;+}++static void rs_read_item(rs_reader_t *r, char **fld, int n) {+ enum { F_MOD = 1, F_START, F_END, F_FLAGS, F_KIND, F_NAME, F_NODE, F_EXTRA, F_COUNT };+ rs_index_t *ix = r->ix;+ int mod = n == F_COUNT ? rs_mod_field(r->f, fld[F_MOD]) : CBM_NOT_FOUND;+ r->owner_item = CBM_NOT_FOUND;+ r->owner_impl = CBM_NOT_FOUND;+ if (mod < 0 || !fld[F_FLAGS][0]) {+ r->f->broken = true;+ return;+ }+ int idx = ix->nitems++;+ rs_item_t *it = &ix->items[idx];+ r->f->item_count++;+ it->file = r->file;+ it->mod = mod;+ it->start = rs_u32_field(fld[F_START]);+ it->end = rs_u32_field(fld[F_END]);+ it->vis = fld[F_FLAGS][0];+ it->test = strchr(fld[F_FLAGS] + SKIP_ONE, 't') != NULL;+ it->macro_export = strchr(fld[F_FLAGS] + SKIP_ONE, 'e') != NULL;+ it->kind = fld[F_KIND][0];+ it->name = rs_plain(fld[F_NAME]);+ rs_parse_node(fld[F_NODE], fld[F_NAME], &it->label, &it->suffix);+ const char *extra = strcmp(fld[F_EXTRA], "-") != 0 ? fld[F_EXTRA] : NULL;+ it->alias = it->kind == 'A' ? extra : NULL;+ it->derives = (it->kind == 'S' || it->kind == 'E' || it->kind == 'U') ? extra : NULL;+ it->member_first = ix->nmembers;+ r->owner_item = idx;+ r->owner_mod = mod;+ r->owner_test = it->test;+ if (r->f->fresh && rs_item_is_type(it->kind)) {+ ix->scopes[ix->nscopes++] =+ (rs_scope_t){.start = it->start, .end = it->end, .item = idx, .impl = CBM_NOT_FOUND};+ r->f->scope_count++;+ }+}++static void rs_read_impl(rs_reader_t *r, char **fld, int n) {+ enum { F_MOD = 1, F_START, F_END, F_SELF, F_TRAIT, F_COUNT };+ rs_index_t *ix = r->ix;+ int mod = n == F_COUNT ? rs_mod_field(r->f, fld[F_MOD]) : CBM_NOT_FOUND;+ r->owner_item = CBM_NOT_FOUND;+ r->owner_impl = CBM_NOT_FOUND;+ if (mod < 0) {+ r->f->broken = true;+ return;+ }+ int idx = ix->nimpls++;+ rs_impl_t *im = &ix->impls[idx];+ im->file = r->file;+ im->mod = mod;+ im->start = rs_u32_field(fld[F_START]);+ im->end = rs_u32_field(fld[F_END]);+ im->self_path = strcmp(fld[F_SELF], "?") == 0 ? NULL : fld[F_SELF];+ im->trait_path = strcmp(fld[F_TRAIT], "-") == 0 ? NULL : fld[F_TRAIT];+ im->member_first = ix->nmembers;+ r->owner_impl = idx;+ r->owner_mod = mod;+ r->owner_test = false;+ if (r->f->fresh) {+ ix->scopes[ix->nscopes++] =+ (rs_scope_t){.start = im->start, .end = im->end, .item = CBM_NOT_FOUND, .impl = idx};+ r->f->scope_count++;+ }+}++static void rs_read_member(rs_reader_t *r, char **fld, int n) {+ enum { F_START = 1, F_KIND, F_NAME, F_NODE, F_COUNT };+ rs_index_t *ix = r->ix;+ if (n != F_COUNT || (r->owner_item < 0 && r->owner_impl < 0)) {+ r->f->broken = true;+ return;+ }+ int idx = ix->nmembers++;+ rs_member_t *m = &ix->members[idx];+ m->file = r->file;+ m->mod = r->owner_mod;+ m->owner_test = r->owner_test;+ m->kind = fld[F_KIND][0];+ m->name = rs_plain(fld[F_NAME]);+ m->seq = idx;+ rs_parse_node(fld[F_NODE], fld[F_NAME], &m->label, &m->suffix);+ if (r->owner_item >= 0) {+ m->owner = r->owner_item;+ ix->items[r->owner_item].member_count++;+ } else {+ m->owner = -r->owner_impl - SKIP_ONE;+ ix->impls[r->owner_impl].member_count++;+ }+}++/* A name a macro invocation may declare. One that may be declared anywhere in+ * the file ('*') follows a parse error, and such a file is `broken` anyway. */+static void rs_read_maybe(rs_reader_t *r, char **fld, int n) {+ enum { F_MOD = 1, F_NAME, F_COUNT };+ rs_index_t *ix = r->ix;+ int mod = n == F_COUNT ? rs_mod_field(r->f, fld[F_MOD]) : CBM_NOT_FOUND;+ if (mod < 0) {+ r->f->broken = true; /* '*', or a record this code did not write */+ return;+ }+ ix->maybe_names[ix->nmaybes] = rs_plain(fld[F_NAME]);+ ix->maybes[ix->nmaybes] = (rs_ref_t){.mod = mod, .seq = ix->nmaybes, .ref = ix->nmaybes};+ ix->nmaybes++;+}++/* `V mod name`: the module invokes a macro of that name. */+static void rs_read_macuse(rs_reader_t *r, char **fld, int n) {+ enum { F_MOD = 1, F_NAME, F_COUNT };+ rs_index_t *ix = r->ix;+ int mod = n == F_COUNT ? rs_mod_field(r->f, fld[F_MOD]) : CBM_NOT_FOUND;+ if (mod < 0) {+ r->f->broken = true;+ return;+ }+ ix->macuses[ix->nmacuses++] = (rs_macuse_t){.mod = mod, .macro = rs_plain(fld[F_NAME])};+}++/* `W name names`: what the body of the macro `name` declares. */+static void rs_read_macdecl(rs_reader_t *r, char **fld, int n) {+ enum { F_MACRO = 1, F_NAMES, F_COUNT };+ rs_index_t *ix = r->ix;+ if (n != F_COUNT) {+ r->f->broken = true;+ return;+ }+ const char *macro = rs_plain(fld[F_MACRO]);+ for (char *p = fld[F_NAMES]; p && *p;) {+ char *comma = strchr(p, ',');+ if (comma) {+ *comma = '\0';+ }+ ix->macdecls[ix->nmacdecls++] = (rs_macdecl_t){.name = rs_plain(p), .macro = macro};+ p = comma ? comma + SKIP_ONE : NULL;+ }+}++static void rs_read_note(rs_reader_t *r, char **fld, int n, bool local) {+ enum { F_LINE = 1, F_TEXT, F_COUNT };+ rs_index_t *ix = r->ix;+ if (n != F_COUNT || !r->f->fresh) {+ return;+ }+ rs_note_t note = {.line = rs_u32_field(fld[F_LINE]), .text = fld[F_TEXT]};+ if (local) {+ ix->locals[ix->nlocals++] = note;+ r->f->local_count++;+ } else {+ ix->unowned[ix->nunowned++] = note;+ r->f->unowned_count++;+ }+}++static void rs_read_record(rs_reader_t *r, char *line) {+ char *fld[RS_FIELDS_MAX];+ char tag = line[0];+ int n = rs_fields(line, fld, RS_FIELDS_MAX);+ switch (tag) {+ case 'B':+ r->f->broken = true;+ break;+ case 'E':+ if (n == PAIR_LEN && r->f->fresh) {+ r->f->err_line = rs_u32_field(fld[SKIP_ONE]);+ }+ break;+ case 'N':+ rs_read_module(r, fld, n);+ break;+ case 'D':+ rs_read_decl(r, fld, n);+ break;+ case 'U':+ rs_read_import(r, fld, n);+ break;+ case 'T':+ rs_read_item(r, fld, n);+ break;+ case 'I':+ rs_read_impl(r, fld, n);+ break;+ case 'M':+ rs_read_member(r, fld, n);+ break;+ case 'Q':+ rs_read_maybe(r, fld, n);+ break;+ case 'V':+ rs_read_macuse(r, fld, n);+ break;+ case 'W':+ rs_read_macdecl(r, fld, n);+ break;+ case 'P':+ rs_read_note(r, fld, n, true);+ break;+ case 'Z':+ rs_read_note(r, fld, n, false);+ break;+ default:+ break;+ }+}++/* Read the scope blob of source file `fi` (its modules are allocated). */+static void rs_read_source(rs_index_t *ix, int fi, const char *blob) {+ rs_file_t *f = &ix->files[fi];+ f->decl_first = ix->ndecls;+ f->item_first = ix->nitems;+ f->scope_first = ix->nscopes;+ f->local_first = ix->nlocals;+ f->unowned_first = ix->nunowned;+ char *buf = blob ? ix_strdup(ix, blob) : NULL;+ if (!buf) {+ f->broken = true; /* no scope: what the file declares is not known */+ return;+ }+ rs_reader_t r = {.ix = ix,+ .f = f,+ .file = fi,+ .next_mod = SKIP_ONE,+ .owner_item = CBM_NOT_FOUND,+ .owner_impl = CBM_NOT_FOUND};+ bool first = true;+ for (char *line = buf; line && *line;) {+ char *nl = strchr(line, '\n');+ if (nl) {+ *nl = '\0';+ }+ if (!first) {+ rs_read_record(&r, line);+ }+ first = false;+ line = nl ? nl + SKIP_ONE : NULL;+ }+ if (r.next_mod != f->nmods) {+ f->broken = true; /* a module record was not read: its number names nothing */+ }+}++/* ── Scope blobs: a Cargo manifest ───────────────────────────────── */++static int rs_parse_edition(const char *value) {+ char *end = NULL;+ long year = strtol(value, &end, CBM_DECIMAL_BASE);+ if (end == value || *end || year < RS_EDITION_2015) {+ return RS_EDITION_UNREADABLE;+ }+ return (int)year;+}++static bool rs_is_false(const char *value) {+ return strcmp(value, "false") == 0;+}++static void rs_package_key(rs_pkg_t *p, const char *key, const char *value) {+ if (strcmp(key, "name") == 0) {+ p->name = strcmp(value, "?") != 0 ? value : NULL;+ } else if (strcmp(key, "edition") == 0) {+ p->edition = rs_parse_edition(value);+ } else if (strcmp(key, "edition.workspace") == 0) {+ p->edition = RS_EDITION_INHERITED;+ } else if (strcmp(key, "build") == 0) {+ p->build = value;+ } else if (strcmp(key, "autobins") == 0) {+ p->no_autobins = rs_is_false(value);+ } else if (strcmp(key, "autoexamples") == 0) {+ p->no_autoexamples = rs_is_false(value);+ } else if (strcmp(key, "autotests") == 0) {+ p->no_autotests = rs_is_false(value);+ } else if (strcmp(key, "autobenches") == 0) {+ p->no_autobenches = rs_is_false(value);+ }+}++static void rs_manifest_key(rs_pkg_t *p, const char *table, const char *key, const char *value) {+ if (strcmp(table, "package") == 0) {+ p->has_package = true;+ rs_package_key(p, key, value);+ } else if (strcmp(table, "lib") == 0) {+ if (strcmp(key, "name") == 0) {+ p->lib_name = value;+ } else if (strcmp(key, "path") == 0) {+ p->lib_path = value;+ }+ } else if (strcmp(table, "workspace.package") == 0 && strcmp(key, "edition") == 0) {+ p->ws_edition = rs_parse_edition(value);+ }+}++static void rs_manifest_record(rs_pkg_t *p, char *line) {+ enum { F_1 = 1, F_2, F_3, F_4, K_FIELDS = 4, A_FIELDS = 3, X_FIELDS = 5 };+ char *fld[X_FIELDS];+ char tag = line[0];+ int n = rs_fields(line, fld, X_FIELDS);+ if (tag == 'K' && n == K_FIELDS) {+ rs_manifest_key(p, fld[F_1], fld[F_2], fld[F_3]);+ } else if (tag == 'a' && n == A_FIELDS && strcmp(fld[F_1], "path") == 0) {+ p->targets[p->ntargets++] = fld[F_2];+ } else if (tag == 'W') {+ p->is_workspace = true;+ } else if (tag == 'X' && n == X_FIELDS && fld[F_1][0]) {+ p->raw[p->nraw] = (rs_rawdep_t){.kind = fld[F_1][0],+ .name = fld[F_2],+ .attr = fld[F_3],+ .value = fld[F_4],+ .seq = p->nraw};+ p->nraw++;+ } else if (tag == 'B') {+ p->broken = true;+ }+}++static void rs_read_manifest(rs_index_t *ix, int fi, const char *blob) {+ rs_pkg_t *p = &ix->pkgs[ix->npkgs];+ const char *rel = ix->files[fi].rel_path;+ const char *slash = strrchr(rel, '/');+ rs_counts_t c = {0};+ rs_count_blob(blob, &c);+ memset(p, 0, sizeof(*p));+ p->file = fi;+ p->dir = ix_strndup(ix, rel, slash ? (size_t)(slash - rel) : 0);+ p->lib_root = CBM_NOT_FOUND;+ p->ws = CBM_NOT_FOUND;+ p->raw = (rs_rawdep_t *)ix_alloc(ix, (size_t)c.deps * sizeof(rs_rawdep_t));+ p->targets = (const char **)ix_alloc(ix, (size_t)c.targets * sizeof(char *));+ char *buf = ix_strdup(ix, blob);+ if (!buf || !p->dir || !p->raw || !p->targets) {+ return;+ }+ int skipped = 0;+ for (char *line = buf; line && *line;) {+ char *nl = strchr(line, '\n');+ if (nl) {+ *nl = '\0';+ }+ if (skipped >= PAIR_LEN) { /* after the tag line and the "C" line */+ rs_manifest_record(p, line);+ }+ skipped++;+ line = nl ? nl + SKIP_ONE : NULL;+ }+ ix->npkgs++;+}++/* ── Paths -> files and packages ─────────────────────────────────── */++static int rs_file_at(const rs_index_t *ix, const char *rel) {+ return (int)(intptr_t)cbm_ht_get(ix->file_by_path, rel) - SKIP_ONE;+}++/* The source file at `rel`, CBM_NOT_FOUND when none is indexed. */+static int rs_source_at(const rs_index_t *ix, const char *rel) {+ int fi = rs_file_at(ix, rel);+ return (fi >= 0 && ix->files[fi].kind == RS_FILE_SOURCE) ? fi : CBM_NOT_FOUND;+}++/* The package whose manifest is in directory `dir` ("" at the root). */+static int rs_pkg_at(const rs_index_t *ix, const char *dir) {+ return (int)(intptr_t)cbm_ht_get(ix->pkg_by_dir, dir[0] ? dir : ".") - SKIP_ONE;+}++/* `-` in a package name is `_` in the crate's name. */+static const char *rs_crate_name(rs_index_t *ix, const char *name) {+ char *out = ix_strdup(ix, name);+ for (char *p = out; p && *p; p++) {+ if (*p == '-') {+ *p = '_';+ }+ }+ return out;+}++/* The workspace root of package `pi`: the nearest manifest with a [workspace]+ * table at or above its directory. */+static int rs_workspace_of(const rs_index_t *ix, int pi) {+ char dir[RS_PATH_BUF];+ if (snprintf(dir, sizeof(dir), "%s", ix->pkgs[pi].dir) >= (int)sizeof(dir)) {+ return CBM_NOT_FOUND;+ }+ for (;;) {+ int q = rs_pkg_at(ix, dir);+ if (q >= 0 && ix->pkgs[q].is_workspace) {+ return q;+ }+ if (!dir[0]) {+ return CBM_NOT_FOUND;+ }+ char *slash = strrchr(dir, '/');+ if (slash) {+ *slash = '\0';+ } else {+ dir[0] = '\0';+ }+ }+}++/* The edition of package `pkg`: a year, or RS_EDITION_UNKNOWN. A manifest+ * without the key is edition 2015 (Cargo's default). */+static int rs_edition(const rs_index_t *ix, int pkg) {+ if (pkg < 0) {+ return RS_EDITION_UNKNOWN;+ }+ const rs_pkg_t *p = &ix->pkgs[pkg];+ int edition = p->edition;+ if (edition == RS_EDITION_INHERITED) {+ edition = p->ws >= 0 ? ix->pkgs[p->ws].ws_edition : RS_EDITION_UNREADABLE;+ }+ if (edition == 0) {+ return p->broken ? RS_EDITION_UNKNOWN : RS_EDITION_2015;+ }+ return edition > 0 ? edition : RS_EDITION_UNKNOWN;+}++/* ── Crate roots ─────────────────────────────────────────────────── */++static void rs_mark_root(rs_index_t *ix, int fi, int pi, bool lib) {+ rs_file_t *f = &ix->files[fi];+ if (!f->crate_root) {+ f->crate_root = true;+ f->root_pkg = pi;+ ix->crate_roots++;+ } else if (f->root_pkg != pi) {+ f->root_pkg = RS_PKG_CONFLICT; /* a target of two packages */+ }+ if (lib && ix->pkgs[pi].lib_root < 0) {+ ix->pkgs[pi].lib_root = f->mod_base;+ }+}++/* A target path written in a manifest. */+static void rs_claim_path(rs_index_t *ix, int pi, const char *path, bool lib) {+ char rel[RS_PATH_BUF];+ if (strcmp(path, "?") == 0 || !rs_join_path(ix->pkgs[pi].dir, path, rel, sizeof(rel))) {+ return;+ }+ int fi = rs_source_at(ix, rel);+ if (fi >= 0) {+ rs_mark_root(ix, fi, pi, lib);+ }+}++static void rs_explicit_roots(rs_index_t *ix, int pi) {+ const rs_pkg_t *p = &ix->pkgs[pi];+ if (!p->has_package) {+ return;+ }+ if (p->lib_path) {+ rs_claim_path(ix, pi, p->lib_path, true);+ }+ for (int i = 0; i < p->ntargets; i++) {+ rs_claim_path(ix, pi, p->targets[i], false);+ }+ if (p->build && !rs_is_false(p->build) && strcmp(p->build, "true") != 0) {+ rs_claim_path(ix, pi, p->build, false);+ }+}++/* The last components of a path, c[0] the file name. */+typedef struct {+ const char *c[RS_TAIL];+ size_t len[RS_TAIL];+ int n;+} rs_tail_t;++static void rs_tail(const char *rel, rs_tail_t *t) {+ memset(t, 0, sizeof(*t));+ const char *end = rel + strlen(rel);+ while (t->n < RS_TAIL && end > rel) {+ const char *s = end;+ while (s > rel && s[-SKIP_ONE] != '/') {+ s--;+ }+ t->c[t->n] = s;+ t->len[t->n] = (size_t)(end - s);+ t->n++;+ end = s > rel ? s - SKIP_ONE : rel;+ }+}++static bool rs_tail_is(const rs_tail_t *t, int k, const char *name) {+ return k < t->n && strlen(name) == t->len[k] && memcmp(t->c[k], name, t->len[k]) == 0;+}++/* The package whose directory holds component `k` of `rel`. */+static int rs_pkg_before(const rs_index_t *ix, const char *rel, const rs_tail_t *t, int k) {+ char dir[RS_PATH_BUF];+ if (k >= t->n) {+ return CBM_NOT_FOUND;+ }+ size_t dl = (size_t)(t->c[k] - rel);+ size_t n = dl > 0 ? dl - SKIP_ONE : 0;+ if (n >= sizeof(dir)) {+ return CBM_NOT_FOUND;+ }+ memcpy(dir, rel, n);+ dir[n] = '\0';+ return rs_pkg_at(ix, dir);+}++/* A file where Cargo discovers a target of package `pi` on its own. */+static void rs_claim_auto(rs_index_t *ix, int fi, int pi, int target) {+ if (pi < 0 || !ix->pkgs[pi].has_package) {+ return;+ }+ const rs_pkg_t *p = &ix->pkgs[pi];+ bool off =+ (target == RS_TARGET_LIB && p->lib_path) || (target == RS_TARGET_BIN && p->no_autobins) ||+ (target == RS_TARGET_EXAMPLE && p->no_autoexamples) ||+ (target == RS_TARGET_TEST && p->no_autotests) ||+ (target == RS_TARGET_BENCH && p->no_autobenches) || (target == RS_TARGET_BUILD && p->build);+ if (!off) {+ rs_mark_root(ix, fi, pi, target == RS_TARGET_LIB);+ }+}++/* Cargo's target auto-discovery, read off the file's own path. */+static void rs_auto_roots(rs_index_t *ix, int fi) {+ static const struct {+ const char *dir;+ int target;+ } dirs[] = {+ {"examples", RS_TARGET_EXAMPLE}, {"tests", RS_TARGET_TEST}, {"benches", RS_TARGET_BENCH}};+ enum { C0 = 0, C1, C2, C3 };+ const char *rel = ix->files[fi].rel_path;+ rs_tail_t t;+ rs_tail(rel, &t);+ bool main_rs = rs_tail_is(&t, C0, "main.rs");+ if (rs_tail_is(&t, C1, "src")) {+ if (rs_tail_is(&t, C0, "lib.rs")) {+ rs_claim_auto(ix, fi, rs_pkg_before(ix, rel, &t, C1), RS_TARGET_LIB);+ }+ if (main_rs) {+ rs_claim_auto(ix, fi, rs_pkg_before(ix, rel, &t, C1), RS_TARGET_BIN);+ }+ }+ if (rs_tail_is(&t, C1, "bin") && rs_tail_is(&t, C2, "src")) {+ rs_claim_auto(ix, fi, rs_pkg_before(ix, rel, &t, C2), RS_TARGET_BIN);+ }+ if (main_rs && rs_tail_is(&t, C2, "bin") && rs_tail_is(&t, C3, "src")) {+ rs_claim_auto(ix, fi, rs_pkg_before(ix, rel, &t, C3), RS_TARGET_BIN);+ }+ for (size_t i = 0; i < sizeof(dirs) / sizeof(dirs[0]); i++) {+ if (rs_tail_is(&t, C1, dirs[i].dir)) {+ rs_claim_auto(ix, fi, rs_pkg_before(ix, rel, &t, C1), dirs[i].target);+ }+ if (main_rs && rs_tail_is(&t, C2, dirs[i].dir)) {+ rs_claim_auto(ix, fi, rs_pkg_before(ix, rel, &t, C2), dirs[i].target);+ }+ }+ if (rs_tail_is(&t, C0, "build.rs")) {+ rs_claim_auto(ix, fi, rs_pkg_before(ix, rel, &t, C0), RS_TARGET_BUILD);+ }+}++static void rs_crate_roots(rs_index_t *ix) {+ for (int pi = 0; pi < ix->npkgs; pi++) {+ ix->pkgs[pi].ws = rs_workspace_of(ix, pi);+ rs_explicit_roots(ix, pi);+ }+ for (int fi = 0; fi < ix->nfiles; fi++) {+ if (ix->files[fi].kind == RS_FILE_SOURCE) {+ rs_auto_roots(ix, fi);+ }+ }+ for (int pi = 0; pi < ix->npkgs; pi++) {+ rs_pkg_t *p = &ix->pkgs[pi];+ const char *name = p->lib_name ? p->lib_name : p->name;+ p->lib_name = (name && strcmp(name, "?") != 0) ? rs_crate_name(ix, name) : NULL;+ }+}++/* ── `mod x;` -> file ────────────────────────────────────────────── */++/* The directory the file of declaration `d` is looked for in, under view+ * `view` of the declaring file: the file's directory, the file's stem (view+ * B), then the inline modules around the declaration. A `#[path]` directly in+ * a file is relative to the file's directory under either view. false when+ * it is not known (a `#[path]` on an inline module) or too long to be a path. */+static bool rs_decl_dir(const rs_index_t *ix, const rs_decl_t *d, int view, char *out, size_t cap) {+ const char *names[RS_PATH_DEPTH];+ int n = 0;+ int m = d->mod;+ while (ix->mods[m].parent >= 0) {+ if (ix->mods[m].path_attr || n >= RS_PATH_DEPTH) {+ return false;+ }+ names[n++] = ix->mods[m].name;+ m = ix->mods[m].parent;+ }+ const char *rel = ix->files[ix->mods[m].file].rel_path;+ const char *base = rs_basename(rel);+ size_t w = 0;+ out[0] = '\0';+ if (base > rel && !rs_path_put(out, cap, &w, rel, (size_t)(base - rel) - SKIP_ONE)) {+ return false;+ }+ bool stem = view == RS_VIEW_B && !(d->path && n == 0);+ size_t bl = strlen(base);+ if (stem && (bl <= RS_RS_EXT || !rs_path_put(out, cap, &w, base, bl - RS_RS_EXT))) {+ return false;+ }+ for (int i = n - SKIP_ONE; i >= 0; i--) {+ if (!rs_path_put(out, cap, &w, names[i], strlen(names[i]))) {+ return false;+ }+ }+ return true;+}++/* A file a declaration can name, and the view the file is then read under. */+typedef struct {+ int file;+ uint8_t implies;+} rs_cand_t;++static int rs_cand_add(const rs_index_t *ix, const char *rel, uint8_t implies, rs_cand_t *out,+ int n) {+ int fi = rs_source_at(ix, rel);+ if (fi >= 0) {+ out[n++] = (rs_cand_t){.file = fi, .implies = implies};+ }+ return n;+}++/* The indexed files declaration `d` can name under `view`: rustc reads+ * `<dir>/<name>.rs` (its own children then live under `<name>/`) or+ * `<dir>/<name>/mod.rs`, or the `#[path]` file (children beside it). */+static int rs_decl_cands(const rs_index_t *ix, const rs_decl_t *d, int view,+ rs_cand_t out[PAIR_LEN]) {+ char dir[RS_PATH_BUF];+ char path[RS_PATH_BUF];+ int n = 0;+ if (d->cond_path || !rs_decl_dir(ix, d, view, dir, sizeof(dir))) {+ return 0;+ }+ if (d->path) {+ if (rs_join_path(dir, d->path, path, sizeof(path))) {+ n = rs_cand_add(ix, path, RS_VIEW_A, out, n);+ }+ return n;+ }+ const char *sep = dir[0] ? "/" : "";+ if (snprintf(path, sizeof(path), "%s%s%s.rs", dir, sep, d->name) < (int)sizeof(path)) {+ n = rs_cand_add(ix, path, RS_VIEW_B, out, n);+ }+ if (snprintf(path, sizeof(path), "%s%s%s/mod.rs", dir, sep, d->name) < (int)sizeof(path)) {+ n = rs_cand_add(ix, path, RS_VIEW_A, out, n);+ }+ return n;+}++typedef struct {+ int *v;+ int n;+} rs_stack_t;++static void rs_views_push(rs_index_t *ix, rs_stack_t *st, int fi, uint8_t bits) {+ rs_file_t *f = &ix->files[fi];+ if ((f->views | bits) == f->views) {+ return;+ }+ f->views |= bits;+ if (!f->queued) {+ f->queued = true;+ st->v[st->n++] = fi;+ }+}++/* Propagate views until nothing changes. A file is processed once per view it+ * gains, so the work is linear in the declarations. */+static void rs_views_run(rs_index_t *ix, rs_stack_t *st) {+ while (st->n > 0) {+ int fi = st->v[--st->n];+ rs_file_t *f = &ix->files[fi];+ f->queued = false;+ uint8_t todo = f->views & (uint8_t)~f->views_done;+ f->views_done |= todo;+ for (int view = RS_VIEW_A; view <= RS_VIEW_B; view++) {+ for (int d = f->decl_first; (todo & view) && d < f->decl_first + f->decl_count; d++) {+ rs_cand_t c[PAIR_LEN];+ int n = rs_decl_cands(ix, &ix->decls[d], view, c);+ for (int k = 0; k < n; k++) {+ rs_views_push(ix, st, c[k].file, c[k].implies);+ }+ }+ }+ }+}++/* The one file declaration `d` names under the views of its file, or+ * CBM_NOT_FOUND when there is none or more than one. */+static int rs_decl_file(const rs_index_t *ix, const rs_decl_t *d) {+ const rs_file_t *f = &ix->files[ix->mods[d->mod].file];+ int found = CBM_NOT_FOUND;+ for (int view = RS_VIEW_A; view <= RS_VIEW_B; view++) {+ rs_cand_t c[PAIR_LEN];+ int n = (f->views & view) ? rs_decl_cands(ix, d, view, c) : 0;+ for (int k = 0; k < n; k++) {+ if (found >= 0 && found != c[k].file) {+ return CBM_NOT_FOUND;+ }+ found = c[k].file;+ }+ }+ return found;+}++static int rs_attach_cmp(const void *a, const void *b) {+ const rs_attach_t *x = (const rs_attach_t *)a;+ const rs_attach_t *y = (const rs_attach_t *)b;+ if (x->child != y->child) {+ return x->child < y->child ? -1 : 1;+ }+ return (x->decl > y->decl) - (x->decl < y->decl);+}++/* Decide which file every `mod x;` names.+ *+ * Where rustc looks depends on how the DECLARING file was reached: beside it+ * (view A: a crate root, a mod.rs, a `#[path]` file) or under a directory+ * named like it (view B: `name.rs` found by its parent). Views are propagated+ * from the crate roots to a fixed point; a file nothing reaches may be either,+ * and so may one reached both ways. Under both views a declaration names a+ * file only when exactly one indexed file fits. */+static void rs_module_tree(rs_index_t *ix) {+ rs_stack_t st = {.v = (int *)ix_alloc(ix, (size_t)ix->nfiles * sizeof(int))};+ ix->attach = (rs_attach_t *)ix_alloc(ix, (size_t)ix->ndecls * sizeof(rs_attach_t));+ if (!st.v || !ix->attach) {+ return;+ }+ for (int fi = 0; fi < ix->nfiles; fi++) {+ const rs_file_t *f = &ix->files[fi];+ bool beside = f->crate_root || strcmp(rs_basename(f->rel_path), "mod.rs") == 0;+ if (f->kind == RS_FILE_SOURCE && beside) {+ rs_views_push(ix, &st, fi, RS_VIEW_A);+ }+ }+ rs_views_run(ix, &st);+ for (int fi = 0; fi < ix->nfiles; fi++) {+ if (ix->files[fi].kind == RS_FILE_SOURCE && ix->files[fi].views == 0) {+ rs_views_push(ix, &st, fi, RS_VIEW_A | RS_VIEW_B);+ }+ }+ rs_views_run(ix, &st);+ for (int d = 0; d < ix->ndecls; d++) {+ int fi = rs_decl_file(ix, &ix->decls[d]);+ if (fi >= 0) {+ ix->decls[d].child = ix->files[fi].mod_base;+ ix->attach[ix->nattach++] = (rs_attach_t){.child = ix->files[fi].mod_base, .decl = d};+ }+ }+ if (ix->nattach > SKIP_ONE) {+ qsort(ix->attach, (size_t)ix->nattach, sizeof(rs_attach_t), rs_attach_cmp);+ }+ for (int i = 0; i < ix->nattach; i++) {+ rs_mod_t *child = &ix->mods[ix->attach[i].child];+ if (child->attach_count == 0) {+ child->attach_first = i;+ }+ child->attach_count++;+ }+}++/* ── Crate roots of every file, product code ─────────────────────── */++static int rs_pkg_join(int a, int b) {+ if (a == RS_PKG_NONE || a == b) {+ return b;+ }+ return b == RS_PKG_NONE ? a : RS_PKG_CONFLICT;+}++static bool rs_roots_add(rs_file_t *f, int root) {+ for (int i = 0; i < f->nroots; i++) {+ if (f->roots[i] == root) {+ return false;+ }+ }+ if (f->nroots >= RS_ROOTS_KEPT) {+ bool changed = !f->roots_top;+ f->roots_top = true;+ return changed;+ }+ f->roots[f->nroots++] = root;+ return true;+}++/* What file `c` takes over from a file that declares it. true on a change. */+static bool rs_file_inherit(rs_file_t *c, const rs_file_t *p) {+ bool changed = p->roots_top && !c->roots_top;+ c->roots_top = c->roots_top || p->roots_top;+ for (int i = 0; i < p->nroots; i++) {+ changed = rs_roots_add(c, p->roots[i]) || changed;+ }+ int pkg = rs_pkg_join(c->pkg, p->pkg);+ changed = changed || pkg != c->pkg || (p->in_lib && !c->in_lib);+ c->pkg = pkg;+ c->in_lib = c->in_lib || p->in_lib;+ return changed;+}++/* The crate roots, the package and the lib membership of every file: a+ * fixed point over the `mod x;` edges. Each value only grows and is bounded,+ * so a file is revisited a bounded number of times. */+static void rs_file_roots(rs_index_t *ix) {+ rs_stack_t st = {.v = (int *)ix_alloc(ix, (size_t)ix->nfiles * sizeof(int))};+ if (!st.v) {+ return;+ }+ for (int fi = 0; fi < ix->nfiles; fi++) {+ rs_file_t *f = &ix->files[fi];+ if (f->kind != RS_FILE_SOURCE || !f->crate_root) {+ continue;+ }+ f->roots[f->nroots++] = f->mod_base;+ f->pkg = f->root_pkg;+ f->in_lib = f->root_pkg >= 0 && ix->pkgs[f->root_pkg].lib_root == f->mod_base;+ f->queued = true;+ st.v[st.n++] = fi;+ }+ while (st.n > 0) {+ int fi = st.v[--st.n];+ rs_file_t *f = &ix->files[fi];+ f->queued = false;+ for (int d = f->decl_first; d < f->decl_first + f->decl_count; d++) {+ int child = ix->decls[d].child;+ if (child < 0) {+ continue;+ }+ rs_file_t *c = &ix->files[ix->mods[child].file];+ if (rs_file_inherit(c, f) && !c->queued) {+ c->queued = true;+ st.v[st.n++] = ix->mods[child].file;+ }+ }+ }+}++/* A file no crate root reaches still lies in some package's directory: its+ * dependencies are that package's. Which target it would belong to (and so+ * what `crate` is) stays unknown. */+static void rs_orphan_packages(rs_index_t *ix) {+ for (int fi = 0; fi < ix->nfiles; fi++) {+ rs_file_t *f = &ix->files[fi];+ char dir[RS_PATH_BUF];+ const char *base = rs_basename(f->rel_path);+ size_t dl = base > f->rel_path ? (size_t)(base - f->rel_path) - SKIP_ONE : 0;+ if (f->kind != RS_FILE_SOURCE || f->nroots > 0 || f->pkg != RS_PKG_NONE ||+ dl >= sizeof(dir)) {+ continue;+ }+ memcpy(dir, f->rel_path, dl);+ dir[dl] = '\0';+ for (;;) {+ int q = rs_pkg_at(ix, dir);+ if (q >= 0 && ix->pkgs[q].has_package) {+ f->pkg = q;+ break;+ }+ char *slash = strrchr(dir, '/');+ if (!dir[0]) {+ break;+ }+ dir[slash ? (size_t)(slash - dir) : 0] = '\0';+ }+ }+}++static void rs_product_seed(rs_index_t *ix, rs_stack_t *st, int fi) {+ const rs_file_t *f = &ix->files[fi];+ rs_mod_t *root = &ix->mods[f->mod_base];+ if (root->product || f->test_path) {+ return;+ }+ root->product = true;+ st->v[st->n++] = fi;+}++/* Product code: what is reached from a crate root (or an orphan file) outside+ * the test directories without passing a `#[cfg(test)]` module or+ * declaration. Everything else is test-only. */+static void rs_product(rs_index_t *ix) {+ rs_stack_t st = {.v = (int *)ix_alloc(ix, (size_t)ix->nfiles * sizeof(int))};+ if (!st.v) {+ return;+ }+ for (int fi = 0; fi < ix->nfiles; fi++) {+ const rs_file_t *f = &ix->files[fi];+ if (f->kind != RS_FILE_SOURCE) {+ continue;+ }+ bool orphan = !f->crate_root && ix->mods[f->mod_base].attach_count == 0;+ ix->orphans += orphan;+ if (f->crate_root || orphan) {+ rs_product_seed(ix, &st, fi);+ }+ }+ while (st.n > 0) {+ const rs_file_t *f = &ix->files[st.v[--st.n]];+ for (int m = SKIP_ONE; m < f->nmods; m++) {+ rs_mod_t *mod = &ix->mods[f->mod_base + m];+ mod->product = mod->parent >= 0 && ix->mods[mod->parent].product && !mod->cfg_test;+ }+ for (int d = f->decl_first; d < f->decl_first + f->decl_count; d++) {+ const rs_decl_t *decl = &ix->decls[d];+ if (decl->child >= 0 && !decl->cfg_test && ix->mods[decl->mod].product) {+ rs_product_seed(ix, &st, ix->mods[decl->child].file);+ }+ }+ }+}++/* ── Lookup: state ───────────────────────────────────────────────── */++typedef struct {+ const rs_index_t *ix;+ int pass; /* while imports are resolved: one done in an earlier pass may be read;+ * 0: all are done */+ bool assoc; /* associated items are looked up (not while the index is built) */+ bool blocked; /* an import the answer depends on is not resolved yet */+} rs_look_t;++/* Where a path is written. */+typedef struct {+ rs_look_t *lk;+ int mod; /* the module */+ int root; /* the crate root module it is resolved under; CBM_NOT_FOUND: not known */+ int pkg; /* that crate's package; CBM_NOT_FOUND: not known */+ bool own_lib; /* the package's lib crate is in the extern prelude */+ int edition;+ int skip; /* the import being resolved; CBM_NOT_FOUND */+} rs_at_t;++/* A path as plain segments (no raw-identifier markers). */+typedef struct {+ const char *const *segs;+ int n;+ bool global; /* written with a leading `::` */+} rs_path_t;++/* What a path names. */+typedef struct {+ rs_set_t ns[RS_NS_COUNT]; /* the last segment, per namespace */+ rs_set_t owners; /* what the last segment was looked up in */+ bool ambiguous; /* a segment before the last names several things */+} rs_found_t;++static bool rs_is(const char *s, const char *word) {+ return strcmp(s, word) == 0;+}++static bool rs_import_ready(const rs_look_t *lk, const rs_import_t *imp) {+ return imp->state == RS_STATE_DONE && (lk->pass == 0 || imp->done_pass < lk->pass);+}++/* First binding in binds[lo, hi) that is not below `name` (`upper`: that is+ * above it). */+static int rs_bind_bound(const rs_index_t *ix, int lo, int hi, const char *name, bool upper) {+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ int c = strcmp(ix->binds[mid].name, name);+ if (c < 0 || (upper && c == 0)) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo;+}++/* The bindings of module `m` named `name`: their count, the first in *first. */+static int rs_bind_range(const rs_index_t *ix, int m, const char *name, int *first) {+ const rs_mod_t *mod = &ix->mods[m];+ int end = mod->bind_first + mod->bind_count;+ *first = rs_bind_bound(ix, mod->bind_first, end, name, false);+ return rs_bind_bound(ix, *first, end, name, true) - *first;+}++static int rs_member_bound(const rs_index_t *ix, int lo, int hi, const char *name, bool upper) {+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ int c = strcmp(ix->members[mid].name, name);+ if (c < 0 || (upper && c == 0)) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo;+}++/* The members named `name` among members[first, first + count) (sorted by+ * name) whose kind is one of `kinds` and whose namespace is in `ns`. */+static void rs_owner_members(const rs_index_t *ix, int first, int count, const char *name, int ns,+ const char *kinds, rs_set_t *out) {+ int lo = rs_member_bound(ix, first, first + count, name, false);+ int hi = rs_member_bound(ix, lo, first + count, name, true);+ for (int i = lo; i < hi && !out->overflow; i++) {+ const rs_member_t *m = &ix->members[i];+ if ((rs_member_ns(m->kind) & ns) && strchr(kinds, m->kind)) {+ rs_set_add(out, rs_ent(RS_E_MEMBER, i));+ }+ }+}++/* ── Lookup: module tree questions ───────────────────────────────── */++/* The modules `super` names in module `m`: the inline parent, or every module+ * that declares the file. An orphan file's parent is not known. */+static void rs_parents(const rs_index_t *ix, int m, rs_set_t *out) {+ const rs_mod_t *mod = &ix->mods[m];+ if (mod->parent >= 0) {+ rs_set_add(out, rs_ent(RS_E_MOD, mod->parent));+ return;+ }+ if (mod->attach_count > RS_SET_CAP ||+ (mod->attach_count == 0 && !ix->files[mod->file].crate_root)) {+ rs_set_add(out, rs_weak(RS_E_GAP));+ return;+ }+ for (int i = 0; i < mod->attach_count; i++) {+ rs_set_add(out, rs_ent(RS_E_MOD, ix->decls[ix->attach[mod->attach_first + i].decl].mod));+ }+}++/* Is module `m` the module `ancestor` or inside it? 1 yes, 0 no, -1 not+ * known (an orphan on the way up, or too far to walk). */+static int rs_mod_within(const rs_index_t *ix, int m, int ancestor) {+ int stack[RS_SET_CAP];+ int sp = 0;+ bool unknown = false;+ stack[sp++] = m;+ for (int steps = 0; sp > 0; steps++) {+ int cur = stack[--sp];+ if (cur == ancestor) {+ return SKIP_ONE;+ }+ const rs_mod_t *mod = &ix->mods[cur];+ if (steps >= RS_UP_STEPS || (mod->parent < 0 && mod->attach_count > RS_SET_CAP - sp)) {+ return CBM_NOT_FOUND;+ }+ if (mod->parent >= 0) {+ stack[sp++] = mod->parent;+ continue;+ }+ unknown = unknown || (mod->attach_count == 0 && !ix->files[mod->file].crate_root);+ for (int i = 0; i < mod->attach_count; i++) {+ stack[sp++] = ix->decls[ix->attach[mod->attach_first + i].decl].mod;+ }+ }+ return unknown ? CBM_NOT_FOUND : 0;+}++/* Are two files part of one crate? 1 yes, 0 no, -1 not known. */+static int rs_same_crate(const rs_index_t *ix, int fa, int fb) {+ const rs_file_t *a = &ix->files[fa];+ const rs_file_t *b = &ix->files[fb];+ if (fa == fb) {+ return SKIP_ONE;+ }+ if (a->roots_top || b->roots_top || a->nroots == 0 || b->nroots == 0) {+ return CBM_NOT_FOUND;+ }+ for (int i = 0; i < a->nroots; i++) {+ for (int j = 0; j < b->nroots; j++) {+ if (a->roots[i] == b->roots[j]) {+ return SKIP_ONE;+ }+ }+ }+ return 0;+}++/* Can module `from` see a binding of visibility `vis` declared in module+ * `owner`? 1 yes, 0 no, -1 not known. */+static int rs_visible(const rs_index_t *ix, char vis, int owner, int from) {+ if (vis == 'p' || owner == from) {+ return SKIP_ONE;+ }+ if (vis == 'c') {+ return rs_same_crate(ix, ix->mods[owner].file, ix->mods[from].file);+ }+ if (vis == '-') {+ return rs_mod_within(ix, from, owner);+ }+ if (vis != 's') {+ return CBM_NOT_FOUND; /* pub(in path): the path is not carried */+ }+ rs_set_t up = {0};+ rs_parents(ix, owner, &up);+ int best = up.n == 0 ? rs_mod_within(ix, from, owner) : 0;+ for (int i = 0; i < up.n && best <= 0; i++) {+ int v = up.v[i].kind == RS_E_MOD ? rs_mod_within(ix, from, up.v[i].idx) : CBM_NOT_FOUND;+ best = (v > 0 || best == 0) ? v : best;+ }+ return best;+}++/* ── Lookup: names a macro's body declares ───────────────────────── */++static int rs_macuse_cmp(const void *a, const void *b) {+ const rs_macuse_t *x = (const rs_macuse_t *)a;+ const rs_macuse_t *y = (const rs_macuse_t *)b;+ if (x->mod != y->mod) {+ return x->mod < y->mod ? -1 : 1;+ }+ return strcmp(x->macro, y->macro);+}++static int rs_macdecl_cmp(const void *a, const void *b) {+ const rs_macdecl_t *x = (const rs_macdecl_t *)a;+ const rs_macdecl_t *y = (const rs_macdecl_t *)b;+ int c = strcmp(x->name, y->name);+ return c ? c : strcmp(x->macro, y->macro);+}++/* True when module `m` invokes a macro named `macro` among its items. */+static bool rs_mod_invokes(const rs_index_t *ix, int m, const char *macro) {+ rs_macuse_t key = {.mod = m, .macro = macro};+ int lo = 0;+ int hi = ix->nmacuses;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (rs_macuse_cmp(&ix->macuses[mid], &key) < 0) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo < ix->nmacuses && rs_macuse_cmp(&ix->macuses[lo], &key) == 0;+}++/* May a macro invoked in module `m` declare `name` there? True when the body+ * of some `macro_rules!` macro of the repository declares that name and the+ * module invokes a macro of that macro's name. Macros are matched by name+ * only (which macro an invocation means is not resolved), so this can say+ * "maybe" too often, never too rarely. */+static bool rs_macro_may_declare(const rs_index_t *ix, int m, const char *name) {+ int lo = 0;+ int hi = ix->nmacdecls;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (strcmp(ix->macdecls[mid].name, name) < 0) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ for (int i = lo; i < ix->nmacdecls && rs_is(ix->macdecls[i].name, name); i++) {+ if (i - lo >= RS_GLOB_VISIT || rs_mod_invokes(ix, m, ix->macdecls[i].macro)) {+ return true; /* declared by more macros than are checked: maybe */+ }+ }+ return false;+}++/* ── Lookup: level 1, a module's own bindings ────────────────────── */++typedef struct {+ int skip; /* an import that is not consulted; CBM_NOT_FOUND */+ int from; /* a glob import of this module asks: only what it can see;+ * CBM_NOT_FOUND: everything */+} rs_own_opt_t;++/* What binding `b` is in namespace `ns`; RS_E_NONE when it is nothing there.+ * `glob`: asked through a glob import, which a textual macro does not pass. */+static rs_ent_t rs_bind_ent(rs_look_t *lk, const rs_bind_t *b, int ns, bool glob) {+ const rs_index_t *ix = lk->ix;+ rs_ent_t none = {0};+ if (b->kind == RS_BIND_ITEM) {+ const rs_item_t *it = &ix->items[b->ref];+ bool textual = it->kind == 'M' && !it->macro_export;+ return ((rs_item_ns(it->kind) & ns) && !(glob && textual)) ? rs_ent(RS_E_ITEM, b->ref)+ : none;+ }+ if (b->kind == RS_BIND_CHILD) {+ if (ns != RS_NS_TYPE) {+ return none;+ }+ return b->ref >= 0 ? rs_ent(RS_E_MOD, b->ref) : rs_ent(RS_E_GAP, 0);+ }+ const rs_import_t *imp = &ix->imports[b->ref];+ if (!rs_import_ready(lk, imp)) {+ lk->blocked = true;+ return none;+ }+ bool type_only = imp->kind != 'b';+ if (type_only && ns != RS_NS_TYPE) {+ return none;+ }+ rs_ent_t e = imp->res[type_only ? 0 : rs_ns_index(ns)];+ e.via_import = e.kind != RS_E_NONE;+ return e;+}++/* Level 1: what module `m` itself binds as `name` in namespace `ns`. A name+ * it does not show may still be declared there when a macro invocation could+ * declare it or the file did not parse: that is a gap, not an absence. */+static void rs_own(rs_look_t *lk, int m, const char *name, int ns, const rs_own_opt_t *opt,+ rs_set_t *out) {+ const rs_index_t *ix = lk->ix;+ int first = 0;+ int n = rs_bind_range(ix, m, name, &first);+ bool maybe = false;+ rs_set_t vague = {0}; /* imports of something whose namespace is not known */+ for (int i = first; i < first + n && !out->overflow; i++) {+ const rs_bind_t *b = &ix->binds[i];+ if (b->kind == RS_BIND_MAYBE) {+ maybe = true;+ continue;+ }+ if (b->kind == RS_BIND_IMPORT && b->ref == opt->skip) {+ continue;+ }+ /* visibility first: a binding the asking module cannot see is not+ * looked at, so an import of its own that is not resolved yet does+ * not hold the answer up */+ int v = opt->from >= 0 ? rs_visible(ix, b->vis, m, opt->from) : SKIP_ONE;+ if (v == 0) {+ continue;+ }+ rs_ent_t e = rs_bind_ent(lk, b, ns, opt->from >= 0);+ if (e.kind == RS_E_NONE) {+ continue;+ }+ bool spread = b->kind == RS_BIND_IMPORT && ix->imports[b->ref].spread;+ rs_set_add(spread ? &vague : out, v > 0 ? e : rs_weak(RS_E_GAP));+ }+ if (rs_set_empty(out)) {+ /* nothing the module really has in this namespace: the import may be it */+ rs_set_merge(out, &vague);+ }+ if (rs_set_empty(out) &&+ (maybe || ix->files[ix->mods[m].file].broken || rs_macro_may_declare(ix, m, name))) {+ rs_set_add(out, rs_weak(RS_E_GAP));+ }+}++/* ── Lookup: level 2, glob imports ───────────────────────────────── */++static bool rs_int_in(const int *v, int n, int x) {+ for (int i = 0; i < n; i++) {+ if (v[i] == x) {+ return true;+ }+ }+ return false;+}++/* What a walk through glob imports met besides bindings. */+typedef struct {+ bool open; /* a glob of something outside the repository: it may hold the name */+ bool gap; /* a glob that cannot be followed, or a binding of unknown visibility */+ bool pending; /* a glob that is not resolved yet (only while imports are resolved) */+} rs_glob_flags_t;++/* One glob import `imp` of module `cur`, asked for `name` on behalf of module+ * `m`. Returns the module whose own globs are to be asked next (the target+ * does not bind the name itself), or CBM_NOT_FOUND. */+static int rs_glob_step(rs_look_t *lk, const rs_import_t *imp, int cur, const rs_own_opt_t *opt,+ const char *name, int ns, rs_set_t *out, rs_glob_flags_t *fl) {+ const rs_index_t *ix = lk->ix;+ int m = opt->from;+ int v = cur == m ? SKIP_ONE : rs_visible(ix, imp->vis, cur, m);+ if (v <= 0) {+ fl->gap = fl->gap || v < 0;+ return CBM_NOT_FOUND;+ }+ if (!rs_import_ready(lk, imp)) {+ fl->pending = true;+ return CBM_NOT_FOUND;+ }+ rs_ent_t t = imp->res[0];+ if (t.kind == RS_E_MOD) {+ rs_set_t found = {0};+ rs_own(lk, t.idx, name, ns, opt, &found);+ for (int i = 0; i < found.n; i++) {+ if (found.v[i].weak) {+ fl->gap = true;+ } else {+ rs_set_add(out, found.v[i]);+ }+ }+ out->overflow = out->overflow || found.overflow;+ return rs_set_empty(&found) ? t.idx : CBM_NOT_FOUND;+ }+ if (t.kind == RS_E_ITEM && ix->items[t.idx].kind == 'E') {+ const rs_item_t *en = &ix->items[t.idx];+ rs_owner_members(ix, en->member_first, en->member_count, name, ns, "v", out);+ return CBM_NOT_FOUND;+ }+ fl->open = fl->open || t.kind == RS_E_EXTERNAL;+ fl->gap = fl->gap || t.kind != RS_E_EXTERNAL;+ return CBM_NOT_FOUND;+}++/* Level 2: what the glob imports of module `m` bring in as `name`, through+ * re-exporting globs. `skip`: the import being resolved, which is neither+ * asked as a glob nor read as a binding (it cannot supply its own name).+ * Anything that cannot be followed is a gap. */+static void rs_globs(rs_look_t *lk, int m, const char *name, int ns, int skip, rs_set_t *out,+ rs_glob_flags_t *fl) {+ const rs_index_t *ix = lk->ix;+ rs_own_opt_t opt = {.skip = skip, .from = m};+ int seen[RS_GLOB_VISIT]; /* also the queue: seen[next, nseen) is still to be asked */+ int nseen = 0;+ int next = 0;+ int steps = 0;+ seen[nseen++] = m;+ while (next < nseen && !out->overflow) {+ int cur = seen[next++];+ const rs_mod_t *cm = &ix->mods[cur];+ for (int g = 0; g < cm->glob_count; g++) {+ int gi = ix->globs[cm->glob_first + g].ref;+ if (gi == skip) {+ continue;+ }+ if (++steps > RS_UP_STEPS) {+ fl->gap = true;+ break;+ }+ int into = rs_glob_step(lk, &ix->imports[gi], cur, &opt, name, ns, out, fl);+ if (into < 0 || rs_int_in(seen, nseen, into)) {+ continue;+ }+ if (nseen >= RS_GLOB_VISIT) {+ fl->gap = true;+ continue;+ }+ seen[nseen++] = into;+ }+ }+ if (rs_set_empty(out) && fl->gap) {+ rs_set_add(out, rs_weak(RS_E_GAP));+ }+}++/* Levels 1 and 2 of module `m`: what `m::name` names. A glob that is not+ * resolved yet may still bring the name in: the answer has to wait. */+static void rs_mod_member(rs_look_t *lk, int m, const char *name, int ns, int skip, rs_set_t *out) {+ rs_own_opt_t opt = {.skip = skip, .from = CBM_NOT_FOUND};+ rs_glob_flags_t fl = {0};+ rs_own(lk, m, name, ns, &opt, out);+ if (!rs_set_empty(out)) {+ return;+ }+ rs_globs(lk, m, name, ns, skip, out, &fl);+ bool real = out->n > 0 && !out->v[0].weak;+ if (fl.pending && !real) {+ memset(out, 0, sizeof(*out));+ lk->blocked = true;+ return;+ }+ if (rs_set_empty(out) && fl.open) {+ rs_set_add(out, rs_weak(RS_E_EXTERNAL));+ }+}++/* ── Lookup: levels 3 and 4, the preludes ────────────────────────── */++/* Defined by the language and its standard library, not by any corpus. */+static const char *const RS_BUILTIN_CRATES[] = {"std", "core", "alloc", "proc_macro", "test"};++/* The std prelude, type namespace (all editions; a name of a later edition's+ * prelude is still the standard library's). */+static const char *const RS_PRELUDE_TYPES[] = {"Option",+ "Result",+ "Vec",+ "String",+ "Box",+ "Some",+ "None",+ "Ok",+ "Err",+ "Send",+ "Sized",+ "Sync",+ "Unpin",+ "Copy",+ "Drop",+ "Fn",+ "FnMut",+ "FnOnce",+ "AsyncFn",+ "AsyncFnMut",+ "AsyncFnOnce",+ "AsMut",+ "AsRef",+ "From",+ "Into",+ "Clone",+ "Default",+ "Eq",+ "Ord",+ "PartialEq",+ "PartialOrd",+ "Extend",+ "IntoIterator",+ "Iterator",+ "DoubleEndedIterator",+ "ExactSizeIterator",+ "ToOwned",+ "ToString",+ "TryFrom",+ "TryInto",+ "FromIterator",+ "Future",+ "IntoFuture"};++static const char *const RS_PRELUDE_VALUES[] = {+ "Some", "None", "Ok", "Err", "drop", "size_of", "size_of_val", "align_of", "align_of_val"};++/* std's macros, and the derive and attribute macros of the prelude. */+static const char *const RS_STD_MACROS[] = {"assert",+ "assert_eq",+ "assert_ne",+ "cfg",+ "column",+ "compile_error",+ "concat",+ "dbg",+ "debug_assert",+ "debug_assert_eq",+ "debug_assert_ne",+ "env",+ "eprint",+ "eprintln",+ "file",+ "format",+ "format_args",+ "include",+ "include_bytes",+ "include_str",+ "is_x86_feature_detected",+ "line",+ "matches",+ "module_path",+ "option_env",+ "panic",+ "print",+ "println",+ "stringify",+ "thread_local",+ "todo",+ "try",+ "unimplemented",+ "unreachable",+ "vec",+ "write",+ "writeln",+ "Clone",+ "Copy",+ "Debug",+ "Default",+ "Eq",+ "Hash",+ "Ord",+ "PartialEq",+ "PartialOrd",+ "derive",+ "test",+ "bench",+ "global_allocator"};++/* rustdoc's names for primitive types (resolve_primitive). */+static const char *const RS_PRIMITIVES[] = {+ "isize", "i8", "i16", "i32", "i64", "i128", "usize", "u8", "u16",+ "u32", "u64", "u128", "f16", "f32", "f64", "f128", "char", "bool",+ "true", "false", "str", "&str", "slice", "array", "tuple", "unit", "pointer",+ "*const", "*mut", "reference", "&", "&mut", "fn", "never", "!"};++static bool rs_std_name(const char *name, int ns) {+ if (ns == RS_NS_TYPE) {+ return RS_IN(RS_PRELUDE_TYPES, name);+ }+ return ns == RS_NS_VALUE ? RS_IN(RS_PRELUDE_VALUES, name) : RS_IN(RS_STD_MACROS, name);+}++/* Level 3: the extern prelude of the crate the path is written in. `*unknown`:+ * that crate's dependencies are not known, so a miss says nothing. */+static void rs_extern(const rs_at_t *at, const char *name, rs_set_t *out, bool *unknown) {+ const rs_index_t *ix = at->lk->ix;+ if (RS_IN(RS_BUILTIN_CRATES, name)) {+ rs_set_add(out, rs_ent(RS_E_EXTERNAL, 0));+ return;+ }+ if (at->pkg < 0) {+ *unknown = true;+ return;+ }+ const rs_pkg_t *p = &ix->pkgs[at->pkg];+ if (p->lib_root >= 0 && p->lib_name && rs_is(p->lib_name, name)) {+ /* the package's own lib: in scope in its other targets only, and which+ * target a file without a crate root belongs to is not known */+ if (at->own_lib) {+ rs_set_add(out, rs_ent(RS_E_MOD, p->lib_root));+ }+ *unknown = !at->own_lib && at->root < 0;+ if (at->own_lib || *unknown) {+ return;+ }+ }+ int lo = 0;+ int hi = p->ndeps;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (strcmp(p->deps[mid].key, name) < 0) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ if (lo < p->ndeps && rs_is(p->deps[lo].key, name)) {+ rs_set_add(out, p->deps[lo].target);+ return;+ }+ *unknown = p->broken;+}++/* A `macro_rules!` macro is in textual scope in the modules below the one+ * that defines it. */+static void rs_textual_macro(const rs_index_t *ix, int m, const char *name, rs_set_t *out) {+ int cur = m;+ for (int step = 0; step < RS_UP_STEPS; step++) {+ const rs_mod_t *mod = &ix->mods[cur];+ int up = mod->parent;+ if (up < 0 && mod->attach_count == SKIP_ONE) {+ up = ix->decls[ix->attach[mod->attach_first].decl].mod;+ }+ if (up < 0) {+ return;+ }+ int first = 0;+ int n = rs_bind_range(ix, up, name, &first);+ for (int i = first; i < first + n; i++) {+ const rs_bind_t *b = &ix->binds[i];+ if (b->kind == RS_BIND_ITEM && ix->items[b->ref].kind == 'M') {+ rs_set_add(out, rs_ent(RS_E_ITEM, b->ref));+ return;+ }+ }+ cur = up;+ }+ rs_set_add(out, rs_weak(RS_E_GAP)); /* deeper than is walked: not known */+}++/* The lexical lookup of a name: levels 1 to 4, the first that binds it in the+ * namespace.+ *+ * Level 2 can hold a name without showing it: a glob of something outside the+ * repository, a glob that cannot be followed, and (while imports are being+ * resolved) a glob that is not resolved yet. What then follows depends on+ * whose path it is:+ * - an import path may look on. rustc rejects an import path whose first+ * name is brought in by a glob AND bound further out (E0659), so in+ * source that compiles a name found at level 3 or 4 is not in the glob;+ * - any other path (a doc link, a type) may not: there a glob's name+ * silently wins over the preludes. The lookup ends with a weak answer.+ * A name found nowhere waits for an unresolved glob, which may still bring+ * it in. */+static void rs_lexical(const rs_at_t *at, const char *name, int ns, rs_set_t *out) {+ rs_look_t *lk = at->lk;+ rs_own_opt_t opt = {.skip = at->skip, .from = CBM_NOT_FOUND};+ rs_glob_flags_t fl = {0};+ rs_set_t outer = {0};+ bool unknown = false;+ rs_own(lk, at->mod, name, ns, &opt, out);+ if (rs_set_empty(out) && ns == RS_NS_MACRO) {+ rs_textual_macro(lk->ix, at->mod, name, out);+ }+ if (!rs_set_empty(out)) {+ if (out->v[0].weak && at->skip >= 0 && ns == RS_NS_TYPE) {+ /* an import path in a module that may declare more than it shows:+ * a crate of the extern prelude stands all the same, because an+ * import path whose first name is both a local name and a crate+ * is an error (E0659) */+ rs_extern(at, name, &outer, &unknown);+ if (!rs_set_empty(&outer)) {+ *out = outer;+ }+ }+ return;+ }+ rs_globs(lk, at->mod, name, ns, at->skip, out, &fl);+ if (out->n > 0 && !out->v[0].weak) {+ return; /* brought in by a glob that is resolved */+ }+ bool hidden = fl.open || fl.pending || !rs_set_empty(out);+ if (!hidden || at->skip >= 0) {+ if (ns == RS_NS_TYPE) {+ rs_extern(at, name, &outer, &unknown);+ }+ if (rs_set_empty(&outer) && rs_std_name(name, ns)) {+ rs_set_add(&outer, rs_ent(RS_E_EXTERNAL, 0));+ }+ if (!rs_set_empty(&outer)) {+ *out = outer;+ return;+ }+ }+ if (fl.pending) {+ memset(out, 0, sizeof(*out));+ lk->blocked = true;+ return;+ }+ if (rs_set_empty(out) && (fl.open || unknown)) {+ rs_set_add(out, rs_weak(fl.open ? RS_E_EXTERNAL : RS_E_GAP));+ }+ if (rs_set_empty(out) && at->skip >= 0 && ns == RS_NS_TYPE && at->pkg >= 0) {+ /* the first name of an import path, bound nowhere: the module shows+ * everything it declares (else the answer above was a gap), so what+ * is left is a crate of the extern prelude under a name the manifest+ * does not give (a lib target named unlike its package) */+ rs_set_add(out, rs_weak(RS_E_EXTERNAL));+ }+}++/* ── Lookup: associated items ────────────────────────────────────── */++/* Declarations of one entity under different cfg: two items of one module,+ * name and kind, or two members of one owner. */+static bool rs_cfg_twins(const rs_index_t *ix, rs_ent_t a, rs_ent_t b) {+ if (a.kind != b.kind) {+ return false;+ }+ if (a.kind == RS_E_ITEM) {+ const rs_item_t *x = &ix->items[a.idx];+ const rs_item_t *y = &ix->items[b.idx];+ return x->mod == y->mod && x->kind == y->kind && rs_is(x->name, y->name);+ }+ if (a.kind == RS_E_MEMBER) {+ const rs_member_t *x = &ix->members[a.idx];+ const rs_member_t *y = &ix->members[b.idx];+ return x->owner == y->owner && x->kind == y->kind && rs_is(x->name, y->name);+ }+ return false;+}++static bool rs_has_node(const rs_index_t *ix, rs_ent_t e) {+ if (e.kind == RS_E_ITEM) {+ return ix->items[e.idx].label != 0;+ }+ return e.kind == RS_E_MEMBER && ix->members[e.idx].label != 0;+}++/* The graph keeps one node per qualified name, so of two cfg twins the one+ * that owns the node stands for both. Two with a node each stay two. */+static void rs_collapse(const rs_index_t *ix, rs_set_t *s) {+ for (int i = 0; i < s->n; i++) {+ for (int j = i + SKIP_ONE; j < s->n;) {+ bool ni = rs_has_node(ix, s->v[i]);+ bool nj = rs_has_node(ix, s->v[j]);+ if (!rs_cfg_twins(ix, s->v[i], s->v[j]) || (ni && nj)) {+ j++;+ continue;+ }+ if (nj) {+ bool via = s->v[i].via_import || s->v[j].via_import;+ s->v[i] = s->v[j];+ s->v[i].via_import = via;+ }+ s->v[j] = s->v[--s->n];+ }+ }+}++/* The item a chain of type aliases ends at; an external or gap entity when it+ * leaves what is known. */+static rs_ent_t rs_alias_end(const rs_index_t *ix, int item) {+ rs_ent_t e = rs_ent(RS_E_ITEM, item);+ for (int hop = 0; hop < RS_ALIAS_HOPS; hop++) {+ if (ix->items[e.idx].kind != 'A') {+ return e;+ }+ e = ix->items[e.idx].alias_ent;+ if (e.kind != RS_E_ITEM) {+ return rs_weak(e.kind == RS_E_EXTERNAL ? RS_E_EXTERNAL : RS_E_GAP);+ }+ }+ return rs_weak(RS_E_GAP);+}++static int rs_assoc_bound(const rs_index_t *ix, int item, const char *name, bool upper) {+ int lo = 0;+ int hi = ix->nassoc;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ const rs_assoc_t *a = &ix->assoc[mid];+ int c = a->item != item ? (a->item < item ? -1 : 1) : strcmp(a->name, name);+ if (c < 0 || (upper && c == 0)) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo;+}++static const char *rs_last_segment(const char *path) {+ const char *last = path;+ for (const char *p = path; *p; p++) {+ if (p[0] == ':' && p[SKIP_ONE] == ':') {+ last = p + PAIR_LEN;+ }+ }+ return rs_plain(last);+}++/* Is the trait of impl `im` in scope in the module the path is written in?+ * rustdoc offers a trait impl's items only then. 1 yes, 0 no, -1 not known.+ * A trait outside the repository is known by its name only. */+static int rs_trait_in_scope(const rs_at_t *at, const rs_impl_t *im) {+ const rs_index_t *ix = at->lk->ix;+ rs_ent_t t = im->trait_ent;+ if (t.kind != RS_E_ITEM && t.kind != RS_E_EXTERNAL) {+ return CBM_NOT_FOUND;+ }+ const char *name =+ t.kind == RS_E_ITEM ? ix->items[t.idx].name : rs_last_segment(im->trait_path);+ rs_set_t found = {0};+ rs_lexical(at, name, RS_NS_TYPE, &found);+ if (rs_set_has(&found, t)) {+ return SKIP_ONE;+ }+ const rs_mod_t *mod = &ix->mods[at->mod];+ for (int i = 0; i < mod->named_count; i++) { /* imported under another name */+ const rs_import_t *imp = &ix->imports[ix->named[mod->named_first + i].ref];+ rs_ent_t e = imp->res[0];+ if (imp->kind != 'b' || e.kind != t.kind || imp->nsegs == 0) {+ continue;+ }+ if (t.kind == RS_E_ITEM ? e.idx == t.idx : rs_is(imp->segs[imp->nsegs - SKIP_ONE], name)) {+ return SKIP_ONE;+ }+ }+ return rs_set_has(&found, rs_ent(RS_E_GAP, 0)) ? CBM_NOT_FOUND : 0;+}++/* Items a trait declares and an impl of it for type `item` does not define+ * itself. Returns true when some could not be decided. */+static bool rs_trait_defaults(const rs_at_t *at, int item, const char *name, int ns,+ rs_set_t *out) {+ const rs_index_t *ix = at->lk->ix;+ const rs_item_t *it = &ix->items[item];+ bool unsure = it->impl_count > RS_IMPL_SCAN;+ for (int i = 0; i < it->impl_count && i < RS_IMPL_SCAN && !out->overflow; i++) {+ const rs_impl_t *im = &ix->impls[ix->item_impls[it->impl_first + i].impl];+ if (!im->trait_path || im->trait_ent.kind != RS_E_ITEM) {+ continue;+ }+ const rs_item_t *tr = &ix->items[im->trait_ent.idx];+ rs_set_t own = {0};+ rs_set_t dflt = {0};+ rs_owner_members(ix, im->member_first, im->member_count, name, ns, "fct", &own);+ if (!rs_set_empty(&own) || tr->kind != 'R') {+ continue;+ }+ rs_owner_members(ix, tr->member_first, tr->member_count, name, ns, "fct", &dflt);+ if (rs_set_empty(&dflt)) {+ continue;+ }+ int v = rs_trait_in_scope(at, im);+ if (v > 0) {+ rs_set_merge(out, &dflt);+ }+ unsure = unsure || v < 0;+ }+ return unsure;+}++/* Two impls of one trait: the scope question has one answer for both. */+static bool rs_same_trait(const rs_impl_t *a, const rs_impl_t *b) {+ if (a->trait_ent.kind != b->trait_ent.kind) {+ return false;+ }+ if (a->trait_ent.kind == RS_E_ITEM) {+ return a->trait_ent.idx == b->trait_ent.idx;+ }+ return a->trait_ent.kind == RS_E_EXTERNAL &&+ rs_is(rs_last_segment(a->trait_path), rs_last_segment(b->trait_path));+}++/* The items of the impls of type `item` named `name`: inherent impls first,+ * then the trait impls whose trait is in scope where the path is written. */+static void rs_impl_items(const rs_at_t *at, int item, const char *name, int ns, rs_set_t *out) {+ const rs_index_t *ix = at->lk->ix;+ int first = rs_assoc_bound(ix, item, name, false);+ int end = rs_assoc_bound(ix, item, name, true);+ bool unsure = false;+ const rs_impl_t *asked = NULL; /* the impl whose trait was asked about last */+ int answer = 0;+ for (int i = first; i < end && !out->overflow; i++) {+ const rs_assoc_t *a = &ix->assoc[i];+ if (!ix->impls[a->impl].trait_path && (rs_member_ns(ix->members[a->member].kind) & ns)) {+ rs_set_add(out, rs_ent(RS_E_MEMBER, a->member));+ }+ }+ bool inherent = !rs_set_empty(out);+ for (int i = first; i < end && !inherent && !out->overflow; i++) {+ const rs_assoc_t *a = &ix->assoc[i];+ const rs_impl_t *im = &ix->impls[a->impl];+ if (!im->trait_path || !(rs_member_ns(ix->members[a->member].kind) & ns)) {+ continue;+ }+ if (!asked || !rs_same_trait(asked, im)) {+ asked = im;+ answer = rs_trait_in_scope(at, im);+ }+ if (answer > 0) {+ rs_set_add(out, rs_ent(RS_E_MEMBER, a->member));+ }+ unsure = unsure || answer < 0;+ }+ if (rs_set_empty(out)) {+ unsure = rs_trait_defaults(at, item, name, ns, out) || unsure;+ }+ if (rs_set_empty(out) && unsure) {+ rs_set_add(out, rs_weak(RS_E_GAP));+ }+}++/* `Type::name`: a variant, an item of an impl, a field (rustdoc's order). */+static void rs_type_assoc(const rs_at_t *at, int item, const char *name, int ns, rs_set_t *out) {+ const rs_index_t *ix = at->lk->ix;+ rs_ent_t end = rs_alias_end(ix, item);+ if (end.kind != RS_E_ITEM) {+ rs_set_add(out, end);+ return;+ }+ const rs_item_t *it = &ix->items[end.idx];+ if (it->kind == 'R') {+ rs_owner_members(ix, it->member_first, it->member_count, name, ns, "fct", out);+ return;+ }+ if (it->kind != 'S' && it->kind != 'E' && it->kind != 'U') {+ return;+ }+ if (it->kind == 'E') {+ rs_owner_members(ix, it->member_first, it->member_count, name, ns, "v", out);+ }+ if (rs_set_empty(out)) {+ rs_impl_items(at, end.idx, name, ns, out);+ }+ if (rs_set_empty(out) && ns == RS_NS_VALUE) {+ rs_owner_members(ix, it->member_first, it->member_count, name, ns, "d", out);+ }+}++/* What `name` is inside item `item`. While the index is being built only an+ * enum's variants are known; anything else through a type is not followed. */+static void rs_item_member(const rs_at_t *at, int item, const char *name, int ns, rs_set_t *out) {+ const rs_index_t *ix = at->lk->ix;+ const rs_item_t *it = &ix->items[item];+ if (!rs_item_is_type(it->kind)) {+ return; /* a function, a constant, a macro: nothing is inside */+ }+ if (at->lk->assoc) {+ rs_type_assoc(at, item, name, ns, out);+ return;+ }+ if (it->kind == 'E') {+ rs_owner_members(ix, it->member_first, it->member_count, name, ns, "v", out);+ }+ if (rs_set_empty(out)) {+ rs_set_add(out, rs_weak(RS_E_GAP));+ }+}++/* What `name` is inside `owner`, in namespace `ns`. */+static void rs_member(const rs_at_t *at, rs_ent_t owner, const char *name, int ns, rs_set_t *out) {+ const rs_index_t *ix = at->lk->ix;+ switch (owner.kind) {+ case RS_E_MOD:+ rs_mod_member(at->lk, owner.idx, name, ns, at->skip, out);+ break;+ case RS_E_ITEM:+ rs_item_member(at, owner.idx, name, ns, out);+ break;+ case RS_E_IMPL: {+ const rs_impl_t *im = &ix->impls[owner.idx];+ rs_owner_members(ix, im->member_first, im->member_count, name, ns, "fct", out);+ if (rs_set_empty(out)) {+ rs_set_add(out, rs_weak(im->self_ent.kind == RS_E_EXTERNAL ? RS_E_EXTERNAL : RS_E_GAP));+ }+ break;+ }+ case RS_E_MEMBER:+ if (ix->members[owner.idx].kind == 'v') {+ rs_set_add(out, rs_weak(RS_E_GAP)); /* a variant's fields are not carried */+ }+ break;+ case RS_E_EXTERNAL:+ case RS_E_GAP:+ rs_set_add(out, rs_weak(owner.kind));+ break;+ default:+ break;+ }+}++/* ── Lookup: a whole path ────────────────────────────────────────── */++/* The modules or the type that the keywords a path starts with name: `crate`,+ * `self`, `super` (repeatable), `Self`, or a leading `::`. Returns how many+ * segments they are; 0 when the path starts with a plain name. */+static int rs_path_head(const rs_at_t *at, const rs_path_t *p, rs_ent_t self, rs_set_t *cur) {+ const rs_index_t *ix = at->lk->ix;+ const char *first = p->segs[0];+ int i = SKIP_ONE;+ if (p->global) {+ bool unknown = false;+ rs_extern(at, first, cur, &unknown);+ if (rs_set_empty(cur) && (unknown || at->edition < RS_EDITION_2018)) {+ rs_set_add(cur, rs_weak(RS_E_GAP)); /* before 2018 `::name` is crate-relative */+ }+ } else if (rs_is(first, "crate")) {+ rs_set_add(cur, at->root >= 0 ? rs_ent(RS_E_MOD, at->root) : rs_weak(RS_E_GAP));+ } else if (rs_is(first, "self")) {+ rs_set_add(cur, rs_ent(RS_E_MOD, at->mod));+ } else if (rs_is(first, "super")) {+ rs_parents(ix, at->mod, cur);+ } else if (rs_is(first, "Self")) {+ rs_set_add(cur, self);+ } else {+ return 0;+ }+ for (; i < p->n && rs_is(p->segs[i], "super"); i++) {+ rs_set_t up = {0};+ for (int k = 0; k < cur->n; k++) {+ if (cur->v[k].kind == RS_E_MOD) {+ rs_parents(ix, cur->v[k].idx, &up);+ } else {+ rs_set_add(&up, rs_weak(RS_E_GAP));+ }+ }+ up.overflow = up.overflow || cur->overflow;+ *cur = up;+ }+ return i;+}++/* A name looked up from the crate root: an edition-2015 `use` path. */+static void rs_crate_relative(const rs_at_t *at, const char *name, int ns, rs_set_t *out) {+ bool unknown = false;+ if (ns == RS_NS_TYPE && RS_IN(RS_BUILTIN_CRATES, name)) {+ rs_set_add(out, rs_ent(RS_E_EXTERNAL, 0));+ return;+ }+ if (at->root < 0) {+ rs_set_add(out, rs_weak(RS_E_GAP));+ return;+ }+ rs_mod_member(at->lk, at->root, name, ns, at->skip, out);+ if (rs_set_empty(out) && ns == RS_NS_TYPE) {+ rs_extern(at, name, out, &unknown);+ }+ if (rs_set_empty(out) && unknown) {+ rs_set_add(out, rs_weak(RS_E_GAP));+ }+}++/* The first segment of a path that starts with a plain name. A doc link, a+ * type path and an edition-2018 import look it up lexically; an edition-2015+ * import starts at the crate root. With the edition unknown both must agree. */+static void rs_first(const rs_at_t *at, const char *name, int ns, bool import, rs_set_t *out) {+ if (!import || at->edition >= RS_EDITION_2018) {+ rs_lexical(at, name, ns, out);+ return;+ }+ rs_set_t rooted = {0};+ rs_crate_relative(at, name, ns, &rooted);+ if (at->edition == RS_EDITION_2015) {+ *out = rooted;+ return;+ }+ rs_lexical(at, name, ns, out);+ if (!rs_set_equal(out, &rooted)) {+ memset(out, 0, sizeof(*out));+ rs_set_add(out, rs_weak(RS_E_GAP));+ }+}++/* One segment before the last: what `name` is, as a type or module, inside+ * each thing of `cur`. false when one of them holds several. */+static bool rs_walk_step(const rs_at_t *at, const rs_set_t *cur, const char *name, rs_set_t *next) {+ for (int k = 0; k < cur->n; k++) {+ rs_set_t one = {0};+ rs_member(at, cur->v[k], name, RS_NS_TYPE, &one);+ rs_collapse(at->lk->ix, &one);+ if (one.n > SKIP_ONE || one.overflow) {+ return false;+ }+ rs_set_merge(next, &one);+ }+ return true;+}++/* Resolve path `p` written at `at`: the candidates of its last segment in+ * every namespace of `mask`. */+static void rs_walk(const rs_at_t *at, const rs_path_t *p, int mask, rs_ent_t self, bool import,+ rs_found_t *out) {+ rs_set_t cur = {0};+ int i = rs_path_head(at, p, self, &cur);+ if (i == 0 && p->n == SKIP_ONE) {+ for (int k = 0; k < RS_NS_COUNT; k++) {+ if (mask & RS_NS_LIST[k]) {+ rs_first(at, p->segs[0], RS_NS_LIST[k], import, &out->ns[k]);+ }+ }+ return;+ }+ if (i == 0) {+ rs_first(at, p->segs[0], RS_NS_TYPE, import, &cur);+ rs_collapse(at->lk->ix, &cur);+ if (cur.n > SKIP_ONE) {+ out->ambiguous = true;+ return;+ }+ if (rs_set_empty(&cur) && RS_IN(RS_PRIMITIVES, p->segs[0])) {+ rs_set_add(&cur, rs_ent(RS_E_EXTERNAL, 0)); /* `str::len`: of a primitive type */+ }+ i = SKIP_ONE;+ }+ if (cur.overflow) {+ out->ambiguous = true;+ return;+ }+ if (i == p->n) { /* the keywords are the whole path */+ if (mask & RS_NS_TYPE) {+ rs_set_merge(&out->ns[0], &cur);+ }+ return;+ }+ for (; i + SKIP_ONE < p->n && !rs_set_empty(&cur); i++) {+ rs_set_t next = {0};+ if (!rs_walk_step(at, &cur, p->segs[i], &next)) {+ out->ambiguous = true;+ return;+ }+ cur = next;+ }+ for (int k = 0; k < RS_NS_COUNT; k++) {+ for (int e = 0; (mask & RS_NS_LIST[k]) && e < cur.n; e++) {+ rs_member(at, cur.v[e], p->segs[p->n - SKIP_ONE], RS_NS_LIST[k], &out->ns[k]);+ }+ }+ out->owners = cur;+}++/* The contexts a path written in module `mod` is resolved under: one per+ * crate root of its file, or a single one without a root when the file has+ * none it can name (an orphan, or a file of more crates than are kept). */+static int rs_contexts(rs_look_t *lk, int mod, int skip, rs_at_t out[RS_ROOTS_KEPT]) {+ const rs_index_t *ix = lk->ix;+ const rs_file_t *f = &ix->files[ix->mods[mod].file];+ rs_at_t base = {+ .lk = lk, .mod = mod, .root = CBM_NOT_FOUND, .pkg = CBM_NOT_FOUND, .skip = skip};+ if (f->nroots == 0 || f->roots_top) {+ base.pkg = f->pkg >= 0 ? f->pkg : CBM_NOT_FOUND;+ base.own_lib = base.pkg >= 0 && f->roots_top && !f->in_lib;+ base.edition = rs_edition(ix, base.pkg);+ out[0] = base;+ return SKIP_ONE;+ }+ for (int i = 0; i < f->nroots; i++) {+ int pkg = ix->files[ix->mods[f->roots[i]].file].root_pkg;+ out[i] = base;+ out[i].root = f->roots[i];+ out[i].pkg = pkg >= 0 ? pkg : CBM_NOT_FOUND;+ out[i].own_lib = pkg >= 0 && ix->pkgs[pkg].lib_root != f->roots[i];+ out[i].edition = rs_edition(ix, out[i].pkg);+ }+ return f->nroots;+}++/* Resolve `p` written in module `mod`, under every crate root of its file:+ * what the roots find is united, so roots that disagree make it ambiguous.+ * `import`: the import whose path it is, CBM_NOT_FOUND for any other path. */+static void rs_resolve_path(rs_look_t *lk, int mod, const rs_path_t *p, int mask, rs_ent_t self,+ int import, rs_found_t *out) {+ rs_at_t at[RS_ROOTS_KEPT];+ int n = rs_contexts(lk, mod, import, at);+ memset(out, 0, sizeof(*out));+ for (int i = 0; i < n; i++) {+ rs_found_t one;+ memset(&one, 0, sizeof(one));+ rs_walk(&at[i], p, mask, self, import >= 0, &one);+ for (int k = 0; k < RS_NS_COUNT; k++) {+ rs_set_merge(&out->ns[k], &one.ns[k]);+ }+ rs_set_merge(&out->owners, &one.owners);+ out->ambiguous = out->ambiguous || one.ambiguous;+ }+}++/* The one thing among the candidates of `s` that were really found: RS_E_NONE+ * when there is none, a gap when there are several. */+static rs_ent_t rs_only_strong(const rs_index_t *ix, const rs_set_t *s) {+ rs_set_t strong = {0};+ for (int i = 0; i < s->n; i++) {+ if (!s->v[i].weak) {+ rs_set_add(&strong, s->v[i]);+ }+ }+ rs_collapse(ix, &strong);+ if (s->overflow || strong.n > SKIP_ONE) {+ return rs_ent(RS_E_GAP, 0);+ }+ return strong.n ? strong.v[0] : (rs_ent_t){0};+}++/* What the weak candidates of `s` come to: a gap before external. */+static uint8_t rs_only_weak(const rs_set_t *s) {+ uint8_t kind = RS_E_NONE;+ for (int i = 0; i < s->n; i++) {+ if (s->v[i].weak && kind != RS_E_GAP) {+ kind = s->v[i].kind;+ }+ }+ return kind;+}++/* ── Build: dependencies ─────────────────────────────────────────── */++static int rs_rawdep_cmp(const void *a, const void *b) {+ const rs_rawdep_t *x = (const rs_rawdep_t *)a;+ const rs_rawdep_t *y = (const rs_rawdep_t *)b;+ int c = strcmp(x->name, y->name);+ return c ? c : (x->seq > y->seq) - (x->seq < y->seq);+}++static int rs_dep_cmp(const void *a, const void *b) {+ return strcmp(((const rs_dep_t *)a)->key, ((const rs_dep_t *)b)->key);+}++/* What the dependency tables of a manifest say about one dependency. */+typedef struct {+ const char *name;+ const char *path; /* NULL: none written */+ const char *package; /* set: `name` is a rename */+ bool workspace; /* inherited from the workspace table */+ bool conflict; /* two tables give it different paths */+} rs_depspec_t;++static void rs_depspec_add(rs_depspec_t *spec, const rs_rawdep_t *r) {+ if (rs_is(r->attr, "path")) {+ spec->conflict = spec->conflict || (spec->path && !rs_is(spec->path, r->value));+ spec->path = r->value;+ } else if (rs_is(r->attr, "package")) {+ spec->package = r->value;+ } else if (rs_is(r->attr, "workspace") && rs_is(r->value, "true")) {+ spec->workspace = true;+ }+}++/* The entry `name` of the [workspace.dependencies] table of `ws` (its raw+ * records are sorted by name). false when there is none. */+static bool rs_ws_dep(const rs_pkg_t *ws, const char *name, rs_depspec_t *spec) {+ int lo = 0;+ int hi = ws->nraw;+ bool found = false;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (strcmp(ws->raw[mid].name, name) < 0) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ for (int i = lo; i < ws->nraw && rs_is(ws->raw[i].name, name); i++) {+ if (ws->raw[i].kind == 'w') {+ found = true;+ rs_depspec_add(spec, &ws->raw[i]);+ }+ }+ return found;+}++/* The crate a dependency brings into the extern prelude. Only a `path`+ * dependency names a crate of the repository; one whose path, manifest or+ * lib target is not known is a gap, never matched by name. */+static rs_dep_t rs_dep_make(rs_index_t *ix, const rs_pkg_t *p, rs_depspec_t spec) {+ rs_dep_t dep = {.key = rs_crate_name(ix, spec.name), .target = rs_ent(RS_E_GAP, 0)};+ const char *base = p->dir;+ char dir[RS_PATH_BUF];+ if (spec.workspace) {+ const rs_pkg_t *ws = p->ws >= 0 ? &ix->pkgs[p->ws] : NULL;+ rs_depspec_t inherited = {.name = spec.name};+ if (!ws || !rs_ws_dep(ws, spec.name, &inherited)) {+ return dep;+ }+ base = ws->dir;+ spec = inherited;+ }+ if (spec.conflict) {+ return dep;+ }+ if (!spec.path) {+ dep.target = rs_ent(RS_E_EXTERNAL, 0);+ return dep;+ }+ if (rs_is(spec.path, "?") || !rs_join_path(base, spec.path, dir, sizeof(dir))) {+ return dep;+ }+ int q = rs_pkg_at(ix, dir);+ if (q < 0 || !ix->pkgs[q].has_package || ix->pkgs[q].lib_root < 0) {+ return dep;+ }+ dep.target = rs_ent(RS_E_MOD, ix->pkgs[q].lib_root);+ if (!spec.package && ix->pkgs[q].lib_name) {+ dep.key = ix->pkgs[q].lib_name; /* not renamed: the lib crate's own name */+ }+ return dep;+}++static void rs_pkg_deps(rs_index_t *ix, int pi) {+ rs_pkg_t *p = &ix->pkgs[pi];+ p->deps = (rs_dep_t *)ix_alloc(ix, (size_t)p->nraw * sizeof(rs_dep_t));+ if (!p->deps) {+ return;+ }+ for (int i = 0; i < p->nraw;) {+ rs_depspec_t spec = {.name = p->raw[i].name};+ bool own = false;+ int j = i;+ for (; j < p->nraw && rs_is(p->raw[j].name, spec.name); j++) {+ if (p->raw[j].kind != 'w') {+ own = true;+ rs_depspec_add(&spec, &p->raw[j]);+ }+ }+ if (own) {+ p->deps[p->ndeps++] = rs_dep_make(ix, p, spec);+ }+ i = j;+ }+ if (p->ndeps > SKIP_ONE) {+ qsort(p->deps, (size_t)p->ndeps, sizeof(rs_dep_t), rs_dep_cmp);+ }+ int w = 0; /* one crate name for two targets: which one is not known */+ for (int i = 0; i < p->ndeps; i++) {+ if (w > 0 && rs_is(p->deps[w - SKIP_ONE].key, p->deps[i].key)) {+ if (!rs_ent_same(p->deps[w - SKIP_ONE].target, p->deps[i].target)) {+ p->deps[w - SKIP_ONE].target = rs_ent(RS_E_GAP, 0);+ }+ continue;+ }+ p->deps[w++] = p->deps[i];+ }+ p->ndeps = w;+}++static void rs_deps(rs_index_t *ix) {+ for (int pi = 0; pi < ix->npkgs; pi++) {+ rs_pkg_t *p = &ix->pkgs[pi];+ if (p->nraw > SKIP_ONE) {+ qsort(p->raw, (size_t)p->nraw, sizeof(rs_rawdep_t), rs_rawdep_cmp);+ }+ }+ for (int pi = 0; pi < ix->npkgs; pi++) {+ rs_pkg_deps(ix, pi);+ }+}++/* ── Build: bindings ─────────────────────────────────────────────── */++static int rs_bind_cmp(const void *a, const void *b) {+ const rs_bind_t *x = (const rs_bind_t *)a;+ const rs_bind_t *y = (const rs_bind_t *)b;+ if (x->mod != y->mod) {+ return x->mod < y->mod ? -1 : 1;+ }+ int c = strcmp(x->name, y->name);+ return c ? c : (x->seq > y->seq) - (x->seq < y->seq);+}++static int rs_ref_cmp(const void *a, const void *b) {+ const rs_ref_t *x = (const rs_ref_t *)a;+ const rs_ref_t *y = (const rs_ref_t *)b;+ if (x->mod != y->mod) {+ return x->mod < y->mod ? -1 : 1;+ }+ return (x->seq > y->seq) - (x->seq < y->seq);+}++static int rs_member_cmp(const void *a, const void *b) {+ const rs_member_t *x = (const rs_member_t *)a;+ const rs_member_t *y = (const rs_member_t *)b;+ int c = strcmp(x->name, y->name);+ return c ? c : (x->seq > y->seq) - (x->seq < y->seq);+}++/* The members of every type, trait and impl, by name. */+static void rs_sort_members(rs_index_t *ix) {+ for (int i = 0; i < ix->nitems; i++) {+ const rs_item_t *it = &ix->items[i];+ if (it->member_count > SKIP_ONE) {+ qsort(&ix->members[it->member_first], (size_t)it->member_count, sizeof(rs_member_t),+ rs_member_cmp);+ }+ }+ for (int i = 0; i < ix->nimpls; i++) {+ const rs_impl_t *im = &ix->impls[i];+ if (im->member_count > SKIP_ONE) {+ qsort(&ix->members[im->member_first], (size_t)im->member_count, sizeof(rs_member_t),+ rs_member_cmp);+ }+ }+}++static void rs_bind_put(rs_index_t *ix, int mod, const char *name, int kind, int ref, char vis) {+ ix->binds[ix->nbinds] = (rs_bind_t){+ .mod = mod, .name = name, .kind = kind, .ref = ref, .seq = ix->nbinds, .vis = vis};+ ix->nbinds++;+}++/* An item: bound in its module, and a `#[macro_export]` macro also at the+ * crate roots of its file. */+static void rs_bind_item(rs_index_t *ix, int idx) {+ const rs_item_t *it = &ix->items[idx];+ const rs_file_t *f = &ix->files[it->file];+ rs_bind_put(ix, it->mod, it->name, RS_BIND_ITEM, idx, it->vis);+ for (int r = 0; it->macro_export && !f->roots_top && r < f->nroots; r++) {+ if (f->roots[r] != it->mod) {+ rs_bind_put(ix, f->roots[r], it->name, RS_BIND_ITEM, idx, 'p');+ }+ }+}++/* Sort `refs` by module and set each module's range through `first`/`count`+ * (offsets of the two fields in rs_mod_t). */+static void rs_ref_ranges(rs_index_t *ix, rs_ref_t *refs, int n, bool globs) {+ if (n > SKIP_ONE) {+ qsort(refs, (size_t)n, sizeof(rs_ref_t), rs_ref_cmp);+ }+ for (int i = 0; i < n; i++) {+ rs_mod_t *m = &ix->mods[refs[i].mod];+ int *first = globs ? &m->glob_first : &m->named_first;+ int *count = globs ? &m->glob_count : &m->named_count;+ if (*count == 0) {+ *first = i;+ }+ (*count)++;+ }+}++static void rs_bindings(rs_index_t *ix) {+ size_t cap = ((size_t)ix->nitems * (RS_ROOTS_KEPT + SKIP_ONE)) + (size_t)ix->ndecls ++ (size_t)ix->nmods + (size_t)ix->nimports + (size_t)ix->nmaybes;+ ix->binds = (rs_bind_t *)ix_alloc(ix, cap * sizeof(rs_bind_t));+ ix->globs = (rs_ref_t *)ix_alloc(ix, (size_t)ix->nimports * sizeof(rs_ref_t));+ ix->named = (rs_ref_t *)ix_alloc(ix, (size_t)ix->nimports * sizeof(rs_ref_t));+ if (!ix->binds || !ix->globs || !ix->named) {+ return;+ }+ for (int i = 0; i < ix->nitems; i++) {+ rs_bind_item(ix, i);+ }+ for (int m = 0; m < ix->nmods; m++) {+ if (ix->mods[m].parent >= 0) {+ rs_bind_put(ix, ix->mods[m].parent, ix->mods[m].name, RS_BIND_CHILD, m,+ ix->mods[m].vis);+ }+ }+ for (int d = 0; d < ix->ndecls; d++) {+ const rs_decl_t *decl = &ix->decls[d];+ rs_bind_put(ix, decl->mod, decl->name, RS_BIND_CHILD, decl->child, decl->vis);+ }+ for (int i = 0; i < ix->nimports; i++) {+ const rs_import_t *imp = &ix->imports[i];+ rs_ref_t ref = {.mod = imp->mod, .seq = imp->seq, .ref = i};+ if (imp->kind == 'g') {+ ix->globs[ix->nglobs++] = ref;+ } else {+ ix->named[ix->nnamed++] = ref;+ rs_bind_put(ix, imp->mod, imp->local, RS_BIND_IMPORT, i, imp->vis);+ }+ }+ for (int i = 0; i < ix->nmaybes; i++) {+ rs_bind_put(ix, ix->maybes[i].mod, ix->maybe_names[i], RS_BIND_MAYBE, i, 'p');+ }+ if (ix->nbinds > SKIP_ONE) {+ qsort(ix->binds, (size_t)ix->nbinds, sizeof(rs_bind_t), rs_bind_cmp);+ }+ for (int i = 0; i < ix->nbinds; i++) {+ rs_mod_t *m = &ix->mods[ix->binds[i].mod];+ if (m->bind_count == 0) {+ m->bind_first = i;+ }+ m->bind_count++;+ }+ rs_ref_ranges(ix, ix->globs, ix->nglobs, true);+ rs_ref_ranges(ix, ix->named, ix->nnamed, false);+}++/* ── Build: imports ──────────────────────────────────────────────── */++/* `extern crate name;`: the crate of that name, or `self` for the crate+ * itself. */+static void rs_import_extern(rs_look_t *lk, const rs_import_t *imp, int idx, rs_found_t *found) {+ rs_at_t at[RS_ROOTS_KEPT];+ int n = rs_contexts(lk, imp->mod, idx, at);+ for (int i = 0; i < n; i++) {+ bool unknown = false;+ if (rs_is(imp->segs[0], "self")) {+ unknown = at[i].root < 0;+ rs_set_add(&found->ns[0], unknown ? rs_weak(RS_E_GAP) : rs_ent(RS_E_MOD, at[i].root));+ continue;+ }+ rs_set_t one = {0};+ rs_extern(&at[i], imp->segs[0], &one, &unknown);+ if (rs_set_empty(&one)) {+ /* a crate the manifest names differently (see rs_lexical), unless+ * the crate's dependencies are not known at all */+ rs_set_add(&one, rs_weak(unknown ? RS_E_GAP : RS_E_EXTERNAL));+ }+ rs_set_merge(&found->ns[0], &one);+ }+}++/* Keep what an import path was found to name. An import DECLARES its name:+ * whatever the path leads to, the name is bound, so a path that leads into+ * something unknown binds the name to a gap (or to something external) in+ * every namespace rather than leaving it unbound. */+static void rs_import_store(rs_index_t *ix, rs_import_t *imp, const rs_found_t *found, int pass) {+ bool strong = false;+ uint8_t weak = RS_E_NONE;+ for (int k = 0; k < RS_NS_COUNT; k++) {+ uint8_t w = rs_only_weak(&found->ns[k]);+ imp->res[k] = rs_only_strong(ix, &found->ns[k]);+ imp->res[k].via_import = false;+ strong = strong || imp->res[k].kind != RS_E_NONE;+ weak = (weak == RS_E_GAP || w == RS_E_NONE) ? weak : w;+ }+ if (found->ambiguous || (!strong && weak != RS_E_EXTERNAL)) {+ weak = RS_E_GAP;+ ix->gap_imports++;+ }+ imp->spread = imp->kind == 'b' && (found->ambiguous || !strong);+ for (int k = 0; k < RS_NS_COUNT && (found->ambiguous || !strong); k++) {+ imp->res[k] = rs_ent(weak, 0);+ }+ imp->state = RS_STATE_DONE;+ imp->done_pass = pass;+}++/* Resolve import `idx` in pass `pass`. An import that waits for another one+ * stays unresolved, unless this is the `last` attempt: then it is not+ * followed. */+static void rs_import_resolve(rs_index_t *ix, int idx, int pass, bool last) {+ rs_import_t *imp = &ix->imports[idx];+ rs_look_t lk = {.ix = ix, .pass = pass};+ rs_found_t found;+ memset(&found, 0, sizeof(found));+ if (imp->nsegs > 0 && imp->kind == 'x') {+ rs_import_extern(&lk, imp, idx, &found);+ } else if (imp->nsegs > 0) {+ rs_path_t p = {.segs = imp->segs, .n = imp->nsegs, .global = imp->global};+ rs_ent_t no_self = {0};+ int mask = imp->kind == 'b' ? RS_NS_ALL : RS_NS_TYPE;+ rs_resolve_path(&lk, imp->mod, &p, mask, no_self, idx, &found);+ }+ if (lk.blocked && !last) {+ return;+ }+ if (lk.blocked) {+ memset(&found, 0, sizeof(found));+ }+ rs_import_store(ix, imp, &found, pass);+}++/* Resolve every import. Imports depend on each other (a path can run through+ * an imported name or a glob), so they are resolved in passes: a pass reads+ * only what EARLIER passes resolved, which makes the result independent of+ * the order of the imports. What is still waiting after the last pass (a+ * cycle, or a chain longer than the passes) is not followed. */+static void rs_imports(rs_index_t *ix) {+ int pending = ix->nimports;+ int pass = SKIP_ONE;+ for (; pass <= RS_IMPORT_PASSES && pending > 0; pass++) {+ int before = pending;+ for (int i = 0; i < ix->nimports; i++) {+ if (ix->imports[i].state != RS_STATE_DONE) {+ rs_import_resolve(ix, i, pass, false);+ pending -= ix->imports[i].state == RS_STATE_DONE;+ }+ }+ if (pending == before) {+ break;+ }+ }+ for (int i = 0; pending > 0 && i < ix->nimports; i++) {+ if (ix->imports[i].state != RS_STATE_DONE) {+ rs_import_resolve(ix, i, pass + SKIP_ONE, true);+ }+ }+}++/* ── Build: aliases and impls ────────────────────────────────────── */++/* What the type path `text`, written in module `mod`, names. */+static rs_ent_t rs_type_path(rs_index_t *ix, int mod, const char *text) {+ CBMDocLinkRsPath parsed;+ const char *segs[CBM_DOCLINK_RS_MAX_SEGS];+ if (cbm_doclink_rs_parse_path(text, strlen(text), false, &parsed) != CBM_DOCLINK_RS_PATH_OK) {+ return rs_ent(RS_E_GAP, 0);+ }+ for (int i = 0; i < parsed.nsegs; i++) {+ segs[i] = rs_plain(parsed.segs[i]);+ }+ rs_path_t p = {.segs = segs, .n = parsed.nsegs, .global = parsed.global};+ rs_look_t lk = {.ix = ix};+ rs_found_t found;+ rs_ent_t no_self = {0};+ rs_resolve_path(&lk, mod, &p, RS_NS_TYPE, no_self, CBM_NOT_FOUND, &found);+ if (found.ambiguous) {+ return rs_ent(RS_E_GAP, 0);+ }+ rs_ent_t e = rs_only_strong(ix, &found.ns[0]);+ uint8_t weak = rs_only_weak(&found.ns[0]);+ return (e.kind == RS_E_NONE && weak != RS_E_NONE) ? rs_ent(weak, 0) : e;+}++static int rs_item_impl_cmp(const void *a, const void *b) {+ const rs_item_impl_t *x = (const rs_item_impl_t *)a;+ const rs_item_impl_t *y = (const rs_item_impl_t *)b;+ if (x->item != y->item) {+ return x->item < y->item ? -1 : 1;+ }+ return (x->impl > y->impl) - (x->impl < y->impl);+}++static int rs_assoc_cmp(const void *a, const void *b) {+ const rs_assoc_t *x = (const rs_assoc_t *)a;+ const rs_assoc_t *y = (const rs_assoc_t *)b;+ if (x->item != y->item) {+ return x->item < y->item ? -1 : 1;+ }+ int c = strcmp(x->name, y->name);+ if (c) {+ return c;+ }+ return x->impl != y->impl ? (x->impl < y->impl ? -1 : 1)+ : (x->member > y->member) - (x->member < y->member);+}++/* The type an impl is for and the trait it implements. */+static void rs_impl_types(rs_index_t *ix, rs_impl_t *im) {+ rs_ent_t none = {0};+ rs_ent_t self = im->self_path ? rs_type_path(ix, im->mod, im->self_path) : none;+ if (self.kind == RS_E_ITEM) {+ self = rs_alias_end(ix, self.idx);+ self.weak = false;+ }+ if (self.kind == RS_E_ITEM && !rs_item_is_type(ix->items[self.idx].kind)) {+ self = rs_ent(RS_E_GAP, 0);+ }+ im->self_ent = self;+ if (im->trait_path) {+ rs_ent_t trait = rs_is(im->trait_path, "?") ? rs_ent(RS_E_GAP, 0)+ : rs_type_path(ix, im->mod, im->trait_path);+ im->trait_ent = trait.kind == RS_E_NONE ? rs_ent(RS_E_GAP, 0) : trait;+ }+}++/* Resolve alias targets and impl headers, and index every impl's members by+ * the type the impl is for. */+static void rs_types(rs_index_t *ix) {+ int members = 0;+ for (int i = 0; i < ix->nitems; i++) {+ rs_item_t *it = &ix->items[i];+ if (it->alias) {+ it->alias_ent = rs_type_path(ix, it->mod, it->alias);+ }+ }+ for (int i = 0; i < ix->nimpls; i++) {+ rs_impl_types(ix, &ix->impls[i]);+ members += ix->impls[i].member_count;+ }+ ix->item_impls = (rs_item_impl_t *)ix_alloc(ix, (size_t)ix->nimpls * sizeof(rs_item_impl_t));+ ix->assoc = (rs_assoc_t *)ix_alloc(ix, (size_t)members * sizeof(rs_assoc_t));+ if (!ix->item_impls || !ix->assoc) {+ return;+ }+ for (int i = 0; i < ix->nimpls; i++) {+ const rs_impl_t *im = &ix->impls[i];+ for (int k = 0; k < im->member_count; k++) {+ int m = im->member_first + k;+ if (im->self_ent.kind == RS_E_ITEM) {+ ix->assoc[ix->nassoc++] = (rs_assoc_t){+ .item = im->self_ent.idx, .name = ix->members[m].name, .impl = i, .member = m};+ } else if (!im->self_path) {+ cbm_ht_set(ix->blanket, ix->members[m].name, (void *)(intptr_t)SKIP_ONE);+ }+ }+ if (im->self_ent.kind == RS_E_ITEM) {+ ix->item_impls[ix->nitem_impls++] =+ (rs_item_impl_t){.item = im->self_ent.idx, .impl = i};+ }+ }+ if (ix->nitem_impls > SKIP_ONE) {+ qsort(ix->item_impls, (size_t)ix->nitem_impls, sizeof(rs_item_impl_t), rs_item_impl_cmp);+ }+ if (ix->nassoc > SKIP_ONE) {+ qsort(ix->assoc, (size_t)ix->nassoc, sizeof(rs_assoc_t), rs_assoc_cmp);+ }+ for (int i = 0; i < ix->nitem_impls; i++) {+ rs_item_t *it = &ix->items[ix->item_impls[i].item];+ if (it->impl_count == 0) {+ it->impl_first = i;+ }+ it->impl_count++;+ }+}++/* ── Build: line indexes of the re-extracted files ───────────────── */++typedef struct {+ uint32_t line;+ int order; /* at one line: modules are left innermost first, then entered outermost first */+ int mod; /* the innermost module from that line on */+} rs_event_t;++static int rs_event_cmp(const void *a, const void *b) {+ const rs_event_t *x = (const rs_event_t *)a;+ const rs_event_t *y = (const rs_event_t *)b;+ if (x->line != y->line) {+ return x->line < y->line ? -1 : 1;+ }+ return (x->order > y->order) - (x->order < y->order);+}++static int rs_scope_cmp(const void *a, const void *b) {+ const rs_scope_t *x = (const rs_scope_t *)a;+ const rs_scope_t *y = (const rs_scope_t *)b;+ if (x->start != y->start) {+ return x->start < y->start ? -1 : 1;+ }+ return (x->end > y->end) - (x->end < y->end);+}++static int rs_note_cmp(const void *a, const void *b) {+ const rs_note_t *x = (const rs_note_t *)a;+ const rs_note_t *y = (const rs_note_t *)b;+ if (x->line != y->line) {+ return x->line < y->line ? -1 : 1;+ }+ return strcmp(x->text, y->text);+}++static int rs_line_cmp(const void *a, const void *b) {+ uint32_t x = *(const uint32_t *)a;+ uint32_t y = *(const uint32_t *)b;+ return (x > y) - (x < y);+}++/* The spans of file `f`: for every line, the innermost inline module. */+static void rs_file_spans(rs_index_t *ix, rs_file_t *f, rs_event_t *ev) {+ int n = 0;+ for (int m = SKIP_ONE; m < f->nmods; m++) {+ const rs_mod_t *mod = &ix->mods[f->mod_base + m];+ if (mod->parent < 0) {+ continue;+ }+ ev[n++] = (rs_event_t){.line = mod->start, .order = m, .mod = f->mod_base + m};+ ev[n++] = (rs_event_t){.line = mod->end + SKIP_ONE, .order = -m, .mod = mod->parent};+ }+ if (n > SKIP_ONE) {+ qsort(ev, (size_t)n, sizeof(rs_event_t), rs_event_cmp);+ }+ f->span_first = ix->nspans;+ ix->spans[ix->nspans++] = (rs_span_t){.from = 0, .mod = f->mod_base};+ for (int i = 0; i < n; i++) {+ ix->spans[ix->nspans++] = (rs_span_t){.from = ev[i].line, .mod = ev[i].mod};+ }+ f->span_count = ix->nspans - f->span_first;+}++static void rs_file_lines(rs_index_t *ix, rs_file_t *f, rs_event_t *ev) {+ rs_file_spans(ix, f, ev);+ if (f->scope_count > SKIP_ONE) {+ qsort(&ix->scopes[f->scope_first], (size_t)f->scope_count, sizeof(rs_scope_t),+ rs_scope_cmp);+ }+ if (f->local_count > SKIP_ONE) {+ qsort(&ix->locals[f->local_first], (size_t)f->local_count, sizeof(rs_note_t), rs_note_cmp);+ }+ if (f->unowned_count > SKIP_ONE) {+ qsort(&ix->unowned[f->unowned_first], (size_t)f->unowned_count, sizeof(rs_note_t),+ rs_note_cmp);+ }+ f->test_first = ix->ntest_lines;+ for (int i = f->item_first; i < f->item_first + f->item_count; i++) {+ if (ix->items[i].test) {+ ix->test_lines[ix->ntest_lines++] = ix->items[i].start;+ }+ }+ f->test_count = ix->ntest_lines - f->test_first;+ if (f->test_count > SKIP_ONE) {+ qsort(&ix->test_lines[f->test_first], (size_t)f->test_count, sizeof(uint32_t), rs_line_cmp);+ }+}++static void rs_line_indexes(rs_index_t *ix) {+ size_t spans = 0;+ size_t events = 0;+ for (int fi = 0; fi < ix->nfiles; fi++) {+ const rs_file_t *f = &ix->files[fi];+ if (f->kind == RS_FILE_SOURCE && f->fresh) {+ size_t ev = (size_t)(f->nmods - SKIP_ONE) * PAIR_LEN;+ spans += ev + SKIP_ONE;+ events = ev > events ? ev : events;+ }+ }+ ix->spans = (rs_span_t *)ix_alloc(ix, spans * sizeof(rs_span_t));+ ix->test_lines = (uint32_t *)ix_alloc(ix, (size_t)ix->nitems * sizeof(uint32_t));+ rs_event_t *ev = (rs_event_t *)ix_alloc(ix, events * sizeof(rs_event_t));+ if (!ix->spans || !ix->test_lines || !ev) {+ return;+ }+ for (int fi = 0; fi < ix->nfiles; fi++) {+ if (ix->files[fi].kind == RS_FILE_SOURCE && ix->files[fi].fresh) {+ rs_file_lines(ix, &ix->files[fi], ev);+ }+ }+}++/* ── Build ───────────────────────────────────────────────────────── */++/* The scope blob of a Rust source file, NULL when it has none this code+ * reads. */+static const char *rs_source_blob(const char *scope) {+ static const char tag[] = CBM_DOCLINK_RS_SCOPE_TAG;+ const size_t tl = sizeof(tag) - SKIP_ONE;+ if (!scope || strncmp(scope, tag, tl) != 0 || (scope[tl] != '\n' && scope[tl] != '\0') ||+ rs_blob_is_manifest(scope)) {+ return NULL;+ }+ return scope;+}++static void rs_count_add(rs_counts_t *sum, const rs_counts_t *c) {+ sum->mods += c->mods;+ sum->decls += c->decls;+ sum->items += c->items;+ sum->members += c->members;+ sum->impls += c->impls;+ sum->imports += c->imports;+ sum->maybes += c->maybes;+ sum->locals += c->locals;+ sum->unowned += c->unowned;+ sum->macuses += c->macuses;+ sum->macdecls += c->macdecls;+}++/* The facts of source file `f` that need no blob, and the size of its blob. */+static void rs_source_meta(rs_index_t *ix, rs_file_t *f, const cbm_doclink_file_t *src,+ rs_counts_t *sum) {+ rs_counts_t c = {0};+ /* the qualified name of an item `x` of this file, minus the `x` */+ const char *probe = cbm_fqn_compute(&ix->arena, ix->project, src->rel_path, "x");+ size_t pl = probe ? strlen(probe) : 0;+ f->kind = RS_FILE_SOURCE;+ f->fresh = src->run_file >= 0;+ f->test_path = rs_is_test_path(src->rel_path);+ f->item_prefix = pl > 0 ? ix_strndup(ix, probe, pl - SKIP_ONE) : NULL;+ f->module_qn =+ cbm_fqn_module_source_lang(&ix->arena, ix->project, src->rel_path, CBM_LANG_RUST);+ ix->oom = ix->oom || !f->item_prefix || !f->module_qn;+ rs_count_blob(rs_source_blob(src->scope), &c);+ f->nmods = c.mods + SKIP_ONE;+ f->mod_base = ix->nmods;+ ix->nmods += f->nmods;+ ix->nsources++;+ rs_count_add(sum, &c);+}++static bool rs_alloc_tables(rs_index_t *ix, const rs_counts_t *c, int manifests) {+ ix->mods = (rs_mod_t *)ix_calloc(ix, (size_t)ix->nmods, sizeof(rs_mod_t));+ ix->decls = (rs_decl_t *)ix_calloc(ix, (size_t)c->decls, sizeof(rs_decl_t));+ ix->items = (rs_item_t *)ix_calloc(ix, (size_t)c->items, sizeof(rs_item_t));+ ix->members = (rs_member_t *)ix_calloc(ix, (size_t)c->members, sizeof(rs_member_t));+ ix->impls = (rs_impl_t *)ix_calloc(ix, (size_t)c->impls, sizeof(rs_impl_t));+ ix->imports = (rs_import_t *)ix_calloc(ix, (size_t)c->imports, sizeof(rs_import_t));+ ix->maybes = (rs_ref_t *)ix_calloc(ix, (size_t)c->maybes, sizeof(rs_ref_t));+ ix->maybe_names = (const char **)ix_calloc(ix, (size_t)c->maybes, sizeof(char *));+ ix->macuses = (rs_macuse_t *)ix_calloc(ix, (size_t)c->macuses, sizeof(rs_macuse_t));+ ix->macdecls = (rs_macdecl_t *)ix_calloc(ix, (size_t)c->macdecls, sizeof(rs_macdecl_t));+ ix->scopes =+ (rs_scope_t *)ix_calloc(ix, (size_t)c->items + (size_t)c->impls, sizeof(rs_scope_t));+ ix->locals = (rs_note_t *)ix_calloc(ix, (size_t)c->locals, sizeof(rs_note_t));+ ix->unowned = (rs_note_t *)ix_calloc(ix, (size_t)c->unowned, sizeof(rs_note_t));+ ix->pkgs = (rs_pkg_t *)ix_calloc(ix, (size_t)manifests, sizeof(rs_pkg_t));+ return !ix->oom;+}++/* Read every file's scope blob into the index. */+static bool rs_load(rs_index_t *ix, const cbm_doclink_build_in_t *in) {+ rs_counts_t sum = {0};+ int manifests = 0;+ ix->nfiles = in->file_count;+ ix->files = (rs_file_t *)ix_calloc(ix, (size_t)in->file_count, sizeof(rs_file_t));+ if (!ix->files) {+ return false;+ }+ for (int i = 0; i < in->file_count; i++) {+ const cbm_doclink_file_t *src = &in->files[i];+ rs_file_t *f = &ix->files[i];+ f->rel_path = src->rel_path;+ f->root_pkg = RS_PKG_NONE;+ f->pkg = RS_PKG_NONE;+ cbm_ht_set(ix->file_by_path, f->rel_path, (void *)(intptr_t)(i + SKIP_ONE));+ if (src->run_file >= 0 && src->run_file < in->run_file_count) {+ ix->run_to_file[src->run_file] = i;+ }+ if (rs_ends_with(src->rel_path, ".rs")) {+ rs_source_meta(ix, f, src, &sum);+ } else if (rs_is(rs_basename(src->rel_path), "Cargo.toml") &&+ rs_blob_is_manifest(src->scope)) {+ f->kind = RS_FILE_MANIFEST;+ manifests++;+ }+ }+ if (!rs_alloc_tables(ix, &sum, manifests)) {+ return false;+ }+ for (int i = 0; i < in->file_count; i++) {+ rs_file_t *f = &ix->files[i];+ if (f->kind == RS_FILE_MANIFEST) {+ rs_read_manifest(ix, i, in->files[i].scope);+ }+ for (int m = 0; f->kind == RS_FILE_SOURCE && m < f->nmods; m++) {+ ix->mods[f->mod_base + m].file = i;+ ix->mods[f->mod_base + m].parent = CBM_NOT_FOUND;+ }+ if (f->kind == RS_FILE_SOURCE) {+ rs_read_source(ix, i, rs_source_blob(in->files[i].scope));+ }+ }+ for (int pi = 0; pi < ix->npkgs; pi++) {+ const char *dir = ix->pkgs[pi].dir;+ cbm_ht_set(ix->pkg_by_dir, dir[0] ? dir : ".", (void *)(intptr_t)(pi + SKIP_ONE));+ }+ if (ix->nmacuses > SKIP_ONE) {+ qsort(ix->macuses, (size_t)ix->nmacuses, sizeof(rs_macuse_t), rs_macuse_cmp);+ }+ if (ix->nmacdecls > SKIP_ONE) {+ qsort(ix->macdecls, (size_t)ix->nmacdecls, sizeof(rs_macdecl_t), rs_macdecl_cmp);+ }+ return !ix->oom;+}++static void rs_destroy(void *index) {+ rs_index_t *ix = (rs_index_t *)index;+ if (!ix) {+ return;+ }+ cbm_ht_free(ix->file_by_path);+ cbm_ht_free(ix->pkg_by_dir);+ cbm_ht_free(ix->blanket);+ cbm_free(CBM_MEM_CLASS_OTHER, ix->run_to_file);+ cbm_arena_destroy(&ix->arena);+ cbm_free(CBM_MEM_CLASS_OTHER, ix);+}++static void rs_log_index(const rs_index_t *ix) {+ enum { N_FILES = 0, N_PKGS, N_ROOTS, N_ORPHANS, N_MODS, N_ITEMS, N_IMPORTS, N_GAPS, N_COUNT };+ char b[N_COUNT][CBM_SZ_32];+ snprintf(b[N_FILES], sizeof(b[N_FILES]), "%d", ix->nsources);+ snprintf(b[N_PKGS], sizeof(b[N_PKGS]), "%d", ix->npkgs);+ snprintf(b[N_ROOTS], sizeof(b[N_ROOTS]), "%d", ix->crate_roots);+ snprintf(b[N_ORPHANS], sizeof(b[N_ORPHANS]), "%d", ix->orphans);+ snprintf(b[N_MODS], sizeof(b[N_MODS]), "%d", ix->nmods);+ snprintf(b[N_ITEMS], sizeof(b[N_ITEMS]), "%d", ix->nitems);+ snprintf(b[N_IMPORTS], sizeof(b[N_IMPORTS]), "%d", ix->nimports);+ snprintf(b[N_GAPS], sizeof(b[N_GAPS]), "%d", ix->gap_imports);+ cbm_log_info("doc_links.rs.index", "files", b[N_FILES], "manifests", b[N_PKGS], "crate_roots",+ b[N_ROOTS], "orphan_files", b[N_ORPHANS], "modules", b[N_MODS], "items",+ b[N_ITEMS], "imports", b[N_IMPORTS], "unfollowed_imports", b[N_GAPS]);+}++static void *rs_build(const cbm_doclink_build_in_t *in) {+ rs_index_t *ix = (rs_index_t *)cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*ix));+ if (!ix) {+ return NULL;+ }+ cbm_arena_init(&ix->arena);+ ix->project = in->ctx->project_name;+ ix->file_by_path = cbm_ht_create(CBM_SZ_4K);+ ix->pkg_by_dir = cbm_ht_create(CBM_SZ_64);+ ix->blanket = cbm_ht_create(CBM_SZ_256);+ ix->run_count = in->run_file_count;+ ix->run_to_file = (int *)cbm_alloc(+ CBM_MEM_CLASS_OTHER,+ (size_t)(in->run_file_count ? in->run_file_count : SKIP_ONE) * sizeof(int));+ if (!ix->file_by_path || !ix->pkg_by_dir || !ix->blanket || !ix->run_to_file) {+ cbm_log_error("doc_links.rs.error", "step", "tables", "reason", "alloc");+ rs_destroy(ix);+ return NULL;+ }+ for (int i = 0; i < in->run_file_count; i++) {+ ix->run_to_file[i] = CBM_NOT_FOUND;+ }+ if (rs_load(ix, in)) {+ rs_crate_roots(ix);+ rs_module_tree(ix);+ rs_file_roots(ix);+ rs_orphan_packages(ix);+ rs_product(ix);+ rs_deps(ix);+ rs_sort_members(ix);+ rs_bindings(ix);+ }+ if (!ix->oom) {+ rs_imports(ix);+ rs_types(ix);+ rs_line_indexes(ix);+ }+ if (ix->oom) {+ cbm_log_error("doc_links.rs.error", "step", "index", "reason", "alloc");+ rs_destroy(ix);+ return NULL;+ }+ rs_log_index(ix);+ return ix;+}++/* ── One reference ───────────────────────────────────────────────── */++typedef struct {+ const rs_index_t *ix;+ const rs_file_t *f;+ const CBMDocLink *link;+ const char *segs[CBM_DOCLINK_RS_MAX_SEGS];+ rs_path_t path;+ int dis;+ int mod; /* the module the documented definition is in */+ rs_ent_t self; /* what `Self` names there */+ bool single; /* one plain name: no `::`, no keyword */+ bool file_level;+ bool product; /* the documented definition is product code */+} rs_link_t;++static bool rs_is_keyword(const char *seg) {+ return rs_is(seg, "crate") || rs_is(seg, "self") || rs_is(seg, "super") || rs_is(seg, "Self");+}++/* The innermost module of file `f` at `line`. */+static int rs_mod_at(const rs_index_t *ix, const rs_file_t *f, uint32_t line) {+ int lo = f->span_first;+ int hi = lo + f->span_count;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (ix->spans[mid].from <= line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo > f->span_first ? ix->spans[lo - SKIP_ONE].mod : f->mod_base;+}++/* What `Self` names at `line`: the type or trait whose definition holds the+ * line, the self type of the impl that does, or nothing. */+static rs_ent_t rs_self_at(const rs_index_t *ix, const rs_file_t *f, uint32_t line) {+ rs_ent_t none = {0};+ int lo = f->scope_first;+ int hi = lo + f->scope_count;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (ix->scopes[mid].start <= line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ if (lo == f->scope_first || ix->scopes[lo - SKIP_ONE].end < line) {+ return none;+ }+ const rs_scope_t *s = &ix->scopes[lo - SKIP_ONE];+ if (s->item >= 0) {+ return rs_ent(RS_E_ITEM, s->item);+ }+ rs_ent_t self = ix->impls[s->impl].self_ent;+ return self.kind == RS_E_ITEM ? self : rs_ent(RS_E_IMPL, s->impl);+}++/* First note of notes[first, first + count) at or after `line`. */+static int rs_note_at(const rs_note_t *notes, int first, int count, uint32_t line) {+ int lo = first;+ int hi = first + count;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (notes[mid].line < line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo;+}++/* True when the documented definition does not own its graph node: another+ * definition of the file has the same qualified name and keeps the node, so+ * an edge would leave from that other definition. */+static bool rs_unowned(const rs_index_t *ix, const rs_file_t *f, const CBMDocLink *link) {+ size_t pl = strlen(f->item_prefix);+ const char *qn = link->source_qn ? link->source_qn : "";+ int end = f->unowned_first + f->unowned_count;+ for (int i = rs_note_at(ix->unowned, f->unowned_first, f->unowned_count, link->def_line);+ i < end && ix->unowned[i].line == link->def_line; i++) {+ if (strncmp(qn, f->item_prefix, pl) == 0 && rs_is(qn + pl, ix->unowned[i].text)) {+ return true;+ }+ }+ return false;+}++/* True when `name` is a parameter or type parameter of the definition the+ * reference documents. */+static bool rs_is_local(const rs_link_t *q, const char *name) {+ const rs_index_t *ix = q->ix;+ const rs_file_t *f = q->f;+ size_t nl = strlen(name);+ int end = f->local_first + f->local_count;+ if (q->file_level) {+ return false;+ }+ for (int i = rs_note_at(ix->locals, f->local_first, f->local_count, q->link->def_line);+ i < end && ix->locals[i].line == q->link->def_line; i++) {+ for (const char *p = ix->locals[i].text; *p;) {+ const char *comma = strchr(p, ',');+ size_t len = comma ? (size_t)(comma - p) : strlen(p);+ const char *plain = (len > PAIR_LEN && p[0] == 'r' && p[1] == '#') ? p + PAIR_LEN : p;+ size_t plen = len - (size_t)(plain - p);+ if (plen == nl && memcmp(plain, name, nl) == 0) {+ return true;+ }+ p = comma ? comma + SKIP_ONE : p + len;+ }+ }+ return false;+}++/* Is the documented definition product code? Not in a test-only module, not+ * an item marked as a test, not inside a type marked as one. */+static bool rs_source_product(const rs_link_t *q) {+ const rs_index_t *ix = q->ix;+ const rs_file_t *f = q->f;+ if (!ix->mods[q->mod].product) {+ return false;+ }+ if (q->file_level) {+ return true;+ }+ if (q->self.kind == RS_E_ITEM && ix->items[q->self.idx].test) {+ return false;+ }+ int lo = f->test_first;+ int hi = lo + f->test_count;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (ix->test_lines[mid] < q->link->def_line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return !(lo < f->test_first + f->test_count && ix->test_lines[lo] == q->link->def_line);+}++static const char *rs_label_name(char code) {+ static const struct {+ char code;+ const char *label;+ } table[] = {+ {'S', "Struct"}, {'E', "Enum"}, {'C', "Class"}, {'I', "Interface"}, {'T', "Type"},+ {'F', "Function"}, {'V', "Variable"}, {'M', "Method"}, {'D', "Field"},+ };+ for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {+ if (table[i].code == code) {+ return table[i].label;+ }+ }+ return NULL;+}++/* The node of a declaration of file `fi`: looked up by qualified name, and+ * taken only when its label and file are the declaration's (another+ * definition can own that name: a same-named item of another kind, another+ * file's module). */+static const cbm_gbuf_node_t *rs_node(const rs_index_t *ix, const cbm_gbuf_t *graph, int fi,+ const char *label, const char *qn) {+ const cbm_gbuf_node_t *n = (label && qn) ? cbm_gbuf_find_by_qn(graph, qn) : NULL;+ if (!n || !n->label || !n->file_path || !rs_is(n->label, label) ||+ !rs_is(n->file_path, ix->files[fi].rel_path)) {+ return NULL;+ }+ return n;+}++static const cbm_gbuf_node_t *rs_decl_node(const rs_index_t *ix, const cbm_gbuf_t *graph, int fi,+ char label, const char *suffix) {+ char qn[RS_QN_BUF];+ if (!label || !suffix ||+ snprintf(qn, sizeof(qn), "%s%s", ix->files[fi].item_prefix, suffix) >= (int)sizeof(qn)) {+ return NULL;+ }+ return rs_node(ix, graph, fi, rs_label_name(label), qn);+}++/* The outcome for the one entity a reference names. */+static void rs_outcome(const rs_link_t *q, const cbm_gbuf_t *graph, rs_ent_t e,+ cbm_doclink_outcome_t *out) {+ const rs_index_t *ix = q->ix;+ const cbm_gbuf_node_t *node = NULL;+ bool product = true;+ out->reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ if (e.kind == RS_E_ITEM) {+ const rs_item_t *it = &ix->items[e.idx];+ product = ix->mods[it->mod].product && !it->test;+ node = rs_decl_node(ix, graph, it->file, it->label, it->suffix);+ } else if (e.kind == RS_E_MEMBER) {+ const rs_member_t *m = &ix->members[e.idx];+ product = ix->mods[m->mod].product && !m->owner_test;+ node = rs_decl_node(ix, graph, m->file, m->label, m->suffix);+ } else if (e.kind == RS_E_MOD) {+ const rs_mod_t *mod = &ix->mods[e.idx];+ product = mod->product;+ node = mod->parent < 0+ ? rs_node(ix, graph, mod->file, "Module", ix->files[mod->file].module_qn)+ : NULL; /* an inline module has no node */+ } else {+ bool external = e.kind == RS_E_EXTERNAL ||+ (e.kind == RS_E_IMPL && ix->impls[e.idx].self_ent.kind == RS_E_EXTERNAL);+ out->reason = external ? CBM_DOCLINK_REASON_EXTERNAL : CBM_DOCLINK_REASON_GRAPH_GAP;+ return;+ }+ if (q->product && !product) {+ out->reason = CBM_DOCLINK_REASON_TEST_ONLY;+ } else if (node) {+ out->kind = CBM_DOCLINK_EDGE;+ out->target = node;+ }+}++/* The namespaces a disambiguator or suffix asks for. */+static int rs_dis_mask(int dis) {+ switch (dis) {+ case CBM_DOCLINK_RS_DIS_NONE:+ return RS_NS_ALL;+ case CBM_DOCLINK_RS_DIS_CONST:+ case CBM_DOCLINK_RS_DIS_STATIC:+ case CBM_DOCLINK_RS_DIS_FN:+ case CBM_DOCLINK_RS_DIS_FIELD:+ case CBM_DOCLINK_RS_DIS_VALUE_NS:+ return RS_NS_VALUE;+ case CBM_DOCLINK_RS_DIS_DERIVE:+ case CBM_DOCLINK_RS_DIS_MACRO_BANG:+ case CBM_DOCLINK_RS_DIS_MACRO_NS:+ return RS_NS_MACRO;+ default:+ return RS_NS_TYPE;+ }+}++/* The item kinds and member kinds a disambiguator accepts ("" for none, NULL+ * for any). */+static void rs_dis_kinds(int dis, const char **items, const char **members, bool *mod) {+ *items = "";+ *members = "";+ *mod = false;+ switch (dis) {+ case CBM_DOCLINK_RS_DIS_NONE:+ case CBM_DOCLINK_RS_DIS_TYPE_NS:+ case CBM_DOCLINK_RS_DIS_VALUE_NS:+ case CBM_DOCLINK_RS_DIS_MACRO_NS:+ *items = NULL;+ *members = NULL;+ *mod = true;+ break;+ case CBM_DOCLINK_RS_DIS_STRUCT:+ *items = "S";+ break;+ case CBM_DOCLINK_RS_DIS_ENUM:+ *items = "E";+ break;+ case CBM_DOCLINK_RS_DIS_TRAIT:+ *items = "R";+ break;+ case CBM_DOCLINK_RS_DIS_UNION:+ *items = "U";+ break;+ case CBM_DOCLINK_RS_DIS_TYALIAS:+ *items = "A";+ break;+ case CBM_DOCLINK_RS_DIS_MOD:+ *mod = true;+ break;+ case CBM_DOCLINK_RS_DIS_CONST:+ *items = "C";+ *members = "c";+ break;+ case CBM_DOCLINK_RS_DIS_STATIC:+ *items = "G";+ break;+ case CBM_DOCLINK_RS_DIS_FN:+ *items = "F";+ *members = "f";+ break;+ case CBM_DOCLINK_RS_DIS_DERIVE:+ *items = "V";+ break;+ case CBM_DOCLINK_RS_DIS_FIELD:+ *members = "d";+ break;+ case CBM_DOCLINK_RS_DIS_VARIANT:+ *members = "v";+ break;+ case CBM_DOCLINK_RS_DIS_MACRO_BANG:+ *items = "MP";+ break;+ default:+ break;+ }+}++/* Drop the candidates of another kind than the disambiguator names. What is+ * outside the repository or not placed has no known kind and stays. */+static void rs_filter_dis(const rs_index_t *ix, rs_set_t *s, int dis) {+ const char *items = NULL;+ const char *members = NULL;+ bool mod = false;+ int w = 0;+ rs_dis_kinds(dis, &items, &members, &mod);+ for (int i = 0; i < s->n; i++) {+ rs_ent_t e = s->v[i];+ bool keep = true;+ if (e.kind == RS_E_ITEM) {+ keep = !items || strchr(items, ix->items[e.idx].kind) != NULL;+ } else if (e.kind == RS_E_MEMBER) {+ keep = !members || strchr(members, ix->members[e.idx].kind) != NULL;+ } else if (e.kind == RS_E_MOD) {+ keep = mod;+ }+ if (keep) {+ s->v[w++] = e;+ }+ }+ s->n = w;+}++/* rustdoc: a trait and a derive macro of one name are the trait. A derive+ * macro of another crate is known only as something external of that name. */+static void rs_trait_wins(const rs_index_t *ix, rs_set_t *s) {+ if (s->overflow || s->n != PAIR_LEN) {+ return;+ }+ for (int i = 0; i < PAIR_LEN; i++) {+ rs_ent_t a = s->v[i];+ rs_ent_t b = s->v[SKIP_ONE - i];+ bool trait = a.kind == RS_E_ITEM && ix->items[a.idx].kind == 'R';+ bool derive =+ b.kind == RS_E_EXTERNAL || (b.kind == RS_E_ITEM && ix->items[b.idx].kind == 'V');+ if (trait && derive) {+ s->v[0] = a;+ s->n = SKIP_ONE;+ return;+ }+ }+}++/* The candidates of a reference: what was really found in any namespace, or,+ * when nothing was, the one weak answer (`*weak`). */+static void rs_candidates(const rs_index_t *ix, const rs_found_t *found, rs_set_t *out,+ bool *weak) {+ uint8_t w = RS_E_NONE;+ for (int k = 0; k < RS_NS_COUNT; k++) {+ const rs_set_t *s = &found->ns[k];+ uint8_t wk = rs_only_weak(s);+ for (int i = 0; i < s->n; i++) {+ if (!s->v[i].weak) {+ rs_set_add(out, s->v[i]);+ }+ }+ out->overflow = out->overflow || s->overflow;+ w = (w == RS_E_GAP || wk == RS_E_NONE) ? w : wk;+ }+ rs_collapse(ix, out);+ *weak = rs_set_empty(out) && w != RS_E_NONE;+ if (*weak) {+ rs_set_add(out, rs_ent(w, 0));+ }+}++/* True when one of the standard derives in the comma-joined list `derives`+ * generates a method `name` (the methods of the trait each one implements:+ * defined by the language). What a derive of another crate generates is not+ * known and is not assumed. */+static bool rs_derive_declares(const char *derives, const char *name) {+ static const struct {+ const char *derive;+ const char *methods; /* each between commas */+ } table[] = {+ {"Clone", ",clone,clone_from,"},+ {"Debug", ",fmt,"},+ {"Default", ",default,"},+ {"PartialEq", ",eq,ne,"},+ {"PartialOrd", ",partial_cmp,lt,le,gt,ge,"},+ {"Ord", ",cmp,max,min,clamp,"},+ {"Hash", ",hash,hash_slice,"},+ };+ char key[CBM_SZ_64];+ if (snprintf(key, sizeof(key), ",%s,", name) >= (int)sizeof(key)) {+ return false;+ }+ for (const char *p = derives; *p;) {+ const char *comma = strchr(p, ',');+ size_t len = comma ? (size_t)(comma - p) : strlen(p);+ for (size_t i = 0; i < sizeof(table) / sizeof(table[0]); i++) {+ if (strlen(table[i].derive) == len && memcmp(table[i].derive, p, len) == 0 &&+ strstr(table[i].methods, key)) {+ return true;+ }+ }+ p = comma ? comma + SKIP_ONE : p + len;+ }+ return false;+}++/* A name no associated item of type `item` carries: is it still declared by+ * something the scan does not show as a member? By a standard derive of the+ * type, or by an impl for no named type (`impl<T: Bound> Trait for T`), or+ * possibly among more impls than are searched. */+static bool rs_assoc_hidden(const rs_index_t *ix, int item, const char *name) {+ rs_ent_t end = rs_alias_end(ix, item);+ if (end.kind != RS_E_ITEM) {+ return false;+ }+ const rs_item_t *it = &ix->items[end.idx];+ if (it->kind != 'S' && it->kind != 'E' && it->kind != 'U') {+ return false;+ }+ return (it->derives && rs_derive_declares(it->derives, name)) ||+ it->impl_count > RS_IMPL_SCAN || cbm_ht_get(ix->blanket, name) != NULL;+}++/* A reference that names nothing that was found. */+static void rs_link_miss(const rs_link_t *q, const rs_set_t *owners, bool mismatch,+ cbm_doclink_outcome_t *out) {+ const char *last = q->segs[q->path.n - SKIP_ONE];+ bool hidden = false;+ for (int i = 0; !mismatch && i < owners->n && !hidden; i++) {+ hidden = owners->v[i].kind == RS_E_ITEM && rs_assoc_hidden(q->ix, owners->v[i].idx, last);+ }+ if (hidden) {+ out->reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ } else if (!mismatch && q->single && rs_is_local(q, q->segs[0])) {+ out->kind = CBM_DOCLINK_LOCAL;+ }+}++static void rs_link_decide(const rs_link_t *q, const cbm_gbuf_t *graph,+ cbm_doclink_outcome_t *out) {+ const rs_index_t *ix = q->ix;+ rs_look_t lk = {.ix = ix, .assoc = true};+ rs_found_t found;+ rs_set_t cand = {0};+ bool weak = false;+ bool prim = q->single && RS_IN(RS_PRIMITIVES, q->segs[0]);+ bool any_type = q->dis == CBM_DOCLINK_RS_DIS_NONE || q->dis == CBM_DOCLINK_RS_DIS_TYPE_NS;+ rs_resolve_path(&lk, q->mod, &q->path, rs_dis_mask(q->dis), q->self, CBM_NOT_FOUND, &found);+ if (found.ambiguous) {+ out->reason = CBM_DOCLINK_REASON_AMBIGUOUS;+ return;+ }+ rs_candidates(ix, &found, &cand, &weak);+ if (q->dis == CBM_DOCLINK_RS_DIS_PRIM || (prim && (weak || rs_set_empty(&cand)))) {+ /* a primitive type: rustdoc's fallback when the path names nothing */+ out->reason = prim ? CBM_DOCLINK_REASON_EXTERNAL : CBM_DOCLINK_REASON_MISSING;+ return;+ }+ if (prim && any_type) {+ out->reason = CBM_DOCLINK_REASON_AMBIGUOUS; /* the primitive, or what the name binds */+ return;+ }+ bool had = !rs_set_empty(&cand);+ rs_filter_dis(ix, &cand, q->dis);+ rs_trait_wins(ix, &cand);+ if (cand.overflow || cand.n > SKIP_ONE) {+ out->reason = CBM_DOCLINK_REASON_AMBIGUOUS;+ return;+ }+ if (cand.n == 0) {+ rs_link_miss(q, &found.owners, had, out);+ return;+ }+ rs_outcome(q, graph, cand.v[0], out);+ out->exact = !q->single || cand.v[0].via_import;+ if (weak && cand.v[0].kind == RS_E_GAP && q->single && rs_is_local(q, q->segs[0])) {+ out->kind = CBM_DOCLINK_LOCAL;+ }+}++/* One reference of run file `run_file`. */+static void rs_resolve(const void *index, void *state, int run_file, const CBMDocLink *link,+ const cbm_gbuf_t *graph, cbm_doclink_outcome_t *out) {+ (void)state; /* Rust keeps no per-file working state */+ const rs_index_t *ix = (const rs_index_t *)index;+ CBMDocLinkRsPath parsed;+ out->kind = CBM_DOCLINK_UNRESOLVED;+ out->reason = CBM_DOCLINK_REASON_MISSING;+ out->target = NULL;+ out->exact = false;+ if (!ix || !link || !link->raw || run_file < 0 || run_file >= ix->run_count ||+ ix->run_to_file[run_file] < 0) {+ return;+ }+ const rs_file_t *f = &ix->files[ix->run_to_file[run_file]];+ if (f->kind != RS_FILE_SOURCE) {+ return;+ }+ if (cbm_doclink_rs_parse_path(link->raw, strlen(link->raw), false, &parsed) !=+ CBM_DOCLINK_RS_PATH_OK) {+ out->reason = CBM_DOCLINK_REASON_UNPARSEABLE;+ return;+ }+ rs_link_t q = {.ix = ix,+ .f = f,+ .link = link,+ .dis = parsed.dis,+ .file_level = (link->flags & CBM_DOCLINK_FLAG_FILE) != 0};+ if (!q.file_level && f->err_line && link->def_line >= f->err_line) {+ /* the definition lies where the file no longer parses: its scope is not known */+ out->reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ return;+ }+ for (int i = 0; i < parsed.nsegs; i++) {+ q.segs[i] = rs_plain(parsed.segs[i]);+ }+ q.path = (rs_path_t){.segs = q.segs, .n = parsed.nsegs, .global = parsed.global};+ q.single = parsed.nsegs == SKIP_ONE && !parsed.global && !rs_is_keyword(q.segs[0]);+ q.mod = q.file_level ? f->mod_base : rs_mod_at(ix, f, link->def_line);+ if (!q.file_level) {+ q.self = rs_self_at(ix, f, link->def_line);+ }+ q.product = rs_source_product(&q);+ rs_link_decide(&q, graph, out);+ if (out->kind == CBM_DOCLINK_EDGE && !q.file_level && rs_unowned(ix, f, link)) {+ out->kind = CBM_DOCLINK_UNRESOLVED; /* no node of its own to leave from */+ out->reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ out->target = NULL;+ out->exact = false;+ }+}++/* ── Incremental scope rules ─────────────────────────────────────── */++/* The next line of a blob; false at the end. */+static bool rs_delta_line(const char **cursor, const char **line, size_t *len) {+ const char *p = *cursor;+ if (!p || !*p) {+ return false;+ }+ const char *nl = strchr(p, '\n');+ *line = p;+ *len = nl ? (size_t)(nl - p) : strlen(p);+ *cursor = nl ? nl + SKIP_ONE : p + *len;+ return true;+}++/* The name of an `M start kind name node` line whose member no path can reach+ * under another name: a function, a constant, a type or a field (not a+ * variant, which `use` can rename). The name must be one the incremental+ * route can find in an unresolved reference: ASCII letters, digits and `_`. */+static bool rs_delta_member(const char *line, size_t len, const char **name, size_t *nlen) {+ enum { F_KIND = 2, F_NAME = 3 };+ const char *field[F_NAME + PAIR_LEN];+ int n = 0;+ field[n++] = line;+ for (size_t i = 0; i < len && n < F_NAME + PAIR_LEN; i++) {+ if (line[i] == '\t') {+ field[n++] = line + i + SKIP_ONE;+ }+ }+ if (line[0] != 'M' || n != F_NAME + PAIR_LEN || field[F_NAME] - field[F_KIND] != PAIR_LEN ||+ !strchr("fctd", field[F_KIND][0])) {+ return false;+ }+ const char *s = field[F_NAME];+ size_t sl = (size_t)(field[F_NAME + SKIP_ONE] - s) - SKIP_ONE;+ if (sl > PAIR_LEN && s[0] == 'r' && s[1] == '#') {+ s += PAIR_LEN;+ sl -= PAIR_LEN;+ }+ for (size_t i = 0; i < sl; i++) {+ if (!(isalnum((unsigned char)s[i]) || s[i] == '_')) {+ return false;+ }+ }+ *name = s;+ *nlen = sl;+ return sl > 0;+}++/* Compare a changed file's stored and fresh scopes line by line, in order+ * (both in the persisted form: no line numbers, no per-definition records).+ *+ * Equal scopes leave every other file's resolution alone: other files see a+ * file only through these records.+ *+ * One difference does too: a member (function, constant, type, field of a+ * type, trait or impl) the fresh scope no longer has. A member is reached+ * only by a path that ends in its name, so a reference that depended on it+ * either bound it (an edge into this file: re-resolved with the closure) or+ * names it in its unresolved row: the name is reported.+ *+ * Everything else is GLOBAL: a new or changed line; a removed item, module,+ * import or variant (`use` can bring any of them into another file under+ * another name, so no name finds the references that depended on it); a+ * changed order (same-named declarations own their node by order); and any+ * change of a manifest. */+static int rs_scope_delta(const char *stored, const char *fresh, cbm_doclink_name_fn removed,+ void *ud) {+ const char *sp = stored;+ const char *fp = fresh;+ const char *sl = NULL;+ const char *fl = NULL;+ size_t slen = 0;+ size_t flen = 0;+ bool hs = rs_delta_line(&sp, &sl, &slen);+ bool hf = rs_delta_line(&fp, &fl, &flen);+ while (hs || hf) {+ if (hs && hf && slen == flen && memcmp(sl, fl, slen) == 0) {+ hs = rs_delta_line(&sp, &sl, &slen);+ hf = rs_delta_line(&fp, &fl, &flen);+ continue;+ }+ const char *name = NULL;+ size_t nlen = 0;+ if (!hs || !rs_delta_member(sl, slen, &name, &nlen)) {+ return CBM_DOCLINK_DELTA_GLOBAL;+ }+ if (!removed || !removed(ud, name, nlen)) {+ return CBM_NOT_FOUND;+ }+ hs = rs_delta_line(&sp, &sl, &slen);+ }+ return CBM_DOCLINK_DELTA_LOCAL;+}++const cbm_doclink_resolver_t cbm_doclink_rs_resolver = {+ .langs = {CBM_LANG_RUST, CBM_LANG_TOML},+ .lang_count = 2,+ .scope_tag = CBM_DOCLINK_RS_SCOPE_TAG,+ .build = rs_build,+ .destroy = rs_destroy,+ .resolve = rs_resolve,+ .scope_delta = rs_scope_delta,+};diff --git a/tests/test_doc_mentions_helpers.h b/tests/test_doc_mentions_helpers.hindex 1053912c9..e37ee9368 100644--- a/tests/test_doc_mentions_helpers.h+++ b/tests/test_doc_mentions_helpers.h@@ -438,7 +438,8 @@ static const int DM_HELD_FAMILIES[] = {CBM_DOCLINK_JAVA_SEE, CBM_DOCLINK_JAVA_THROWS,CBM_DOCLINK_JAVA_VALUE, CBM_DOCLINK_KT_KDOC_LINK,CBM_DOCLINK_KT_SEE, CBM_DOCLINK_KT_THROWS,- CBM_DOCLINK_KT_SAMPLE,+ CBM_DOCLINK_KT_SAMPLE, CBM_DOCLINK_RS_INTRA_DOC,+ CBM_DOCLINK_RS_LINK_DEF,};static inline void dm_ship_held_families(void) {diff --git a/tests/test_doc_mentions_rs.c b/tests/test_doc_mentions_rs.cnew file mode 100644index 000000000..95ec05f1a--- /dev/null+++ b/tests/test_doc_mentions_rs.c@@ -0,0 +1,1734 @@+/*+ * test_doc_mentions_rs.c — Rust intra-doc links -> MENTIONS edges.+ *+ * Extraction (internal/cbm/doclink_rs.c): which text is a link, the path+ * grammar, the scope blob of a source file and of a Cargo manifest.+ * Resolution (src/pipeline/doc_links_rs.c): every pipeline test indexes a real+ * fixture through cbm_pipeline_run and reads the published database (helpers:+ * test_doc_mentions_helpers.h).+ */+#include "../src/foundation/compat.h"+#include "test_framework.h"+#include "test_helpers.h"+#include "test_doc_mentions_helpers.h"++/* ── extraction: which text is a link ────────────────────────────── */++/* The token written as `raw` on `line`; NULL when there is none. */+static const CBMDocLink *rs_token_at(const CBMFileResult *r, const char *raw, uint32_t line) {+ for (int i = 0; i < r->doc_links.count; i++) {+ const CBMDocLink *l = &r->doc_links.items[i];+ if (l->line == line && strcmp(l->raw, raw) == 0) {+ return l;+ }+ }+ return NULL;+}++static int rs_tokens_on(const CBMFileResult *r, uint32_t line) {+ int n = 0;+ for (int i = 0; i < r->doc_links.count; i++) {+ n += r->doc_links.items[i].line == line;+ }+ return n;+}++TEST(doc_mentions_rs_tokens) {+ const char *src =+ "//! File doc with [`Alpha`] here.\n" /* 1 */+ "#![allow(dead_code)]\n" /* 2 */+ "//! After an attribute: [beta::Gamma].\n" /* 3 */+ "\n" /* 4 */+ "/// Inline [the text](alpha::Path) and shortcut [`Short`] and [plain::path].\n" /* 5 */+ "/// Collapsed [`Coll`][] and reference [see this][lbl] and [lbl].\n" /* 6 */+ "/// URL [site](https://example.org/a), file [guide](../guide.md), [top](#top).\n" /* 7 */+ "/// Fragment [`Frag#method.x`], image , footnote [^1].\n" /* 8 */+ "/// Code `[NotALink]`, escaped \\[NotThis\\], prose [two words].\n" /* 9 */+ "/// Kinds [struct@Dis], [call()], [mac!], generic [Vec<u8>].\n" /* 10 */+ "/// - [ ] task\n" /* 11 */+ "/// - [x] done\n" /* 12 */+ "/// [!NOTE]\n" /* 13 */+ "/// Backticked [`weird(x)`] and nested [outer [`Inner`] text].\n" /* 14 */+ "///\n" /* 15 */+ "/// ```\n" /* 16 */+ "/// [InFence]\n" /* 17 */+ "/// ```\n" /* 18 */+ "///\n" /* 19 */+ "/// [InIndentedCode]\n" /* 20 */+ "///\n" /* 21 */+ "/// <!-- [InComment] -->\n" /* 22 */+ "/// [lbl]: defined::Target\n" /* 23 */+ "/// [unused]: https://example.org/unused\n" /* 24 */+ "pub struct Documented;\n" /* 25 */+ "\n" /* 26 */+ "//// [FourSlashes]\n" /* 27 */+ "// [PlainComment]\n" /* 28 */+ "pub struct NotDocumented;\n" /* 29 */+ "\n" /* 30 */+ "/** Block doc with [`InBlock`]\n" /* 31 */+ " * and a second line [second::Line].\n" /* 32 */+ " */\n" /* 33 */+ "pub fn block_documented() {}\n"; /* 34 */+ CBMFileResult *r = dm_extract(src, CBM_LANG_RUST, "src/lib.rs");+ ASSERT_NOT_NULL(r);++ /* the file's own doc: marked, with the real line of every doc line (the+ * attribute between them is no doc line) */+ const CBMDocLink *alpha = rs_token_at(r, "Alpha", 1);+ ASSERT_NOT_NULL(alpha);+ ASSERT_EQ(alpha->syntax, CBM_DOCLINK_RS_INTRA_DOC);+ ASSERT_TRUE((alpha->flags & CBM_DOCLINK_FLAG_FILE) != 0);+ const CBMDocLink *gamma = rs_token_at(r, "beta::Gamma", 3);+ ASSERT_NOT_NULL(gamma);+ ASSERT_TRUE((gamma->flags & CBM_DOCLINK_FLAG_FILE) != 0);++ /* an item's doc: inline, shortcut (backticks go), plain shortcut */+ const CBMDocLink *inl = rs_token_at(r, "alpha::Path", 5);+ ASSERT_NOT_NULL(inl);+ ASSERT_EQ(inl->syntax, CBM_DOCLINK_RS_INTRA_DOC);+ ASSERT_EQ(inl->flags & CBM_DOCLINK_FLAG_FILE, 0);+ ASSERT_STR_EQ(inl->source_qn, "p.src.lib.Documented");+ ASSERT_EQ(inl->def_line, 25);+ ASSERT_NOT_NULL(rs_token_at(r, "Short", 5));+ ASSERT_NOT_NULL(rs_token_at(r, "plain::path", 5));+ ASSERT_EQ(rs_tokens_on(r, 5), 3);++ /* collapsed; a label with a definition takes the definition's destination */+ ASSERT_NOT_NULL(rs_token_at(r, "Coll", 6));+ const CBMDocLink *def = rs_token_at(r, "defined::Target", 6);+ ASSERT_NOT_NULL(def);+ ASSERT_EQ(def->syntax, CBM_DOCLINK_RS_LINK_DEF);+ ASSERT_EQ(dm_count_tokens(r, "defined::Target"), 2); /* [see this][lbl] and [lbl] */+ ASSERT_EQ(rs_tokens_on(r, 6), 3);++ /* a URL is the core's href family; a relative file and a page anchor are+ * not harvested */+ const CBMDocLink *url = rs_token_at(r, "https://example.org/a", 7);+ ASSERT_NOT_NULL(url);+ ASSERT_EQ(url->syntax, CBM_DOCLINK_HREF);+ ASSERT_EQ(rs_tokens_on(r, 7), 1);++ /* the fragment is cut; an image and a footnote are no links */+ ASSERT_NOT_NULL(rs_token_at(r, "Frag", 8));+ ASSERT_EQ(rs_tokens_on(r, 8), 1);++ /* a code span, escaped brackets and prose hold no link */+ ASSERT_EQ(rs_tokens_on(r, 9), 0);++ /* disambiguators, suffixes and generics stay in the token */+ ASSERT_NOT_NULL(rs_token_at(r, "struct@Dis", 10));+ ASSERT_NOT_NULL(rs_token_at(r, "call()", 10));+ ASSERT_NOT_NULL(rs_token_at(r, "mac!", 10));+ ASSERT_NOT_NULL(rs_token_at(r, "Vec<u8>", 10));++ /* task markers and an admonition are no links */+ ASSERT_EQ(rs_tokens_on(r, 11), 0);+ ASSERT_EQ(rs_tokens_on(r, 12), 0);+ ASSERT_EQ(rs_tokens_on(r, 13), 0);++ /* backticks make rustdoc keep what it would otherwise drop as prose; of+ * nested brackets the inner pair is the link */+ ASSERT_NOT_NULL(rs_token_at(r, "weird(x)", 14));+ ASSERT_NOT_NULL(rs_token_at(r, "Inner", 14));+ ASSERT_EQ(rs_tokens_on(r, 14), 2);++ /* code blocks, an HTML comment and the definitions themselves */+ ASSERT_EQ(rs_tokens_on(r, 17), 0);+ ASSERT_EQ(rs_tokens_on(r, 20), 0);+ ASSERT_EQ(rs_tokens_on(r, 22), 0);+ ASSERT_EQ(rs_tokens_on(r, 23), 0);+ ASSERT_EQ(rs_tokens_on(r, 24), 0);++ /* `////` and `//` are comments, not documentation */+ ASSERT_NULL(dm_find_token(r, "FourSlashes"));+ ASSERT_NULL(dm_find_token(r, "PlainComment"));++ /* a block doc, its decoration removed */+ const CBMDocLink *blk = rs_token_at(r, "InBlock", 31);+ ASSERT_NOT_NULL(blk);+ ASSERT_STR_EQ(blk->source_qn, "p.src.lib.block_documented");+ ASSERT_NOT_NULL(rs_token_at(r, "second::Line", 32));+ cbm_free_result(r);+ PASS();+}++/* The doc of the first item is the item's, never the file's. */+TEST(doc_mentions_rs_item_doc_is_not_file_doc) {+ const char *src = "/// Outer doc of the first item: [`Target`].\n"+ "pub struct First;\n";+ CBMFileResult *r = dm_extract(src, CBM_LANG_RUST, "src/first.rs");+ ASSERT_NOT_NULL(r);+ const CBMDocLink *t = dm_find_token(r, "Target");+ ASSERT_NOT_NULL(t);+ ASSERT_EQ(t->flags & CBM_DOCLINK_FLAG_FILE, 0);+ ASSERT_STR_EQ(t->source_qn, "p.src.first.First");+ ASSERT_EQ(r->doc_links.count, 1);+ cbm_free_result(r);+ PASS();+}++/* Text nobody controls: nothing here may crash, hang or grow without bound. */+TEST(doc_mentions_rs_untrusted_text) {+ enum { DEEP = 20000, LONG = 1 << 20, LABEL = 700 };+ /* a megabyte destination, a megabyte label, a megabyte of opening brackets,+ * a megabyte of backticks, and a label longer than a token carries */+ char *big = malloc((size_t)LONG * 4 + 4096);+ ASSERT_NOT_NULL(big);+ size_t w = (size_t)snprintf(big, 64, "/// [dest](");+ memset(big + w, 'a', LONG);+ w += LONG;+ w += (size_t)snprintf(big + w, 64, ")\n/// [`");+ memset(big + w, 'b', LONG);+ w += LONG;+ w += (size_t)snprintf(big + w, 64, "`]\n/// ");+ memset(big + w, '[', LONG);+ w += LONG;+ w += (size_t)snprintf(big + w, 64, "\n/// ticks "); /* not at the line start: no fence */+ memset(big + w, '`', LONG);+ w += LONG;+ w += (size_t)snprintf(big + w, 64, "\n///\n/// [`");+ memset(big + w, 'c', LABEL);+ w += LABEL;+ snprintf(big + w, 64, "`]\npub struct Big;\n");+ CBMFileResult *r = dm_extract(big, CBM_LANG_RUST, "src/big.rs");+ ASSERT_NOT_NULL(r);+ /* an over-long destination is one token, cut and marked: it can never+ * parse, so no truncated prefix is ever resolved. A label of more than+ * 999 characters is no link label at all (CommonMark). */+ ASSERT_EQ(r->doc_links.count, 2);+ for (int i = 0; i < r->doc_links.count; i++) {+ const char *raw = r->doc_links.items[i].raw;+ size_t rl = strlen(raw);+ CBMDocLinkRsPath path;+ ASSERT_TRUE(rl < CBM_DOCLINK_RS_RAW_CAP);+ ASSERT_TRUE(raw[0] == (i == 0 ? 'a' : 'c'));+ ASSERT_STR_EQ(raw + rl - 3, "...");+ ASSERT_EQ(cbm_doclink_rs_parse_path(raw, rl, false, &path), CBM_DOCLINK_RS_PATH_MALFORMED);+ }+ cbm_free_result(r);++ /* deeply nested links, lists and block quotes */+ size_t pos = (size_t)snprintf(big, 64, "/// ");+ for (int i = 0; i < DEEP; i++) {+ big[pos++] = '[';+ }+ pos += (size_t)snprintf(big + pos, 64, "`Core`");+ for (int i = 0; i < DEEP; i++) {+ big[pos++] = ']';+ }+ pos += (size_t)snprintf(big + pos, 64, "\n/// ");+ for (int i = 0; i < DEEP; i++) {+ big[pos++] = '>';+ }+ pos += (size_t)snprintf(big + pos, 64, " [`Quoted`]\n/// ");+ for (int i = 0; i < DEEP; i++) {+ big[pos++] = '-';+ big[pos++] = ' ';+ }+ snprintf(big + pos, 64, "[`Listed`]\npub struct Nested;\n");+ r = dm_extract(big, CBM_LANG_RUST, "src/nested.rs");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(dm_find_token(r, "Core"));+ cbm_free_result(r);++ /* bytes that are no UTF-8, and a NUL inside the doc */+ const char bad[] = "/// [`Caf\xC3`] [`\xFF\xFE`] [`Ok`]\n/// [`Af\0ter`]\npub struct Bytes;\n";+ r = cbm_extract_file(bad, (int)sizeof(bad) - 1, CBM_LANG_RUST, "p", "src/bytes.rs", 0, NULL,+ NULL);+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(dm_find_token(r, "Ok"));+ cbm_free_result(r);+ free(big);+ PASS();+}++/* ── extraction: the path grammar (rustdoc's preprocess_link) ────── */++TEST(doc_mentions_rs_parse_path) {+ /* where the grammar decides what is harvested: text in plain brackets+ * that can be no path is prose (no token); the same text in backticks,+ * and a path that is broken, is a link rustdoc reports (a token, which+ * the resolver turns into an `unparseable` row) */+ CBMFileResult *r = dm_extract("/// [a+b] [`c+d`] [bogus@Foo] [Vec<] [x y] [`x y`]\n"+ "pub struct Grammar;\n",+ CBM_LANG_RUST, "src/g.rs");+ ASSERT_NOT_NULL(r);+ ASSERT_NULL(dm_find_token(r, "a+b"));+ ASSERT_NOT_NULL(dm_find_token(r, "c+d"));+ ASSERT_NOT_NULL(dm_find_token(r, "bogus@Foo"));+ ASSERT_NOT_NULL(dm_find_token(r, "Vec<"));+ ASSERT_NULL(dm_find_token(r, "x y"));+ ASSERT_EQ(r->doc_links.count, 3);+ cbm_free_result(r);++ struct {+ const char *raw;+ bool lenient;+ CBMDocLinkRsPathStatus want;+ int nsegs;+ const char *last; /* last segment */+ int dis;+ bool global;+ } cases[] = {+ {"Foo", false, CBM_DOCLINK_RS_PATH_OK, 1, "Foo", CBM_DOCLINK_RS_DIS_NONE, false},+ {"a::b::C", false, CBM_DOCLINK_RS_PATH_OK, 3, "C", CBM_DOCLINK_RS_DIS_NONE, false},+ {"::std::fmt", false, CBM_DOCLINK_RS_PATH_OK, 2, "fmt", CBM_DOCLINK_RS_DIS_NONE, true},+ {" crate::x ", false, CBM_DOCLINK_RS_PATH_OK, 2, "x", CBM_DOCLINK_RS_DIS_NONE, false},+ /* generics are stripped, as rustdoc does */+ {"Vec<T>::new", false, CBM_DOCLINK_RS_PATH_OK, 2, "new", CBM_DOCLINK_RS_DIS_NONE, false},+ {"HashMap<K, V>", false, CBM_DOCLINK_RS_PATH_OK, 1, "HashMap", CBM_DOCLINK_RS_DIS_NONE,+ false},+ /* disambiguators and suffixes */+ {"struct@Foo", false, CBM_DOCLINK_RS_PATH_OK, 1, "Foo", CBM_DOCLINK_RS_DIS_STRUCT, false},+ {"fn@a::run", false, CBM_DOCLINK_RS_PATH_OK, 2, "run", CBM_DOCLINK_RS_DIS_FN, false},+ {"method@T::m", false, CBM_DOCLINK_RS_PATH_OK, 2, "m", CBM_DOCLINK_RS_DIS_FN, false},+ {"mod@x", false, CBM_DOCLINK_RS_PATH_OK, 1, "x", CBM_DOCLINK_RS_DIS_MOD, false},+ {"prim@str", false, CBM_DOCLINK_RS_PATH_OK, 1, "str", CBM_DOCLINK_RS_DIS_PRIM, false},+ {"type@X", false, CBM_DOCLINK_RS_PATH_OK, 1, "X", CBM_DOCLINK_RS_DIS_TYPE_NS, false},+ {"run()", false, CBM_DOCLINK_RS_PATH_OK, 1, "run", CBM_DOCLINK_RS_DIS_FN, false},+ {"vec!", false, CBM_DOCLINK_RS_PATH_OK, 1, "vec", CBM_DOCLINK_RS_DIS_MACRO_BANG, false},+ {"vec![]", false, CBM_DOCLINK_RS_PATH_OK, 1, "vec", CBM_DOCLINK_RS_DIS_MACRO_BANG, false},+ /* a raw identifier, a tuple field, a name that is no ASCII */+ {"r#type", false, CBM_DOCLINK_RS_PATH_OK, 1, "r#type", CBM_DOCLINK_RS_DIS_NONE, false},+ {"Pair::0", false, CBM_DOCLINK_RS_PATH_OK, 2, "0", CBM_DOCLINK_RS_DIS_NONE, false},+ {"Gr\xC3\xB6\xC3\x9F"+ "e",+ false, CBM_DOCLINK_RS_PATH_OK, 1,+ "Gr\xC3\xB6\xC3\x9F"+ "e",+ CBM_DOCLINK_RS_DIS_NONE, false},+ /* rustdoc's spellings of primitive types that are no identifiers */+ {"!", false, CBM_DOCLINK_RS_PATH_OK, 1, "!", CBM_DOCLINK_RS_DIS_NONE, false},+ {"&mut", false, CBM_DOCLINK_RS_PATH_OK, 1, "&mut", CBM_DOCLINK_RS_DIS_NONE, false},+ {"*const", false, CBM_DOCLINK_RS_PATH_OK, 1, "*const", CBM_DOCLINK_RS_DIS_NONE, false},+ /* prose: no link at all */+ {"two words", true, CBM_DOCLINK_RS_PATH_NOT_LINK, 0, NULL, 0, false},+ {"a+b", true, CBM_DOCLINK_RS_PATH_NOT_LINK, 0, NULL, 0, false},+ {"!NOTE", false, CBM_DOCLINK_RS_PATH_NOT_LINK, 0, NULL, 0, false},+ {"", false, CBM_DOCLINK_RS_PATH_NOT_LINK, 0, NULL, 0, false},+ /* a link, but no path */+ {"a+b", false, CBM_DOCLINK_RS_PATH_MALFORMED, 0, NULL, 0, false},+ {"weird(x)", false, CBM_DOCLINK_RS_PATH_MALFORMED, 0, NULL, 0, false},+ {"Vec<", false, CBM_DOCLINK_RS_PATH_MALFORMED, 0, NULL, 0, false},+ {"a:b", false, CBM_DOCLINK_RS_PATH_MALFORMED, 0, NULL, 0, false},+ {"a::", false, CBM_DOCLINK_RS_PATH_MALFORMED, 0, NULL, 0, false},+ {"bogus@Foo", false, CBM_DOCLINK_RS_PATH_MALFORMED, 0, NULL, 0, false},+ {"<T as Tr>::m", false, CBM_DOCLINK_RS_PATH_MALFORMED, 0, NULL, 0, false},+ };+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ CBMDocLinkRsPath p;+ CBMDocLinkRsPathStatus got =+ cbm_doclink_rs_parse_path(cases[i].raw, strlen(cases[i].raw), cases[i].lenient, &p);+ bool ok = got == cases[i].want;+ if (ok && got == CBM_DOCLINK_RS_PATH_OK) {+ ok = p.nsegs == cases[i].nsegs && p.dis == cases[i].dis &&+ p.global == cases[i].global && strcmp(p.segs[p.nsegs - 1], cases[i].last) == 0;+ }+ if (!ok) {+ printf(" [%s]: status %d segs %d dis %d\n", cases[i].raw, (int)got, p.nsegs, p.dis);+ FAIL("path grammar");+ }+ }+ /* more segments than are carried, and a segment longer than is carried */+ char many[256] = "a";+ for (int i = 0; i < CBM_DOCLINK_RS_MAX_SEGS; i++) {+ strcat(many, "::a");+ }+ CBMDocLinkRsPath p;+ ASSERT_EQ(cbm_doclink_rs_parse_path(many, strlen(many), false, &p),+ CBM_DOCLINK_RS_PATH_MALFORMED);+ char wide[CBM_DOCLINK_RS_SEG_CAP + 8];+ memset(wide, 'w', sizeof(wide) - 1);+ wide[sizeof(wide) - 1] = '\0';+ ASSERT_EQ(cbm_doclink_rs_parse_path(wide, strlen(wide), false, &p),+ CBM_DOCLINK_RS_PATH_MALFORMED);+ PASS();+}++/* ── extraction: the scope blob ──────────────────────────────────── */++/* True when the blob holds exactly this line. */+static bool rs_blob_has(const char *blob, const char *line) {+ size_t n = strlen(line);+ for (const char *p = blob; p && *p;) {+ const char *nl = strchr(p, '\n');+ size_t len = nl ? (size_t)(nl - p) : strlen(p);+ if (len == n && memcmp(p, line, n) == 0) {+ return true;+ }+ p = nl ? nl + 1 : NULL;+ }+ return false;+}++TEST(doc_mentions_rs_scope_blob) {+ const char *src = "use std::fmt::{self, Debug as Dbg};\n" /* 1 */+ "pub use crate::shapes::*;\n" /* 2 */+ "extern crate alloc as heap;\n" /* 3 */+ "mod shapes;\n" /* 4 */+ "#[cfg(test)]\n" /* 5 */+ "mod checks;\n" /* 6 */+ "#[path = \"odd/place.rs\"]\n" /* 7 */+ "pub(crate) mod odd;\n" /* 8 */+ "/// A widget: [`Gadget`], [`size`], [`T`].\n" /* 9 */+ "#[derive(Clone, serde::Serialize)]\n" /* 10 */+ "pub struct Widget<T> {\n" /* 11 */+ " pub size: u32,\n" /* 12 */+ " inner: T,\n" /* 13 */+ "}\n" /* 14 */+ "pub enum Kind { Round, Flat }\n" /* 15 */+ "pub struct Pair(pub u32, pub u32);\n" /* 16 */+ "pub trait Draw {\n" /* 17 */+ " const SIDES: u32;\n" /* 18 */+ " type Out;\n" /* 19 */+ " fn draw(&self);\n" /* 20 */+ "}\n" /* 21 */+ "impl<T> Widget<T> {\n" /* 22 */+ " pub const UNIT: u32 = 1;\n" /* 23 */+ " /// Resize by [`factor`].\n" /* 24 */+ " pub fn resize(&mut self, factor: u32) {}\n" /* 25 */+ "}\n" /* 26 */+ "impl<T> Draw for Widget<T> {\n" /* 27 */+ " const SIDES: u32 = 0;\n" /* 28 */+ " type Out = ();\n" /* 29 */+ " fn draw(&self) {}\n" /* 30 */+ "}\n" /* 31 */+ "impl<T: Debug> Draw for T {\n" /* 32 */+ " const SIDES: u32 = 0;\n" /* 33 */+ " type Out = ();\n" /* 34 */+ " fn draw(&self) {}\n" /* 35 */+ "}\n" /* 36 */+ "pub type Alias = shapes::Circle;\n" /* 37 */+ "pub const LIMIT: u32 = 3;\n" /* 38 */+ "pub static NAME: &str = \"\";\n" /* 39 */+ "pub(super) fn helper() {}\n" /* 40 */+ "#[macro_export]\n" /* 41 */+ "macro_rules! declare {\n" /* 42 */+ " ($n:ident) => { pub struct Knob; pub struct $n; };\n" /* 43 */+ "}\n" /* 44 */+ "declare!(Dial);\n" /* 45 */+ "lazy_static! { pub static ref TABLE: u32 = 0; }\n" /* 46 */+ "#[cfg(test)]\n" /* 47 */+ "mod tests {\n" /* 48 */+ " use super::*;\n" /* 49 */+ " fn helper() {}\n" /* 50 */+ "}\n"; /* 51 */+ CBMFileResult *r = dm_extract(src, CBM_LANG_RUST, "src/lib.rs");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ const char *b = r->doc_scope;+ ASSERT_TRUE(strncmp(b, CBM_DOCLINK_RS_SCOPE_TAG "\n", 4) == 0);+ /* imports: a `self` import, a renamed one, a glob, an extern crate */+ ASSERT_TRUE(rs_blob_has(b, "U\t0\t-\ts\tfmt\tstd::fmt"));+ ASSERT_TRUE(rs_blob_has(b, "U\t0\t-\tb\tDbg\tstd::fmt::Debug"));+ ASSERT_TRUE(rs_blob_has(b, "U\t0\tp\tg\t-\tcrate::shapes"));+ ASSERT_TRUE(rs_blob_has(b, "U\t0\t-\tx\theap\talloc"));+ /* `mod x;`: plain, test-only, with a path */+ ASSERT_TRUE(rs_blob_has(b, "D\t0\t-\tshapes\t-"));+ ASSERT_TRUE(rs_blob_has(b, "D\t0\t-t\tchecks\t-"));+ ASSERT_TRUE(rs_blob_has(b, "D\t0\tc\todd\todd/place.rs"));+ /* items with their node, members with theirs, derive names */+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t11\t14\tp\tS\tWidget\tS=\tClone,Serialize"));+ ASSERT_TRUE(rs_blob_has(b, "M\t12\td\tsize\tD:Widget.size"));+ ASSERT_TRUE(rs_blob_has(b, "M\t13\td\tinner\tD:Widget.inner"));+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t15\t15\tp\tE\tKind\tE=\t-"));+ ASSERT_TRUE(rs_blob_has(b, "M\t15\tv\tRound\t!")); /* a variant has no node */+ ASSERT_TRUE(rs_blob_has(b, "M\t0\td\t0\t!")); /* nor has a tuple field */+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t17\t21\tp\tR\tDraw\tI=\t-"));+ ASSERT_TRUE(rs_blob_has(b, "M\t19\tt\tOut\t!"));+ ASSERT_TRUE(rs_blob_has(b, "M\t20\tf\tdraw\tM:Draw.draw"));+ /* impls: inherent, of a trait, and for no named type */+ ASSERT_TRUE(rs_blob_has(b, "I\t0\t22\t26\tWidget\t-"));+ ASSERT_TRUE(rs_blob_has(b, "M\t23\tc\tUNIT\t!")); /* an impl's constant has no node */+ ASSERT_TRUE(rs_blob_has(b, "M\t25\tf\tresize\tM:Widget.resize"));+ ASSERT_TRUE(rs_blob_has(b, "I\t0\t27\t31\tWidget\tDraw"));+ ASSERT_TRUE(rs_blob_has(b, "I\t0\t32\t36\t?\tDraw"));+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t37\t37\tp\tA\tAlias\tT=\tshapes::Circle"));+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t38\t38\tp\tC\tLIMIT\tV=\t-"));+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t39\t39\tp\tG\tNAME\tV=\t-"));+ /* the module-level helper lost its node to the one in `mod tests` (the+ * extractor flattens inline modules) */+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t40\t40\ts\tF\thelper\t!\t-"));+ ASSERT_TRUE(rs_blob_has(b, "T\t1\t50\t50\t-\tF\thelper\tF=\t-"));+ ASSERT_TRUE(rs_blob_has(b, "N\t1\t0\t48\t51\t-t\ttests"));+ ASSERT_TRUE(rs_blob_has(b, "U\t1\t-\tg\t-\tsuper"));+ /* macros: an exported definition and what its body declares by name (the+ * metavariable is no name); the invocation; the name written at it; a+ * `static ref` of a macro body */+ ASSERT_TRUE(rs_blob_has(b, "T\t0\t42\t44\t-e\tM\tdeclare\t!\t-"));+ ASSERT_TRUE(rs_blob_has(b, "W\tdeclare\tKnob"));+ ASSERT_TRUE(rs_blob_has(b, "V\t0\tdeclare"));+ ASSERT_TRUE(rs_blob_has(b, "Q\t0\tDial"));+ ASSERT_TRUE(rs_blob_has(b, "V\t0\tlazy_static"));+ ASSERT_TRUE(rs_blob_has(b, "Q\t0\tTABLE"));+ /* the names local to a documented definition that carries references */+ ASSERT_TRUE(rs_blob_has(b, "P\t11\tT"));+ ASSERT_TRUE(rs_blob_has(b, "P\t25\tT,factor"));+ ASSERT_FALSE(rs_blob_has(b, "B"));++ /* the persisted form: no line numbers, no per-definition records */+ char *portable = cbm_doclink_portable_scope(b);+ ASSERT_NOT_NULL(portable);+ ASSERT_TRUE(rs_blob_has(portable, "T\t0\t0\t0\tp\tS\tWidget\tS=\tClone,Serialize"));+ ASSERT_TRUE(rs_blob_has(portable, "M\t0\tf\tresize\tM:Widget.resize"));+ ASSERT_TRUE(rs_blob_has(portable, "N\t1\t0\t0\t0\t-t\ttests"));+ ASSERT_NULL(strstr(portable, "\nP\t"));+ ASSERT_NULL(strstr(portable, "\nZ\t"));+ cbm_free(CBM_MEM_CLASS_OTHER, portable);+ cbm_free_result(r);+ PASS();+}++/* A parse error: what follows it has no scope, unless the error stayed inside+ * a function body with its delimiters paired. */+TEST(doc_mentions_rs_scope_parse_errors) {+ /* syntax the grammar does not know, inside a body: the items around it+ * are where the tree puts them */+ const char *contained = "pub fn odd() {\n"+ " let x = 1 @@ 2;\n"+ "}\n"+ "pub struct After;\n";+ CBMFileResult *r = dm_extract(contained, CBM_LANG_RUST, "src/a.rs");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT_TRUE(rs_blob_has(r->doc_scope, "T\t0\t4\t4\tp\tS\tAfter\tS=\t-"));+ ASSERT_FALSE(rs_blob_has(r->doc_scope, "B"));+ ASSERT_NULL(strstr(r->doc_scope, "\nE\t"));+ cbm_free_result(r);++ /* an unpaired brace in a body can move every later item boundary: the+ * parser gave up on the whole file, and nothing of it is trusted */+ const char *open = "pub struct Before;\n"+ "pub fn half() {\n"+ " if true {\n"+ "}\n"+ "pub struct Lost;\n";+ r = dm_extract(open, CBM_LANG_RUST, "src/b.rs");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT_TRUE(rs_blob_has(r->doc_scope, "E\t1"));+ ASSERT_TRUE(rs_blob_has(r->doc_scope, "B"));+ ASSERT_NULL(strstr(r->doc_scope, "\nT\t"));+ cbm_free_result(r);++ /* an error between items: what stands before it keeps its scope, what+ * follows is only a name the file may declare somewhere */+ const char *between = "pub struct One;\n"+ "pub struct {\n"+ "pub struct Two;\n";+ r = dm_extract(between, CBM_LANG_RUST, "src/c.rs");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT_TRUE(rs_blob_has(r->doc_scope, "T\t0\t1\t1\tp\tS\tOne\tS=\t-"));+ ASSERT_TRUE(rs_blob_has(r->doc_scope, "E\t2"));+ ASSERT_TRUE(rs_blob_has(r->doc_scope, "Q\t*\tTwo"));+ ASSERT_TRUE(rs_blob_has(r->doc_scope, "B"));+ cbm_free_result(r);+ PASS();+}++TEST(doc_mentions_rs_manifest_blob) {+ const char *toml = "[package]\n"+ "name = \"acme-core\"\n"+ "edition.workspace = true\n"+ "build = \"gen/build.rs\"\n"+ "autobins = false\n"+ "\n"+ "[lib]\n"+ "name = \"acme\"\n"+ "path = \"lib/root.rs\"\n"+ "\n"+ "[[bin]]\n"+ "name = \"tool\"\n"+ "path = \"cli/tool.rs\"\n"+ "\n"+ "[dependencies]\n"+ "serde = \"1\"\n"+ "util = { path = \"../util\" }\n"+ "alias = { package = \"real-name\", path = \"../real\" }\n"+ "shared.workspace = true\n"+ "\n"+ "[dev-dependencies.helper]\n"+ "path = \"../helper\"\n"+ "\n"+ "[target.'cfg(unix)'.dependencies]\n"+ "nix = \"0.29\"\n"+ "\n"+ "[workspace]\n"+ "members = [\"crates/*\"]\n"+ "\n"+ "[workspace.package]\n"+ "edition = \"2021\"\n"+ "\n"+ "[workspace.dependencies]\n"+ "shared = { path = \"crates/shared\" }\n";+ CBMFileResult *r = dm_extract(toml, CBM_LANG_TOML, "crates/core/Cargo.toml");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ const char *b = r->doc_scope;+ ASSERT_TRUE(strncmp(b, CBM_DOCLINK_RS_SCOPE_TAG "\nC\n", 6) == 0);+ ASSERT_TRUE(rs_blob_has(b, "K\tpackage\tname\tacme-core"));+ ASSERT_TRUE(rs_blob_has(b, "K\tpackage\tedition.workspace\ttrue"));+ ASSERT_TRUE(rs_blob_has(b, "K\tpackage\tbuild\tgen/build.rs"));+ ASSERT_TRUE(rs_blob_has(b, "K\tpackage\tautobins\tfalse"));+ ASSERT_TRUE(rs_blob_has(b, "K\tlib\tname\tacme"));+ ASSERT_TRUE(rs_blob_has(b, "K\tlib\tpath\tlib/root.rs"));+ ASSERT_TRUE(rs_blob_has(b, "A\tbin"));+ ASSERT_TRUE(rs_blob_has(b, "a\tpath\tcli/tool.rs"));+ ASSERT_TRUE(rs_blob_has(b, "X\td\tserde\t-\t-"));+ ASSERT_TRUE(rs_blob_has(b, "X\td\tutil\tpath\t../util"));+ ASSERT_TRUE(rs_blob_has(b, "X\td\talias\tpackage\treal-name"));+ ASSERT_TRUE(rs_blob_has(b, "X\td\talias\tpath\t../real"));+ ASSERT_TRUE(rs_blob_has(b, "X\td\tshared\tworkspace\ttrue"));+ ASSERT_TRUE(rs_blob_has(b, "X\tv\thelper\tpath\t../helper"));+ ASSERT_TRUE(rs_blob_has(b, "X\td\tnix\t-\t-"));+ ASSERT_TRUE(rs_blob_has(b, "W"));+ ASSERT_TRUE(rs_blob_has(b, "K\tworkspace.package\tedition\t2021"));+ ASSERT_TRUE(rs_blob_has(b, "X\tw\tshared\tpath\tcrates/shared"));+ cbm_free_result(r);++ /* any other TOML file has no scope */+ r = dm_extract("[package]\nname = \"x\"\n", CBM_LANG_TOML, "config/settings.toml");+ ASSERT_NOT_NULL(r);+ ASSERT_NULL(r->doc_scope);+ cbm_free_result(r);+ PASS();+}++/* ── resolution: the fixture workspace ───────────────────────────── */++typedef struct {+ const char *path;+ const char *text;+} rs_fixture_file_t;++static void rs_write_files(const char *root, const rs_fixture_file_t *files, size_t n) {+ for (size_t i = 0; i < n; i++) {+ th_write_file(TH_PATH(root, files[i].path), files[i].text);+ }+}++/* A workspace of five packages. `core` is the one under test; `util` and+ * `extra` are path dependencies of it; `twin` has a lib and two binaries that+ * share a module; `old` is an edition-2015 crate. */+static void rs_write_workspace(const char *root) {+ static const rs_fixture_file_t files[] = {+ {"Cargo.toml",+ "[workspace]\n"+ "members = [\"crates/core\", \"crates/util\", \"crates/extra\", \"crates/twin\",\n"+ " \"crates/old\"]\n"+ "\n"+ "[workspace.package]\n"+ "edition = \"2021\"\n"+ "\n"+ "[workspace.dependencies]\n"+ "util = { path = \"crates/util\" }\n"},++ /* util: a path dependency, inherited through the workspace table */+ {"crates/util/Cargo.toml", "[package]\nname = \"util\"\nedition = \"2021\"\n"},+ {"crates/util/src/lib.rs", "//! Utilities.\n"+ "mod inner;\n"+ "pub use crate::inner::Hidden as Shown;\n"+ "/// A tool.\n"+ "pub struct Tool;\n"+ "impl Tool {\n"+ " /// Runs.\n"+ " pub fn run(&self) {}\n"+ "}\n"},+ {"crates/util/src/inner.rs", "/// Hidden away.\npub struct Hidden;\n"},++ /* extra: its lib target is named unlike its package */+ {"crates/extra/Cargo.toml", "[package]\nname = \"acme-extra\"\nedition = \"2021\"\n"+ "\n[lib]\nname = \"extra_lib\"\n"},+ {"crates/extra/src/lib.rs", "/// Extra.\npub struct Extra;\n"},++ {"crates/core/Cargo.toml", "[package]\n"+ "name = \"acme-core\"\n"+ "edition.workspace = true\n"+ "\n"+ "[dependencies]\n"+ "util.workspace = true\n"+ "serde = \"1\"\n"+ "acme-extra = { path = \"../extra\" }\n"+ "Option = { package = \"acme-extra\", path = \"../extra\" }\n"},+ {"crates/core/src/lib.rs",+ "//! Crate doc: [`Gadget`] and [shapes::Circle], also [the tool][tool].\n" /* 1 */+ "//! Rotten: [`NoSuchThing`].\n" /* 2 */+ "//!\n"+ "//! [tool]: util::Tool\n"+ "\n"+ "pub mod shapes;\n"+ "pub mod deep;\n"+ "pub mod fake;\n"+ "pub mod shadow;\n"+ "pub mod levels;\n"+ "pub mod char;\n"+ "pub mod first;\n"+ "pub mod chain;\n"+ "pub mod strict;\n"+ "pub mod broken;\n"+ "#[cfg(test)]\n"+ "mod tests_support;\n"+ "#[path = \"elsewhere/odd.rs\"]\n"+ "pub mod odd;\n"+ "pub mod outer_inline {\n"+ " pub mod leaf;\n"+ " /// In an inline module.\n"+ " pub struct InInline;\n"+ "}\n"+ "#[cfg(unix)]\n"+ "#[path = \"imp_unix.rs\"]\n"+ "mod imp;\n"+ "#[cfg(windows)]\n"+ "#[path = \"imp_win.rs\"]\n"+ "mod imp;\n"+ "\n"+ "use fake::*;\n"+ "pub use shapes::Circle;\n"+ "use shapes::Circle as Disc;\n"+ "use util::Tool as Hammer;\n"+ "pub use paint_derive::Paintable;\n"+ "\n"+ "/// A gadget.\n"+ "pub struct Gadget;\n"+ "/// Own shape (the glob brings another one).\n"+ "pub struct Shape;\n"+ "/// A name that is no ASCII.\n"+ "pub struct Gr\xC3\xB6\xC3\x9F"+ "e;\n"+ "/// A trait named like a derive macro.\n"+ "pub trait Paintable {}\n"+ "/// Both a function and a macro.\n"+ "pub fn dual() {}\n"+ "#[macro_export]\n"+ "macro_rules! dual {\n"+ " () => {};\n"+ "}\n"+ "/// Unix.\n"+ "#[cfg(unix)]\n"+ "pub fn plat() {}\n"+ "/// Windows.\n"+ "#[cfg(windows)]\n"+ "pub fn plat() {}\n"+ "/// One of two declarations under cfg.\n"+ "#[cfg(unix)]\n"+ "pub struct Twin;\n"+ "/// The other.\n"+ "#[cfg(not(unix))]\n"+ "pub struct Twin;\n"+ "/// Only for tests.\n"+ "#[cfg(test)]\n"+ "pub fn only_in_tests() {}\n"+ "macro_rules! declare_knob {\n"+ " () => {\n"+ " pub struct Knob;\n"+ " };\n"+ "}\n"+ "declare_knob!();\n"+ "define_things! {\n"+ " pub struct Made;\n"+ "}\n"+ "\n"+ "/// [`Gadget`]\n"+ "pub struct SrcShortcut;\n"+ "/// [the circle](shapes::Circle)\n"+ "pub struct SrcInline;\n"+ "/// [`Circle`][]\n"+ "pub struct SrcCollapsed;\n"+ "/// [the hammer][ham]\n"+ "///\n"+ "/// [ham]: Hammer\n"+ "pub struct SrcLinkDef;\n"+ "/// [`Disc`]\n"+ "pub struct SrcRenamed;\n"+ "/// [site](https://example.org/docs) and [guide](../guide.md)\n"+ "pub struct SrcUrl;\n"+ "/// [`Shape`]\n"+ "pub struct SrcOwnOverGlob;\n"+ "/// [`OnlyInFake`] [`CrateWide`] [`Secret`]\n"+ "pub struct SrcGlob;\n"+ "/// [util::Tool::run] [extra_lib::Extra] [Option::Extra] [serde::Serialize]\n"+ "/// [std::fmt::Debug] [util::Shown]\n"+ "pub struct SrcExtern;\n"+ "/// [`String`] [`u8`] [str::len] [`char`] [prim@char] [mod@char] [prim@Gadget]\n"+ "pub struct SrcStd;\n"+ "/// [crate::shapes::Kind] [self::Gadget] [crate]\n"+ "pub struct SrcKeywords;\n"+ "/// [Circle::area] [Circle::area()] [Circle::radius] [Circle::UNIT]\n"+ "/// [shapes::Kind::Round] [shapes::Draw::draw] [Circle::draw] [shapes::Ring::area]\n"+ "/// [shapes::Ring] [shapes::Pair] [shapes::Pair()] [shapes::Pair::0] [shapes::Bits]\n"+ "/// [Circle::no_such] [Circle::clone] [shapes::Lamp::glow]\n"+ "pub struct SrcMembers;\n"+ "/// [`dual`] [`dual()`] [`dual!`] [fn@dual] [macro@dual]\n"+ "pub struct SrcNamespaces;\n"+ "/// [struct@Gadget] [enum@Gadget] [fn@Gadget] [type@Gadget] [`Paintable`] [`plat`]\n"+ "/// [`Twin`]\n"+ "pub struct SrcKinds;\n"+ "/// [`NoSuchName`] [shapes::NoSuch] [`Gr\xC3\xB6\xC3\x9F"+ "e`] [`\xC3\x9C"+ "bel`]\n"+ "/// [outer_inline] [outer_inline::InInline] [`Knob`] [`Made`]\n"+ "/// [tests_support::Fixture] [`only_in_tests`] [`Circle::area(x)`] [Circle#a#b]\n"+ "/// [imp::Thing]\n"+ "pub struct SrcReasons;\n"+ "/// [deep::pit::Hole] [shapes::round::Ball] [odd::Odd] [outer_inline::leaf::Leaf]\n"+ "pub struct SrcModules;\n"+ "/// [`count`] and [`T`] and [`Gadget`]\n"+ "pub fn src_local<T>(count: u32) {}\n"},+ {"crates/core/src/shapes.rs",+ "pub mod round;\n"+ "/// A circle. [`Self`] [`Self::area`]\n"+ "#[derive(Clone)]\n"+ "pub struct Circle {\n"+ " /// The radius; see [`Circle::area`].\n"+ " pub radius: f64,\n"+ "}\n"+ "impl Circle {\n"+ " /// The unit.\n"+ " pub const UNIT: f64 = 1.0;\n"+ " /// Area from [`Self::radius`]; see [`Draw::draw`], [`Circle::draw`],\n"+ " /// [`Circle::outline`], [`Self::UNIT`].\n"+ " pub fn area(&self) -> f64 {\n"+ " 0.0\n"+ " }\n"+ "}\n"+ "/// Kinds.\n"+ "pub enum Kind {\n"+ " Round,\n"+ " Flat,\n"+ "}\n"+ "/// Draws.\n"+ "pub trait Draw {\n"+ " /// Draw; see [`Self::outline`].\n"+ " fn draw(&self);\n"+ " /// Outline.\n"+ " fn outline(&self) {}\n"+ "}\n"+ "impl Draw for Circle {\n"+ " /// Draws a circle: [`Self::area`].\n"+ " fn draw(&self) {}\n"+ "}\n"+ "/// Alias.\n"+ "pub type Ring = Circle;\n"+ "/// Tuple.\n"+ "pub struct Pair(pub u32, pub u32);\n"+ "/// Bits.\n"+ "pub union Bits {\n"+ " pub a: u32,\n"+ " pub b: f32,\n"+ "}\n"+ "/// A field and a method of one name: the method is what a path names.\n"+ "pub struct Lamp {\n"+ " pub glow: u32,\n"+ "}\n"+ "impl Lamp {\n"+ " /// Glows.\n"+ " pub fn glow(&self) -> u32 {\n"+ " self.glow\n"+ " }\n"+ "}\n"},+ {"crates/core/src/shapes/round.rs",+ "/// A ball: [super::Circle] [super::super::Gadget] [`super::Kind`]\n"+ "pub struct Ball;\n"},+ {"crates/core/src/deep/mod.rs", "pub mod pit;\n"},+ {"crates/core/src/deep/pit.rs", "/// A hole.\npub struct Hole;\n"},+ {"crates/core/src/fake.rs", "/// Decoy shape.\n"+ "pub struct Shape;\n"+ "/// Only here.\n"+ "pub struct OnlyInFake;\n"+ "/// Crate wide.\n"+ "pub(crate) struct CrateWide;\n"+ "struct Secret;\n"},+ {"crates/core/src/shadow.rs", "pub mod util;\n"},+ {"crates/core/src/shadow/util.rs", "/// The shadowing tool.\npub struct Tool;\n"},+ {"crates/core/src/levels.rs", "use crate::shadow::*;\n"+ "/// Own Vec.\n"+ "pub struct Vec;\n"+ "/// [util::Tool] [`Vec`]\n"+ "pub struct LevelGlob;\n"},+ {"crates/core/src/char.rs", "/// In a module named like a primitive type.\n"+ "pub struct Unit;\n"},+ {"crates/core/src/first.rs", "/// [`crate::Gadget`]\npub struct First;\n"},+ {"crates/core/src/chain.rs", "mod a {\n"+ " /// Deep.\n"+ " pub struct Deep;\n"+ "}\n"+ "mod b {\n"+ " pub use super::a::Deep as Mid;\n"+ "}\n"+ "pub use self::b::Mid as Top;\n"+ "mod g1 {\n"+ " pub use super::g2::*;\n"+ "}\n"+ "mod g2 {\n"+ " /// Via globs.\n"+ " pub struct ViaGlobs;\n"+ "}\n"+ "use self::g1::*;\n"+ "mod c1 {\n"+ " pub use super::c2::Loop;\n"+ "}\n"+ "mod c2 {\n"+ " pub use super::c1::Loop;\n"+ "}\n"+ "/// [`Top`] [`ViaGlobs`] [c1::Loop]\n"+ "pub struct ChainUser;\n"},+ {"crates/core/src/strict.rs", "use serde::*;\n"+ "use util::Tool as Wrench;\n"+ "/// [util::Tool] [`Wrench`]\n"+ "pub struct StrictUser;\n"},+ {"crates/core/src/broken.rs", "/// Before the error: [`crate::Gadget`] [`Vec`]\n"+ "pub struct Whole;\n"+ "pub struct {\n"+ "/// After the error: [`crate::Shape`]\n"+ "pub struct Cut;\n"},+ /* declared by no `mod`: an orphan */+ {"crates/core/src/orphan.rs", "/// [crate::Gadget] [`String`] [serde::Serialize]\n"+ "pub struct Orphan;\n"},+ {"crates/core/src/tests_support.rs",+ "/// A fixture: [`crate::Gadget`] [`super::only_in_tests`]\n"+ "pub struct Fixture;\n"},+ {"crates/core/src/elsewhere/odd.rs", "/// Odd.\npub struct Odd;\n"},+ {"crates/core/src/outer_inline/leaf.rs", "/// Leaf.\npub struct Leaf;\n"},+ {"crates/core/src/imp_unix.rs", "/// Unix thing.\npub struct Thing;\n"},+ {"crates/core/src/imp_win.rs", "/// Windows thing.\npub struct Thing;\n"},+ {"crates/core/tests/it.rs", "/// [acme_core::Gadget] [`acme_core::shapes::Circle::area`]\n"+ "fn it_works() {}\n"},++ /* twin: one module file under two crate roots, and a second binary */+ {"crates/twin/Cargo.toml", "[package]\nname = \"twin\"\nedition = \"2021\"\n"},+ {"crates/twin/src/lib.rs", "mod common;\n"+ "/// Only in the lib.\n"+ "pub struct Only;\n"+ "/// In both roots.\n"+ "pub struct Both;\n"},+ {"crates/twin/src/main.rs", "mod common;\n"+ "/// In both roots.\n"+ "pub struct Both;\n"+ "fn main() {}\n"},+ {"crates/twin/src/common.rs", "/// [crate::Only] [crate::Both]\npub struct Shared;\n"},+ {"crates/twin/src/bin/tool.rs", "/// [twin::Only]\npub fn run_tool() {}\n"},++ /* old: no edition key means 2015, where a `use` path starts at the root */+ {"crates/old/Cargo.toml", "[package]\nname = \"old\"\n"},+ {"crates/old/src/lib.rs", "mod a;\nmod b;\n"},+ {"crates/old/src/a.rs", "/// Thing.\npub struct Thing;\n"},+ {"crates/old/src/b.rs", "use a::Thing;\n/// [`Thing`]\npub struct UsesThing;\n"},+ };+ rs_write_files(root, files, sizeof(files) / sizeof(files[0]));+}++/* One edge from the definition ending in `src` to the one ending in `tgt`,+ * with every fragment of `want` (separated by '|') in its properties. */+static bool rs_edge_is(const char *db, const char *src, const char *tgt, const char *want) {+ char props[512];+ char frags[256];+ int n = 0;+ dm_edge(db, src, tgt, props, sizeof(props), &n);+ if (n != 1) {+ printf(" edge %s -> %s: %d found\n", src, tgt, n);+ return false;+ }+ snprintf(frags, sizeof(frags), "%s", want);+ for (char *f = strtok(frags, "|"); f; f = strtok(NULL, "|")) {+ if (!strstr(props, f)) {+ printf(" edge %s -> %s: %s lacks %s\n", src, tgt, props, f);+ return false;+ }+ }+ return true;+}++static bool rs_no_edge(const char *db, const char *src, const char *tgt) {+ char props[512];+ int n = 0;+ dm_edge(db, src, tgt, props, sizeof(props), &n);+ if (n != 0) {+ printf(" edge %s -> %s: %d found, none expected\n", src, tgt, n);+ }+ return n == 0;+}++/* The unresolved row of `raw` in `rel` has this reason ("" for no row). */+static bool rs_row_is(const char *db, const char *rel, const char *raw, const char *want) {+ char reason[64];+ dm_row(db, rel, raw, reason, sizeof(reason), NULL, 0);+ if (strcmp(reason, want) != 0) {+ printf(" row %s [%s]: \"%s\", expected \"%s\"\n", rel, raw, reason, want);+ return false;+ }+ return true;+}++#define RS_SYNTAX_INTRA "\"syntax\":\"intra_doc\""+#define RS_SYNTAX_DEF "\"syntax\":\"link_def\""+#define RS_EXACT "\"tier\":\"exact\""+#define RS_UNIQUE "\"tier\":\"unique\""++/* One indexed copy of the workspace for the resolver tests. */+typedef struct {+ char tmp[256];+ char db[512];+} rs_ws_t;++static bool rs_ws_open(rs_ws_t *ws) {+ snprintf(ws->tmp, sizeof(ws->tmp), "/tmp/cbm_dmrs_XXXXXX");+ if (!cbm_mkdtemp(ws->tmp)) {+ return false;+ }+ rs_write_workspace(ws->tmp);+ snprintf(ws->db, sizeof(ws->db), "%s/ws.db", ws->tmp);+ return dm_index(ws->tmp, ws->db, NULL) == 0;+}++static void rs_ws_close(rs_ws_t *ws) {+ dm_unlink_db(ws->db);+ th_rmtree(ws->tmp);+}++static const char RS_LIB[] = "crates/core/src/lib.rs";++/* The two families, both tiers, and what is no reference at all. */+TEST(doc_mentions_rs_families_and_tiers) {+ rs_ws_t ws;+ ASSERT_TRUE(rs_ws_open(&ws));+ const char *db = ws.db;+ char syntax[64];+ char reason[64];+ /* intra_doc: the destination is written at the link */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcShortcut", "lib.Gadget",+ "\"via\":\"doc_comment\"|" RS_SYNTAX_INTRA "|" RS_UNIQUE+ "|\"count\":1"));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcInline", "shapes.Circle", RS_SYNTAX_INTRA "|" RS_EXACT));+ /* a name bound by a named import is an exact naming */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcCollapsed", "shapes.Circle", RS_SYNTAX_INTRA "|" RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcRenamed", "shapes.Circle", RS_EXACT));+ /* link_def: the destination comes from a link reference definition */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcLinkDef", "util.src.lib.Tool", RS_SYNTAX_DEF "|" RS_EXACT));+ /* a URL is the core's href family; a relative file is not harvested */+ dm_row(db, RS_LIB, "https://example.org/docs", reason, sizeof(reason), syntax, sizeof(syntax));+ ASSERT_STR_EQ(reason, "external");+ ASSERT_STR_EQ(syntax, "href");+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "../guide.md", ""));+ ASSERT_EQ(dm_mentions_from(db, "lib.SrcUrl"), 0);+ /* the definition's own parameter and type parameter: no edge, no row */+ ASSERT_TRUE(rs_edge_is(db, "lib.src_local", "lib.Gadget", RS_UNIQUE));+ ASSERT_EQ(dm_mentions_from(db, "lib.src_local"), 1);+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "count", ""));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "T", ""));+ rs_ws_close(&ws);+ PASS();+}++/* A file's own doc: the File node is the source. */+TEST(doc_mentions_rs_file_level_docs) {+ rs_ws_t ws;+ ASSERT_TRUE(rs_ws_open(&ws));+ const char *db = ws.db;+ const char *file = "core.src.lib.rs.__file__";+ ASSERT_TRUE(+ rs_edge_is(db, file, "core.src.lib.Gadget", RS_SYNTAX_INTRA "|" RS_UNIQUE "|\"line\":1"));+ ASSERT_TRUE(rs_edge_is(db, file, "shapes.Circle", RS_SYNTAX_INTRA "|" RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, file, "util.src.lib.Tool", RS_SYNTAX_DEF "|" RS_EXACT));+ ASSERT_EQ(dm_mentions_from(db, file), 3);+ /* an unresolved one: a row with the file's path and the reference's line */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "NoSuchThing", "missing"));+ ASSERT_EQ(dm_count(db, "SELECT line FROM doc_link_unresolved WHERE raw = 'NoSuchThing'"), 2);+ /* the outer doc of a file's first item belongs to the item */+ ASSERT_TRUE(rs_edge_is(db, "first.First", "core.src.lib.Gadget", RS_EXACT));+ ASSERT_EQ(dm_mentions_from(db, "first.rs.__file__"), 0);+ rs_ws_close(&ws);+ PASS();+}++/* The lookup levels, each with a decoy one level further out. */+TEST(doc_mentions_rs_lookup_levels) {+ rs_ws_t ws;+ ASSERT_TRUE(rs_ws_open(&ws));+ const char *db = ws.db;+ /* level 1 before level 2: the module's own item, not the glob's */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcOwnOverGlob", "core.src.lib.Shape", RS_UNIQUE));+ ASSERT_TRUE(rs_no_edge(db, "lib.SrcOwnOverGlob", "fake.Shape"));+ /* level 2: a glob import brings in what the importing module can see */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcGlob", "fake.OnlyInFake", RS_UNIQUE));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcGlob", "fake.CrateWide", RS_UNIQUE));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Secret", "missing")); /* private to `fake` */+ /* level 2 before level 3: the module a glob brings in, not the crate of+ * the extern prelude named like it */+ ASSERT_TRUE(rs_edge_is(db, "levels.LevelGlob", "shadow.util.Tool", RS_EXACT));+ ASSERT_TRUE(rs_no_edge(db, "levels.LevelGlob", "util.src.lib.Tool"));+ /* level 1 before level 4: the module's own `Vec`, not the prelude's */+ ASSERT_TRUE(rs_edge_is(db, "levels.LevelGlob", "levels.Vec", RS_UNIQUE));+ /* level 3: a path dependency (through the workspace table), a lib target+ * named unlike its package, and a re-export of the dependency */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcExtern", "util.src.lib.Tool.run", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcExtern", "extra.src.lib.Extra", RS_EXACT "|\"count\":2"));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcExtern", "util.src.inner.Hidden", RS_EXACT));+ /* level 3 before level 4: a dependency renamed `Option` is that crate,+ * not the prelude's type (the second of the two references above) */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Option::Extra", ""));+ /* a dependency without a path, and the standard library */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "serde::Serialize", "external"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "std::fmt::Debug", "external"));+ /* level 4: the std prelude and the primitive types */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "String", "external"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "u8", "external"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "str::len", "external"));+ /* a module named like a primitive type: rustdoc wants a disambiguator */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "char", "ambiguous"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "prim@char", "external"));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcStd", "core.src.char", RS_UNIQUE));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "prim@Gadget", "missing"));+ /* a doc-link path does not look past a glob of something outside the+ * repository (its names would silently win); an import path does */+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/strict.rs", "util::Tool", "external"));+ ASSERT_TRUE(rs_edge_is(db, "strict.StrictUser", "util.src.lib.Tool", RS_EXACT));+ rs_ws_close(&ws);+ PASS();+}++/* `crate`, `self`, `super`, `Self`, and what a path walks through. */+TEST(doc_mentions_rs_paths_and_modules) {+ rs_ws_t ws;+ ASSERT_TRUE(rs_ws_open(&ws));+ const char *db = ws.db;+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcKeywords", "shapes.Kind", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcKeywords", "core.src.lib.Gadget", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcKeywords", "core.src.lib", RS_EXACT)); /* the root module */+ /* `super`, twice: the file that declares the module, then the crate root */+ ASSERT_TRUE(rs_edge_is(db, "round.Ball", "shapes.Circle", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "round.Ball", "core.src.lib.Gadget", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "round.Ball", "shapes.Kind", RS_EXACT));+ /* `Self`: the documented type (a reference to itself is no edge), the+ * impl's self type, the trait */+ ASSERT_TRUE(rs_edge_is(db, "shapes.Circle", "shapes.Circle.area", RS_EXACT));+ ASSERT_TRUE(rs_no_edge(db, "shapes.Circle", "shapes.Circle"));+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/shapes.rs", "Self", ""));+ ASSERT_TRUE(rs_edge_is(db, "shapes.Circle.area", "shapes.Circle.radius", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "shapes.Draw.draw", "shapes.Draw.outline", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "shapes.Circle.draw", "shapes.Circle.area", RS_EXACT));+ /* a field's doc */+ ASSERT_TRUE(rs_edge_is(db, "shapes.Circle.radius", "shapes.Circle.area", RS_EXACT));+ /* where `mod x;` files are: beside a mod.rs, under the directory of any+ * other file, at a `#[path]`, under an inline module's directory */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcModules", "deep.pit.Hole", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcModules", "shapes.round.Ball", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcModules", "elsewhere.odd.Odd", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcModules", "outer_inline.leaf.Leaf", RS_EXACT));+ /* two files for one module name under different cfg */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "imp::Thing", "ambiguous"));+ /* imports: a chain of renaming re-exports, a chain of globs, a cycle */+ ASSERT_TRUE(rs_edge_is(db, "chain.ChainUser", "chain.Deep", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "chain.ChainUser", "chain.ViaGlobs", RS_UNIQUE));+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/chain.rs", "c1::Loop", "graph_gap"));+ /* one module file under two crate roots: what one root declares binds,+ * what both declare is ambiguous */+ ASSERT_TRUE(rs_edge_is(db, "common.Shared", "twin.src.lib.Only", RS_EXACT));+ ASSERT_TRUE(rs_row_is(db, "crates/twin/src/common.rs", "crate::Both", "ambiguous"));+ /* a package's other targets see its lib by name */+ ASSERT_TRUE(rs_edge_is(db, "bin.tool.run_tool", "twin.src.lib.Only", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "tests.it.it_works", "core.src.lib.Gadget", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "tests.it.it_works", "shapes.Circle.area", RS_EXACT));+ /* edition 2015: a `use` path starts at the crate root */+ ASSERT_TRUE(rs_edge_is(db, "old.src.b.UsesThing", "old.src.a.Thing", RS_EXACT));+ rs_ws_close(&ws);+ PASS();+}++/* Associated items, namespaces, disambiguators. */+TEST(doc_mentions_rs_members_and_kinds) {+ rs_ws_t ws;+ ASSERT_TRUE(rs_ws_open(&ws));+ const char *db = ws.db;+ /* a method, with and without `()`, and through a type alias: one edge */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcMembers", "shapes.Circle.area", RS_EXACT "|\"count\":3"));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcMembers", "shapes.Circle.radius", RS_EXACT));+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM nodes WHERE label = 'Field' AND "+ "qualified_name LIKE '%.shapes.Circle.radius'"),+ 1);+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcMembers", "shapes.Draw.draw", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcMembers", "shapes.Ring", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcMembers", "shapes.Pair", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcMembers", "shapes.Bits", RS_EXACT));+ /* a field and a method of one name: the method (rustdoc's order) */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcMembers", "shapes.Lamp.glow", RS_EXACT));+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM nodes WHERE label = 'Method' AND "+ "qualified_name LIKE '%.shapes.Lamp.glow'"),+ 1);+ /* an item of a trait impl needs its trait in scope where the link is+ * written: not in lib.rs, but in shapes.rs, where a default item of the+ * trait is found through the impl as well */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Circle::draw", "missing"));+ ASSERT_TRUE(rs_edge_is(db, "shapes.Circle.area", "shapes.Circle.draw", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "shapes.Circle.area", "shapes.Draw.outline", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "shapes.Circle.area", "shapes.Draw.draw", RS_EXACT));+ /* declared, but without a graph node */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Circle::UNIT", "graph_gap")); /* impl constant */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "shapes::Kind::Round", "graph_gap")); /* variant */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "shapes::Pair::0", "graph_gap")); /* tuple field */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Circle::clone", "graph_gap")); /* #[derive(Clone)] */+ /* not declared at all; a tuple struct is no function */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Circle::no_such", "missing"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "shapes::Pair()", "missing"));+ /* a function and a macro of one name */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "dual", "ambiguous"));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcNamespaces", "core.src.lib.dual", "\"count\":2"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "dual!", "graph_gap"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "macro@dual", "graph_gap"));+ /* a disambiguator of another kind is no match */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcKinds", "core.src.lib.Gadget", "\"count\":2"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "enum@Gadget", "missing"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "fn@Gadget", "missing"));+ /* a trait and a derive macro of one name are the trait */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcKinds", "core.src.lib.Paintable", RS_UNIQUE));+ /* declared twice under cfg: one definition with its variants on one node,+ * so the item binds */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "plat", ""));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcKinds", "core.src.lib.plat", RS_UNIQUE));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcKinds", "core.src.lib.Twin", RS_UNIQUE));+ rs_ws_close(&ws);+ PASS();+}++/* Every reason, with the cases that are easy to mislabel. */+TEST(doc_mentions_rs_reasons) {+ rs_ws_t ws;+ ASSERT_TRUE(rs_ws_open(&ws));+ const char *db = ws.db;+ /* missing: nothing of that name where the language looks */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "NoSuchName", "missing"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "shapes::NoSuch", "missing"));+ /* a name that is no ASCII is a name like any other */+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcReasons",+ "lib.Gr\xC3\xB6\xC3\x9F"+ "e",+ RS_UNIQUE));+ ASSERT_TRUE(rs_row_is(db, RS_LIB,+ "\xC3\x9C"+ "bel",+ "missing"));+ /* graph_gap: an inline module has no node, its items have */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "outer_inline", "graph_gap"));+ ASSERT_TRUE(rs_edge_is(db, "lib.SrcReasons", "lib.InInline", RS_EXACT));+ /* graph_gap: declared by a macro, in its body or at the invocation */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Knob", "graph_gap"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Made", "graph_gap"));+ /* test_only_target: product code never binds test code ... */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "tests_support::Fixture", "test_only_target"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "only_in_tests", "test_only_target"));+ /* ... test code binds both */+ ASSERT_TRUE(rs_edge_is(db, "tests_support.Fixture", "core.src.lib.Gadget", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(db, "tests_support.Fixture", "lib.only_in_tests", RS_EXACT));+ /* unparseable: a link whose destination is no path */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Circle::area(x)", "unparseable"));+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "Circle#a#b", "unparseable"));+ /* ambiguous */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "imp::Thing", "ambiguous"));+ /* external */+ ASSERT_TRUE(rs_row_is(db, RS_LIB, "serde::Serialize", "external"));+ /* a file with a parse error: what stands before the error resolves what+ * it can name for sure; a name the file does not show is a gap, not the+ * prelude's; what follows the error has no scope */+ ASSERT_TRUE(rs_edge_is(db, "broken.Whole", "core.src.lib.Gadget", RS_EXACT));+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/broken.rs", "Vec", "graph_gap"));+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/broken.rs", "crate::Shape", "graph_gap"));+ /* a file no crate root reaches: its `crate` is not known, its package is */+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/orphan.rs", "crate::Gadget", "graph_gap"));+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/orphan.rs", "String", "external"));+ ASSERT_TRUE(rs_row_is(db, "crates/core/src/orphan.rs", "serde::Serialize", "external"));+ /* no reason outside the core's set, and none left as an unknown one */+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE reason NOT IN "+ "('missing','ambiguous','external','test_only_target','graph_gap',"+ "'unparseable')"),+ 0);+ rs_ws_close(&ws);+ PASS();+}++/* ── resolution: structure nobody controls ───────────────────────── */++/* Deep nesting, long chains, cycles and crowds: every one resolves or ends+ * in a row; none may hang, crash or pick something at random. */+TEST(doc_mentions_rs_untrusted_structure) {+ enum { DEPTH = 600, CHAIN = 100, CROWD = 3000, RING = 40, BUF = 1 << 20 };+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_dmrs_un_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char *src = malloc(BUF);+ ASSERT_NOT_NULL(src);+ th_write_file(TH_PATH(tmp, "Cargo.toml"), "[package]\nname = \"wild\"\nedition = \"2021\"\n");+ th_write_file(TH_PATH(tmp, "src/lib.rs"),+ "pub mod nest;\npub mod globs;\npub mod ring;\npub mod crowd;\n"+ "/// The root's target.\npub struct Top;\n");++ /* inline modules nested DEPTH deep; the innermost names the root through+ * `crate`, and through more `super`s than a path carries */+ size_t w = 0;+ for (int i = 0; i < DEPTH; i++) {+ w += (size_t)snprintf(src + w, BUF - w, "pub mod m {\n");+ }+ w += (size_t)snprintf(src + w, BUF - w, "/// [crate::Top] [");+ for (int i = 0; i < CBM_DOCLINK_RS_MAX_SEGS + 4; i++) {+ w += (size_t)snprintf(src + w, BUF - w, "super::");+ }+ w += (size_t)snprintf(src + w, BUF - w, "Top]\npub struct Innermost;\n");+ for (int i = 0; i < DEPTH; i++) {+ w += (size_t)snprintf(src + w, BUF - w, "}\n");+ }+ th_write_file(TH_PATH(tmp, "src/nest.rs"), src);++ /* a chain of re-exporting globs longer than is followed, and a short one */+ w = (size_t)snprintf(src, BUF, "use self::g0::*;\nuse self::s0::*;\n");+ for (int i = 0; i < CHAIN; i++) {+ w += (size_t)snprintf(src + w, BUF - w, "mod g%d { pub use super::g%d::*; }\n", i, i + 1);+ }+ w += (size_t)snprintf(src + w, BUF - w,+ "mod g%d { /// Far.\n pub struct Far; }\n"+ "mod s0 { pub use super::s1::*; }\n"+ "mod s1 { /// Near.\n pub struct Near; }\n"+ "/// [`Far`] [`Near`]\npub struct GlobUser;\n",+ CHAIN);+ th_write_file(TH_PATH(tmp, "src/globs.rs"), src);++ /* a ring of imports, each waiting for the next */+ w = 0;+ for (int i = 0; i < RING; i++) {+ w += (size_t)snprintf(src + w, BUF - w, "mod r%d { pub use super::r%d::Round; }\n", i,+ (i + 1) % RING);+ }+ w += (size_t)snprintf(src + w, BUF - w, "/// [r0::Round]\npub struct RingUser;\n");+ th_write_file(TH_PATH(tmp, "src/ring.rs"), src);++ /* thousands of declarations of one name, and of impls of one type */+ w = 0;+ for (int i = 0; i < CROWD; i++) {+ w += (size_t)snprintf(src + w, BUF - w, "#[cfg(c%d)]\npub fn many() {}\n", i);+ }+ w += (size_t)snprintf(src + w, BUF - w, "/// One type, many impls.\npub struct Hub;\n");+ for (int i = 0; i < CROWD; i++) {+ w += (size_t)snprintf(src + w, BUF - w,+ "impl From<[u8; %d]> for Hub {\n"+ " fn from(_: [u8; %d]) -> Self { Hub }\n}\n",+ i, i);+ }+ w += (size_t)snprintf(src + w, BUF - w,+ "/// [`many`] [`Hub::from`] [`Hub`]\n"+ "pub struct CrowdUser;\n");+ th_write_file(TH_PATH(tmp, "src/crowd.rs"), src);+ free(src);++ char db[512];+ snprintf(db, sizeof(db), "%s/wild.db", tmp);+ ASSERT_EQ(dm_index(tmp, db, NULL), 0);+ /* depth is no limit for `crate`; a path of more segments than are carried+ * is no path */+ ASSERT_TRUE(rs_edge_is(db, "nest.Innermost", "src.lib.Top", RS_EXACT));+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/nest.rs' AND reason = 'unparseable'"),+ 1);+ /* a glob chain that is followed, and one that is not: a gap, never a miss */+ ASSERT_TRUE(rs_edge_is(db, "globs.GlobUser", "globs.Near", RS_UNIQUE));+ ASSERT_TRUE(rs_row_is(db, "src/globs.rs", "Far", "graph_gap"));+ /* a cycle of imports is not followed */+ ASSERT_TRUE(rs_row_is(db, "src/ring.rs", "r0::Round", "graph_gap"));+ /* a crowd of one name is ambiguous, whatever its size */+ ASSERT_TRUE(rs_row_is(db, "src/crowd.rs", "many", "ambiguous"));+ ASSERT_TRUE(rs_row_is(db, "src/crowd.rs", "Hub::from", "ambiguous"));+ ASSERT_TRUE(rs_edge_is(db, "crowd.CrowdUser", "crowd.Hub", RS_UNIQUE));+ dm_unlink_db(db);+ th_rmtree(tmp);+ PASS();+}++/* ── which scope changes are repairable file by file ─────────────── */++static int rs_delta(const char *before, const char *after, char *names, size_t cap) {+ return dm_scope_delta(CBM_LANG_RUST, "src/s.rs", before, after, names, cap);+}++#define RS_D_USE "use std::fmt;\n"+#define RS_D_STRUCT "pub struct W {\n pub size: u32,\n pub name: u32,\n}\n"+#define RS_D_IMPL_OPEN "impl W {\n"+#define RS_D_RUN " pub fn run(&self) {}\n"+#define RS_D_STOP " pub fn stop(&self) {}\n"+#define RS_D_LIMIT " pub const LIMIT: u32 = 1;\n"+#define RS_D_IMPL_CLOSE "}\n"+#define RS_D_ENUM "pub enum Kind {\n A,\n B,\n}\n"+#define RS_D_FREE "pub fn free() {}\n"+#define RS_D_OTHER "pub struct Other;\n"+#define RS_D_IMPL RS_D_IMPL_OPEN RS_D_RUN RS_D_STOP RS_D_LIMIT RS_D_IMPL_CLOSE+#define RS_D_TAIL RS_D_ENUM RS_D_FREE RS_D_OTHER++TEST(doc_mentions_rs_scope_delta_rules) {+ const char *base = RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_TAIL;+ struct {+ const char *what;+ const char *after;+ int want;+ const char *names;+ } cases[] = {+ {"unchanged", base, CBM_DOCLINK_DELTA_LOCAL, ""},+ /* the persisted scope carries no line number, no body and no doc */+ {"lines moved", "// moved\n\n" RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, ""},+ {"body edit",+ RS_D_USE RS_D_STRUCT RS_D_IMPL_OPEN+ " pub fn run(&self) {\n let _ = 1;\n }\n" RS_D_STOP RS_D_LIMIT RS_D_IMPL_CLOSE+ RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, ""},+ {"doc edit",+ RS_D_USE "/// Now documented: [`Other`], [`size`].\n" RS_D_STRUCT RS_D_IMPL RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, ""},+ /* a member's own visibility is no part of what a path can name */+ {"method made private",+ RS_D_USE RS_D_STRUCT RS_D_IMPL_OPEN+ " fn run(&self) {}\n" RS_D_STOP RS_D_LIMIT RS_D_IMPL_CLOSE RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, ""},+ /* a removed member is reported by name */+ {"method removed",+ RS_D_USE RS_D_STRUCT RS_D_IMPL_OPEN RS_D_RUN RS_D_LIMIT RS_D_IMPL_CLOSE RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, "stop"},+ {"field removed", RS_D_USE "pub struct W {\n pub size: u32,\n}\n" RS_D_IMPL RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, "name"},+ {"constant removed",+ RS_D_USE RS_D_STRUCT RS_D_IMPL_OPEN RS_D_RUN RS_D_STOP RS_D_IMPL_CLOSE RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, "LIMIT"},+ {"two members removed",+ RS_D_USE "pub struct W {\n pub size: u32,\n}\n" RS_D_IMPL_OPEN RS_D_RUN RS_D_LIMIT+ RS_D_IMPL_CLOSE RS_D_TAIL,+ CBM_DOCLINK_DELTA_LOCAL, "name,stop"},+ /* everything else can re-route references of files with no edge here */+ {"method added",+ RS_D_USE RS_D_STRUCT RS_D_IMPL_OPEN RS_D_RUN RS_D_STOP RS_D_LIMIT+ " pub fn more(&self) {}\n" RS_D_IMPL_CLOSE RS_D_TAIL,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"method renamed",+ RS_D_USE RS_D_STRUCT RS_D_IMPL_OPEN+ " pub fn go(&self) {}\n" RS_D_STOP RS_D_LIMIT RS_D_IMPL_CLOSE RS_D_TAIL,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"members reordered",+ RS_D_USE RS_D_STRUCT RS_D_IMPL_OPEN RS_D_STOP RS_D_RUN RS_D_LIMIT RS_D_IMPL_CLOSE+ RS_D_TAIL,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ /* a variant can be imported under another name: no name finds the+ * references that depended on it */+ {"variant removed",+ RS_D_USE RS_D_STRUCT RS_D_IMPL "pub enum Kind {\n A,\n}\n" RS_D_FREE RS_D_OTHER,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ /* ... and so can every item */+ {"function removed", RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_ENUM RS_D_OTHER,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"type removed", RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_ENUM RS_D_FREE,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"type added", RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_TAIL "pub struct New;\n",+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"item made private", RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_ENUM RS_D_FREE "struct Other;\n",+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"item made test-only",+ RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_ENUM RS_D_FREE "#[cfg(test)]\n" RS_D_OTHER,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"derive added", RS_D_USE "#[derive(Clone)]\n" RS_D_STRUCT RS_D_IMPL RS_D_TAIL,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"import added", RS_D_USE "use std::io;\n" RS_D_STRUCT RS_D_IMPL RS_D_TAIL,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"import removed", RS_D_STRUCT RS_D_IMPL RS_D_TAIL, CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"module declared", RS_D_USE "mod extra;\n" RS_D_STRUCT RS_D_IMPL RS_D_TAIL,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"impl header changed",+ RS_D_USE RS_D_STRUCT+ "impl fmt::Debug for W {\n" RS_D_RUN RS_D_STOP RS_D_LIMIT RS_D_IMPL_CLOSE RS_D_TAIL,+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ /* an impl is more than its members: through it a type takes the+ * default items of a trait, which live in another file */+ {"impl removed", RS_D_USE RS_D_STRUCT RS_D_TAIL, CBM_DOCLINK_DELTA_GLOBAL, NULL},+ /* a parse error where there was none */+ {"parse error", RS_D_USE RS_D_STRUCT RS_D_IMPL RS_D_TAIL "pub struct {\n",+ CBM_DOCLINK_DELTA_GLOBAL, NULL},+ {"file deleted", NULL, CBM_DOCLINK_DELTA_GLOBAL, NULL},+ };+ char names[256];+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ int got = rs_delta(base, cases[i].after, names, sizeof(names));+ if (got != cases[i].want || (cases[i].names && strcmp(names, cases[i].names) != 0)) {+ printf(" %s: delta %d [%s], want %d [%s]\n", cases[i].what, got, names, cases[i].want,+ cases[i].names ? cases[i].names : "any");+ FAIL("scope delta");+ }+ }+ /* a member whose name the incremental route cannot look for in a row+ * (it splits rows at every byte that is no ASCII letter, digit or `_`) */+ const char *wide = "pub struct W {\n pub gr\xC3\xB6\xC3\x9F"+ "e: u32,\n pub b: u32,\n}\n";+ ASSERT_EQ(rs_delta(wide, "pub struct W {\n pub b: u32,\n}\n", names, sizeof(names)),+ CBM_DOCLINK_DELTA_GLOBAL);+ /* a raw identifier is reported as the name a reference writes */+ ASSERT_EQ(rs_delta("pub struct W {\n pub r#type: u32,\n pub b: u32,\n}\n",+ "pub struct W {\n pub b: u32,\n}\n", names, sizeof(names)),+ CBM_DOCLINK_DELTA_LOCAL);+ ASSERT_STR_EQ(names, "type");+ /* a scope that appears is as global as one that leaves */+ ASSERT_EQ(rs_delta(NULL, base, names, sizeof(names)), CBM_DOCLINK_DELTA_GLOBAL);++ /* a manifest: only what the resolver reads of it counts, and every such+ * change is global (it re-scopes the files of its package) */+ const char *toml = "[package]\nname = \"p\"\nedition = \"2021\"\n\n"+ "[dependencies]\nserde = \"1\"\nutil = { path = \"../util\" }\n";+ struct {+ const char *what;+ const char *after;+ int want;+ } manifests[] = {+ {"unchanged", toml, CBM_DOCLINK_DELTA_LOCAL},+ {"comment and version",+ "# a comment\n[package]\nname = \"p\"\nedition = \"2021\"\nversion = \"2.0.0\"\n\n"+ "[dependencies]\nserde = \"2\"\nutil = { path = \"../util\" }\n",+ CBM_DOCLINK_DELTA_LOCAL},+ {"dependency added",+ "[package]\nname = \"p\"\nedition = \"2021\"\n\n"+ "[dependencies]\nserde = \"1\"\nutil = { path = \"../util\" }\nmore = \"1\"\n",+ CBM_DOCLINK_DELTA_GLOBAL},+ {"path changed",+ "[package]\nname = \"p\"\nedition = \"2021\"\n\n"+ "[dependencies]\nserde = \"1\"\nutil = { path = \"../other\" }\n",+ CBM_DOCLINK_DELTA_GLOBAL},+ {"edition changed",+ "[package]\nname = \"p\"\nedition = \"2018\"\n\n"+ "[dependencies]\nserde = \"1\"\nutil = { path = \"../util\" }\n",+ CBM_DOCLINK_DELTA_GLOBAL},+ };+ for (size_t i = 0; i < sizeof(manifests) / sizeof(manifests[0]); i++) {+ int got = dm_scope_delta(CBM_LANG_TOML, "Cargo.toml", toml, manifests[i].after, names,+ sizeof(names));+ if (got != manifests[i].want) {+ printf(" manifest %s: delta %d, want %d\n", manifests[i].what, got, manifests[i].want);+ FAIL("manifest scope delta");+ }+ }+ PASS();+}++/* ── incremental == full ─────────────────────────────────────────── */++static const char RS_INC_LIB[] = "//! The crate: [`Target`].\n"+ "mod a;\n"+ "mod b;\n"+ "mod user;\n"+ "mod rows;\n"+ "pub use a::Target;\n"+ "use b::Other;\n";+static const char RS_INC_LIB_DOC[] = "//! The crate: [`Target`] and [`Other`].\n"+ "mod a;\n"+ "mod b;\n"+ "mod user;\n"+ "mod rows;\n"+ "pub use a::Target;\n"+ "use b::Other;\n";+#define RS_INC_A_HEAD "/// The target.\npub struct Target;\nimpl Target {\n"+#define RS_INC_A_GO " /// Go.\n pub fn go(&self) {}\n"+#define RS_INC_A_STOP " /// Stop.\n pub fn stop(&self) {}\n"+/* two impl blocks with a method of one name: the later one owns the node */+#define RS_INC_A_TWIN1 \+ "impl Target {\n /// Twin.\n pub fn twin(&self) {}\n /// Kept.\n" \+ " pub fn keep(&self) {}\n}\n"+#define RS_INC_A_KEEP "impl Target {\n /// Kept.\n pub fn keep(&self) {}\n}\n"+#define RS_INC_A_TWIN2 "impl Target {\n /// Twin.\n pub fn twin(&self) {}\n}\n"+#define RS_INC_A_DUP "/// A duplicate.\npub struct Dup;\n"+static const char RS_INC_A[] =+ RS_INC_A_HEAD RS_INC_A_GO RS_INC_A_STOP "}\n" RS_INC_A_TWIN1 RS_INC_A_TWIN2 RS_INC_A_DUP;+static const char RS_INC_A_BODY[] =+ RS_INC_A_HEAD " /// Go.\n pub fn go(&self) {\n let _ = 1;\n }\n" RS_INC_A_STOP+ "}\n" RS_INC_A_TWIN1 RS_INC_A_TWIN2 RS_INC_A_DUP;+static const char RS_INC_A_NO_STOP[] = RS_INC_A_HEAD+ " /// Go.\n pub fn go(&self) {\n let _ = 1;\n }\n}\n" RS_INC_A_TWIN1+ RS_INC_A_TWIN2 RS_INC_A_DUP;+static const char RS_INC_A_ONE_TWIN[] = RS_INC_A_HEAD+ " /// Go.\n pub fn go(&self) {\n let _ = 1;\n }\n}\n" RS_INC_A_KEEP+ RS_INC_A_TWIN2 RS_INC_A_DUP;+static const char RS_INC_A_RENAMED[] =+ "/// The target.\npub struct Renamed;\nimpl Renamed {\n" RS_INC_A_GO "}\n" RS_INC_A_DUP;+static const char RS_INC_B[] = "/// A duplicate.\npub struct Dup;\n/// Other.\npub struct Other;\n";+static const char RS_INC_B_NO_DUP[] = "/// Other.\npub struct Other;\n";+static const char RS_INC_USER[] =+ "use crate::a::*;\n"+ "use crate::b::*;\n"+ "/// [`Target`] [`Target::go`] [`Target::stop`] [`Dup`] [`Missing`]\n"+ "pub struct User;\n";+static const char RS_INC_USER_DOC[] =+ "use crate::a::*;\n"+ "use crate::b::*;\n"+ "/// [`Target`] [`Target::go`] [`Target::stop`] [`Dup`] [`Missing`] [`Other`]\n"+ "pub struct User;\n";+/* its only reference is unresolved: it has no edge into the file it names */+static const char RS_INC_ROWS[] = "/// [crate::a::Target::twin]\npub struct Rows;\n";++TEST(doc_mentions_rs_incremental_equals_full) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_dmrs_inc_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char repo[400];+ snprintf(repo, sizeof(repo), "%s/repo", tmp);+ th_write_file(TH_PATH(repo, "Cargo.toml"), "[package]\nname = \"inc\"\nedition = \"2021\"\n");+ th_write_file(TH_PATH(repo, "src/lib.rs"), RS_INC_LIB);+ th_write_file(TH_PATH(repo, "src/a.rs"), RS_INC_A);+ th_write_file(TH_PATH(repo, "src/b.rs"), RS_INC_B);+ th_write_file(TH_PATH(repo, "src/user.rs"), RS_INC_USER);+ th_write_file(TH_PATH(repo, "src/rows.rs"), RS_INC_ROWS);+ char inc_db[512];+ char full_db[512];+ snprintf(inc_db, sizeof(inc_db), "%s/inc.db", tmp);+ snprintf(full_db, sizeof(full_db), "%s/full.db", tmp);+ ASSERT_EQ(dm_index(repo, inc_db, NULL), 0);+ const char *file = "src.lib.rs.__file__";+ const char *user_rs = "src/user.rs";+ /* the preconditions the steps below move away from */+ ASSERT_TRUE(rs_edge_is(inc_db, file, "a.Target", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(inc_db, "user.User", "a.Target", RS_UNIQUE));+ ASSERT_TRUE(rs_edge_is(inc_db, "user.User", "a.Target.go", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(inc_db, "user.User", "a.Target.stop", RS_EXACT));+ ASSERT_TRUE(rs_row_is(inc_db, user_rs, "Dup", "ambiguous")); /* a::Dup and b::Dup */+ ASSERT_TRUE(rs_row_is(inc_db, user_rs, "Missing", "missing"));+ ASSERT_TRUE(rs_row_is(inc_db, "src/rows.rs", "crate::a::Target::twin", "ambiguous"));++ /* a doc edit re-extracts the file alone */+ th_write_file(TH_PATH(repo, "src/user.rs"), RS_INC_USER_DOC);+ ASSERT_EQ(dm_step(repo, inc_db, full_db, "doc edit", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR), 0);+ ASSERT_TRUE(rs_edge_is(inc_db, "user.User", "b.Other", RS_UNIQUE));++ /* a reference in the FILE's own doc, added by an edit of that doc alone */+ th_write_file(TH_PATH(repo, "src/lib.rs"), RS_INC_LIB_DOC);+ ASSERT_EQ(dm_step(repo, inc_db, full_db, "file doc edit", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR),+ 0);+ ASSERT_TRUE(rs_edge_is(inc_db, file, "b.Other", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(inc_db, file, "a.Target", RS_EXACT));++ /* a body edit in a file others point into: its scope is unchanged, the+ * edges into it stand (from an item and from a file's own doc) */+ th_write_file(TH_PATH(repo, "src/a.rs"), RS_INC_A_BODY);+ ASSERT_EQ(+ dm_step(repo, inc_db, full_db, "target body edit", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR),+ 0);+ ASSERT_TRUE(rs_edge_is(inc_db, "user.User", "a.Target.go", RS_EXACT));+ ASSERT_TRUE(rs_edge_is(inc_db, file, "a.Target", RS_EXACT));++ /* a removed member: the file with an edge to it gets a row instead */+ th_write_file(TH_PATH(repo, "src/a.rs"), RS_INC_A_NO_STOP);+ ASSERT_EQ(+ dm_step(repo, inc_db, full_db, "member removed", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR), 0);+ ASSERT_TRUE(rs_no_edge(inc_db, "user.User", "a.Target.stop"));+ ASSERT_TRUE(rs_row_is(inc_db, user_rs, "Target::stop", "missing"));++ /* ... and a file with NO edge into the changed one, whose row names the+ * removed member, is resolved again: two candidates shrink to one */+ th_write_file(TH_PATH(repo, "src/a.rs"), RS_INC_A_ONE_TWIN);+ ASSERT_EQ(dm_step(repo, inc_db, full_db, "twin removed", CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR),+ 0);+ ASSERT_TRUE(rs_edge_is(inc_db, "rows.Rows", "a.Target.twin", RS_EXACT));++ /* a removed item is not repaired file by file: one of two ambiguous+ * candidates goes, the other binds */+ th_write_file(TH_PATH(repo, "src/b.rs"), RS_INC_B_NO_DUP);+ ASSERT_EQ(dm_step(repo, inc_db, full_db, "item removed", CBM_INCREMENTAL_ROUTE_FORCED_FULL), 0);+ ASSERT_TRUE(rs_edge_is(inc_db, "user.User", "a.Dup", RS_UNIQUE));++ /* renaming a target */+ th_write_file(TH_PATH(repo, "src/a.rs"), RS_INC_A_RENAMED);+ ASSERT_EQ(dm_step(repo, inc_db, full_db, "rename", CBM_INCREMENTAL_ROUTE_FORCED_FULL), 0);+ ASSERT_TRUE(rs_row_is(inc_db, user_rs, "Target", "missing"));+ ASSERT_TRUE(rs_row_is(inc_db, "src/lib.rs", "Target", "graph_gap")); /* `pub use a::Target` */+ ASSERT_TRUE(rs_edge_is(inc_db, file, "b.Other", RS_EXACT));++ /* the manifest scopes every file of its package */+ th_write_file(+ TH_PATH(repo, "Cargo.toml"),+ "[package]\nname = \"inc\"\nedition = \"2021\"\n\n[dependencies]\nserde = \"1\"\n");+ ASSERT_EQ(dm_step(repo, inc_db, full_db, "manifest", CBM_INCREMENTAL_ROUTE_FORCED_FULL), 0);++ /* deleting a file others point into */+ ASSERT_EQ(unlink(TH_PATH(repo, "src/b.rs")), 0);+ ASSERT_EQ(dm_step(repo, inc_db, full_db, "delete file", CBM_INCREMENTAL_ROUTE_FORCED_FULL), 0);+ ASSERT_TRUE(rs_no_edge(inc_db, "user.User", "b.Other"));+ ASSERT_EQ(dm_mentions_from(inc_db, file), 0);++ dm_unlink_db(inc_db);+ dm_unlink_db(full_db);+ th_rmtree(tmp);+ PASS();+}++/* ── the parallel path == the sequential path ────────────────────── */++enum { RS_RING = 64 }; /* above MIN_FILES_FOR_PARALLEL */++/* Every module documents its successor (through `crate`), a shared target (by+ * a glob, by a path into its methods) and a name nothing declares; the root+ * documents the hub in its own doc. */+static void rs_write_ring_fixture(const char *repo) {+ char path[512];+ char body[1024];+ char lib[8192];+ size_t w = (size_t)snprintf(lib, sizeof(lib), "//! The ring's [`hub::Hub`].\npub mod hub;\n");+ for (int i = 0; i < RS_RING; i++) {+ w += (size_t)snprintf(lib + w, sizeof(lib) - w, "pub mod m%02d;\n", i);+ snprintf(path, sizeof(path), "%s/src/m%02d.rs", repo, i);+ snprintf(body, sizeof(body),+ "use crate::hub::*;\n"+ "/// Next [crate::m%02d::C%02d], shared [`Hub`], [`Hub::run`], [`Nothing%02d`].\n"+ "pub struct C%02d;\n",+ (i + 1) % RS_RING, (i + 1) % RS_RING, i, i);+ th_write_file(path, body);+ }+ th_write_file(TH_PATH(repo, "src/lib.rs"), lib);+ th_write_file(TH_PATH(repo, "src/hub.rs"), "/// The hub.\n"+ "pub struct Hub;\n"+ "impl Hub {\n"+ " /// Runs.\n"+ " pub fn run(&self) {}\n"+ "}\n");+ th_write_file(TH_PATH(repo, "Cargo.toml"), "[package]\nname = \"ring\"\nedition = \"2021\"\n");+}++TEST(doc_mentions_rs_parallel_equals_sequential) {+ char tmp[256];+ snprintf(tmp, sizeof(tmp), "/tmp/cbm_dmrs_par_XXXXXX");+ ASSERT_NOT_NULL(cbm_mkdtemp(tmp));+ char repo[400];+ snprintf(repo, sizeof(repo), "%s/repo", tmp);+ rs_write_ring_fixture(repo);+ char par_db[512];+ char seq_db[512];+ snprintf(par_db, sizeof(par_db), "%s/par.db", tmp);+ snprintf(seq_db, sizeof(seq_db), "%s/seq.db", tmp);+ ASSERT_EQ(dm_workers_agree(repo, par_db, seq_db), 0);+ /* per module: its successor, the hub, the hub's method; the root: the hub */+ ASSERT_EQ(dm_count(par_db, "SELECT COUNT(*) FROM edges WHERE type = 'MENTIONS'"),+ RS_RING * 3 + 1);+ /* per module: the undeclared name */+ ASSERT_EQ(dm_count(par_db, "SELECT COUNT(*) FROM doc_link_unresolved"), RS_RING);+ ASSERT_EQ(dm_count(par_db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE reason = 'missing'"),+ RS_RING);+ dm_unlink_db(par_db);+ dm_unlink_db(seq_db);+ th_rmtree(tmp);+ PASS();+}++SUITE(doc_mentions_rs) {+ dm_ship_held_families();+ RUN_TEST(doc_mentions_rs_tokens);+ RUN_TEST(doc_mentions_rs_item_doc_is_not_file_doc);+ RUN_TEST(doc_mentions_rs_untrusted_text);+ RUN_TEST(doc_mentions_rs_parse_path);+ RUN_TEST(doc_mentions_rs_scope_blob);+ RUN_TEST(doc_mentions_rs_scope_parse_errors);+ RUN_TEST(doc_mentions_rs_manifest_blob);+ RUN_TEST(doc_mentions_rs_families_and_tiers);+ RUN_TEST(doc_mentions_rs_file_level_docs);+ RUN_TEST(doc_mentions_rs_lookup_levels);+ RUN_TEST(doc_mentions_rs_paths_and_modules);+ RUN_TEST(doc_mentions_rs_members_and_kinds);+ RUN_TEST(doc_mentions_rs_reasons);+ RUN_TEST(doc_mentions_rs_untrusted_structure);+ RUN_TEST(doc_mentions_rs_scope_delta_rules);+ RUN_TEST(doc_mentions_rs_incremental_equals_full);+ RUN_TEST(doc_mentions_rs_parallel_equals_sequential);+}diff --git a/tests/test_main.c b/tests/test_main.cindex 746ee2bc3..ae29520be 100644--- a/tests/test_main.c+++ b/tests/test_main.c@@ -1827,6 +1827,7 @@ extern void suite_doc_links_rst(void);extern void suite_doc_links_adoc(void);extern void suite_doc_mentions_go(void);extern void suite_doc_mentions_jvm(void);+extern void suite_doc_mentions_rs(void);extern void suite_infrascan(void);extern void suite_cli(void);extern void suite_agent_clients(void);@@ -2300,6 +2301,7 @@ int main(int argc, char **argv) {RUN_SELECTED_SUITE(doc_links_adoc);RUN_SELECTED_SUITE(doc_mentions_go);RUN_SELECTED_SUITE(doc_mentions_jvm);+ RUN_SELECTED_SUITE(doc_mentions_rs);/* Infrastructure scanning */RUN_SELECTED_SUITE(infrascan);