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(java, kotlin): Javadoc and KDoc references become MENTIONS edges, held until their audit
Martin Vogela1190afbb0f2
diff --git a/Makefile.cbm b/Makefile.cbmindex bee0f531d..29f5896d0 100644--- a/Makefile.cbm+++ b/Makefile.cbm@@ -387,6 +387,7 @@ EXTRACTION_SRCS = \$(CBM_DIR)/pdf/pdf_tables.c \$(CBM_DIR)/pdf/pdf_unicode.c \$(CBM_DIR)/doclink_go.c \+ $(CBM_DIR)/doclink_jvm.c \$(CBM_DIR)/sql_values.c \$(CBM_DIR)/helpers.c \$(CBM_DIR)/cpp_branch_views.c \@@ -514,6 +515,7 @@ PIPELINE_SRCS = \src/pipeline/doc_links_rst.c \src/pipeline/doc_links_adoc.c \src/pipeline/doc_links_go.c \+ src/pipeline/doc_links_jvm.c \src/pipeline/doc_links_msbuild.c \src/pipeline/pass_route_nodes.c \src/pipeline/pass_enrichment.c \@@ -776,7 +778,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_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_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 0d8c1e753..6e58f34c2 100644--- a/internal/cbm/doclink.c+++ b/internal/cbm/doclink.c@@ -190,6 +190,16 @@ static const doclink_lang_t DOCLINK_LANGS[] = {.scan_scope = cbm_doclink_gomod_scan_scope,.scope_tag = CBM_DOCLINK_GO_SCOPE_TAG,.portable_scope = cbm_doclink_go_portable_scope},+ {.lang = CBM_LANG_JAVA,+ .parse_doc = cbm_doclink_java_parse_doc,+ .scan_scope = cbm_doclink_java_scan_scope,+ .scope_tag = CBM_DOCLINK_JVM_SCOPE_TAG,+ .portable_scope = cbm_doclink_jvm_portable_scope},+ {.lang = CBM_LANG_KOTLIN,+ .parse_doc = cbm_doclink_kotlin_parse_doc,+ .scan_scope = cbm_doclink_kotlin_scan_scope,+ .scope_tag = CBM_DOCLINK_JVM_SCOPE_TAG,+ .portable_scope = cbm_doclink_jvm_portable_scope},};static const doclink_lang_t *doclink_lang(CBMLanguage lang) {diff --git a/internal/cbm/doclink.h b/internal/cbm/doclink.hindex ab97ac0f4..c3a94cca3 100644--- a/internal/cbm/doclink.h+++ b/internal/cbm/doclink.h@@ -85,6 +85,16 @@X(CBM_DOCLINK_CS_INHERITDOC, CBM_LANG_CSHARP, "inheritdoc", false, true, "MENTIONS") \/* go (doclink_go.c): [Name] doc links; held until its held-out audit passes */ \X(CBM_DOCLINK_GO_DOC_LINK, CBM_LANG_GO, "doc_link", false, false, "MENTIONS") \+ /* java and kotlin (doclink_jvm.c): Javadoc and KDoc; held until their audit passes */ \+ X(CBM_DOCLINK_JAVA_LINK, CBM_LANG_JAVA, "link", false, false, "MENTIONS") \+ X(CBM_DOCLINK_JAVA_LINKPLAIN, CBM_LANG_JAVA, "linkplain", false, false, "MENTIONS") \+ X(CBM_DOCLINK_JAVA_SEE, CBM_LANG_JAVA, "see", false, false, "MENTIONS") \+ X(CBM_DOCLINK_JAVA_THROWS, CBM_LANG_JAVA, "throws", false, false, "MENTIONS") \+ X(CBM_DOCLINK_JAVA_VALUE, CBM_LANG_JAVA, "value", false, false, "MENTIONS") \+ X(CBM_DOCLINK_KT_KDOC_LINK, CBM_LANG_KOTLIN, "kdoc_link", false, false, "MENTIONS") \+ 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") \/* 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") \@@ -427,5 +437,29 @@ bool cbm_doclink_go_parse_ref(const char *raw, size_t len, CBMDocLinkGoRef *out)/* The Go scope blob (Go files and go.mod files) starts with this tag line. */#define CBM_DOCLINK_GO_SCOPE_TAG "go1"+/* ── Java and Kotlin (doclink_jvm.c) ───────────────────────────────── */++void cbm_doclink_java_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def, const char *doc,+ uint32_t doc_line);+void cbm_doclink_kotlin_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def, const char *doc,+ uint32_t doc_line);+const char *cbm_doclink_java_scan_scope(CBMExtractCtx *ctx);+const char *cbm_doclink_kotlin_scan_scope(CBMExtractCtx *ctx);+char *cbm_doclink_jvm_portable_scope(const char *scope);++/* Normalize one Java parameter type as written in a declaration or in a+ * Javadoc `#member(...)` list: annotations, `final`, type arguments, package+ * and outer-type qualifiers and a trailing parameter name are dropped,+ * `...` becomes `[]`, array brackets stay. "?" when nothing is left. Writes a+ * NUL-terminated string into `out` (truncated at cap) and returns its+ * length. */+size_t cbm_doclink_java_norm_type(const char *in, size_t len, char *out, size_t cap);++/* Java and Kotlin files share one scope tag: one resolver indexes both. */+#define CBM_DOCLINK_JVM_SCOPE_TAG "jvm1"++/* 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#endif /* CBM_DOCLINK_H */diff --git a/internal/cbm/doclink_jvm.c b/internal/cbm/doclink_jvm.cnew file mode 100644index 000000000..b33d37f75--- /dev/null+++ b/internal/cbm/doclink_jvm.c@@ -0,0 +1,2983 @@+/*+ * doclink_jvm.c — Java and Kotlin doc-comment references and the JVM doc-link+ * scope.+ *+ * Tokens.+ * Javadoc: `{@link R}` / `{@link R label}`, `{@linkplain R label}`,+ * `{@value R#F}` (a bare `{@value}` names the documented field itself and is+ * no token), `@see R` at the start of a block-tag line (`@see <a href=..>` is+ * a URL, `@see "text"` is prose), `@throws T` / `@exception T`. Nothing in+ * `{@code}`, `{@literal}`, `{@snippet}` or an HTML comment is a reference.+ * KDoc: `[Name]` and `[text][Name]` in the comment text (not `[text](url)`,+ * not an image, not a `[label]: url` definition, not in a code span or a+ * fenced or indented code block), `@see Name`, `@throws T` / `@exception T`,+ * `@sample qualified.name`. The subject of `@param` / `@property` is the+ * definition's own parameter, never a reference.+ * Only block doc comments (slash, two stars) are read: that is what javadoc+ * and Dokka read.+ *+ * Scope blob (one record per line, tab-separated, first line "jvm1"; records+ * in document order, a member after its type):+ * L lang j Java, k Kotlin+ * P package "" when the file declares none+ * I kind alias target import: s single (alias = the simple+ * name it binds), w on-demand / star,+ * m Java static single (alias = member,+ * target = type), n Java static+ * on-demand (target = type)+ * T start end kind path tparams supers slot own pnames+ * type: c class, i interface, e enum,+ * r record, a annotation, o object,+ * C companion object, t typealias; '!'+ * after the kind when a parse error+ * hides some of its members. path is+ * the dotted LOGICAL path (Outer.Inner),+ * tparams ','-joined, supers '|'-joined+ * as written without type arguments+ * ('?' for one that is no name)+ * M start kind flags owner name tparams sig recv slot own pnames+ * member: c callable, v value. flags: K+ * constructor, p constructor property /+ * record component, n enum constant, i+ * implicit (declared by no text of its+ * own). owner is the index of its T+ * record ('-' for a Kotlin top-level+ * declaration), sig the '|'-joined+ * normalized parameter types ('-' for a+ * value), recv the receiver type of a+ * Kotlin extension+ * Q name a type that is declared, but could not+ * be placed (parse error)+ * X from to lines whose declarations could not be+ * placed+ * slot / own say where the extractor put the declaration's node: slot is the+ * qualified name of its definition relative to the file's module ('=' when it+ * is the logical path, '-' when the declaration has no definition), own is 1+ * when that definition is the one the graph keeps for the qualified name+ * inside this file. Both are read off the extractor's own definitions (same+ * start line, name and kind), so this file models neither the qualified-name+ * scheme nor its collisions: Kotlin flattens nested types and puts class+ * properties at module level, Java names a field after its whole declarator+ * (`MAX = 10`), overloads share one name, and whatever the scheme does next is+ * followed without a change here.+ * pnames (the parameter names of a callable, the primary-constructor+ * parameters of a Kotlin class) and all line numbers serve the file's own+ * references only: the persisted form drops them.+ *+ * Everything is a pure function of the file's bytes. Nesting is the tree's+ * while the tree has no parse error; otherwise it is checked against the+ * braces (see "Braces").+ */+#include "doclink.h"++#include "arena.h"+#include "foundation/constants.h"+#include "foundation/mem_core.h"+#include "helpers.h"+#include "tree_sitter/api.h"++#include <ctype.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++enum {+ JV_SB_INIT = 1024,+ JV_MAX_DEPTH = 128, /* nested type declarations */+ JV_NAME_MAX = 255, /* one identifier */+ JV_TYPE_MAX = 512, /* one written type */+ JV_SLOT_MAX = 512, /* a definition's name relative to its module */+ JV_UINT_DIGITS = 16,+ JV_ITEMS_INIT = 64,+ JV_BRACES_INIT = 1024,+ JV_CHAR_LITERAL_MAX = 12, /* a quoted unicode escape */+ JV_QUOTES = 3, /* """ */+ JV_UTF8_TAIL_MAX = 3,+};++/* ── Small arena string builder ──────────────────────────────────── */++typedef struct {+ CBMArena *a;+ char *buf;+ size_t len;+ size_t cap;+ bool failed;+} jv_sb_t;++static void jv_reserve(jv_sb_t *sb, size_t extra) {+ if (sb->failed || sb->len + extra + SKIP_ONE <= sb->cap) {+ return;+ }+ size_t ncap = sb->cap ? sb->cap : JV_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 jv_putn(jv_sb_t *sb, const char *s, size_t n) {+ jv_reserve(sb, n);+ if (sb->failed) {+ return;+ }+ memcpy(sb->buf + sb->len, s, n);+ sb->len += n;+ sb->buf[sb->len] = '\0';+}++static void jv_puts(jv_sb_t *sb, const char *s) {+ jv_putn(sb, s, strlen(s));+}++static void jv_putc(jv_sb_t *sb, char c) {+ jv_putn(sb, &c, SKIP_ONE);+}++static void jv_putu(jv_sb_t *sb, uint32_t v) {+ char tmp[JV_UINT_DIGITS];+ int n = snprintf(tmp, sizeof(tmp), "%u", v);+ if (n > 0) {+ jv_putn(sb, tmp, (size_t)n);+ }+}++/* ── Characters ──────────────────────────────────────────────────── */++static bool jv_blank(char c) {+ return c == ' ' || c == '\t' || c == '\r' || c == '\n' || c == '\f' || c == '\v';+}++/* Identifier characters: Java and Kotlin identifiers are Unicode, so every+ * byte of a multi-byte character counts. */+static bool jv_ident_start(char c) {+ unsigned char u = (unsigned char)c;+ return isalpha(u) || c == '_' || c == '$' || u >= 0x80;+}++static bool jv_ident_char(char c) {+ unsigned char u = (unsigned char)c;+ return isalnum(u) || c == '_' || c == '$' || u >= 0x80;+}++/* ── Doc text ────────────────────────────────────────────────────── */++/* The text of the block doc comments in `doc` (slash, two stars) without its+ * decoration: every line break stays (a position's line is the doc's first+ * line plus the breaks before it), each continuation line loses its leading+ * blanks, its asterisks and one blank. Line comments and plain block comments+ * between doc comments leave only their line breaks. `nesting`: block+ * comments nest (Kotlin), so a comment written inside the doc is part of its+ * text and its end is not the doc's. */+static char *jv_clean_doc(CBMArena *a, const char *doc, bool nesting, size_t *out_len) {+ size_t n = strlen(doc);+ char *out = (char *)cbm_arena_alloc(a, n + SKIP_ONE);+ if (!out) {+ return NULL;+ }+ size_t w = 0;+ size_t i = 0;+ bool in_doc = false;+ size_t inner = 0; /* comments open inside the doc */+ while (i < n) {+ char c = doc[i];+ if (!in_doc) {+ if (c == '/' && doc[i + 1] == '*' && doc[i + 2] == '*' && doc[i + 3] != '/') {+ in_doc = true;+ inner = 0;+ i += 3;+ while (doc[i] == '*' && doc[i + 1] != '/') {+ i++;+ }+ continue;+ }+ if (c == '\n') {+ out[w++] = '\n';+ }+ i++;+ continue;+ }+ if (nesting && c == '/' && doc[i + 1] == '*') {+ inner++;+ out[w++] = '/';+ out[w++] = '*';+ i += 2;+ continue;+ }+ if (c == '*' && doc[i + 1] == '/') {+ if (inner > 0) {+ inner--;+ out[w++] = '*';+ out[w++] = '/';+ } else {+ in_doc = false;+ }+ i += 2;+ continue;+ }+ if (c == '\n') {+ out[w++] = '\n';+ i++;+ while (doc[i] == ' ' || doc[i] == '\t' || doc[i] == '\r') {+ i++;+ }+ if (doc[i] == '*' && doc[i + 1] != '/') {+ while (doc[i] == '*' && doc[i + 1] != '/') {+ i++;+ }+ if (doc[i] == ' ') {+ i++;+ }+ }+ continue;+ }+ if (c != '\r') {+ out[w++] = c;+ }+ i++;+ }+ out[w] = '\0';+ *out_len = w;+ return out;+}++typedef struct {+ CBMExtractCtx *ctx;+ const CBMDefinition *def;+ const char *t; /* the cleaned doc text */+ size_t n;+} jv_doc_t;++/* Push the reference s[0, len) written on source line `line`: whitespace runs+ * become one blank, control characters go, and a reference longer than any+ * name is cut (on a character boundary) just past CBM_DOCLINK_JVM_REF_MAX,+ * which is how the resolver knows it was oversized. */+static void jv_push(jv_doc_t *d, const char *s, size_t len, uint32_t line, int syntax) {+ size_t cap = (size_t)CBM_DOCLINK_JVM_REF_MAX + JV_UTF8_TAIL_MAX + SKIP_ONE;+ size_t take = len < cap ? len : cap;+ char *raw = (char *)cbm_arena_alloc(d->ctx->arena, take + SKIP_ONE);+ if (!raw) {+ return;+ }+ size_t w = 0;+ bool space = false;+ for (size_t i = 0; i < len && w < take; i++) {+ unsigned char c = (unsigned char)s[i];+ if (c <= ' ') {+ space = w > 0;+ continue;+ }+ if (space && w + SKIP_ONE < take) {+ raw[w++] = ' ';+ }+ space = false;+ raw[w++] = (char)c;+ }+ if (w == take && len > take) {+ /* cut: do not leave half a multi-byte character behind */+ while (w > 0 && ((unsigned char)raw[w - SKIP_ONE] & 0xC0) == 0x80) {+ w--;+ }+ if (w > 0 && (unsigned char)raw[w - SKIP_ONE] >= 0xC0) {+ w--;+ }+ }+ raw[w] = '\0';+ if (w == 0) {+ return;+ }+ CBMDocLink link = {+ .source_qn = d->def->qualified_name,+ .raw = raw,+ .line = line,+ .def_line = d->def->start_line,+ .syntax = (uint16_t)syntax,+ };+ cbm_doclinks_push(&d->ctx->result->doc_links, d->ctx->arena, link);+}++/* Index just past the group opened at s[i] by `open` (nesting groups of the+ * same kind), or n when it does not close. */+static size_t jv_group_end(const char *s, size_t n, size_t i, char open, char close) {+ int depth = 0;+ for (size_t k = i; k < n; k++) {+ if (s[k] == open) {+ depth++;+ } else if (s[k] == close) {+ depth--;+ if (depth == 0) {+ return k + SKIP_ONE;+ }+ }+ }+ return n;+}++static bool jv_word_is(const char *s, size_t len, const char *word) {+ return strlen(word) == len && memcmp(s, word, len) == 0;+}++/* ── Javadoc ─────────────────────────────────────────────────────── */++/* Length of the Javadoc reference at s: a (qualified) type, `#member`,+ * `module/`, type arguments, array brackets and a parameter list. A parameter+ * list that does not close takes the rest (the reference is malformed, and+ * the resolver says so). */+static size_t jv_java_ref_len(const char *s, size_t n) {+ size_t j = 0;+ while (j < n) {+ char c = s[j];+ if (jv_ident_char(c) || c == '.' || c == '#' || c == '/') {+ j++;+ } else if (c == '<') {+ size_t e = jv_group_end(s, n, j, '<', '>');+ if (e >= n && (n == 0 || s[n - SKIP_ONE] != '>')) {+ break;+ }+ j = e;+ } else if (c == '[' && j + SKIP_ONE < n && s[j + SKIP_ONE] == ']') {+ j += PAIR_LEN;+ } else {+ break;+ }+ }+ if (j < n && s[j] == '(') {+ j = jv_group_end(s, n, j, '(', ')');+ }+ return j;+}++/* The reference at s[0, n): what the doc tool reads as one reference. Text+ * glued to it (`Foo,`, `http://x`) makes the whole word the (malformed)+ * reference. Returns its length, 0 when there is none. */+static size_t jv_java_ref(const char *s, size_t n) {+ size_t r = jv_java_ref_len(s, n);+ if (r < n && !jv_blank(s[r])) {+ while (r < n && !jv_blank(s[r])) {+ r++;+ }+ }+ return r;+}++/* The href of an `<a href="...">` at s[0, n): pushed as a URL. */+static void jv_java_href(jv_doc_t *d, const char *s, size_t n, uint32_t line) {+ static const char key[] = "href";+ for (size_t i = 0; i + sizeof(key) <= n && s[i] != '>'; i++) {+ if (memcmp(s + i, key, sizeof(key) - SKIP_ONE) != 0) {+ continue;+ }+ size_t j = i + sizeof(key) - SKIP_ONE;+ while (j < n && (s[j] == ' ' || s[j] == '\t')) {+ j++;+ }+ if (j >= n || s[j] != '=') {+ continue;+ }+ j++;+ while (j < n && (s[j] == ' ' || s[j] == '\t')) {+ j++;+ }+ if (j >= n || (s[j] != '"' && s[j] != '\'')) {+ return;+ }+ char quote = s[j];+ size_t v = j + SKIP_ONE;+ size_t e = v;+ while (e < n && s[e] != quote) {+ e++;+ }+ if (e < n && e > v) {+ jv_push(d, s + v, e - v, line, CBM_DOCLINK_HREF);+ }+ return;+ }+}++/* `@see ...` / `@throws ...`: the rest of the tag's line starts at `i`. */+static void jv_java_block_tag(jv_doc_t *d, size_t i, uint32_t line, bool see) {+ const char *t = d->t;+ while (i < d->n && (t[i] == ' ' || t[i] == '\t')) {+ i++;+ }+ size_t eol = i;+ while (eol < d->n && t[eol] != '\n') {+ eol++;+ }+ if (i >= eol) {+ return;+ }+ if (see && t[i] == '<') {+ jv_java_href(d, t + i, eol - i, line);+ return;+ }+ if (t[i] == '"' || t[i] == '{') {+ return; /* a quoted title; an inline tag is found by the text scan */+ }+ size_t r = jv_java_ref(t + i, eol - i);+ if (r > 0) {+ jv_push(d, t + i, r, line, see ? CBM_DOCLINK_JAVA_SEE : CBM_DOCLINK_JAVA_THROWS);+ }+}++/* An inline tag `{@name body}` whose body is t[b, e) and starts on `line`:+ * its reference. */+static void jv_java_inline(jv_doc_t *d, size_t b, size_t e, uint32_t line, int syntax) {+ const char *t = d->t;+ for (; b < e && jv_blank(t[b]); b++) {+ line += t[b] == '\n';+ }+ if (syntax == CBM_DOCLINK_JAVA_VALUE && b < e && t[b] == '"') {+ /* {@value "format" ref}: the format string is not the reference */+ size_t q = b + SKIP_ONE;+ while (q < e && t[q] != '"') {+ line += t[q] == '\n';+ q++;+ }+ for (b = q < e ? q + SKIP_ONE : e; b < e && jv_blank(t[b]); b++) {+ line += t[b] == '\n';+ }+ }+ size_t r = jv_java_ref(t + b, e - b);+ if (r > 0) {+ jv_push(d, t + b, r, line, syntax);+ }+}++/* An open inline tag. javadoc ends it at the brace that balances its own+ * `{`; braces outside inline tags are plain text and balance nothing. */+typedef struct {+ int syntax; /* a link family, JV_TAG_OTHER, or JV_TAG_TEXT */+ size_t body; /* first byte after the tag's name */+ uint32_t line; /* the line of that byte */+ int depth; /* plain braces open inside it */+} jv_tag_t;++enum {+ JV_TAG_OTHER = -1, /* another inline tag: its body is scanned */+ JV_TAG_TEXT = -2, /* code, literal, snippet: the body is text, not markup */+ JV_TAG_NEST_MAX = 32,+};++/* The kind of the inline tag `{@name`; `next` is the character after the+ * name (a tag named `linkage` is not `link`). */+static int jv_java_tag_kind(const char *name, size_t len, char next) {+ if (jv_word_is(name, len, "code") || jv_word_is(name, len, "literal") ||+ jv_word_is(name, len, "snippet")) {+ return JV_TAG_TEXT;+ }+ if (!jv_blank(next) && next != '}') {+ return JV_TAG_OTHER;+ }+ if (jv_word_is(name, len, "link")) {+ return CBM_DOCLINK_JAVA_LINK;+ }+ if (jv_word_is(name, len, "linkplain")) {+ return CBM_DOCLINK_JAVA_LINKPLAIN;+ }+ if (jv_word_is(name, len, "value")) {+ return CBM_DOCLINK_JAVA_VALUE;+ }+ return JV_TAG_OTHER;+}++/* Past an HTML comment or a CDATA section that starts at t[i] (the doc tool+ * reads no markup in either); i itself when none starts there. Line breaks+ * passed are added to *line. One that never ends takes the rest. */+static size_t jv_skip_hidden(const jv_doc_t *d, size_t i, uint32_t *line) {+ static const struct {+ const char *open;+ const char *close;+ } kinds[] = {{"<!--", "-->"}, {"<![CDATA[", "]]>"}};+ for (size_t k = 0; k < sizeof(kinds) / sizeof(kinds[0]); k++) {+ size_t ol = strlen(kinds[k].open);+ if (d->n - i < ol || memcmp(d->t + i, kinds[k].open, ol) != 0) {+ continue;+ }+ const char *close = strstr(d->t + i + ol, kinds[k].close);+ size_t past = close ? (size_t)(close - d->t) + strlen(kinds[k].close) : d->n;+ for (size_t p = i; p < past; p++) {+ *line += d->t[p] == '\n';+ }+ return past;+ }+ return i;+}++void cbm_doclink_java_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def, const char *doc,+ uint32_t doc_line) {+ /* A field is also emitted as a package-level Variable with the same doc:+ * the Field carries the references. A module declaration is no code+ * definition (its "class" is named like a package). */+ if (!def->label || (strcmp(def->label, "Variable") == 0 && def->parent_class) ||+ (strcmp(def->label, "Class") == 0 && strchr(def->name, '.'))) {+ return;+ }+ CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena;+ jv_doc_t d = {.ctx = ctx, .def = def};+ d.t = jv_clean_doc(scratch, doc, false, &d.n);+ if (!d.t) {+ return;+ }+ const char *t = d.t;+ size_t n = d.n;+ jv_tag_t tags[JV_TAG_NEST_MAX];+ int sp = 0; /* open inline tags */+ uint32_t line = doc_line;+ size_t i = 0;+ bool bol = true; /* only blanks since the line began */+ while (i < n) {+ char c = t[i];+ if (c == '\n') {+ line++;+ bol = true;+ i++;+ continue;+ }+ if (bol && (c == ' ' || c == '\t')) {+ i++;+ continue;+ }+ bool in_text = sp > 0 && tags[sp - SKIP_ONE].syntax == JV_TAG_TEXT;+ if (bol && !in_text && c == '@' && i + SKIP_ONE < n &&+ isalpha((unsigned char)t[i + SKIP_ONE])) {+ /* A block tag. javadoc ends an open {@link ..} (or any inline tag+ * whose content is markup) at it: that tag never closed and is no+ * link. Inside {@code}, {@literal} and {@snippet} an `@` at the+ * start of a line is text (annotations in sample code). */+ size_t e = i + SKIP_ONE;+ while (e < n && isalpha((unsigned char)t[e])) {+ e++;+ }+ const char *name = t + i + SKIP_ONE;+ size_t len = e - i - SKIP_ONE;+ bool gap = e >= n || jv_blank(t[e]);+ if (gap && jv_word_is(name, len, "see")) {+ jv_java_block_tag(&d, e, line, true);+ } else if (gap &&+ (jv_word_is(name, len, "throws") || jv_word_is(name, len, "exception"))) {+ jv_java_block_tag(&d, e, line, false);+ }+ sp = 0;+ bol = false;+ i = e;+ continue;+ }+ bol = false;+ bool text = in_text;+ if (c == '<' && sp == 0) {+ size_t past = jv_skip_hidden(&d, i, &line);+ if (past > i) {+ i = past;+ continue;+ }+ }+ if (c == '{' && !text && i + SKIP_ONE < n && t[i + SKIP_ONE] == '@' &&+ sp < JV_TAG_NEST_MAX) {+ size_t ne = i + PAIR_LEN;+ while (ne < n && isalpha((unsigned char)t[ne])) {+ ne++;+ }+ tags[sp++] = (jv_tag_t){.syntax = jv_java_tag_kind(t + i + PAIR_LEN, ne - i - PAIR_LEN,+ ne < n ? t[ne] : '}'),+ .body = ne,+ .line = line};+ i = ne;+ continue;+ }+ if (c == '{' && sp > 0) {+ tags[sp - SKIP_ONE].depth++;+ } else if (c == '}' && sp > 0) {+ if (tags[sp - SKIP_ONE].depth > 0) {+ tags[sp - SKIP_ONE].depth--;+ } else {+ jv_tag_t done = tags[--sp];+ if (done.syntax > CBM_DOCLINK_NONE) {+ jv_java_inline(&d, done.body, i, done.line, done.syntax);+ }+ }+ }+ i++;+ }+}++/* ── KDoc ────────────────────────────────────────────────────────── */++/* Length of the KDoc link target at s[0, n): a qualified name whose segments+ * are identifiers or backticked names. 0 when s is not exactly one. */+static size_t jv_kdoc_target_len(const char *s, size_t n) {+ size_t i = 0;+ for (;;) {+ if (i < n && s[i] == '`') {+ size_t e = i + SKIP_ONE;+ while (e < n && s[e] != '`' && s[e] != '\n') {+ e++;+ }+ if (e >= n || s[e] != '`' || e == i + SKIP_ONE) {+ return 0;+ }+ i = e + SKIP_ONE;+ } else {+ if (i >= n || !jv_ident_start(s[i]) || s[i] == '$') {+ return 0;+ }+ while (i < n && jv_ident_char(s[i]) && s[i] != '$') {+ i++;+ }+ }+ if (i < n && s[i] == '.') {+ i++;+ continue;+ }+ return i == n ? i : 0;+ }+}++/* A `[...]` group opening at `i` on the line that ends at `eol`: the index of+ * its `]`, or eol when it holds a bracket or does not close on the line. */+static size_t jv_kdoc_bracket_close(const char *t, size_t i, size_t eol) {+ for (size_t k = i + SKIP_ONE; k < eol; k++) {+ if (t[k] == ']') {+ return k;+ }+ if (t[k] == '[') {+ return eol;+ }+ }+ return eol;+}++/* One line of KDoc text. */+typedef struct {+ size_t first; /* its first byte that is no blank */+ size_t eol; /* its end */+ uint32_t line; /* its source line */+} jv_kline_t;++/* `[Name]` / `[text][Name]` at `i`. Returns the index to continue from. */+static size_t jv_kdoc_link(jv_doc_t *d, size_t i, const jv_kline_t *ln) {+ const char *t = d->t;+ size_t eol = ln->eol;+ size_t close = jv_kdoc_bracket_close(t, i, eol);+ if (close >= eol || close == i + SKIP_ONE) {+ return i + SKIP_ONE;+ }+ size_t b = i + SKIP_ONE;+ size_t e = close;+ size_t next = close + SKIP_ONE;+ if (next < eol && t[next] == '(') {+ return next; /* [text](url): a Markdown link, not a code reference */+ }+ if (next < eol && t[next] == '[') {+ size_t close2 = jv_kdoc_bracket_close(t, next, eol);+ if (close2 >= eol) {+ return next;+ }+ if (close2 > next + SKIP_ONE) {+ b = next + SKIP_ONE; /* [text][Name] */+ e = close2;+ }+ next = close2 + SKIP_ONE;+ } else if (next < eol && t[next] == ':' && i == ln->first) {+ return next; /* [label]: url -- a link definition */+ }+ while (b < e && (t[b] == ' ' || t[b] == '\t')) {+ b++;+ }+ while (e > b && (t[e - SKIP_ONE] == ' ' || t[e - SKIP_ONE] == '\t')) {+ e--;+ }+ if (jv_kdoc_target_len(t + b, e - b) > 0) {+ jv_push(d, t + b, e - b, ln->line, CBM_DOCLINK_KT_KDOC_LINK);+ }+ return next;+}++/* The subject of `@see` / `@throws` / `@sample` starting at `i`: one word.+ * Returns the index to continue the line's text scan from. */+static size_t jv_kdoc_subject(jv_doc_t *d, size_t i, const jv_kline_t *ln, int syntax) {+ const char *t = d->t;+ size_t eol = ln->eol;+ while (i < eol && (t[i] == ' ' || t[i] == '\t')) {+ i++;+ }+ size_t e = i;+ while (e < eol && t[e] != ' ' && t[e] != '\t') {+ e++;+ }+ if (e == i) {+ return i;+ }+ size_t b = i;+ size_t w = e;+ if (t[b] == '[') {+ size_t close = jv_kdoc_bracket_close(t, b, eol);+ if (close >= eol) {+ return e;+ }+ b++;+ w = close;+ e = close + SKIP_ONE;+ } else {+ while (w > b && strchr(".,;:", t[w - SKIP_ONE])) {+ w--;+ }+ }+ bool url =+ t[b] == '<' || (w - b > 4 && memcmp(t + b, "http", 4) == 0 && memchr(t + b, ':', w - b));+ if (w > b && !url) {+ jv_push(d, t + b, w - b, ln->line, syntax);+ }+ return e;+}++static int jv_kdoc_tag_syntax(const char *name, size_t len) {+ if (jv_word_is(name, len, "see")) {+ return CBM_DOCLINK_KT_SEE;+ }+ if (jv_word_is(name, len, "throws") || jv_word_is(name, len, "exception")) {+ return CBM_DOCLINK_KT_THROWS;+ }+ if (jv_word_is(name, len, "sample")) {+ return CBM_DOCLINK_KT_SAMPLE;+ }+ return CBM_DOCLINK_NONE;+}++/* Just past the code span that the run of `len` backticks ending before `run`+ * opens: the next run of exactly that many. 0 when the line has none (the+ * backticks are then text). */+static size_t jv_kdoc_span_end(const char *t, size_t run, size_t len, size_t eol) {+ size_t k = run;+ while (k < eol) {+ if (t[k] != '`') {+ k++;+ continue;+ }+ size_t r = k;+ while (r < eol && t[r] == '`') {+ r++;+ }+ if (r - k == len) {+ return r;+ }+ k = r;+ }+ return 0;+}++/* The text of one KDoc line from `i`: code spans and HTML comments are+ * skipped, bracket links pushed. *in_comment: an HTML comment is open (it may+ * have begun on an earlier line). */+static void jv_kdoc_text(jv_doc_t *d, size_t i, const jv_kline_t *ln, bool *in_comment) {+ const char *t = d->t;+ size_t eol = ln->eol;+ /* A run of n backticks was looked for once and the rest of the line has no+ * second one: a later run of n is text as well. Longer runs than a fence+ * are not looked for (they would be searched once per length). */+ bool no_span[JV_QUOTES + SKIP_ONE] = {false};+ while (i < eol) {+ char c = t[i];+ if (*in_comment) {+ if (c == '-' && eol - i >= 3 && t[i + 1] == '-' && t[i + 2] == '>') {+ *in_comment = false;+ i += 3;+ } else {+ i++;+ }+ } else if (c == '\\') {+ i += PAIR_LEN;+ } else if (c == '`') {+ size_t run = i;+ while (run < eol && t[run] == '`') {+ run++;+ }+ size_t len = run - i;+ size_t past =+ (len > JV_QUOTES || no_span[len]) ? 0 : jv_kdoc_span_end(t, run, len, eol);+ if (past == 0 && len <= JV_QUOTES) {+ no_span[len] = true;+ }+ i = past ? past : run;+ } else if (c == '<' && eol - i >= 4 && memcmp(t + i, "<!--", 4) == 0) {+ *in_comment = true;+ i += 4;+ } else if (c == '!' && i + SKIP_ONE < eol && t[i + SKIP_ONE] == '[') {+ /* an image: ``, `![alt][label]` -- its label names no code */+ size_t close = jv_kdoc_bracket_close(t, i + SKIP_ONE, eol);+ i = close < eol ? close + SKIP_ONE : i + PAIR_LEN;+ if (close < eol && i < eol && t[i] == '[') {+ size_t label = jv_kdoc_bracket_close(t, i, eol);+ i = label < eol ? label + SKIP_ONE : i + SKIP_ONE;+ }+ } else if (c == '[') {+ i = jv_kdoc_link(d, i, ln);+ } else {+ i++;+ }+ }+}++/* The width of the code fence (``` or ~~~) a line opens or closes, 0 when it+ * does neither. */+static size_t jv_kdoc_fence(const char *s, size_t n, char *mark) {+ if (n < JV_QUOTES || (s[0] != '`' && s[0] != '~')) {+ return 0;+ }+ size_t k = 0;+ while (k < n && s[k] == s[0]) {+ k++;+ }+ if (k < JV_QUOTES) {+ return 0;+ }+ *mark = s[0];+ return k;+}++enum { JV_KDOC_CODE_INDENT = 4 };++void cbm_doclink_kotlin_parse_doc(CBMExtractCtx *ctx, const CBMDefinition *def, const char *doc,+ uint32_t doc_line) {+ CBMArena *scratch = ctx->scratch ? ctx->scratch : ctx->arena;+ jv_doc_t d = {.ctx = ctx, .def = def};+ d.t = jv_clean_doc(scratch, doc, true, &d.n);+ if (!d.t) {+ return;+ }+ const char *t = d.t;+ size_t n = d.n;+ size_t fence = 0; /* width of the open code fence */+ char fence_mark = 0;+ bool after_blank = true; /* the comment's start counts as a blank line */+ bool in_code = false; /* in an indented code block */+ bool in_comment = false; /* in an HTML comment */+ uint32_t line = doc_line;+ for (size_t ls = 0; ls < n; line++) {+ size_t eol = ls;+ while (eol < n && t[eol] != '\n') {+ eol++;+ }+ size_t i = ls;+ size_t indent = 0;+ while (i < eol && (t[i] == ' ' || t[i] == '\t')) {+ indent += t[i] == '\t' ? JV_KDOC_CODE_INDENT : SKIP_ONE;+ i++;+ }+ jv_kline_t ln = {.first = i, .eol = eol, .line = line};+ char mark = 0;+ size_t f = in_comment ? 0 : jv_kdoc_fence(t + i, eol - i, &mark);+ if (in_comment) {+ jv_kdoc_text(&d, i, &ln, &in_comment); /* up to its end, then text */+ } else if (fence > 0) {+ if (f >= fence && mark == fence_mark) {+ fence = 0;+ }+ } else if (f > 0) {+ fence = f;+ fence_mark = mark;+ in_code = false;+ after_blank = false;+ } else if (i >= eol) {+ after_blank = true; /* an indented block continues over blank lines */+ } else if (indent >= JV_KDOC_CODE_INDENT && (after_blank || in_code)) {+ in_code = true;+ after_blank = false;+ } else {+ in_code = false;+ after_blank = false;+ if (t[i] == '@') {+ size_t e = i + SKIP_ONE;+ while (e < eol && isalpha((unsigned char)t[e])) {+ e++;+ }+ const char *name = t + i + SKIP_ONE;+ size_t len = e - i - SKIP_ONE;+ int syntax = jv_kdoc_tag_syntax(name, len);+ bool gap = e >= eol || t[e] == ' ' || t[e] == '\t';+ i = e;+ if (syntax != CBM_DOCLINK_NONE && gap) {+ i = jv_kdoc_subject(&d, e, &ln, syntax);+ } else if (jv_word_is(name, len, "param") || jv_word_is(name, len, "property")) {+ /* `@param name`, `@param [name]`, `@param[name]`: the+ * definition's own parameter */+ while (i < eol && (t[i] == ' ' || t[i] == '\t')) {+ i++;+ }+ if (i < eol && t[i] == '[') {+ size_t close = jv_kdoc_bracket_close(t, i, eol);+ i = close < eol ? close + SKIP_ONE : i + SKIP_ONE;+ }+ }+ }+ jv_kdoc_text(&d, i, &ln, &in_comment);+ }+ ls = eol + SKIP_ONE;+ }+}++/* ── Parameter type normalization (Java) ─────────────────────────── */++/* Remove [start, end) from the NUL-terminated s of length *len. */+static void jv_cut(char *s, size_t *len, size_t start, size_t end) {+ memmove(s + start, s + end, *len - end + SKIP_ONE);+ *len -= end - start;+}++/* Annotations (`@NonNull`, `@Size(max = 3)`) and every type-argument group. */+static void jv_drop_annotations_and_args(char *s, size_t *len) {+ for (size_t i = 0; i < *len;) {+ if (s[i] == '@') {+ size_t e = i + SKIP_ONE;+ while (e < *len && (jv_ident_char(s[e]) || s[e] == '.')) {+ e++;+ }+ size_t g = e;+ while (g < *len && jv_blank(s[g])) {+ g++;+ }+ if (g < *len && s[g] == '(') {+ e = jv_group_end(s, *len, g, '(', ')');+ }+ jv_cut(s, len, i, e);+ } else if (s[i] == '<') {+ jv_cut(s, len, i, jv_group_end(s, *len, i, '<', '>'));+ } else {+ i++;+ }+ }+}++size_t cbm_doclink_java_norm_type(const char *in, size_t len, char *out, size_t cap) {+ if (!out || cap == 0) {+ return 0;+ }+ out[0] = '\0';+ char work[JV_TYPE_MAX];+ if (!in || len == 0 || len >= sizeof(work)) {+ snprintf(out, cap, "?");+ return strlen(out);+ }+ memcpy(work, in, len);+ work[len] = '\0';+ size_t n = len;+ jv_drop_annotations_and_args(work, &n);+ /* "..." -> "[]" (a variable-arity parameter is an array) */+ for (size_t i = 0; i + PAIR_LEN < n; i++) {+ if (work[i] == '.' && work[i + 1] == '.' && work[i + 2] == '.') {+ work[i] = '[';+ work[i + 1] = ']';+ jv_cut(work, &n, i + 2, i + 3);+ }+ }+ /* words: [final] Type [name]; brackets written after the name belong to+ * the type (`int x[]`) */+ char base[JV_TYPE_MAX];+ size_t bl = 0;+ size_t dims = 0;+ int words = 0;+ for (size_t i = 0; i < n;) {+ while (i < n && jv_blank(work[i])) {+ i++;+ }+ size_t b = i;+ while (i < n && !jv_blank(work[i])) {+ i++;+ }+ if (i == b) {+ break;+ }+ if (i - b == 5 && memcmp(work + b, "final", 5) == 0) {+ continue;+ }+ if (words == 0) {+ memcpy(base, work + b, i - b);+ bl = i - b;+ } else if (work[b] == '[') {+ memcpy(base + bl, work + b, i - b); /* `int []`: brackets apart from the type */+ bl += i - b;+ } else {+ for (size_t k = b; k < i; k++) {+ dims += work[k] == '['; /* the parameter name, with its own brackets */+ }+ }+ words++;+ }+ base[bl] = '\0';+ /* the simple name: package and outer-type qualifiers go */+ size_t suffix = bl;+ while (suffix > 0 && (base[suffix - SKIP_ONE] == ']' || base[suffix - SKIP_ONE] == '[')) {+ suffix--;+ }+ size_t start = 0;+ for (size_t i = 0; i < suffix; i++) {+ if (base[i] == '.') {+ start = i + SKIP_ONE;+ }+ }+ /* no name, or one that does not fit: no type, never a truncated one */+ if (suffix <= start || (bl - start) + (dims * PAIR_LEN) + SKIP_ONE > cap) {+ snprintf(out, cap, "?");+ return strlen(out);+ }+ size_t w = 0;+ for (size_t i = start; i < bl; i++) {+ out[w++] = base[i];+ }+ for (size_t k = 0; k < dims; k++) {+ out[w++] = '[';+ out[w++] = ']';+ }+ out[w] = '\0';+ return w;+}++/* ── Scope scan: state ───────────────────────────────────────────── */++/* A definition the extractor made for this file. */+typedef struct {+ const CBMDefinition *def;+ const char *tail; /* its qualified name below the file's module */+ int order; /* position among the file's definitions */+ bool winner; /* the graph keeps this one for its qualified name */+} jv_def_t;++/* A structural brace of a file with parse errors. */+typedef struct {+ uint32_t pos;+ uint32_t row; /* 0-based */+ int match; /* index of the paired brace, CBM_NOT_FOUND when unpaired */+ int depth; /* nesting depth just after this brace */+ char kind; /* '{' or '}' */+} jv_brace_t;++/* A byte range: the name a declaration keyword is followed by, or a member+ * whose inside is known to be its own. */+typedef struct {+ uint32_t start;+ uint32_t end;+} jv_range_t;++typedef struct {+ jv_range_t *items;+ int count;+ int cap;+} jv_ranges_t;++/* The container whose members are being read. */+typedef struct {+ int owner; /* index of its T record; JV_NO_OWNER at file level */+ const char *path; /* "" at file level */+ const char *name; /* its simple name ("" at file level) */+ int inner_depth; /* brace depth of its members (files with parse errors) */+} jv_frame_t;++enum { JV_NO_OWNER = -1, JV_LEX_NEST_MAX = 64 };++typedef struct {+ CBMExtractCtx *ctx;+ CBMArena *tmp; /* names, lists, braces: nothing of it outlives the scan */+ jv_sb_t sb;+ const char *src;+ uint32_t src_len;+ bool kotlin;+ const char *module_qn;+ size_t module_len;+ jv_def_t *defs; /* sorted by (start line, order) */+ int ndefs;+ int ntypes; /* T records written so far */+ bool lexical; /* the tree has parse errors: nesting is checked against the braces */+ jv_brace_t *braces;+ int nbraces;+ int cap_braces;+ int *stack; /* brace pairing: the open braces */+ int sp;+ int cap_stack;+ jv_ranges_t heads; /* names that follow a type keyword in the text */+ jv_ranges_t seen; /* names of the type declarations the tree has */+ jv_ranges_t members; /* members whose inside is known to be their own */+ uint32_t untrusted; /* byte offset from which the braces do not pair up */+ uint32_t row_pos; /* row cursor: the row of byte row_pos is `row` */+ uint32_t row;+ bool failed;+} jv_scan_t;++static void *jv_tmp_alloc(jv_scan_t *s, size_t n) {+ void *p = cbm_arena_alloc(s->tmp, n ? n : SKIP_ONE);+ if (!p) {+ s->failed = true;+ }+ return p;+}++static void jv_ranges_push(jv_scan_t *s, jv_ranges_t *r, uint32_t start, uint32_t end) {+ if (s->failed) {+ return;+ }+ if (r->count >= r->cap) {+ int ncap = r->cap ? r->cap * PAIR_LEN : JV_ITEMS_INIT;+ jv_range_t *grown = (jv_range_t *)jv_tmp_alloc(s, (size_t)ncap * sizeof(*grown));+ if (!grown) {+ return;+ }+ if (r->count > 0) {+ memcpy(grown, r->items, (size_t)r->count * sizeof(*grown));+ }+ r->items = grown;+ r->cap = ncap;+ }+ r->items[r->count++] = (jv_range_t){.start = start, .end = end};+}++static bool jv_kind(TSNode n, const char *kind) {+ return strcmp(ts_node_type(n), kind) == 0;+}++static TSNode jv_field(TSNode n, const char *field) {+ return ts_node_child_by_field_name(n, field, (uint32_t)strlen(field));+}++/* The first named child of that kind; a null node when there is none. */+static TSNode jv_child(TSNode n, const char *kind) {+ uint32_t nc = ts_node_named_child_count(n);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode c = ts_node_named_child(n, i);+ if (jv_kind(c, kind)) {+ return c;+ }+ }+ return (TSNode){0};+}++static uint32_t jv_line(TSNode n) {+ return ts_node_start_point(n).row + TS_LINE_OFFSET;+}++static uint32_t jv_end_line(TSNode n) {+ return ts_node_end_point(n).row + TS_LINE_OFFSET;+}++/* ── Definitions of the file ─────────────────────────────────────── */++static int jv_def_qn_cmp(const void *a, const void *b) {+ const jv_def_t *x = (const jv_def_t *)a;+ const jv_def_t *y = (const jv_def_t *)b;+ int c = strcmp(x->tail, y->tail);+ if (c == 0 && x->def->start_line != y->def->start_line) {+ c = x->def->start_line < y->def->start_line ? -1 : 1;+ }+ if (c == 0) {+ c = strcmp(x->def->name, y->def->name);+ }+ if (c == 0) {+ c = strcmp(x->def->label, y->def->label);+ }+ if (c == 0) {+ c = (x->order > y->order) - (x->order < y->order);+ }+ return c;+}++static int jv_def_line_cmp(const void *a, const void *b) {+ const jv_def_t *x = (const jv_def_t *)a;+ const jv_def_t *y = (const jv_def_t *)b;+ if (x->def->start_line != y->def->start_line) {+ return x->def->start_line < y->def->start_line ? -1 : 1;+ }+ int c = strcmp(x->def->name, y->def->name);+ if (c != 0) {+ return c;+ }+ return (x->order > y->order) - (x->order < y->order);+}++/* The file's definitions below its module, and which of them the graph keeps+ * when several share one qualified name: the graph buffer's rule inside one+ * file is the largest start line, then name, then label, then the later+ * arrival (cbm_gbuf_upsert_node). */+static void jv_defs_index(jv_scan_t *s) {+ const CBMDefArray *defs = &s->ctx->result->defs;+ if (defs->count <= 0) {+ return;+ }+ s->defs = (jv_def_t *)jv_tmp_alloc(s, (size_t)defs->count * sizeof(jv_def_t));+ if (!s->defs) {+ return;+ }+ int n = 0;+ for (int i = 0; i < defs->count; i++) {+ const CBMDefinition *d = &defs->items[i];+ if (!d->name || !d->qualified_name || !d->label ||+ strncmp(d->qualified_name, s->module_qn, s->module_len) != 0 ||+ d->qualified_name[s->module_len] != '.') {+ continue;+ }+ s->defs[n++] =+ (jv_def_t){.def = d, .tail = d->qualified_name + s->module_len + SKIP_ONE, .order = i};+ }+ s->ndefs = n;+ if (n == 0) {+ return;+ }+ qsort(s->defs, (size_t)n, sizeof(jv_def_t), jv_def_qn_cmp);+ for (int i = 0; i < n; i++) {+ s->defs[i].winner =+ i + SKIP_ONE >= n || strcmp(s->defs[i + SKIP_ONE].tail, s->defs[i].tail) != 0;+ }+ qsort(s->defs, (size_t)n, sizeof(jv_def_t), jv_def_line_cmp);+}++static bool jv_label_fits(const char *label, char kind) {+ if (kind == 'T') {+ return cbm_label_is_type_like(label);+ }+ if (kind == 'c') {+ return strcmp(label, "Method") == 0 || strcmp(label, "Function") == 0;+ }+ return strcmp(label, "Field") == 0 || strcmp(label, "Variable") == 0;+}++/* The definition of kind `kind` (T type, c callable, v value) on `line` that+ * is named key[0, len) -- or, with `prefix`, whose name begins with it. A+ * Field is preferred to the Variable twin the extractor emits beside it. The+ * definitions are sorted by (line, name): the candidates are one run. */+static const jv_def_t *jv_def_pick(const jv_scan_t *s, uint32_t line, const char *key, size_t len,+ char kind, bool prefix) {+ int lo = 0;+ int hi = s->ndefs;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ const CBMDefinition *d = s->defs[mid].def;+ bool below = d->start_line != line ? d->start_line < line : strncmp(d->name, key, len) < 0;+ if (below) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ const jv_def_t *best = NULL;+ for (int i = lo; i < s->ndefs; i++) {+ const CBMDefinition *d = s->defs[i].def;+ if (d->start_line != line || strncmp(d->name, key, len) != 0 ||+ (!prefix && d->name[len] != '\0')) {+ break;+ }+ if (!jv_label_fits(d->label, kind)) {+ continue;+ }+ if (strcmp(d->label, "Field") == 0) {+ return &s->defs[i];+ }+ if (!best) {+ best = &s->defs[i];+ }+ }+ return best;+}++/* The definition the extractor made for the declaration that starts on+ * `line` and is named name[0, len). A Java field's definition is named after+ * its whole declarator (`MAX = 10`, `MAX=10`). */+static const jv_def_t *jv_def_match(const jv_scan_t *s, uint32_t line, const char *name, size_t len,+ char kind) {+ const jv_def_t *exact = jv_def_pick(s, line, name, len, kind, false);+ if (kind != 'v' || s->kotlin || len > JV_NAME_MAX ||+ (exact && strcmp(exact->def->label, "Field") == 0)) {+ return exact;+ }+ /* the Field of an initialized declarator, before its Variable twin */+ char key[JV_NAME_MAX + PAIR_LEN];+ memcpy(key, name, len);+ key[len] = ' ';+ const jv_def_t *field = jv_def_pick(s, line, key, len + SKIP_ONE, kind, true);+ if (!field) {+ key[len] = '=';+ field = jv_def_pick(s, line, key, len + SKIP_ONE, kind, true);+ }+ return field ? field : exact;+}++/* ── Braces: the block structure of a file with parse errors ─────────+ *+ * Error recovery closes blocks early and late and leaves declarations in+ * error nodes, which moves what follows into the wrong type or out of it. In+ * the Kotlin dev corpus 55 of 837 files have a parse error (the central ones+ * among them: Table.kt, ColumnType.kt), nearly always inside one function+ * body, where it disturbs nothing outside. So a file whose tree has errors is+ * not given up: its declarations are checked against the braces of the text.+ * A declaration counts when the braces of its body pair up in the text and+ * its own depth is that of its container's members; a type with an error+ * among its members is marked incomplete; a type the tree has no declaration+ * for (its keyword and name stand in the text) is quarantined by name; what+ * lies behind the first brace without a partner is not placed at all.+ * The parser's own tokens cannot serve (it lexes code as string content once+ * it loses the thread), so the text is scanned here with the lexical grammar+ * a brace scanner needs: comments, character and string literals, Java text+ * blocks, Kotlin raw strings and template holes. */++static uint32_t jv_row_of(jv_scan_t *s, uint32_t pos) {+ if (pos < s->row_pos) {+ s->row_pos = 0;+ s->row = 0;+ }+ for (uint32_t i = s->row_pos; i < pos; i++) {+ s->row += s->src[i] == '\n';+ }+ s->row_pos = pos;+ return s->row;+}++static void jv_mark_untrusted(jv_scan_t *s, uint32_t pos) {+ if (pos < s->untrusted) {+ s->untrusted = pos;+ }+}++static void jv_lex_brace(jv_scan_t *s, uint32_t pos, bool open) {+ if (s->failed) {+ return;+ }+ if (s->nbraces >= s->cap_braces) {+ int ncap = s->cap_braces ? s->cap_braces * PAIR_LEN : JV_BRACES_INIT;+ jv_brace_t *grown = (jv_brace_t *)jv_tmp_alloc(s, (size_t)ncap * sizeof(*grown));+ if (!grown) {+ return;+ }+ if (s->nbraces > 0) {+ memcpy(grown, s->braces, (size_t)s->nbraces * sizeof(*grown));+ }+ s->braces = grown;+ s->cap_braces = ncap;+ }+ int b = s->nbraces++;+ s->braces[b] = (jv_brace_t){+ .pos = pos, .row = jv_row_of(s, pos), .match = CBM_NOT_FOUND, .kind = open ? '{' : '}'};+ if (open) {+ if (s->sp >= s->cap_stack) {+ int ncap = s->cap_stack ? s->cap_stack * PAIR_LEN : JV_ITEMS_INIT;+ int *grown = (int *)jv_tmp_alloc(s, (size_t)ncap * sizeof(int));+ if (!grown) {+ return;+ }+ if (s->sp > 0) {+ memcpy(grown, s->stack, (size_t)s->sp * sizeof(int));+ }+ s->stack = grown;+ s->cap_stack = ncap;+ }+ s->stack[s->sp++] = b;+ } else if (s->sp == 0) {+ jv_mark_untrusted(s, pos); /* closes nothing */+ } else {+ int o = s->stack[--s->sp];+ s->braces[o].match = b;+ s->braces[b].match = o;+ }+ s->braces[b].depth = s->sp;+}++/* Past a comment at src[i], or i when there is none. Kotlin block comments+ * nest. */+static uint32_t jv_lex_comment(const jv_scan_t *s, uint32_t i) {+ const char *src = s->src;+ uint32_t n = s->src_len;+ if (src[i] != '/' || i + SKIP_ONE >= n) {+ return i;+ }+ if (src[i + SKIP_ONE] == '/') {+ while (i < n && src[i] != '\n') {+ i++;+ }+ return i;+ }+ if (src[i + SKIP_ONE] != '*') {+ return i;+ }+ int depth = 1;+ i += PAIR_LEN;+ while (i + SKIP_ONE < n && depth > 0) {+ if (src[i] == '*' && src[i + SKIP_ONE] == '/') {+ depth--;+ i += PAIR_LEN;+ } else if (s->kotlin && src[i] == '/' && src[i + SKIP_ONE] == '*') {+ depth++;+ i += PAIR_LEN;+ } else {+ i++;+ }+ }+ return depth > 0 ? n : i;+}++/* 'x', '\n', a quoted unicode escape: past the literal, or past the lone+ * quote when it is not one. */+static uint32_t jv_lex_char(const jv_scan_t *s, uint32_t i) {+ const char *src = s->src;+ uint32_t n = s->src_len;+ uint32_t j = i + SKIP_ONE;+ if (j < n && src[j] == '\\') {+ j += PAIR_LEN;+ }+ while (j < n && src[j] != '\'' && src[j] != '\n' && j - i < JV_CHAR_LITERAL_MAX) {+ j++;+ }+ return (j < n && src[j] == '\'') ? j + SKIP_ONE : i + SKIP_ONE;+}++/* A Java string or text block at the quote src[i]: past it. An unterminated+ * string ends with its line. */+static uint32_t jv_lex_java_string(const jv_scan_t *s, uint32_t i) {+ const char *src = s->src;+ uint32_t n = s->src_len;+ bool block = i + PAIR_LEN < n && src[i + SKIP_ONE] == '"' && src[i + PAIR_LEN] == '"';+ uint32_t j = i + (block ? JV_QUOTES : SKIP_ONE);+ while (j < n) {+ char c = src[j];+ if (c == '\\') {+ j += PAIR_LEN;+ } else if (block && c == '"' && j + PAIR_LEN < n && src[j + SKIP_ONE] == '"' &&+ src[j + PAIR_LEN] == '"') {+ return j + JV_QUOTES;+ } else if (!block && c == '"') {+ return j + SKIP_ONE;+ } else if (!block && c == '\n') {+ return j;+ } else {+ j++;+ }+ }+ return n;+}++/* The declaration keywords a type starts with. */+static bool jv_type_keyword(const jv_scan_t *s, const char *w, uint32_t len) {+ static const char *const java[] = {"class", "interface", "enum", "record", NULL};+ static const char *const kotlin[] = {"class", "interface", "object", "typealias", NULL};+ const char *const *words = s->kotlin ? kotlin : java;+ for (int i = 0; words[i]; i++) {+ if (strlen(words[i]) == len && memcmp(words[i], w, len) == 0) {+ return true;+ }+ }+ return false;+}++/* A word at src[i]: when it is a type keyword followed by a name, the name is+ * recorded (the tree may have no declaration for it). Returns the end of the+ * word. */+static uint32_t jv_lex_word(jv_scan_t *s, uint32_t i, char prev, bool record) {+ const char *src = s->src;+ uint32_t n = s->src_len;+ uint32_t e = i;+ while (e < n && jv_ident_char(src[e])) {+ e++;+ }+ if (!record || prev == '.' || prev == ':' || !jv_type_keyword(s, src + i, e - i)) {+ return e;+ }+ uint32_t a = e;+ while (a < n && (src[a] == ' ' || src[a] == '\t')) {+ a++;+ }+ if (a == e || a >= n) {+ return e;+ }+ uint32_t b = a;+ if (s->kotlin && src[a] == '`') {+ b = a + SKIP_ONE;+ while (b < n && src[b] != '`' && src[b] != '\n') {+ b++;+ }+ b = (b < n && src[b] == '`') ? b + SKIP_ONE : a;+ } else if (jv_ident_start(src[a])) {+ while (b < n && jv_ident_char(src[b])) {+ b++;+ }+ }+ if (b > a) {+ jv_ranges_push(s, &s->heads, a, b);+ }+ return e;+}++enum { JV_MODE_CODE = 0, JV_MODE_HOLE, JV_MODE_STRING, JV_MODE_RAW };++/* Scan the braces and the type keywords of the text and pair the braces. The+ * first brace without a partner starts the untrusted part of the file. Kotlin+ * strings hold code (`${...}`): the modes nest on an explicit stack, and a+ * text nested deeper than any program is not trusted from there on. */+static void jv_scan_text(jv_scan_t *s) {+ const char *src = s->src;+ uint32_t n = s->src_len;+ struct {+ int mode;+ int depth; /* a hole's own open braces */+ } modes[JV_LEX_NEST_MAX];+ int mp = 0;+ modes[mp].mode = JV_MODE_CODE;+ modes[mp].depth = 0;+ char prev = 0; /* the last significant character of code */+ uint32_t i = 0;+ while (i < n && !s->failed) {+ char c = src[i];+ int mode = modes[mp].mode;+ bool hole = c == '$' && i + SKIP_ONE < n && src[i + SKIP_ONE] == '{';+ if (mode == JV_MODE_STRING || mode == JV_MODE_RAW) {+ bool raw = mode == JV_MODE_RAW;+ if (hole) {+ if (mp + SKIP_ONE >= JV_LEX_NEST_MAX) {+ jv_mark_untrusted(s, i);+ return;+ }+ mp++;+ modes[mp].mode = JV_MODE_HOLE;+ modes[mp].depth = 0;+ i += PAIR_LEN;+ } else if (!raw && c == '\\') {+ i += PAIR_LEN;+ } else if (!raw && (c == '"' || c == '\n')) {+ mp--;+ i += c == '"';+ } else if (raw && c == '"' && i + PAIR_LEN < n && src[i + SKIP_ONE] == '"' &&+ src[i + PAIR_LEN] == '"') {+ while (i < n && src[i] == '"') {+ i++;+ }+ mp--;+ } else {+ i++;+ }+ continue;+ }+ if (jv_blank(c)) {+ i++;+ continue;+ }+ uint32_t e = jv_lex_comment(s, i);+ if (e > i) {+ i = e;+ continue;+ }+ if (c == '"' && !s->kotlin) {+ i = jv_lex_java_string(s, i);+ } else if (c == '"') {+ bool raw = i + PAIR_LEN < n && src[i + SKIP_ONE] == '"' && src[i + PAIR_LEN] == '"';+ if (mp + SKIP_ONE >= JV_LEX_NEST_MAX) {+ jv_mark_untrusted(s, i);+ return;+ }+ mp++;+ modes[mp].mode = raw ? JV_MODE_RAW : JV_MODE_STRING;+ modes[mp].depth = 0;+ i += raw ? JV_QUOTES : SKIP_ONE;+ } else if (c == '\'') {+ i = jv_lex_char(s, i);+ } else if (c == '`' && s->kotlin) {+ uint32_t b = i + SKIP_ONE;+ while (b < n && src[b] != '`' && src[b] != '\n') {+ b++;+ }+ i = (b < n && src[b] == '`') ? b + SKIP_ONE : i + SKIP_ONE;+ } else if (c == '{' || c == '}') {+ if (mode == JV_MODE_HOLE) {+ if (c == '{') {+ modes[mp].depth++;+ } else if (modes[mp].depth == 0) {+ mp--; /* the hole ends: back in its string */+ } else {+ modes[mp].depth--;+ }+ } else {+ jv_lex_brace(s, i, c == '{');+ }+ i++;+ } else if (jv_ident_start(c)) {+ i = jv_lex_word(s, i, prev, mode == JV_MODE_CODE);+ } else {+ i++;+ }+ prev = c;+ }+ if (s->sp > 0) {+ jv_mark_untrusted(s, s->braces[s->stack[0]].pos);+ }+}++/* Index of the first brace at or after byte `pos`. */+static int jv_brace_lower(const jv_scan_t *s, uint32_t pos) {+ int lo = 0;+ int hi = s->nbraces;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (s->braces[mid].pos < pos) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo;+}++/* Brace nesting depth at byte `pos`. */+static int jv_depth_at(const jv_scan_t *s, uint32_t pos) {+ int i = jv_brace_lower(s, pos);+ return i > 0 ? s->braces[i - SKIP_ONE].depth : 0;+}++/* True when the block the tree gives `body` is a block of the text: it opens+ * with a brace whose partner is its last byte. */+static bool jv_block_pairs(const jv_scan_t *s, TSNode body) {+ uint32_t a = ts_node_start_byte(body);+ uint32_t b = ts_node_end_byte(body);+ int i = jv_brace_lower(s, a);+ if (i >= s->nbraces || s->braces[i].pos != a || s->braces[i].kind != '{' ||+ s->braces[i].match < 0) {+ return false;+ }+ return b > 0 && s->braces[s->braces[i].match].pos == b - SKIP_ONE;+}++/* True when a parse error sits among the parts of `decl` other than `body`:+ * an error or missing node there, or (`deep`) an error anywhere inside one. */+static bool jv_header_broken(TSNode decl, TSNode body, bool deep) {+ bool broken = false;+ TSTreeCursor cur = ts_tree_cursor_new(decl);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ do {+ TSNode ch = ts_tree_cursor_current_node(&cur);+ if (!ts_node_is_null(body) && ts_node_eq(ch, body)) {+ continue;+ }+ broken =+ ts_node_is_error(ch) || ts_node_is_missing(ch) || (deep && ts_node_has_error(ch));+ } while (!broken && ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+ return broken;+}++/* True when the tree's placement of a type declaration holds: no parse error+ * in its header, its depth is that of `depth` (its container's members), and+ * its body is a block of the text. Always true in a file without errors. */+static bool jv_type_placed(const jv_scan_t *s, TSNode decl, TSNode body, int depth) {+ if (!s->lexical) {+ return true;+ }+ uint32_t start = ts_node_start_byte(decl);+ if (start >= s->untrusted || jv_depth_at(s, start) != depth ||+ jv_header_broken(decl, body, true)) {+ return false;+ }+ return ts_node_is_null(body) || jv_block_pairs(s, body);+}++/* The same for a member: an error node among its own parts hides what it is;+ * a callable must have parsed up to its body, and a body in braces must be a+ * block of the text (what happens inside it is then its own affair). */+static bool jv_member_ok(const jv_scan_t *s, TSNode decl, TSNode body, bool callable, int depth) {+ if (!s->lexical) {+ return true;+ }+ uint32_t start = ts_node_start_byte(decl);+ if (start >= s->untrusted || jv_depth_at(s, start) != depth ||+ jv_header_broken(decl, body, callable)) {+ return false;+ }+ bool block = !ts_node_is_null(body) && s->src[ts_node_start_byte(body)] == '{';+ return !callable || !block || jv_block_pairs(s, body);+}++/* True when every parse error inside `decl` is held by braces of the text+ * that open and close inside it: an accessor's body, a `when`, a lambda, an+ * anonymous class. The declaration then ends where the tree says, whatever+ * went wrong within those braces. Needs the brace table (a file with+ * errors). */+static bool jv_errors_contained(const jv_scan_t *s, TSNode decl) {+ uint32_t a = ts_node_start_byte(decl);+ uint32_t b = ts_node_end_byte(decl);+ int base = jv_depth_at(s, a);+ int first = jv_brace_lower(s, a);+ int end = jv_brace_lower(s, b);+ for (int i = first; i < end; i++) {+ int m = s->braces[i].match;+ if (m < first || m >= end) {+ return false; /* a brace whose partner is outside the declaration */+ }+ }+ bool contained = true;+ bool down = true;+ TSTreeCursor cur = ts_tree_cursor_new(decl);+ while (contained) {+ TSNode n = ts_tree_cursor_current_node(&cur);+ bool error = ts_node_is_error(n) || ts_node_is_missing(n);+ if (down && error) {+ contained = jv_depth_at(s, ts_node_start_byte(n)) > base &&+ jv_depth_at(s, ts_node_end_byte(n)) > base;+ }+ /* an error node is judged as a whole; only what holds one is entered */+ if (down && !error && ts_node_has_error(n) && ts_tree_cursor_goto_first_child(&cur)) {+ continue;+ }+ if (ts_node_eq(n, decl)) {+ break;+ }+ if (ts_tree_cursor_goto_next_sibling(&cur)) {+ down = true;+ continue;+ }+ if (!ts_tree_cursor_goto_parent(&cur)) {+ break;+ }+ down = false;+ }+ ts_tree_cursor_delete(&cur);+ return contained;+}++/* True when a parse error inside `decl` may reach past it. */+static bool jv_errors_leak(const jv_scan_t *s, TSNode decl) {+ return ts_node_has_error(decl) && !jv_errors_contained(s, decl);+}++/* A member the scan keeps, in a file with parse errors: when nothing in it+ * failed to parse, or its body is a block of the text, or its errors are held+ * by blocks inside it, a type keyword inside it names a local type, not one+ * the tree lost. */+static void jv_member_seen(jv_scan_t *s, TSNode decl, TSNode body, bool callable) {+ if (!s->lexical) {+ return;+ }+ bool block = callable && !ts_node_is_null(body) && s->src[ts_node_start_byte(body)] == '{';+ if (block || !jv_errors_leak(s, decl)) {+ jv_ranges_push(s, &s->members, ts_node_start_byte(decl), ts_node_end_byte(decl));+ }+}++/* ── Names and types as written ──────────────────────────────────── */++/* The declared name at `node`: *raw is its text as the extractor names the+ * definition (a Kotlin name keeps its backticks there), the result is the+ * name itself. NULL unless it is one name of sane length. */+static const char *jv_name_of(jv_scan_t *s, TSNode node, const char **raw, size_t *raw_len) {+ if (ts_node_is_null(node)) {+ return NULL;+ }+ uint32_t a = ts_node_start_byte(node);+ uint32_t b = ts_node_end_byte(node);+ if (b <= a || b > s->src_len || b - a > JV_NAME_MAX) {+ return NULL;+ }+ const char *p = s->src + a;+ size_t n = b - a;+ *raw = p;+ *raw_len = n;+ bool quoted = n > PAIR_LEN && p[0] == '`' && p[n - SKIP_ONE] == '`';+ if (quoted) {+ p++;+ n -= PAIR_LEN;+ }+ for (size_t i = 0; i < n; i++) {+ char c = p[i];+ bool ok = quoted ? ((unsigned char)c >= ' ' && !strchr(".|,`", c)) : jv_ident_char(c);+ if (!ok) {+ return NULL;+ }+ }+ char *out = (char *)jv_tmp_alloc(s, n + SKIP_ONE);+ if (!out) {+ return NULL;+ }+ memcpy(out, p, n);+ out[n] = '\0';+ return out;+}++static const char *jv_join(jv_scan_t *s, const char *outer, const char *name) {+ if (!outer[0]) {+ return name;+ }+ size_t ol = strlen(outer);+ size_t nl = strlen(name);+ char *out = (char *)jv_tmp_alloc(s, ol + nl + PAIR_LEN);+ if (!out) {+ return NULL;+ }+ memcpy(out, outer, ol);+ out[ol] = '.';+ memcpy(out + ol + SKIP_ONE, name, nl + SKIP_ONE);+ return out;+}++/* Source text [a, b) as a (qualified) name into `out`: blanks, annotations,+ * type arguments, nullable marks and backticks go. false when what is left is+ * no name. */+static bool jv_type_name(const jv_scan_t *s, uint32_t a, uint32_t b, char *out, size_t cap) {+ char work[JV_TYPE_MAX];+ if (b <= a || b > s->src_len || b - a >= sizeof(work)) {+ return false;+ }+ size_t n = b - a;+ memcpy(work, s->src + a, n);+ work[n] = '\0';+ jv_drop_annotations_and_args(work, &n);+ size_t w = 0;+ for (size_t i = 0; i < n; i++) {+ char c = work[i];+ if (jv_blank(c) || c == '?' || c == '`') {+ continue;+ }+ if (!(jv_ident_char(c) || c == '.') || w + SKIP_ONE >= cap) {+ return false;+ }+ out[w++] = c;+ }+ out[w] = '\0';+ return w > 0 && out[0] != '.' && out[w - SKIP_ONE] != '.';+}++/* A written type as a name; "?" when it is none (a function type, text an+ * error left behind): the declaring type then has a supertype nobody can+ * follow. */+static void jv_put_type_name(jv_scan_t *s, TSNode node) {+ char name[JV_TYPE_MAX];+ if (!ts_node_is_null(node) &&+ jv_type_name(s, ts_node_start_byte(node), ts_node_end_byte(node), name, sizeof(name))) {+ jv_puts(&s->sb, name);+ } else {+ jv_putc(&s->sb, '?');+ }+}++/* `<T, U extends X>` / `<in T, out U : X>` -> "T,U:X" (Java) / "T,U" (Kotlin).+ * A Java type variable keeps its first bound: that is its erasure, and a+ * Javadoc signature names a parameter of that type by it. */+static void jv_put_tparams(jv_scan_t *s, TSNode list) {+ if (ts_node_is_null(list)) {+ return;+ }+ TSTreeCursor cur = ts_tree_cursor_new(list);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ bool first = true;+ do {+ TSNode tp = ts_tree_cursor_current_node(&cur);+ if (!jv_kind(tp, "type_parameter")) {+ continue;+ }+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = jv_name_of(s, jv_child(tp, "type_identifier"), &raw, &raw_len);+ if (!name) {+ continue;+ }+ if (!first) {+ jv_putc(&s->sb, ',');+ }+ jv_puts(&s->sb, name);+ first = false;+ TSNode bound = s->kotlin ? (TSNode){0} : jv_child(tp, "type_bound");+ TSNode bt = (ts_node_is_null(bound) || ts_node_named_child_count(bound) == 0)+ ? (TSNode){0}+ : ts_node_named_child(bound, 0);+ if (!ts_node_is_null(bt) && ts_node_end_byte(bt) <= s->src_len) {+ char norm[CBM_SZ_256];+ uint32_t a = ts_node_start_byte(bt);+ cbm_doclink_java_norm_type(s->src + a, ts_node_end_byte(bt) - a, norm,+ sizeof(norm));+ if (norm[0] && !strpbrk(norm, ",:\t\n")) {+ jv_putc(&s->sb, ':');+ jv_puts(&s->sb, norm);+ }+ }+ } while (ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+}++/* ── Records ─────────────────────────────────────────────────────── */++/* slot and own of a declaration whose definition is `def` (NULL: it has+ * none) and whose logical path is `logical`. */+static void jv_put_slot(jv_scan_t *s, const jv_def_t *def, const char *logical) {+ size_t len = def ? strlen(def->tail) : 0;+ bool usable = def && logical && len > 0 && len <= JV_SLOT_MAX;+ for (size_t i = 0; usable && i < len; i++) {+ usable = (unsigned char)def->tail[i] >= ' ';+ }+ if (!usable) {+ jv_puts(&s->sb, "-\t0");+ return;+ }+ if (strcmp(def->tail, logical) == 0) {+ jv_putc(&s->sb, '=');+ } else {+ jv_putn(&s->sb, def->tail, len);+ }+ jv_putc(&s->sb, '\t');+ jv_putc(&s->sb, def->winner ? '1' : '0');+}++/* "T start end kind[!] path " -- the caller adds tparams, supers, slot, own,+ * pnames. */+static void jv_type_open(jv_scan_t *s, TSNode decl, char kind, bool incomplete, const char *path) {+ jv_puts(&s->sb, "T\t");+ jv_putu(&s->sb, jv_line(decl));+ jv_putc(&s->sb, '\t');+ jv_putu(&s->sb, jv_end_line(decl));+ jv_putc(&s->sb, '\t');+ jv_putc(&s->sb, kind);+ if (incomplete) {+ jv_putc(&s->sb, '!');+ }+ jv_putc(&s->sb, '\t');+ jv_puts(&s->sb, path);+ jv_putc(&s->sb, '\t');+}++/* "M start kind flags owner name " -- the caller adds tparams, sig, recv,+ * slot, own, pnames. */+static void jv_member_open(jv_scan_t *s, uint32_t line, char kind, const char *flags,+ const jv_frame_t *fr, const char *name) {+ jv_puts(&s->sb, "M\t");+ jv_putu(&s->sb, line);+ jv_putc(&s->sb, '\t');+ jv_putc(&s->sb, kind);+ jv_putc(&s->sb, '\t');+ jv_puts(&s->sb, flags);+ jv_putc(&s->sb, '\t');+ if (fr->owner == JV_NO_OWNER) {+ jv_putc(&s->sb, '-');+ } else {+ jv_putu(&s->sb, (uint32_t)fr->owner);+ }+ jv_putc(&s->sb, '\t');+ jv_puts(&s->sb, name);+ jv_putc(&s->sb, '\t');+}++/* A value member without type parameters, receiver or parameter names: `sig`+ * is "-", or what its kind keeps there (a record component's type). */+static void jv_emit_value(jv_scan_t *s, uint32_t line, TSNode name_node, const char *flags,+ const char *sig, const jv_frame_t *fr) {+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = jv_name_of(s, name_node, &raw, &raw_len);+ if (!name) {+ return;+ }+ const jv_def_t *def = jv_def_match(s, line, raw, raw_len, 'v');+ jv_member_open(s, line, 'v', flags, fr, name);+ jv_putc(&s->sb, '\t');+ jv_puts(&s->sb, sig);+ jv_puts(&s->sb, "\t\t");+ jv_put_slot(s, def, jv_join(s, fr->path, name));+ jv_puts(&s->sb, "\t\n");+}++static void jv_emit_unplaced(jv_scan_t *s, uint32_t from, uint32_t to) {+ jv_puts(&s->sb, "X\t");+ jv_putu(&s->sb, from);+ jv_putc(&s->sb, '\t');+ jv_putu(&s->sb, to);+ jv_putc(&s->sb, '\n');+}++static char jv_java_type_kind(const char *k) {+ static const struct {+ const char *node;+ char kind;+ } kinds[] = {{"class_declaration", 'c'},+ {"interface_declaration", 'i'},+ {"enum_declaration", 'e'},+ {"record_declaration", 'r'},+ {"annotation_type_declaration", 'a'}};+ for (size_t i = 0; i < sizeof(kinds) / sizeof(kinds[0]); i++) {+ if (strcmp(k, kinds[i].node) == 0) {+ return kinds[i].kind;+ }+ }+ return 0;+}++static bool jv_kotlin_is_type(const char *k) {+ return strcmp(k, "class_declaration") == 0 || strcmp(k, "object_declaration") == 0 ||+ strcmp(k, "companion_object") == 0 || strcmp(k, "type_alias") == 0;+}++/* The name of a type declaration node; a null node for an unnamed one. */+static TSNode jv_type_name_node(const jv_scan_t *s, TSNode decl) {+ return s->kotlin ? jv_child(decl, "type_identifier") : jv_field(decl, "name");+}++/* Every type declared in the subtree is declared, but where is unknown (the+ * subtree is an error node, or a declaration that could not be placed): its+ * name must not resolve to anything else either. */+static void jv_quarantine(jv_scan_t *s, TSNode node) {+ TSTreeCursor cur = ts_tree_cursor_new(node);+ bool down = true;+ for (;;) {+ if (down) {+ TSNode n = ts_tree_cursor_current_node(&cur);+ const char *k = ts_node_type(n);+ if (s->kotlin ? jv_kotlin_is_type(k) : jv_java_type_kind(k) != 0) {+ TSNode name_node = jv_type_name_node(s, n);+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = jv_name_of(s, name_node, &raw, &raw_len);+ if (name) {+ jv_ranges_push(s, &s->seen, ts_node_start_byte(name_node),+ ts_node_end_byte(name_node));+ jv_puts(&s->sb, "Q\t");+ jv_puts(&s->sb, name);+ jv_putc(&s->sb, '\n');+ }+ }+ if (ts_tree_cursor_goto_first_child(&cur)) {+ continue;+ }+ }+ if (ts_tree_cursor_goto_next_sibling(&cur)) {+ down = true;+ continue;+ }+ if (!ts_tree_cursor_goto_parent(&cur)) {+ break;+ }+ down = false;+ }+ ts_tree_cursor_delete(&cur);+}++/* A declaration or an error node that could not be placed. */+static void jv_unplaced(jv_scan_t *s, TSNode node, bool report_lines) {+ if (report_lines) {+ jv_emit_unplaced(s, jv_line(node), jv_end_line(node));+ }+ jv_quarantine(s, node);+}++/* ── Java ────────────────────────────────────────────────────────── */++static void jv_java_container(jv_scan_t *s, TSNode body, const jv_frame_t *fr, int depth);++static bool jv_java_is_callable(const char *k) {+ return strcmp(k, "method_declaration") == 0 || strcmp(k, "constructor_declaration") == 0 ||+ strcmp(k, "compact_constructor_declaration") == 0 ||+ strcmp(k, "annotation_type_element_declaration") == 0;+}++static bool jv_java_is_value(const char *k) {+ return strcmp(k, "field_declaration") == 0 || strcmp(k, "constant_declaration") == 0 ||+ strcmp(k, "enum_constant") == 0;+}++/* True when the scan does not show every member of the type whose body this+ * is: an error node among its members, a member or nested type that could+ * not be placed, an error inside a member that has no block of its own to+ * hold it, or (`leaf`: the type is as deep as the scan goes) a nested type. */+static bool jv_java_body_broken(const jv_scan_t *s, TSNode body, int inner, bool leaf) {+ bool broken = false;+ bool nested = jv_kind(body, "enum_body_declarations");+ TSTreeCursor cur = ts_tree_cursor_new(body);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ do {+ TSNode c = ts_tree_cursor_current_node(&cur);+ const char *k = ts_node_type(c);+ if (ts_node_is_error(c) || ts_node_is_missing(c)) {+ broken = true;+ } else if (strcmp(k, "enum_body_declarations") == 0) {+ /* the members of an enum, one level below its constants */+ broken = nested || jv_java_body_broken(s, c, inner, leaf);+ } else if (jv_java_type_kind(k)) {+ broken = leaf || !jv_type_placed(s, c, jv_field(c, "body"), inner);+ } else if (jv_java_is_callable(k)) {+ broken = !jv_member_ok(s, c, jv_field(c, "body"), true, inner);+ } else if (jv_java_is_value(k)) {+ broken = jv_errors_leak(s, c) || !jv_member_ok(s, c, (TSNode){0}, false, inner);+ }+ } while (!broken && ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+ return broken;+}++static void jv_java_put_supers(jv_scan_t *s, TSNode decl) {+ bool first = true;+ TSNode sc = jv_field(decl, "superclass");+ uint32_t snc = ts_node_is_null(sc) ? 0 : ts_node_named_child_count(sc);+ if (snc > 0) {+ jv_put_type_name(s, ts_node_named_child(sc, snc - SKIP_ONE));+ first = false;+ }+ TSNode lists[] = {jv_field(decl, "interfaces"), jv_child(decl, "extends_interfaces")};+ for (size_t l = 0; l < sizeof(lists) / sizeof(lists[0]); l++) {+ TSNode tl = ts_node_is_null(lists[l]) ? lists[l] : jv_child(lists[l], "type_list");+ uint32_t nc = ts_node_is_null(tl) ? 0 : ts_node_named_child_count(tl);+ for (uint32_t i = 0; i < nc; i++) {+ if (!first) {+ jv_putc(&s->sb, '|');+ }+ jv_put_type_name(s, ts_node_named_child(tl, i));+ first = false;+ }+ }+}++/* One declared parameter type, normalized, with the brackets that follow the+ * parameter's name (`int x[]`) or its ellipsis. */+static void jv_java_put_param_type(jv_scan_t *s, TSNode ty, int extra_dims) {+ char norm[CBM_SZ_256];+ if (ts_node_is_null(ty) || ts_node_end_byte(ty) > s->src_len) {+ snprintf(norm, sizeof(norm), "?");+ } else {+ uint32_t a = ts_node_start_byte(ty);+ cbm_doclink_java_norm_type(s->src + a, ts_node_end_byte(ty) - a, norm, sizeof(norm));+ }+ jv_puts(&s->sb, norm);+ for (int i = 0; i < extra_dims; i++) {+ jv_puts(&s->sb, "[]");+ }+}++static void jv_java_put_sig(jv_scan_t *s, TSNode params) {+ if (ts_node_is_null(params)) {+ return;+ }+ bool first = true;+ uint32_t nc = ts_node_named_child_count(params);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode p = ts_node_named_child(params, i);+ TSNode ty = {0};+ int dims = 0;+ if (jv_kind(p, "formal_parameter")) {+ ty = jv_field(p, "type");+ TSNode d = jv_field(p, "dimensions");+ for (uint32_t k = ts_node_is_null(d) ? 0 : ts_node_start_byte(d);+ !ts_node_is_null(d) && k < ts_node_end_byte(d) && k < s->src_len; k++) {+ dims += s->src[k] == '[';+ }+ } else if (jv_kind(p, "spread_parameter")) {+ uint32_t pc = ts_node_named_child_count(p);+ for (uint32_t k = 0; k < pc && ts_node_is_null(ty); k++) {+ TSNode ch = ts_node_named_child(p, k);+ if (!jv_kind(ch, "modifiers")) {+ ty = ch;+ }+ }+ dims = SKIP_ONE;+ } else {+ continue; /* a receiver parameter, a comment */+ }+ if (!first) {+ jv_putc(&s->sb, '|');+ }+ jv_java_put_param_type(s, ty, dims);+ first = false;+ }+}++static void jv_java_callable(jv_scan_t *s, TSNode decl, const char *k, const jv_frame_t *fr) {+ bool compact = strcmp(k, "compact_constructor_declaration") == 0;+ bool ctor = compact || strcmp(k, "constructor_declaration") == 0;+ TSNode body = jv_field(decl, "body");+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = jv_name_of(s, jv_field(decl, "name"), &raw, &raw_len);+ if (!name || !jv_member_ok(s, decl, body, true, fr->inner_depth)) {+ return;+ }+ jv_member_seen(s, decl, body, true);+ uint32_t line = jv_line(decl);+ const jv_def_t *def = jv_def_match(s, line, raw, raw_len, 'c');+ jv_member_open(s, line, 'c', ctor ? "K" : "", fr, name);+ jv_put_tparams(s, jv_field(decl, "type_parameters"));+ jv_putc(&s->sb, '\t');+ if (compact) {+ jv_putc(&s->sb, '*'); /* the canonical constructor: the components' types */+ } else {+ jv_java_put_sig(s, jv_field(decl, "parameters"));+ }+ jv_puts(&s->sb, "\t\t");+ jv_put_slot(s, def, jv_join(s, fr->path, name));+ jv_puts(&s->sb, "\t\n");+}++/* A field or constant declaration: one member per declarator. */+static void jv_java_fields(jv_scan_t *s, TSNode decl, const jv_frame_t *fr) {+ if (!jv_member_ok(s, decl, (TSNode){0}, false, fr->inner_depth)) {+ return;+ }+ jv_member_seen(s, decl, (TSNode){0}, false);+ uint32_t line = jv_line(decl);+ uint32_t nc = ts_node_named_child_count(decl);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode vd = ts_node_named_child(decl, i);+ if (jv_kind(vd, "variable_declarator")) {+ jv_emit_value(s, line, jv_field(vd, "name"), "", "-", fr);+ }+ }+}++/* The components of a record are its fields; each keeps its type, which is+ * the canonical constructor's signature. */+static void jv_java_components(jv_scan_t *s, TSNode decl, const jv_frame_t *fr) {+ TSNode params = jv_field(decl, "parameters");+ uint32_t nc = ts_node_is_null(params) ? 0 : ts_node_named_child_count(params);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode p = ts_node_named_child(params, i);+ if (!jv_kind(p, "formal_parameter")) {+ continue;+ }+ char norm[CBM_SZ_256];+ TSNode ty = jv_field(p, "type");+ if (ts_node_is_null(ty) || ts_node_end_byte(ty) > s->src_len) {+ snprintf(norm, sizeof(norm), "?");+ } else {+ uint32_t a = ts_node_start_byte(ty);+ cbm_doclink_java_norm_type(s->src + a, ts_node_end_byte(ty) - a, norm, sizeof(norm));+ }+ jv_emit_value(s, jv_line(p), jv_field(p, "name"), "p", norm, fr);+ }+}++static void jv_java_import(jv_scan_t *s, TSNode decl) {+ if (s->lexical && (ts_node_start_byte(decl) >= s->untrusted || ts_node_has_error(decl))) {+ return;+ }+ bool is_static = false;+ bool star = false;+ TSNode name = {0};+ uint32_t cc = ts_node_child_count(decl);+ for (uint32_t i = 0; i < cc; i++) {+ TSNode ch = ts_node_child(decl, i);+ const char *k = ts_node_type(ch);+ if (strcmp(k, "static") == 0) {+ is_static = true;+ } else if (strcmp(k, "asterisk") == 0) {+ star = true;+ } else if (strcmp(k, "scoped_identifier") == 0 || strcmp(k, "identifier") == 0) {+ name = ch;+ }+ }+ char text[JV_TYPE_MAX];+ if (ts_node_is_null(name) ||+ !jv_type_name(s, ts_node_start_byte(name), ts_node_end_byte(name), text, sizeof(text))) {+ return;+ }+ char *dot = strrchr(text, '.');+ if (star) {+ jv_puts(&s->sb, is_static ? "I\tn\t-\t" : "I\tw\t-\t");+ jv_puts(&s->sb, text);+ } else if (!is_static) {+ jv_puts(&s->sb, "I\ts\t");+ jv_puts(&s->sb, dot ? dot + SKIP_ONE : text);+ jv_putc(&s->sb, '\t');+ jv_puts(&s->sb, text);+ } else if (dot) {+ *dot = '\0'; /* `import static a.b.C.member;`: the member of a type */+ jv_puts(&s->sb, "I\tm\t");+ jv_puts(&s->sb, dot + SKIP_ONE);+ jv_putc(&s->sb, '\t');+ jv_puts(&s->sb, text);+ } else {+ return;+ }+ jv_putc(&s->sb, '\n');+}++static void jv_java_type(jv_scan_t *s, TSNode decl, char kind, const jv_frame_t *outer, int depth) {+ TSNode name_node = jv_field(decl, "name");+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = jv_name_of(s, name_node, &raw, &raw_len);+ if (!name) {+ return;+ }+ TSNode body = jv_field(decl, "body");+ const char *path = jv_join(s, outer->path, name);+ /* nested deeper than any real program: not placed, like a parse error */+ if (!path || depth >= JV_MAX_DEPTH || !jv_type_placed(s, decl, body, outer->inner_depth)) {+ jv_unplaced(s, decl, true);+ return;+ }+ if (s->lexical) {+ jv_ranges_push(s, &s->seen, ts_node_start_byte(name_node), ts_node_end_byte(name_node));+ }+ int inner = outer->inner_depth + SKIP_ONE;+ bool leaf = depth + SKIP_ONE >= JV_MAX_DEPTH;+ bool incomplete =+ (s->lexical || leaf) && !ts_node_is_null(body) && jv_java_body_broken(s, body, inner, leaf);+ const jv_def_t *def = jv_def_match(s, jv_line(decl), raw, raw_len, 'T');+ jv_frame_t fr = {.owner = s->ntypes++, .path = path, .name = name, .inner_depth = inner};+ jv_type_open(s, decl, kind, incomplete, path);+ jv_put_tparams(s, jv_field(decl, "type_parameters"));+ jv_putc(&s->sb, '\t');+ jv_java_put_supers(s, decl);+ jv_putc(&s->sb, '\t');+ jv_put_slot(s, def, path);+ jv_puts(&s->sb, "\t\n");+ if (kind == 'r') {+ jv_java_components(s, decl, &fr);+ }+ if (!ts_node_is_null(body)) {+ jv_java_container(s, body, &fr, depth + SKIP_ONE);+ }+}++/* The declarations of a class body (or of the file): types, members,+ * imports. `depth` is the nesting of the types declared here; jv_java_type+ * bounds it, and so the recursion. */+static void jv_java_container(jv_scan_t *s, TSNode body, const jv_frame_t *fr, int depth) {+ bool enum_members = jv_kind(body, "enum_body_declarations");+ TSTreeCursor cur = ts_tree_cursor_new(body);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ do {+ TSNode c = ts_tree_cursor_current_node(&cur);+ const char *k = ts_node_type(c);+ char tk = jv_java_type_kind(k);+ if (ts_node_is_error(c)) {+ jv_unplaced(s, c, true);+ } else if (ts_node_is_missing(c)) {+ continue;+ } else if (tk) {+ jv_java_type(s, c, tk, fr, depth);+ } else if (strcmp(k, "import_declaration") == 0) {+ jv_java_import(s, c);+ } else if (strcmp(k, "enum_body_declarations") == 0) {+ if (!enum_members) {+ jv_java_container(s, c, fr, depth); /* the same type's members */+ }+ } else if (fr->owner == JV_NO_OWNER) {+ continue; /* the file itself has no members */+ } else if (jv_java_is_callable(k)) {+ jv_java_callable(s, c, k, fr);+ } else if (strcmp(k, "enum_constant") == 0) {+ if (jv_member_ok(s, c, (TSNode){0}, false, fr->inner_depth)) {+ jv_member_seen(s, c, (TSNode){0}, false);+ jv_emit_value(s, jv_line(c), jv_field(c, "name"), "n", "-", fr);+ }+ } else if (jv_java_is_value(k)) {+ jv_java_fields(s, c, fr);+ }+ } while (!s->failed && ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+}++/* ── Kotlin ──────────────────────────────────────────────────────── */++static void jv_kotlin_container(jv_scan_t *s, TSNode body, const jv_frame_t *fr, int depth);++static TSNode jv_kotlin_body(TSNode decl) {+ TSNode body = jv_child(decl, "class_body");+ return ts_node_is_null(body) ? jv_child(decl, "enum_class_body") : body;+}++/* True when the scan does not show every member of the type whose body this+ * is (see jv_java_body_broken). A function with an expression body, a+ * property initializer or an accessor has no braces of its own to hold an+ * error. */+static bool jv_kotlin_body_broken(const jv_scan_t *s, TSNode body, int inner, bool leaf) {+ bool broken = false;+ TSTreeCursor cur = ts_tree_cursor_new(body);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ do {+ TSNode c = ts_tree_cursor_current_node(&cur);+ const char *k = ts_node_type(c);+ if (ts_node_is_error(c) || ts_node_is_missing(c)) {+ broken = true;+ } else if (jv_kotlin_is_type(k)) {+ broken = leaf || !jv_type_placed(s, c, jv_kotlin_body(c), inner);+ } else if (strcmp(k, "function_declaration") == 0) {+ TSNode fb = jv_child(c, "function_body");+ bool block = !ts_node_is_null(fb) && s->src[ts_node_start_byte(fb)] == '{';+ broken = !jv_member_ok(s, c, fb, true, inner) || (!block && jv_errors_leak(s, c));+ } else if (ts_node_is_named(c)) {+ broken = jv_errors_leak(s, c) || ((strcmp(k, "property_declaration") == 0 ||+ strcmp(k, "secondary_constructor") == 0 ||+ strcmp(k, "enum_entry") == 0) &&+ !jv_member_ok(s, c, (TSNode){0}, false, inner));+ }+ } while (!broken && ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+ return broken;+}++static void jv_kotlin_put_supers(jv_scan_t *s, TSNode decl) {+ bool first = true;+ uint32_t nc = ts_node_named_child_count(decl);+ if (jv_kind(decl, "type_alias")) {+ /* `typealias A = B`: A has what B has, so B stands where a supertype+ * does. An alias of anything but a named type has no known members. */+ TSNode target = nc > 0 ? ts_node_named_child(decl, nc - SKIP_ONE) : (TSNode){0};+ bool is_type = !ts_node_is_null(target) && !jv_kind(target, "type_identifier") &&+ !jv_kind(target, "type_parameters") && !jv_kind(target, "modifiers");+ jv_put_type_name(s, is_type ? target : (TSNode){0});+ return;+ }+ for (uint32_t i = 0; i < nc; i++) {+ TSNode ds = ts_node_named_child(decl, i);+ if (!jv_kind(ds, "delegation_specifier")) {+ continue;+ }+ TSNode x = ts_node_named_child_count(ds) > 0 ? ts_node_named_child(ds, 0) : (TSNode){0};+ if (!ts_node_is_null(x) &&+ (jv_kind(x, "constructor_invocation") || jv_kind(x, "explicit_delegation"))) {+ x = jv_child(x, "user_type");+ }+ if (!first) {+ jv_putc(&s->sb, '|');+ }+ jv_put_type_name(s, (!ts_node_is_null(x) && jv_kind(x, "user_type")) ? x : (TSNode){0});+ first = false;+ }+}++/* The names of the parameters under `list`, ','-joined (`item`: the node kind+ * of one parameter). */+static void jv_kotlin_put_pnames(jv_scan_t *s, TSNode list, const char *item) {+ bool first = true;+ uint32_t nc = ts_node_is_null(list) ? 0 : ts_node_named_child_count(list);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode p = ts_node_named_child(list, i);+ if (!jv_kind(p, item)) {+ continue;+ }+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = jv_name_of(s, jv_child(p, "simple_identifier"), &raw, &raw_len);+ if (!name) {+ continue;+ }+ if (!first) {+ jv_putc(&s->sb, ',');+ }+ jv_puts(&s->sb, name);+ first = false;+ }+}++/* Source text [a, b) without blanks; a byte that would break a record is+ * written as '?'. Text too long to be a type is "?". */+static void jv_put_compact(jv_scan_t *s, uint32_t a, uint32_t b) {+ if (b <= a || b > s->src_len || b - a > JV_TYPE_MAX) {+ jv_putc(&s->sb, '?');+ return;+ }+ for (uint32_t i = a; i < b; i++) {+ char c = s->src[i];+ if (jv_blank(c)) {+ continue;+ }+ jv_putc(&s->sb, ((unsigned char)c < ' ' || c == '|') ? '?' : c);+ }+}++/* The signature of a Kotlin declaration: what tells one declaration of a name+ * from another. `R=<receiver>` for an extension, then the parameter types as+ * written. KDoc cannot name a signature, so it is compared, never parsed. */+static void jv_kotlin_put_sig(jv_scan_t *s, TSNode receiver, TSNode params, bool callable) {+ bool any = false;+ if (!ts_node_is_null(receiver)) {+ jv_puts(&s->sb, "R=");+ jv_put_compact(s, ts_node_start_byte(receiver), ts_node_end_byte(receiver));+ any = true;+ }+ uint32_t nc = ts_node_is_null(params) ? 0 : ts_node_named_child_count(params);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode p = ts_node_named_child(params, i);+ if (!jv_kind(p, "parameter")) {+ continue;+ }+ if (any) {+ jv_putc(&s->sb, '|');+ }+ uint32_t pc = ts_node_named_child_count(p);+ if (pc > SKIP_ONE) {+ TSNode ty = ts_node_named_child(p, SKIP_ONE);+ jv_put_compact(s, ts_node_start_byte(ty), ts_node_end_byte(ty));+ } else {+ jv_putc(&s->sb, '?');+ }+ any = true;+ }+ if (!any && !callable) {+ jv_putc(&s->sb, '-');+ }+}++/* The receiver type of an extension, as written (a dotted name): the type a+ * reference `Type.member` finds the extension under. A receiver that is one+ * of the declaration's own type parameters stands for its bound; one without+ * a bound (or a function type) has no name: "?". */+static void jv_kotlin_put_recv(jv_scan_t *s, TSNode receiver, TSNode tparams) {+ char name[JV_TYPE_MAX];+ if (ts_node_is_null(receiver)) {+ return;+ }+ if (!jv_type_name(s, ts_node_start_byte(receiver), ts_node_end_byte(receiver), name,+ sizeof(name))) {+ jv_putc(&s->sb, '?');+ return;+ }+ bool simple = strchr(name, '.') == NULL;+ TSTreeCursor cur = ts_tree_cursor_new(ts_node_is_null(tparams) ? receiver : tparams);+ bool more = simple && !ts_node_is_null(tparams) && ts_tree_cursor_goto_first_child(&cur);+ for (; more; more = ts_tree_cursor_goto_next_sibling(&cur)) {+ TSNode tp = ts_tree_cursor_current_node(&cur);+ TSNode id = jv_kind(tp, "type_parameter") ? jv_child(tp, "type_identifier") : (TSNode){0};+ uint32_t a = ts_node_is_null(id) ? 0 : ts_node_start_byte(id);+ uint32_t b = ts_node_is_null(id) ? 0 : ts_node_end_byte(id);+ if (b - a != strlen(name) || b > s->src_len || memcmp(s->src + a, name, b - a) != 0) {+ continue;+ }+ /* its bound is the type after the name */+ char bound[JV_TYPE_MAX];+ uint32_t tc = ts_node_named_child_count(tp);+ TSNode bn = tc > SKIP_ONE ? ts_node_named_child(tp, tc - SKIP_ONE) : (TSNode){0};+ bool named =+ !ts_node_is_null(bn) && !ts_node_eq(bn, id) &&+ jv_type_name(s, ts_node_start_byte(bn), ts_node_end_byte(bn), bound, sizeof(bound));+ ts_tree_cursor_delete(&cur);+ jv_puts(&s->sb, named ? bound : "?");+ return;+ }+ ts_tree_cursor_delete(&cur);+ jv_puts(&s->sb, name);+}++static void jv_kotlin_function(jv_scan_t *s, TSNode decl, const jv_frame_t *fr) {+ TSNode body = jv_child(decl, "function_body");+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = jv_name_of(s, jv_child(decl, "simple_identifier"), &raw, &raw_len);+ if (!name || !jv_member_ok(s, decl, body, true, fr->inner_depth)) {+ return;+ }+ jv_member_seen(s, decl, body, true);+ uint32_t line = jv_line(decl);+ TSNode receiver = jv_field(decl, "receiver");+ TSNode tparams = jv_child(decl, "type_parameters");+ TSNode params = jv_child(decl, "function_value_parameters");+ const jv_def_t *def = jv_def_match(s, line, raw, raw_len, 'c');+ jv_member_open(s, line, 'c', "", fr, name);+ jv_put_tparams(s, tparams);+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_sig(s, receiver, params, true);+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_recv(s, receiver, tparams);+ jv_putc(&s->sb, '\t');+ jv_put_slot(s, def, jv_join(s, fr->path, name));+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_pnames(s, params, "parameter");+ jv_putc(&s->sb, '\n');+}++static void jv_kotlin_property(jv_scan_t *s, TSNode decl, const jv_frame_t *fr) {+ TSNode vd = jv_child(decl, "variable_declaration");+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = ts_node_is_null(vd)+ ? NULL+ : jv_name_of(s, jv_child(vd, "simple_identifier"), &raw, &raw_len);+ if (!name || !jv_member_ok(s, decl, (TSNode){0}, false, fr->inner_depth)) {+ return; /* a destructuring declaration names no member */+ }+ jv_member_seen(s, decl, (TSNode){0}, false);+ uint32_t line = jv_line(decl);+ TSNode receiver = jv_field(decl, "receiver");+ TSNode tparams = jv_child(decl, "type_parameters");+ const jv_def_t *def = jv_def_match(s, line, raw, raw_len, 'v');+ jv_member_open(s, line, 'v', "", fr, name);+ jv_put_tparams(s, tparams);+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_sig(s, receiver, (TSNode){0}, false);+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_recv(s, receiver, tparams);+ jv_putc(&s->sb, '\t');+ jv_put_slot(s, def, jv_join(s, fr->path, name));+ jv_puts(&s->sb, "\t\n");+}++/* A secondary constructor: the extractor names it after its class. */+static void jv_kotlin_constructor(jv_scan_t *s, TSNode decl, const jv_frame_t *fr) {+ if (fr->owner == JV_NO_OWNER || !jv_member_ok(s, decl, (TSNode){0}, true, fr->inner_depth)) {+ return;+ }+ jv_member_seen(s, decl, (TSNode){0}, true);+ uint32_t line = jv_line(decl);+ TSNode params = jv_child(decl, "function_value_parameters");+ const jv_def_t *def = jv_def_match(s, line, fr->name, strlen(fr->name), 'c');+ jv_member_open(s, line, 'c', "K", fr, fr->name);+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_sig(s, (TSNode){0}, params, true);+ jv_puts(&s->sb, "\t\t");+ jv_put_slot(s, def, jv_join(s, fr->path, fr->name));+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_pnames(s, params, "parameter");+ jv_putc(&s->sb, '\n');+}++static void jv_kotlin_import(jv_scan_t *s, TSNode header) {+ if (s->lexical && (ts_node_start_byte(header) >= s->untrusted || ts_node_has_error(header))) {+ return;+ }+ TSNode id = jv_child(header, "identifier");+ char text[JV_TYPE_MAX];+ if (ts_node_is_null(id) ||+ !jv_type_name(s, ts_node_start_byte(id), ts_node_end_byte(id), text, sizeof(text))) {+ return;+ }+ if (!ts_node_is_null(jv_child(header, "wildcard_import"))) {+ jv_puts(&s->sb, "I\tw\t-\t");+ jv_puts(&s->sb, text);+ jv_putc(&s->sb, '\n');+ return;+ }+ const char *dot = strrchr(text, '.');+ const char *alias = dot ? dot + SKIP_ONE : text;+ TSNode an = jv_child(header, "import_alias");+ if (!ts_node_is_null(an)) {+ const char *raw = NULL;+ size_t raw_len = 0;+ alias = jv_name_of(s, jv_child(an, "type_identifier"), &raw, &raw_len);+ if (!alias) {+ return;+ }+ }+ jv_puts(&s->sb, "I\ts\t");+ jv_puts(&s->sb, alias);+ jv_putc(&s->sb, '\t');+ jv_puts(&s->sb, text);+ jv_putc(&s->sb, '\n');+}++static char jv_kotlin_type_kind(const jv_scan_t *s, TSNode decl, TSNode body) {+ const char *k = ts_node_type(decl);+ if (strcmp(k, "companion_object") == 0) {+ return 'C';+ }+ if (strcmp(k, "object_declaration") == 0) {+ return 'o';+ }+ if (strcmp(k, "type_alias") == 0) {+ return 't';+ }+ if (!ts_node_is_null(body) && jv_kind(body, "enum_class_body")) {+ return 'e';+ }+ /* the keywords before the name: `interface`, `enum class` */+ uint32_t cc = ts_node_child_count(decl);+ for (uint32_t i = 0; i < cc; i++) {+ TSNode ch = ts_node_child(decl, i);+ if (ts_node_is_named(ch)) {+ if (jv_kind(ch, "type_identifier")) {+ break;+ }+ continue;+ }+ uint32_t a = ts_node_start_byte(ch);+ uint32_t len = ts_node_end_byte(ch) - a;+ if (jv_word_is(s->src + a, len, "interface")) {+ return 'i';+ }+ if (jv_word_is(s->src + a, len, "enum")) {+ return 'e';+ }+ }+ return 'c';+}++static void jv_kotlin_type(jv_scan_t *s, TSNode decl, const jv_frame_t *outer, int depth) {+ TSNode body = jv_kotlin_body(decl);+ char kind = jv_kotlin_type_kind(s, decl, body);+ TSNode name_node = jv_child(decl, "type_identifier");+ const char *raw = NULL;+ size_t raw_len = 0;+ const char *name = (kind == 'C' && ts_node_is_null(name_node))+ ? "Companion"+ : jv_name_of(s, name_node, &raw, &raw_len);+ if (!name) {+ return;+ }+ const char *path = jv_join(s, outer->path, name);+ /* nested deeper than any real program: not placed, like a parse error */+ if (!path || depth >= JV_MAX_DEPTH || !jv_type_placed(s, decl, body, outer->inner_depth)) {+ jv_unplaced(s, decl, true);+ return;+ }+ if (s->lexical && !ts_node_is_null(name_node)) {+ jv_ranges_push(s, &s->seen, ts_node_start_byte(name_node), ts_node_end_byte(name_node));+ }+ int inner = outer->inner_depth + SKIP_ONE;+ bool leaf = depth + SKIP_ONE >= JV_MAX_DEPTH;+ bool incomplete = (s->lexical || leaf) && !ts_node_is_null(body) &&+ jv_kotlin_body_broken(s, body, inner, leaf);+ const jv_def_t *def = raw ? jv_def_match(s, jv_line(decl), raw, raw_len, 'T') : NULL;+ TSNode ctor = jv_child(decl, "primary_constructor");+ jv_frame_t fr = {.owner = s->ntypes++, .path = path, .name = name, .inner_depth = inner};+ jv_type_open(s, decl, kind, incomplete, path);+ jv_put_tparams(s, jv_child(decl, "type_parameters"));+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_supers(s, decl);+ jv_putc(&s->sb, '\t');+ jv_put_slot(s, def, path);+ jv_putc(&s->sb, '\t');+ jv_kotlin_put_pnames(s, ctor, "class_parameter");+ jv_putc(&s->sb, '\n');+ /* a constructor parameter declared with val / var is a property */+ uint32_t pc = ts_node_is_null(ctor) ? 0 : ts_node_named_child_count(ctor);+ for (uint32_t i = 0; i < pc; i++) {+ TSNode p = ts_node_named_child(ctor, i);+ if (jv_kind(p, "class_parameter") &&+ !ts_node_is_null(jv_child(p, "binding_pattern_kind"))) {+ jv_emit_value(s, jv_line(p), jv_child(p, "simple_identifier"), "p", "-", &fr);+ }+ }+ if (!ts_node_is_null(body)) {+ jv_kotlin_container(s, body, &fr, depth + SKIP_ONE);+ }+}++/* The declarations of a class body (or of the file). `depth` is the nesting+ * of the types declared here; jv_kotlin_type bounds it, and so the recursion. */+static void jv_kotlin_container(jv_scan_t *s, TSNode body, const jv_frame_t *fr, int depth) {+ TSTreeCursor cur = ts_tree_cursor_new(body);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ do {+ TSNode c = ts_tree_cursor_current_node(&cur);+ const char *k = ts_node_type(c);+ if (ts_node_is_error(c)) {+ jv_unplaced(s, c, true);+ } else if (ts_node_is_missing(c)) {+ continue;+ } else if (jv_kotlin_is_type(k)) {+ jv_kotlin_type(s, c, fr, depth);+ } else if (strcmp(k, "function_declaration") == 0) {+ jv_kotlin_function(s, c, fr);+ } else if (strcmp(k, "property_declaration") == 0) {+ jv_kotlin_property(s, c, fr);+ } else if (strcmp(k, "secondary_constructor") == 0) {+ jv_kotlin_constructor(s, c, fr);+ } else if (strcmp(k, "enum_entry") == 0) {+ if (jv_member_ok(s, c, (TSNode){0}, false, fr->inner_depth)) {+ jv_member_seen(s, c, (TSNode){0}, false);+ jv_emit_value(s, jv_line(c), jv_child(c, "simple_identifier"), "n", "-", fr);+ }+ } else if (strcmp(k, "import_list") == 0) {+ /* a cursor: an import list can have any number of entries */+ TSTreeCursor ic = ts_tree_cursor_new(c);+ if (ts_tree_cursor_goto_first_child(&ic)) {+ do {+ TSNode h = ts_tree_cursor_current_node(&ic);+ if (jv_kind(h, "import_header")) {+ jv_kotlin_import(s, h);+ }+ } while (ts_tree_cursor_goto_next_sibling(&ic));+ }+ ts_tree_cursor_delete(&ic);+ } else if (strcmp(k, "import_header") == 0) {+ jv_kotlin_import(s, c);+ }+ } while (!s->failed && ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+}++/* ── The scan ────────────────────────────────────────────────────── */++/* The package the file declares, as a record. The declaration is looked for+ * with a cursor: the root can have any number of children. */+static void jv_put_package(jv_scan_t *s) {+ char text[JV_TYPE_MAX];+ text[0] = '\0';+ const char *kind = s->kotlin ? "package_header" : "package_declaration";+ TSNode decl = {0};+ TSTreeCursor cur = ts_tree_cursor_new(s->ctx->root);+ if (ts_tree_cursor_goto_first_child(&cur)) {+ do {+ TSNode c = ts_tree_cursor_current_node(&cur);+ if (jv_kind(c, kind)) {+ decl = c;+ }+ } while (ts_node_is_null(decl) && ts_tree_cursor_goto_next_sibling(&cur));+ }+ ts_tree_cursor_delete(&cur);+ uint32_t nc = ts_node_is_null(decl) ? 0 : ts_node_named_child_count(decl);+ for (uint32_t i = 0; i < nc; i++) {+ TSNode ch = ts_node_named_child(decl, i);+ const char *k = ts_node_type(ch);+ if ((strcmp(k, "scoped_identifier") == 0 || strcmp(k, "identifier") == 0) &&+ !jv_type_name(s, ts_node_start_byte(ch), ts_node_end_byte(ch), text, sizeof(text))) {+ text[0] = '\0';+ }+ }+ jv_puts(&s->sb, "P\t");+ jv_puts(&s->sb, text);+ jv_putc(&s->sb, '\n');+}++/* What only the text shows in a file with parse errors: a type keyword and+ * name the tree has no declaration for (outside the members whose inside is+ * their own) is a quarantined name, and nothing behind the first brace+ * without a partner is placed. */+static void jv_finish_lexical(jv_scan_t *s) {+ int si = 0;+ int mi = 0;+ for (int h = 0; h < s->heads.count && !s->failed; h++) {+ jv_range_t head = s->heads.items[h];+ while (si < s->seen.count && s->seen.items[si].start < head.start) {+ si++;+ }+ if (si < s->seen.count && s->seen.items[si].start == head.start) {+ continue; /* the tree has this declaration */+ }+ while (mi < s->members.count && s->members.items[mi].end <= head.start) {+ mi++;+ }+ if (mi < s->members.count && s->members.items[mi].start <= head.start) {+ continue; /* a local type of a member that is its own */+ }+ uint32_t a = head.start;+ uint32_t b = head.end;+ if (b - a > PAIR_LEN && s->src[a] == '`') {+ a++;+ b--;+ }+ bool ok = b > a && b - a <= JV_NAME_MAX;+ for (uint32_t i = a; ok && i < b; i++) {+ ok = (unsigned char)s->src[i] >= ' ' && s->src[i] != '.';+ }+ if (ok) {+ jv_puts(&s->sb, "Q\t");+ jv_putn(&s->sb, s->src + a, b - a);+ jv_putc(&s->sb, '\n');+ }+ }+ if (s->untrusted < s->src_len) {+ jv_emit_unplaced(s, jv_row_of(s, s->untrusted) + TS_LINE_OFFSET, jv_end_line(s->ctx->root));+ }+}++static const char *jv_scan_scope(CBMExtractCtx *ctx, bool kotlin) {+ if (ts_node_is_null(ctx->root) || !ctx->source) {+ return NULL;+ }+ jv_scan_t s = {.ctx = ctx,+ .tmp = ctx->scratch ? ctx->scratch : ctx->arena,+ .sb = {.a = ctx->arena},+ .src = ctx->source,+ .src_len = ctx->source_len > 0 ? (uint32_t)ctx->source_len : 0,+ .kotlin = kotlin,+ .untrusted = UINT32_MAX};+ s.module_qn = cbm_fqn_module_source_lang(s.tmp, ctx->project, ctx->rel_path, ctx->language);+ if (!s.module_qn) {+ return NULL;+ }+ s.module_len = strlen(s.module_qn);+ s.lexical = ts_node_has_error(ctx->root);+ jv_defs_index(&s);+ if (s.lexical) {+ jv_scan_text(&s);+ }+ jv_puts(&s.sb, CBM_DOCLINK_JVM_SCOPE_TAG "\nL\t");+ jv_putc(&s.sb, kotlin ? 'k' : 'j');+ jv_putc(&s.sb, '\n');+ jv_put_package(&s);+ jv_frame_t top = {.owner = JV_NO_OWNER, .path = "", .name = ""};+ if (kotlin) {+ jv_kotlin_container(&s, ctx->root, &top, 0);+ } else {+ jv_java_container(&s, ctx->root, &top, 0);+ }+ if (s.lexical) {+ jv_finish_lexical(&s);+ }+ if (s.failed || s.sb.failed || !s.sb.buf) {+ return NULL;+ }+ return s.sb.buf;+}++const char *cbm_doclink_java_scan_scope(CBMExtractCtx *ctx) {+ return jv_scan_scope(ctx, false);+}++const char *cbm_doclink_kotlin_scan_scope(CBMExtractCtx *ctx) {+ return jv_scan_scope(ctx, true);+}++/* ── Persisted form ──────────────────────────────────────────────── */++/* Fields (0-based, the tag is field 0) that hold line numbers. */+static bool jv_line_field(char tag, int field) {+ switch (tag) {+ case 'T':+ case 'X':+ return field == 1 || field == 2;+ case 'M':+ return field == 1;+ default:+ return false;+ }+}++/* The parameter names: the last field of a type and of a member record. They+ * serve the file's own references only. */+enum { JV_T_PNAMES = 9, JV_M_PNAMES = 11 };++static bool jv_own_field(char tag, int field) {+ return (tag == 'T' && field == JV_T_PNAMES) || (tag == 'M' && field == JV_M_PNAMES);+}++char *cbm_doclink_jvm_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;+ while (*p) {+ const char *nl = strchr(p, '\n');+ size_t len = nl ? (size_t)(nl - p) : strlen(p);+ char tag = p[0];+ int field = 0;+ size_t i = 0;+ while (i < len) {+ size_t fend = i;+ while (fend < len && p[fend] != '\t') {+ fend++;+ }+ if (jv_line_field(tag, field)) {+ out[w++] = '0';+ } else if (!jv_own_field(tag, field)) {+ 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 = nl + SKIP_ONE;+ } else {+ p += len;+ }+ }+ out[w] = '\0';+ return out;+}diff --git a/src/pipeline/doc_links.c b/src/pipeline/doc_links.cindex 17e84eecb..b486d6267 100644--- a/src/pipeline/doc_links.c+++ b/src/pipeline/doc_links.c@@ -47,6 +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,};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 13eaea13c..5ea4e46af 100644--- a/src/pipeline/doc_links.h+++ b/src/pipeline/doc_links.h@@ -296,6 +296,7 @@ void cbm_doclink_cs_test_unit_memo(bool on);* re-resolves such documents with the edited file. */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;/* 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_jvm.c b/src/pipeline/doc_links_jvm.cnew file mode 100644index 000000000..e01343298--- /dev/null+++ b/src/pipeline/doc_links_jvm.c@@ -0,0 +1,4599 @@+/*+ * doc_links_jvm.c — Javadoc and KDoc reference resolution for doc_links.h.+ *+ * One index over the Java and the Kotlin files of a repository, built from+ * their doc-link scopes (internal/cbm/doclink_jvm.c): on the JVM a package is+ * one namespace whatever language declares into it, so a Kotlin import of a+ * Java class and a Javadoc link to a Kotlin class must meet in one type table.+ * The language of the SOURCE file decides the lookup order; where a target's+ * node is comes from the target's own scope record (slot, own), never from a+ * naming scheme assumed here. Graph nodes are looked up by qualified name+ * only, and only their label and file path are read, so the closure-repair+ * route (whose unchanged nodes are line-less proxies) resolves exactly as a+ * full build does.+ *+ * Entities. A type entity is its binary-style name: package + '.' + the+ * dotted logical path (com.acme.Outer.Inner). Several declarations of one+ * name (source sets, expect/actual) are one entity. A member belongs to the+ * declaration that holds it; overloads of one type share a node.+ *+ * Lookup (the first level with a visible candidate decides; more than one+ * entity there is ambiguous, never a pick):+ * Java type name (javac's order)+ * the method's own type variables (local) -> the enclosing types,+ * innermost first (the type and its member types, its type variables, the+ * member types it inherits) -> the file's own top-level types and its+ * single imports (a static import imports a member type too) -> the+ * file's package -> on-demand imports, with java.lang among them.+ * A qualified name: the head through those levels, the rest as member+ * types; a head no level has is read from the root (packages, then a+ * type). `Type.member` is no reference: Javadoc wants a '#'.+ * Java METHOD, `#m` and `Type#m`: javadoc's own search (jr_walk, read in+ * the JDK source), from the documented definition's type or the type+ * named: the type's own methods -> its superclass, by the whole search+ * (its superclass, its interfaces, the type around IT) -> its+ * interfaces in the order written, likewise -> the type around it,+ * likewise; each type once, the first method found. A type outside the+ * repository on the way, or a method the language gives (Object's,+ * Enum's, Annotation's, an enum's values/valueOf, a record's+ * equals/hashCode/toString), ends it as `external`. Static imports are+ * no step: javadoc does not search them for a member.+ * Java FIELD, `#x` and `Type#x` without a parameter list: javadoc looks in+ * the type, then the types around it, then the supertypes; an inherited+ * field binds only when no type further out has one of that name, else+ * it is ambiguous. ({@value Type#X}: the type and its supertypes.)+ * Java kinds+ * `#x` is the field when javadoc takes it over the method its search+ * finds: the field's class is the method's class or below it, also for+ * every type outside the repository the search passes (jr_java_field);+ * else that method, when it is one of the repository with nothing+ * unseen before it (javadoc links it), or external.+ * A parameter list selects callables:+ * the first type whose overloads have that signature, never another+ * overload. A declared type variable matches its own name or its erasure.+ * A method name without a list that has several signatures is ambiguous.+ * A record's component declares an accessor of its name (no node).+ * `#Type(..)` names the constructors of that type only. A bare+ * identifier that is no type is javadoc's `#identifier`.+ * Kotlin (the order KDoc resolves in)+ * the definition's own parameters, type parameters and `this` (local) ->+ * each enclosing type, innermost first: what it holds itself together+ * with its companion (one scope), its type parameters and constructor+ * parameters (local), then what it inherits and what its companion+ * inherits -> explicit imports -> the file's package (types and top-level+ * declarations) -> star imports -> default imports.+ * A FUNCTION or PROPERTY found further out than an enclosing type binds+ * only when that type is known not to have a member of the name: a type+ * that has it from the language (kotlin.Any's members, an enum class's),+ * or whose supertypes leave the repository, makes it `external`+ * (jr_kotlin_simple). A type found further out binds.+ * A dotted name: the qualifier is a type (through those levels, or from+ * the root) and the last name what that type holds, inherits, or gets+ * from an extension in scope whose receiver it is (an extension only+ * where the type's supertypes all lie in the repository: a member comes+ * before an extension); or the qualifier is a+ * package and the last name one of its types or top-level declarations.+ * Kotlin kinds+ * a type and a function of one name at one level (a class and its factory+ * function) are the type: KDoc resolves a classifier before a function+ * (jr_kl_result). A type without a node of its own is then a graph gap,+ * never the function. A property and a function of one name are+ * ambiguous, and so is an overload group.+ * A `[name]` that resolves to nothing is plain text to KDoc (Markdown):+ * no reference at all. @see, @throws and @sample name their subject and+ * keep a row.+ * Visibility: product code never binds a declaration that only test code+ * holds (test_only_target, no fallback to it); `@sample` is exempt.+ * External: a name a single import brings from a package the repository does+ * not declare; a qualified `pkg.Type` whose package it does not declare; a+ * name only an on-demand import of such a package can supply; java.lang and+ * the Kotlin default imports (the languages' own implicit imports, the only+ * name lists here, and consulted after the repository's own declarations); an+ * all-lower-case path under `java`, `javax` or `kotlin` (the platforms' own+ * namespaces; no library family is one), or under a package the file imports+ * from and the repository does not declare; a+ * member that a supertype outside the repository may declare; the members+ * every type has without declaring them (Object's, an enum's).+ * Not indexed: a package below one the repository owns, in a directory the+ * indexer skips by name (discovery's own rule, no file system access here).+ * Graph gaps: a declaration without a definition (slot '-'), one whose+ * qualified name another declaration took (own 0), a node of another kind or+ * file, a package (it has no node), a member a parse error hides, a name the+ * scan could not place, a definition in a part of its file it could not+ * place -- and a reference that resolves, written on a definition that has+ * no node of its own to leave from.+ */+#include "pipeline/doc_links.h"++#include "doclink.h"+#include "helpers.h" /* cbm_fqn_module_source_lang */+#include "discover/discover.h" /* cbm_should_skip_dir */+#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 <stdatomic.h>+#include <stdio.h>+#include <stdlib.h>+#include <string.h>++enum {+ JR_KEY_BUF = 2048,+ JR_MAX_SEGS = 32, /* dotted segments of one reference; more is unparseable */+ JR_MAX_PARAMS = 32, /* written parameters of one reference; more is unparseable */+ JR_PARAM_BUF = 160,+ JR_T_FIELDS = 10,+ JR_M_FIELDS = 12,+ JR_NONE = -1,+};++/* ── Index data ──────────────────────────────────────────────────── */++typedef struct {+ char kind; /* s single, w on-demand, m static single, n static on-demand */+ const char *alias;+ const char *target;+} jr_import_t;++typedef struct {+ uint32_t from;+ uint32_t to;+} jr_lines_t;++/* Line numbers are meaningful only in a file re-extracted by this run: the+ * persisted scope of every other file carries zeros. They are read for the+ * SOURCE file's own context, never for a target. */+typedef struct {+ uint32_t start;+ uint32_t end;+ char kind; /* c i e r a o C t */+ bool incomplete;+ bool own; /* its definition is the one the graph keeps for the slot */+ const char *path; /* logical path */+ const char *name;+ const char *tparams;+ const char *supers;+ const char+ *slot; /* NULL: no definition; "=": the logical path; else the name below the module */+ const char *pnames; /* run files only */+ int outer; /* the enclosing type of this file, or JR_NONE */+ int entity;+} jr_type_t;++typedef struct {+ uint32_t start;+ char kind; /* c callable, v value */+ bool ctor; /* K */+ bool component; /* p: a record component or constructor property */+ bool own;+ int owner; /* its type in this file; JR_NONE: a Kotlin top-level declaration */+ int order; /* position in the scope */+ int shares; /* the member of this file whose node it shares; JR_NONE: it has none */+ int recv_entity; /* a Kotlin extension's receiver type, when the repository declares it */+ const char *name;+ const char *tparams;+ const char *sig;+ const char *recv;+ const char *slot;+ const char *pnames;+} jr_member_t;++typedef struct {+ const char *rel_path;+ const char *module_qn;+ const char *package;+ bool kotlin;+ bool is_test;+ bool scoped; /* its scope was read: without one nothing in it resolves */+ jr_import_t *imports; /* single imports, sorted by alias then target */+ int nimports;+ jr_import_t *wild; /* on-demand imports, scope order */+ int nwild;+ jr_type_t *types; /* scope order: an outer type before its nested ones */+ int ntypes;+ jr_member_t *members; /* sorted by (owner, name, order) */+ int nmembers;+ int *by_start; /* member indices sorted by (start, order) */+ jr_lines_t *unplaced;+ int nunplaced;+} jr_file_t;++typedef struct {+ int file;+ int type;+} jr_decl_t;++/* A step of javadoc's search for a method (jr_walk) that is no type of the+ * repository. */+enum {+ JR_W_NONE = JR_NONE, /* no step: an interface has no superclass */+ JR_W_OBJECT = -2, /* java.lang.Object */+ JR_W_ENUM = -3, /* java.lang.Enum, then Object */+ JR_W_ANNOTATION = -4, /* java.lang.annotation.Annotation */+ JR_W_OUTSIDE = -5, /* a type outside the repository, or a step whose place+ in the order the index cannot tell */+};++typedef struct {+ const char *fqn;+ const char *name;+ char kind;+ jr_decl_t *decls; /* sorted by file (path order), then scope order */+ int ndecls;+ int dcap;+ int *bases; /* the supertypes its declarations name, as far as the repository declares them */+ int nbases;+ int *closure; /* every supertype the repository declares, nearest first */+ int nclosure;+ int companion; /* Kotlin: its companion object, or JR_NONE */+ bool open; /* a supertype outside the repository, or one that could not be bound */+ bool incomplete; /* a declaration of it has members a parse error hides */+ bool any_prod;+ /* javadoc's search for a method at this type (jr_walk): the superclass+ * step (a type, or JR_W_*), the interface steps in the order written,+ * and the type around it */+ int wsuper;+ int *wifaces;+ int nwifaces;+ int encl;+} jr_entity_t;++typedef struct {+ int *items;+ int count;+ int cap;+} jr_ilist_t;++/* What the resolve phase counts for the run's log line. The index itself is+ * read-only then; these are the only words it writes. */+typedef struct {+ _Atomic int64_t source_gaps; /* resolved, but the documented definition has no node */+ _Atomic int64_t plain_text; /* KDoc `[name]` that names nothing: plain text */+ _Atomic int64_t type_and_function; /* KDoc name that is a type and a function at one+ * level: resolved as the type */+ _Atomic int64_t type_and_function_node; /* ... where the type has a node (an edge) */+ /* Members further on that a lookup did not take, because something+ * before them may have the member unseen (javadoc's search, jr_walk; the+ * guards of jr_kotlin_simple and jr_kotlin_in_type): `external`. */+ _Atomic int64_t java_given; /* Javadoc method: the language gives one first */+ _Atomic int64_t java_open; /* ... or a type outside the repository comes first */+ _Atomic int64_t kotlin_given; /* KDoc name: the same two cases */+ _Atomic int64_t kotlin_open;+ _Atomic int64_t kotlin_extension; /* KDoc `Type.name`: an extension, the type's+ * hierarchy leaving the repository */+ /* Javadoc fields not taken, because a method that javadoc's search may+ * reach first, outside the repository, may be what it links+ * (jr_java_field). */+ _Atomic int64_t java_field; /* `#x` */+ _Atomic int64_t java_field_named; /* `Type#x` */+} jr_stats_t;++typedef struct {+ CBMArena arena;+ bool oom;+ jr_stats_t *stats;+ int mode; /* the run's index mode: which directories discovery skips */+ const char *project;+ jr_file_t *files;+ int nfiles;+ int *run_to_file;+ int run_count;+ jr_entity_t *ents;+ int nents;+ int ecap;+ CBMHashTable *ent_by_fqn; /* fqn -> entity + 1 */+ CBMHashTable *pkg_types; /* "package\x1f name" -> entity + 1 (top-level types) */+ CBMHashTable *packages; /* every package a file declares */+ CBMHashTable *pkg_prefixes; /* ... and every prefix of one */+ CBMHashTable *pkg_members; /* "package\x1f name" -> jr_ilist_t* of files (Kotlin top level) */+ CBMHashTable *extensions; /* "<entity>\x1f name" -> jr_ilist_t* of (file, member) pairs */+ CBMHashTable *quarantine; /* names of types declared where no scope is known */+ CBMHashTable *quarantine_test; /* the same, declared by test code only */+} jr_index_t;++/* ── Small helpers ───────────────────────────────────────────────── */++/* Index memory. A failed allocation is remembered: whatever a caller does+ * with its NULL, the build as a whole reports failure instead of handing out+ * an index that silently lacks a declaration. */+static void *jr_alloc(jr_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 char *jr_strdup(jr_index_t *ix, const char *s) {+ char *p = cbm_arena_strdup(&ix->arena, s ? s : "");+ ix->oom = ix->oom || !p;+ return p;+}++static bool jr_ilist_push(jr_index_t *ix, jr_ilist_t *l, int v) {+ if (l->count >= l->cap) {+ int ncap = l->cap ? l->cap * PAIR_LEN : CBM_SZ_4;+ int *grown = (int *)jr_alloc(ix, (size_t)ncap * sizeof(int));+ if (!grown) {+ return false;+ }+ if (l->count > 0) {+ memcpy(grown, l->items, (size_t)l->count * sizeof(int));+ }+ l->items = grown;+ l->cap = ncap;+ }+ l->items[l->count++] = v;+ return true;+}++static jr_ilist_t *jr_ht_ilist(jr_index_t *ix, CBMHashTable *ht, const char *key, bool create) {+ jr_ilist_t *l = (jr_ilist_t *)cbm_ht_get(ht, key);+ if (l || !create) {+ return l;+ }+ l = (jr_ilist_t *)jr_alloc(ix, sizeof(*l));+ char *k = jr_strdup(ix, key);+ if (!l || !k) {+ return NULL;+ }+ memset(l, 0, sizeof(*l));+ cbm_ht_set(ht, k, l);+ return l;+}++/* Add `key` to a name set; false when memory ran out. */+static bool jr_mark(jr_index_t *ix, CBMHashTable *ht, const char *key) {+ if (cbm_ht_get(ht, key)) {+ return true;+ }+ char *k = jr_strdup(ix, key);+ if (!k) {+ return false;+ }+ cbm_ht_set(ht, k, (void *)k);+ return true;+}++static bool jr_ci_equal(const char *s, size_t n, const char *word) {+ if (strlen(word) != n) {+ return false;+ }+ for (size_t i = 0; i < n; i++) {+ if (tolower((unsigned char)s[i]) != word[i]) {+ return false;+ }+ }+ return true;+}++static bool jr_ci_contains(const char *s, size_t n, const char *word) {+ size_t wl = strlen(word);+ for (size_t i = 0; i + wl <= n; i++) {+ size_t k = 0;+ while (k < wl && tolower((unsigned char)s[i + k]) == word[k]) {+ k++;+ }+ if (k == wl) {+ return true;+ }+ }+ return false;+}++/* True when one word of the directory name s[0, n) says test code: the name+ * is split at '-', '_', '.' and at a lower-to-upper case step (`commonTest`,+ * `json-tests`, `testFixtures`, `smoke-test-http`), and a word is compared+ * whole, so `latest` and `attestation` say nothing. */+static bool jr_test_dir_name(const char *s, size_t n) {+ static const char *const words[] = {"test", "tests", "fixture", "fixtures",+ "sample", "samples", "example", "examples"};+ size_t start = 0;+ for (size_t i = 0; i <= n; i++) {+ bool sep = i == n || s[i] == '-' || s[i] == '_' || s[i] == '.';+ bool step = !sep && i > start && isupper((unsigned char)s[i]) &&+ !isupper((unsigned char)s[i - SKIP_ONE]);+ if (!sep && !step) {+ continue;+ }+ for (size_t w = 0; w < sizeof(words) / sizeof(words[0]); w++) {+ if (jr_ci_equal(s + start, i - start, words[w])) {+ return true;+ }+ }+ start = sep ? i + SKIP_ONE : i;+ }+ return false;+}++/* Test code, by where a build puts it:+ * - the source set after the last `src` directory holds "test" (`src/test`,+ * `src/jvmTest`, `src/testFixtures`, `src/internalClusterTest`), or+ * - a directory above that source root (any directory, when there is no+ * `src`) has a word test, fixture, sample or example in its name: a test+ * project, a `commonTest/src` source set, a samples tree.+ * Directories below a source set are packages: `src/main/java/org/acme/test/+ * Tool.java` is product code. A file name decides nothing. */+static bool jr_is_test_path(const char *rel) {+ const char *src_set = NULL; /* the segment after the last `src` directory */+ size_t src_set_len = 0;+ const char *last_src = NULL;+ for (const char *p = rel;;) {+ const char *slash = strchr(p, '/');+ if (!slash) {+ break;+ }+ if (slash - p == 3 && memcmp(p, "src", 3) == 0) {+ const char *next = slash + SKIP_ONE;+ const char *end = strchr(next, '/');+ last_src = p;+ src_set = end ? next : NULL; /* a file right under src is no source set */+ src_set_len = end ? (size_t)(end - next) : 0;+ }+ p = slash + SKIP_ONE;+ }+ if (src_set && jr_ci_contains(src_set, src_set_len, "test")) {+ return true;+ }+ for (const char *p = rel; !last_src || p < last_src;) {+ const char *slash = strchr(p, '/');+ if (!slash) {+ break;+ }+ if (jr_test_dir_name(p, (size_t)(slash - p))) {+ return true;+ }+ p = slash + SKIP_ONE;+ }+ return false;+}++/* Split `s` in place at tabs into at most `max` fields; returns the count. */+static int jr_split(char *s, char **out, int max) {+ int n = 0;+ out[n++] = s;+ for (char *p = s; *p && n < max; p++) {+ if (*p == '\t') {+ *p = '\0';+ out[n++] = p + SKIP_ONE;+ }+ }+ return n;+}++/* True when name[0, nl) is one of the ','-joined names of `list`. An entry may+ * carry a bound (`T:Comparable`, a Java type variable's): *bound / *blen are+ * set to it (length 0 when it has none). */+static bool jr_listed_n(const char *list, const char *name, size_t nl, const char **bound,+ size_t *blen) {+ for (const char *p = list; p && *p;) {+ const char *e = strchr(p, ',');+ size_t n = e ? (size_t)(e - p) : strlen(p);+ const char *colon = (const char *)memchr(p, ':', n);+ size_t name_len = colon ? (size_t)(colon - p) : n;+ if (name_len == nl && memcmp(p, name, nl) == 0) {+ if (bound) {+ *bound = colon ? colon + SKIP_ONE : p + n;+ *blen = colon ? n - name_len - SKIP_ONE : 0;+ }+ return true;+ }+ p = e ? e + SKIP_ONE : NULL;+ }+ return false;+}++static bool jr_listed(const char *list, const char *name) {+ return jr_listed_n(list, name, strlen(name), NULL, NULL);+}++/* ── Scope parsing ───────────────────────────────────────────────── */++static int jr_import_cmp(const void *a, const void *b) {+ const jr_import_t *x = (const jr_import_t *)a;+ const jr_import_t *y = (const jr_import_t *)b;+ int c = strcmp(x->alias, y->alias);+ return c ? c : strcmp(x->target, y->target);+}++static int jr_member_cmp(const void *a, const void *b) {+ const jr_member_t *x = (const jr_member_t *)a;+ const jr_member_t *y = (const jr_member_t *)b;+ if (x->owner != y->owner) {+ return x->owner < y->owner ? -1 : 1;+ }+ int c = strcmp(x->name, y->name);+ if (c) {+ return c;+ }+ return (x->order > y->order) - (x->order < y->order);+}++typedef struct {+ uint32_t start;+ int order;+ int idx;+} jr_start_key_t;++static int jr_start_cmp(const void *a, const void *b) {+ const jr_start_key_t *x = (const jr_start_key_t *)a;+ const jr_start_key_t *y = (const jr_start_key_t *)b;+ if (x->start != y->start) {+ return x->start < y->start ? -1 : 1;+ }+ return (x->order > y->order) - (x->order < y->order);+}++static int jr_lines_cmp(const void *a, const void *b) {+ const jr_lines_t *x = (const jr_lines_t *)a;+ const jr_lines_t *y = (const jr_lines_t *)b;+ if (x->from != y->from) {+ return x->from < y->from ? -1 : 1;+ }+ return (x->to > y->to) - (x->to < y->to);+}++static void jr_parse_type(jr_file_t *f, char **fld, int *stack, int *sp) {+ jr_type_t *t = &f->types[f->ntypes];+ memset(t, 0, sizeof(*t));+ t->start = (uint32_t)strtoul(fld[1], NULL, 10);+ t->end = (uint32_t)strtoul(fld[2], NULL, 10);+ t->kind = fld[3][0];+ t->incomplete = fld[3][0] && fld[3][1] == '!';+ t->path = fld[4];+ const char *dot = strrchr(t->path, '.');+ t->name = dot ? dot + SKIP_ONE : t->path;+ t->tparams = fld[5];+ t->supers = fld[6];+ t->slot = strcmp(fld[7], "-") == 0 ? NULL : fld[7];+ t->own = fld[8][0] == '1';+ t->pnames = fld[9];+ t->entity = JR_NONE;+ /* the enclosing type: the nearest earlier type whose path is this path+ * without its last name (a nested type follows its outer type) */+ size_t outer_len = dot ? (size_t)(dot - t->path) : 0;+ while (*sp > 0) {+ const char *op = f->types[stack[*sp - SKIP_ONE]].path;+ if (dot && strlen(op) == outer_len && memcmp(op, t->path, outer_len) == 0) {+ break;+ }+ (*sp)--;+ }+ t->outer = (dot && *sp > 0) ? stack[*sp - SKIP_ONE] : JR_NONE;+ stack[(*sp)++] = f->ntypes;+ f->ntypes++;+}++static bool jr_parse_member(jr_file_t *f, char **fld) {+ jr_member_t *m = &f->members[f->nmembers];+ memset(m, 0, sizeof(*m));+ m->start = (uint32_t)strtoul(fld[1], NULL, 10);+ m->kind = fld[2][0];+ m->ctor = strchr(fld[3], 'K') != NULL;+ m->component = strchr(fld[3], 'p') != NULL;+ m->owner = strcmp(fld[4], "-") == 0 ? JR_NONE : atoi(fld[4]);+ if (m->owner >= f->ntypes || (m->owner < 0 && m->owner != JR_NONE) || !fld[5][0] ||+ (m->kind != 'c' && m->kind != 'v')) {+ return false; /* not a record this code wrote */+ }+ m->name = fld[5];+ m->tparams = fld[6];+ m->sig = fld[7];+ m->recv = fld[8];+ m->slot = strcmp(fld[9], "-") == 0 ? NULL : fld[9];+ m->own = fld[10][0] == '1';+ m->pnames = fld[11];+ m->order = f->nmembers;+ m->shares = JR_NONE;+ m->recv_entity = JR_NONE;+ f->nmembers++;+ return true;+}++/* Which member's node each member shares. A value has its own or none.+ * Callables of one name in one type (overloads) share the node of the one+ * that owns their slot. */+static void jr_link_shared_nodes(jr_file_t *f) {+ for (int i = 0; i < f->nmembers;) {+ int j = i;+ int owner = JR_NONE; /* the callable of this run that owns the node */+ while (j < f->nmembers && f->members[j].owner == f->members[i].owner &&+ strcmp(f->members[j].name, f->members[i].name) == 0) {+ jr_member_t *m = &f->members[j];+ if (m->kind == 'c' && m->slot && m->own) {+ owner = j;+ }+ j++;+ }+ for (int k = i; k < j; k++) {+ jr_member_t *m = &f->members[k];+ if (!m->slot) {+ continue;+ }+ if (m->own) {+ m->shares = k;+ } else if (m->kind == 'c' && owner != JR_NONE &&+ strcmp(f->members[owner].slot, m->slot) == 0 &&+ f->members[owner].ctor == m->ctor) {+ m->shares = owner;+ }+ }+ i = j;+ }+}++/* Parse one file's scope. false when it is not a scope this code wrote, or+ * memory ran out. */+static bool jr_parse_scope(jr_index_t *ix, jr_file_t *f, const char *blob) {+ char *buf = jr_strdup(ix, blob);+ if (!buf) {+ return false;+ }+ int ni = 0;+ int nt = 0;+ int nm = 0;+ int nx = 0;+ for (const char *p = buf; *p;) {+ ni += *p == 'I';+ nt += *p == 'T';+ nm += *p == 'M';+ nx += *p == 'X';+ const char *nl = strchr(p, '\n');+ if (!nl) {+ break;+ }+ p = nl + SKIP_ONE;+ }+ f->imports = (jr_import_t *)jr_alloc(ix, (size_t)ni * sizeof(jr_import_t));+ f->wild = (jr_import_t *)jr_alloc(ix, (size_t)ni * sizeof(jr_import_t));+ f->types = (jr_type_t *)jr_alloc(ix, (size_t)nt * sizeof(jr_type_t));+ f->members = (jr_member_t *)jr_alloc(ix, (size_t)nm * sizeof(jr_member_t));+ f->unplaced = (jr_lines_t *)jr_alloc(ix, (size_t)nx * sizeof(jr_lines_t));+ int *stack = (int *)cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)(nt + SKIP_ONE) * sizeof(int));+ if (!f->imports || !f->wild || !f->types || !f->members || !f->unplaced || !stack) {+ cbm_free(CBM_MEM_CLASS_OTHER, stack);+ ix->oom = true;+ return false;+ }+ int sp = 0;+ bool first = true;+ bool ok = true;+ for (char *line = buf; ok && line && *line;) {+ char *nl = strchr(line, '\n');+ if (nl) {+ *nl = '\0';+ }+ char *fld[JR_M_FIELDS];+ if (first) {+ first = false;+ ok = strcmp(line, CBM_DOCLINK_JVM_SCOPE_TAG) == 0;+ } else if (line[0] == 'L') {+ f->kotlin = jr_split(line, fld, PAIR_LEN) == PAIR_LEN && fld[1][0] == 'k';+ } else if (line[0] == 'P') {+ if (jr_split(line, fld, PAIR_LEN) == PAIR_LEN) {+ f->package = fld[1];+ }+ } else if (line[0] == 'I') {+ if (jr_split(line, fld, CBM_SZ_4) == CBM_SZ_4 && fld[1][0] && fld[3][0]) {+ jr_import_t imp = {.kind = fld[1][0], .alias = fld[2], .target = fld[3]};+ if (imp.kind == 'w' || imp.kind == 'n') {+ f->wild[f->nwild++] = imp;+ } else {+ f->imports[f->nimports++] = imp;+ }+ }+ } else if (line[0] == 'T') {+ /* a member names its type by position: a type record that cannot+ * be read spoils the whole scope */+ ok = jr_split(line, fld, JR_T_FIELDS) == JR_T_FIELDS && fld[4][0];+ if (ok) {+ jr_parse_type(f, fld, stack, &sp);+ }+ } else if (line[0] == 'M') {+ ok = jr_split(line, fld, JR_M_FIELDS) == JR_M_FIELDS && jr_parse_member(f, fld);+ } else if (line[0] == 'X') {+ if (jr_split(line, fld, 3) == 3) {+ f->unplaced[f->nunplaced++] =+ (jr_lines_t){.from = (uint32_t)strtoul(fld[1], NULL, 10),+ .to = (uint32_t)strtoul(fld[2], NULL, 10)};+ }+ } else if (line[0] == 'Q') {+ if (jr_split(line, fld, PAIR_LEN) == PAIR_LEN && fld[1][0]) {+ ok = jr_mark(ix, f->is_test ? ix->quarantine_test : ix->quarantine, fld[1]);+ }+ }+ line = nl ? nl + SKIP_ONE : NULL;+ }+ cbm_free(CBM_MEM_CLASS_OTHER, stack);+ if (!ok || first) {+ return false;+ }+ if (f->nimports > 1) {+ qsort(f->imports, (size_t)f->nimports, sizeof(jr_import_t), jr_import_cmp);+ }+ if (f->nmembers > 1) {+ qsort(f->members, (size_t)f->nmembers, sizeof(jr_member_t), jr_member_cmp);+ }+ jr_link_shared_nodes(f);+ /* the unplaced line ranges: sorted and disjoint, for a binary search */+ if (f->nunplaced > 1) {+ qsort(f->unplaced, (size_t)f->nunplaced, sizeof(jr_lines_t), jr_lines_cmp);+ int w = 0;+ for (int i = SKIP_ONE; i < f->nunplaced; i++) {+ if (f->unplaced[i].from <= f->unplaced[w].to) {+ if (f->unplaced[i].to > f->unplaced[w].to) {+ f->unplaced[w].to = f->unplaced[i].to;+ }+ } else {+ f->unplaced[++w] = f->unplaced[i];+ }+ }+ f->nunplaced = w + SKIP_ONE;+ }+ f->by_start = (int *)jr_alloc(ix, (size_t)f->nmembers * sizeof(int));+ jr_start_key_t *keys =+ f->nmembers > 0+ ? (jr_start_key_t *)cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)f->nmembers * sizeof(*keys))+ : NULL;+ if (f->nmembers > 0 && (!f->by_start || !keys)) {+ cbm_free(CBM_MEM_CLASS_OTHER, keys);+ ix->oom = true;+ return false;+ }+ for (int i = 0; i < f->nmembers; i++) {+ keys[i] =+ (jr_start_key_t){.start = f->members[i].start, .order = f->members[i].order, .idx = i};+ }+ if (f->nmembers > 1) {+ qsort(keys, (size_t)f->nmembers, sizeof(*keys), jr_start_cmp);+ }+ for (int i = 0; i < f->nmembers; i++) {+ f->by_start[i] = keys[i].idx;+ }+ cbm_free(CBM_MEM_CLASS_OTHER, keys);+ return true;+}++/* ── Entities ────────────────────────────────────────────────────── */++enum { JR_ENT_FAIL = -1, JR_ENT_SKIP = -2 };++/* "package.path", or "path" in the default package. false when it does not+ * fit (a name longer than any real one). */+static bool jr_fqn(const char *package, const char *path, char *out, size_t cap) {+ int n = (package && package[0]) ? snprintf(out, cap, "%s.%s", package, path)+ : snprintf(out, cap, "%s", path);+ return n >= 0 && (size_t)n < cap;+}++static bool jr_pair_key(const char *a, const char *b, char *out, size_t cap) {+ int n = snprintf(out, cap, "%s\x1f%s", a ? a : "", b);+ return n >= 0 && (size_t)n < cap;+}++static int jr_ent(const jr_index_t *ix, const char *fqn) {+ intptr_t v = (intptr_t)cbm_ht_get(ix->ent_by_fqn, fqn);+ return v > 0 ? (int)(v - SKIP_ONE) : JR_NONE;+}++/* The entity `fqn`, created on first sight. */+static int jr_entity_get(jr_index_t *ix, const char *fqn, const char *name, char kind) {+ int found = jr_ent(ix, fqn);+ if (found != JR_NONE) {+ return found;+ }+ if (ix->nents >= ix->ecap) {+ int ncap = ix->ecap ? ix->ecap * PAIR_LEN : CBM_SZ_1K;+ jr_entity_t *grown =+ (jr_entity_t *)cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)ncap * sizeof(jr_entity_t));+ if (!grown) {+ return JR_ENT_FAIL;+ }+ if (ix->nents > 0) {+ memcpy(grown, ix->ents, (size_t)ix->nents * sizeof(jr_entity_t));+ }+ cbm_free(CBM_MEM_CLASS_OTHER, ix->ents);+ ix->ents = grown;+ ix->ecap = ncap;+ }+ int id = ix->nents;+ jr_entity_t *e = &ix->ents[id];+ memset(e, 0, sizeof(*e));+ e->fqn = jr_strdup(ix, fqn);+ e->name = name;+ e->kind = kind;+ e->companion = JR_NONE;+ e->wsuper = JR_W_OUTSIDE; /* until jr_resolve_supers has read its declarations */+ e->encl = JR_NONE;+ if (!e->fqn) {+ return JR_ENT_FAIL;+ }+ ix->nents++;+ cbm_ht_set(ix->ent_by_fqn, e->fqn, (void *)(intptr_t)(id + SKIP_ONE));+ return id;+}++static bool jr_entity_add_decl(jr_index_t *ix, jr_entity_t *e, int file, int type) {+ if (e->ndecls >= e->dcap) {+ int ncap = e->dcap ? e->dcap * PAIR_LEN : CBM_SZ_2;+ jr_decl_t *grown = (jr_decl_t *)jr_alloc(ix, (size_t)ncap * sizeof(jr_decl_t));+ if (!grown) {+ return false;+ }+ if (e->ndecls > 0) {+ memcpy(grown, e->decls, (size_t)e->ndecls * sizeof(jr_decl_t));+ }+ e->decls = grown;+ e->dcap = ncap;+ }+ e->decls[e->ndecls++] = (jr_decl_t){.file = file, .type = type};+ e->any_prod = e->any_prod || !ix->files[file].is_test;+ e->incomplete = e->incomplete || ix->files[file].types[type].incomplete;+ return true;+}++static bool jr_mark_package(jr_index_t *ix, const char *package) {+ if (!package || !package[0]) {+ return true;+ }+ if (!jr_mark(ix, ix->packages, package)) {+ return false;+ }+ char buf[JR_KEY_BUF];+ if (snprintf(buf, sizeof(buf), "%s", package) >= (int)sizeof(buf)) {+ return true;+ }+ for (char *dot = strrchr(buf, '.'); dot; dot = strrchr(buf, '.')) {+ *dot = '\0';+ if (!jr_mark(ix, ix->pkg_prefixes, buf)) {+ return false;+ }+ }+ return true;+}++/* The entities of every declared type and the package tables. Files come in+ * path order and types in scope order, so every declaration list is in that+ * order too. *skipped counts declarations whose name is too long to index;+ * their names are quarantined, so a reference to one binds nothing else. */+static bool jr_build_entities(jr_index_t *ix, int *skipped) {+ for (int fi = 0; fi < ix->nfiles; fi++) {+ jr_file_t *f = &ix->files[fi];+ if (!jr_mark_package(ix, f->package)) {+ return false;+ }+ for (int ti = 0; ti < f->ntypes; ti++) {+ jr_type_t *t = &f->types[ti];+ char fqn[JR_KEY_BUF];+ char key[JR_KEY_BUF];+ int id = jr_fqn(f->package, t->path, fqn, sizeof(fqn)) &&+ jr_pair_key(f->package, t->name, key, sizeof(key))+ ? jr_entity_get(ix, fqn, t->name, t->kind)+ : JR_ENT_SKIP;+ if (id == JR_ENT_SKIP) {+ (*skipped)++;+ if (!jr_mark(ix, f->is_test ? ix->quarantine_test : ix->quarantine, t->name)) {+ return false;+ }+ continue;+ }+ if (id < 0 || !jr_entity_add_decl(ix, &ix->ents[id], fi, ti)) {+ return false;+ }+ t->entity = id;+ if (t->kind == 'C' && t->outer != JR_NONE && f->types[t->outer].entity >= 0) {+ ix->ents[f->types[t->outer].entity].companion = id;+ }+ if (t->outer == JR_NONE && !cbm_ht_get(ix->pkg_types, key)) {+ char *k = jr_strdup(ix, key);+ if (!k) {+ return false;+ }+ cbm_ht_set(ix->pkg_types, k, (void *)(intptr_t)(id + SKIP_ONE));+ }+ }+ /* Kotlin top-level declarations: the files of a package that declare+ * a name (each file once: its members of one name are one run) */+ for (int mi = 0; mi < f->nmembers && f->members[mi].owner == JR_NONE; mi++) {+ const jr_member_t *m = &f->members[mi];+ if (mi > 0 && strcmp(f->members[mi - SKIP_ONE].name, m->name) == 0) {+ continue;+ }+ char key[JR_KEY_BUF];+ if (!jr_pair_key(f->package, m->name, key, sizeof(key))) {+ continue;+ }+ jr_ilist_t *l = jr_ht_ilist(ix, ix->pkg_members, key, true);+ if (!l || !jr_ilist_push(ix, l, fi)) {+ return false;+ }+ }+ }+ return true;+}++/* ── The languages' own implicit imports ─────────────────────────────+ *+ * java.lang (Java and Kotlin/JVM) and the Kotlin default imports are part of+ * the lookup order of every file. They are consulted last, after everything+ * the repository declares, and only say "this simple name is the language's":+ * external. Nothing else here is a list of names. */++static const char *const JR_JAVA_LANG[] = {+ "AbstractMethodError",+ "Appendable",+ "ArithmeticException",+ "ArrayIndexOutOfBoundsException",+ "ArrayStoreException",+ "AssertionError",+ "AutoCloseable",+ "Boolean",+ "BootstrapMethodError",+ "Byte",+ "CharSequence",+ "Character",+ "Class",+ "ClassCastException",+ "ClassCircularityError",+ "ClassFormatError",+ "ClassLoader",+ "ClassNotFoundException",+ "ClassValue",+ "CloneNotSupportedException",+ "Cloneable",+ "Comparable",+ "Compiler",+ "Deprecated",+ "Double",+ "Enum",+ "EnumConstantNotPresentException",+ "Error",+ "Exception",+ "ExceptionInInitializerError",+ "Float",+ "FunctionalInterface",+ "IllegalAccessError",+ "IllegalAccessException",+ "IllegalArgumentException",+ "IllegalCallerException",+ "IllegalMonitorStateException",+ "IllegalStateException",+ "IllegalThreadStateException",+ "IncompatibleClassChangeError",+ "IndexOutOfBoundsException",+ "InheritableThreadLocal",+ "InstantiationError",+ "InstantiationException",+ "Integer",+ "InternalError",+ "InterruptedException",+ "Iterable",+ "LayerInstantiationException",+ "LinkageError",+ "Long",+ "MatchException",+ "Math",+ "Module",+ "ModuleLayer",+ "NegativeArraySizeException",+ "NoClassDefFoundError",+ "NoSuchFieldError",+ "NoSuchFieldException",+ "NoSuchMethodError",+ "NoSuchMethodException",+ "NullPointerException",+ "Number",+ "NumberFormatException",+ "Object",+ "OutOfMemoryError",+ "Override",+ "Package",+ "Process",+ "ProcessBuilder",+ "ProcessHandle",+ "Readable",+ "Record",+ "ReflectiveOperationException",+ "Runnable",+ "Runtime",+ "RuntimeException",+ "RuntimePermission",+ "SafeVarargs",+ "ScopedValue",+ "SecurityException",+ "SecurityManager",+ "Short",+ "StackOverflowError",+ "StackTraceElement",+ "StackWalker",+ "StrictMath",+ "String",+ "StringBuffer",+ "StringBuilder",+ "StringIndexOutOfBoundsException",+ "StringTemplate",+ "SuppressWarnings",+ "System",+ "Thread",+ "ThreadDeath",+ "ThreadGroup",+ "ThreadLocal",+ "Throwable",+ "TypeNotPresentException",+ "UnknownError",+ "UnsatisfiedLinkError",+ "UnsupportedClassVersionError",+ "UnsupportedOperationException",+ "VerifyError",+ "VirtualMachineError",+ "Void",+ "WrongThreadException",+};++/* kotlin.*, kotlin.annotation.*, kotlin.collections.*, kotlin.comparisons.*,+ * kotlin.io.*, kotlin.ranges.*, kotlin.sequences.*, kotlin.text.* and+ * kotlin.jvm.*: their types and the standard scope functions. */+static const char *const JR_KOTLIN_DEFAULT[] = {+ "AbstractCollection",+ "AbstractIterator",+ "AbstractList",+ "AbstractMap",+ "AbstractMutableCollection",+ "AbstractMutableList",+ "AbstractMutableMap",+ "AbstractMutableSet",+ "AbstractSet",+ "Annotation",+ "AnnotationRetention",+ "AnnotationTarget",+ "Any",+ "Array",+ "ArrayDeque",+ "ArrayList",+ "Boolean",+ "BooleanArray",+ "BuilderInference",+ "Byte",+ "ByteArray",+ "Char",+ "CharArray",+ "CharCategory",+ "CharProgression",+ "CharRange",+ "CharSequence",+ "Charsets",+ "ClosedFloatingPointRange",+ "ClosedRange",+ "Collection",+ "Comparable",+ "Comparator",+ "ConcurrentModificationException",+ "DeepRecursiveFunction",+ "Deprecated",+ "DeprecationLevel",+ "Double",+ "DoubleArray",+ "DslMarker",+ "Enum",+ "Float",+ "FloatArray",+ "Function",+ "Grouping",+ "HashMap",+ "HashSet",+ "IndexedValue",+ "Int",+ "IntArray",+ "IntProgression",+ "IntRange",+ "Iterable",+ "Iterator",+ "JvmField",+ "JvmInline",+ "JvmName",+ "JvmOverloads",+ "JvmRecord",+ "JvmStatic",+ "JvmSuppressWildcards",+ "JvmSynthetic",+ "JvmWildcard",+ "KotlinVersion",+ "Lazy",+ "LazyThreadSafetyMode",+ "LinkedHashMap",+ "LinkedHashSet",+ "List",+ "ListIterator",+ "Long",+ "LongArray",+ "LongProgression",+ "LongRange",+ "Map",+ "MatchGroup",+ "MatchGroupCollection",+ "MatchResult",+ "Metadata",+ "MustBeDocumented",+ "MutableCollection",+ "MutableIterable",+ "MutableIterator",+ "MutableList",+ "MutableListIterator",+ "MutableMap",+ "MutableSet",+ "NoSuchElementException",+ "NotImplementedError",+ "Nothing",+ "Number",+ "OpenEndRange",+ "OptIn",+ "Pair",+ "ParameterName",+ "PublishedApi",+ "RandomAccess",+ "Regex",+ "RegexOption",+ "Repeatable",+ "ReplaceWith",+ "RequiresOptIn",+ "Result",+ "Retention",+ "Sequence",+ "SequenceScope",+ "Set",+ "Short",+ "ShortArray",+ "SinceKotlin",+ "String",+ "StringBuilder",+ "Strictfp",+ "Suppress",+ "Synchronized",+ "Target",+ "Throws",+ "Transient",+ "Triple",+ "UByte",+ "UByteArray",+ "UInt",+ "UIntArray",+ "UIntRange",+ "ULong",+ "ULongArray",+ "ULongRange",+ "UShort",+ "UShortArray",+ "UninitializedPropertyAccessException",+ "Unit",+ "Volatile",+ /* functions */+ "TODO",+ "also",+ "apply",+ "arrayListOf",+ "arrayOf",+ "arrayOfNulls",+ "assert",+ "buildList",+ "buildMap",+ "buildSet",+ "buildString",+ "check",+ "checkNotNull",+ "compareBy",+ "compareValues",+ "emptyArray",+ "emptyList",+ "emptyMap",+ "emptySequence",+ "emptySet",+ "enumValueOf",+ "enumValues",+ "error",+ "generateSequence",+ "hashMapOf",+ "hashSetOf",+ "lazy",+ "lazyOf",+ "let",+ "linkedMapOf",+ "linkedSetOf",+ "listOf",+ "listOfNotNull",+ "mapOf",+ "maxOf",+ "minOf",+ "mutableListOf",+ "mutableMapOf",+ "mutableSetOf",+ "print",+ "println",+ "readLine",+ "readln",+ "repeat",+ "require",+ "requireNotNull",+ "run",+ "runCatching",+ "sequence",+ "sequenceOf",+ "setOf",+ "synchronized",+ "takeIf",+ "takeUnless",+ "to",+ "use",+ "with",+};++static const char *const JR_JAVA_PRIMITIVES[] = {"boolean", "byte", "char", "short", "int",+ "long", "float", "double", "void"};++/* The members a type has without declaring them. These lists are defined by+ * the two languages, not collected from a library: the methods of+ * java.lang.Object with their parameter lists ('|'-joined, as a declared+ * signature is normalized), the three members of kotlin.Any, and what an enum+ * has in either language (the methods of java.lang.Enum with the two static+ * ones the language declares; the Kotlin counterparts). Written from knowledge+ * of the two language specifications; not checked online. */+typedef struct {+ const char *name;+ const char *sig;+} jr_given_t;++static const jr_given_t JR_OBJECT_METHODS[] = {+ {"equals", "Object"}, {"hashCode", ""}, {"toString", ""}, {"clone", ""},+ {"finalize", ""}, {"getClass", ""}, {"notify", ""}, {"notifyAll", ""},+ {"wait", ""}, {"wait", "long"}, {"wait", "long|int"}};+static const char *const JR_ANY_MEMBERS[] = {"equals", "hashCode", "toString"};+static const char *const JR_JAVA_ENUM_MEMBERS[] = {+ "values", "valueOf", "name", "ordinal", "compareTo", "getDeclaringClass", "describeConstable"};+static const char *const JR_KOTLIN_ENUM_MEMBERS[] = {"values", "valueOf", "entries",+ "name", "ordinal", "compareTo"};++static bool jr_named(const char *const *table, size_t n, const char *name) {+ for (size_t i = 0; i < n; i++) {+ if (strcmp(table[i], name) == 0) {+ return true;+ }+ }+ return false;+}++#define JR_NAMED(table, name) jr_named(table, sizeof(table) / sizeof((table)[0]), name)++/* ── Resolution context ──────────────────────────────────────────── */++/* The scan nests types JV_MAX_DEPTH (128) deep at most; a chain is never+ * longer. */+enum { JR_CHAIN_MAX = 136 };++enum { JR_OK = 0, JR_UNRES, JR_LOCAL };++typedef struct {+ int st;+ const cbm_gbuf_node_t *node;+ bool exact;+ int reason;+} jr_res_t;++typedef struct {+ const jr_index_t *ix;+ const cbm_gbuf_t *g;+ int file;+ const jr_file_t *f;+ bool prod; /* test-only declarations are invisible */+ bool sample; /* a `@sample` subject: it names a function */+ bool inherit; /* false while supertypes are being bound */+ int chain[JR_CHAIN_MAX]; /* enclosing types, innermost first */+ const jr_type_t *chain_decl[JR_CHAIN_MAX]; /* ... and their declarations in this file */+ int nchain;+ const jr_member_t *member; /* the documented member, when the definition is one */+ const jr_type_t *type; /* the documented type, when the definition is one */+} jr_ctx_t;++static jr_res_t jr_edge(const cbm_gbuf_node_t *n, bool exact) {+ return (jr_res_t){.st = JR_OK, .node = n, .exact = exact};+}++static jr_res_t jr_unres(int reason) {+ return (jr_res_t){.st = JR_UNRES, .reason = reason};+}++static bool jr_visible(const jr_ctx_t *c, int ent) {+ return !c->prod || c->ix->ents[ent].any_prod;+}++/* The enclosing types of type `t` of the context's file, `t` first. */+static void jr_chain_from(jr_ctx_t *c, int t) {+ while (t != JR_NONE && c->nchain < JR_CHAIN_MAX) {+ const jr_type_t *ty = &c->f->types[t];+ if (ty->entity >= 0) {+ c->chain[c->nchain] = ty->entity;+ c->chain_decl[c->nchain] = ty;+ c->nchain++;+ }+ t = ty->outer;+ }+}++/* ── Type candidates of one scope level ──────────────────────────── */++typedef struct {+ char kind; /* 0 none; T a type, X a name outside the repository, G a name the+ repository declares where no scope shows it, N a name in a+ package of the repository that the indexer does not read */+ int ent; /* T: the type */+ int count; /* distinct candidates; 2 stands for "several" */+ bool invisible; /* a candidate product code may not bind was passed over */+ bool exact; /* named by an explicit import */+} jr_cands_t;++static void jr_cand(jr_cands_t *out, char kind, int ent) {+ if (out->count > 0 && out->kind == kind && out->ent == ent) {+ return;+ }+ if (out->count == 0) {+ out->kind = kind;+ out->ent = ent;+ }+ out->count += out->count < PAIR_LEN;+}++/* A type, unless the source may not name it: product code does not see what+ * only test code declares, and Java does not see a Kotlin type alias. */+static void jr_cand_type(const jr_ctx_t *c, jr_cands_t *out, int ent) {+ if (ent < 0 || (!c->f->kotlin && c->ix->ents[ent].kind == 't')) {+ return;+ }+ if (!jr_visible(c, ent)) {+ out->invisible = true;+ return;+ }+ jr_cand(out, 'T', ent);+}++/* ── Types: lookup tables ────────────────────────────────────────── */++static int jr_pkg_type(const jr_index_t *ix, const char *package, const char *name) {+ char key[JR_KEY_BUF];+ if (!jr_pair_key(package, name, key, sizeof(key))) {+ return JR_NONE;+ }+ intptr_t v = (intptr_t)cbm_ht_get(ix->pkg_types, key);+ return v > 0 ? (int)(v - SKIP_ONE) : JR_NONE;+}++/* The type `name` nested directly in entity `ent`. */+static int jr_nested(const jr_index_t *ix, int ent, const char *name) {+ char fqn[JR_KEY_BUF];+ if (!jr_fqn(ix->ents[ent].fqn, name, fqn, sizeof(fqn))) {+ return JR_NONE;+ }+ return jr_ent(ix, fqn);+}++/* The member type `name` of `ent`: its own, else the one of the nearest+ * supertype that declares one. */+static int jr_member_type(const jr_ctx_t *c, int ent, const char *name) {+ int own = jr_nested(c->ix, ent, name);+ if (own != JR_NONE || !c->inherit) {+ return own;+ }+ const jr_entity_t *e = &c->ix->ents[ent];+ for (int i = 0; i < e->nclosure; i++) {+ int n = jr_nested(c->ix, e->closure[i], name);+ if (n != JR_NONE) {+ return n;+ }+ }+ return JR_NONE;+}++static bool jr_open(const jr_index_t *ix, int ent) {+ const jr_entity_t *e = &ix->ents[ent];+ if (e->open) {+ return true;+ }+ for (int i = 0; i < e->nclosure; i++) {+ if (ix->ents[e->closure[i]].open) {+ return true;+ }+ }+ return false;+}++/* True when `sup` is `ent` or one of its supertypes. */+static bool jr_is_or_extends(const jr_index_t *ix, int ent, int sup) {+ if (ent == sup) {+ return true;+ }+ const jr_entity_t *e = &ix->ents[ent];+ for (int i = 0; i < e->nclosure; i++) {+ if (e->closure[i] == sup) {+ return true;+ }+ }+ return false;+}++/* ── Node binding ────────────────────────────────────────────────── */++/* Representative ordering of the declarations of one entity, without node+ * ids or lines: the source file itself, the longest common directory prefix+ * with it, then path and declaration order. */+static int jr_common_dirs(const char *a, const char *b) {+ int n = 0;+ for (;;) {+ const char *sa = strchr(a, '/');+ const char *sb = strchr(b, '/');+ if (!sa || !sb) {+ return n;+ }+ size_t la = (size_t)(sa - a);+ if (la != (size_t)(sb - b) || memcmp(a, b, la) != 0) {+ return n;+ }+ n++;+ a = sa + SKIP_ONE;+ b = sb + SKIP_ONE;+ }+}++static bool jr_decl_better(const jr_index_t *ix, int fa, int oa, int fb, int ob, const char *src) {+ const char *ra = ix->files[fa].rel_path;+ const char *rb = ix->files[fb].rel_path;+ bool sa = strcmp(ra, src) == 0;+ bool sb = strcmp(rb, src) == 0;+ if (sa != sb) {+ return sa;+ }+ int pa = jr_common_dirs(ra, src);+ int pb = jr_common_dirs(rb, src);+ if (pa != pb) {+ return pa > pb;+ }+ int cmp = strcmp(ra, rb);+ if (cmp != 0) {+ return cmp < 0;+ }+ return oa < ob;+}++static bool jr_label_callable(const char *l) {+ return l && (strcmp(l, "Method") == 0 || strcmp(l, "Function") == 0);+}++static bool jr_label_value(const char *l) {+ return l && (strcmp(l, "Field") == 0 || strcmp(l, "Variable") == 0);+}++/* The node at "<module>.<tail>" when it is this file's own: one node per+ * qualified name, and across files the graph keeps one file's. */+static const cbm_gbuf_node_t *jr_node_at(const jr_ctx_t *c, const jr_file_t *f, const char *tail) {+ char qn[JR_KEY_BUF];+ if (snprintf(qn, sizeof(qn), "%s.%s", f->module_qn, tail) >= (int)sizeof(qn)) {+ return NULL;+ }+ const cbm_gbuf_node_t *n = cbm_gbuf_find_by_qn(c->g, qn);+ return (n && n->file_path && strcmp(n->file_path, f->rel_path) == 0) ? n : NULL;+}++/* The node of a type declaration; NULL when it has none of its own. */+static const cbm_gbuf_node_t *jr_type_node(const jr_ctx_t *c, jr_decl_t d) {+ const jr_file_t *f = &c->ix->files[d.file];+ const jr_type_t *t = &f->types[d.type];+ if (!t->slot || !t->own) {+ return NULL;+ }+ const cbm_gbuf_node_t *n = jr_node_at(c, f, strcmp(t->slot, "=") == 0 ? t->path : t->slot);+ return (n && cbm_label_is_type_like(n->label)) ? n : NULL;+}++/* The node of a member: its own, or the one the overloads of its name share.+ * NULL when it has none, or when the slot holds a node of the other kind. */+static const cbm_gbuf_node_t *jr_member_node(const jr_ctx_t *c, int file, const jr_member_t *m) {+ const jr_file_t *f = &c->ix->files[file];+ if (m->shares == JR_NONE) {+ return NULL;+ }+ const jr_member_t *o = &f->members[m->shares];+ char tail[JR_KEY_BUF];+ const char *slot = o->slot;+ if (strcmp(slot, "=") == 0) {+ int n = o->owner == JR_NONE+ ? snprintf(tail, sizeof(tail), "%s", o->name)+ : snprintf(tail, sizeof(tail), "%s.%s", f->types[o->owner].path, o->name);+ if (n < 0 || n >= (int)sizeof(tail)) {+ return NULL;+ }+ slot = tail;+ }+ const cbm_gbuf_node_t *n = jr_node_at(c, f, slot);+ if (!n) {+ return NULL;+ }+ return (o->kind == 'c' ? jr_label_callable(n->label) : jr_label_value(n->label)) ? n : NULL;+}++/* The entity's representative node: never a test declaration for product+ * code. An entity none of whose eligible declarations has a node is a graph+ * gap. */+static jr_res_t jr_type_result(const jr_ctx_t *c, int ent, bool exact) {+ const jr_index_t *ix = c->ix;+ const jr_entity_t *e = &ix->ents[ent];+ const cbm_gbuf_node_t *best = NULL;+ int bf = 0;+ int bo = 0;+ for (int d = 0; d < e->ndecls; d++) {+ int file = e->decls[d].file;+ if (c->prod && ix->files[file].is_test) {+ continue;+ }+ const cbm_gbuf_node_t *n = jr_type_node(c, e->decls[d]);+ if (n && (!best || jr_decl_better(ix, file, e->decls[d].type, bf, bo, c->f->rel_path))) {+ best = n;+ bf = file;+ bo = e->decls[d].type;+ }+ }+ return best ? jr_edge(best, exact) : jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+}++/* ── Reference syntax ────────────────────────────────────────────── */++typedef struct {+ char text[CBM_DOCLINK_JVM_REF_MAX + CBM_SZ_8]; /* the segments point in here */+ char *segs[JR_MAX_SEGS];+ int nsegs;+ char *member; /* Java: the name after '#' (or of a bare `name(..)`); NULL when none */+ bool has_params;+ char params[JR_MAX_PARAMS][JR_PARAM_BUF];+ int nparams;+} jr_ref_t;++static bool jr_ident(const char *s) {+ unsigned char first = (unsigned char)s[0];+ if (!(isalpha(first) || first == '_' || first == '$' || first >= 0x80)) {+ return false;+ }+ for (const char *p = s + SKIP_ONE; *p; p++) {+ unsigned char u = (unsigned char)*p;+ if (!(isalnum(u) || u == '_' || u == '$' || u >= 0x80)) {+ return false;+ }+ }+ return true;+}++/* Split a dotted path in place into identifiers; false when a part is none+ * or there are more parts than a name has. */+static bool jr_split_path(char *s, jr_ref_t *r) {+ r->nsegs = 0;+ if (!s[0]) {+ return true;+ }+ for (char *p = s;;) {+ char *dot = strchr(p, '.');+ if (dot) {+ *dot = '\0';+ }+ if (r->nsegs >= JR_MAX_SEGS || !jr_ident(p)) {+ return false;+ }+ r->segs[r->nsegs++] = p;+ if (!dot) {+ return true;+ }+ p = dot + SKIP_ONE;+ }+}++/* The written parameter list s[0, n) of a Javadoc member reference:+ * normalized like the declared signatures. false when it has more+ * parameters than any method. */+static bool jr_parse_params(const char *s, size_t n, jr_ref_t *r) {+ r->has_params = true;+ r->nparams = 0;+ bool any = false;+ for (size_t i = 0; i < n; i++) {+ any = any || !isspace((unsigned char)s[i]);+ }+ if (!any) {+ return true;+ }+ size_t start = 0;+ int depth = 0;+ for (size_t i = 0; i <= n; i++) {+ char ch = i < n ? s[i] : ',';+ if (ch == '<' || ch == '(' || ch == '[') {+ depth++;+ } else if (ch == '>' || ch == ')' || ch == ']') {+ depth--;+ } else if (ch == ',' && depth <= 0) {+ if (r->nparams >= JR_MAX_PARAMS) {+ return false;+ }+ char *p = r->params[r->nparams];+ cbm_doclink_java_norm_type(s + start, i - start, p, sizeof(r->params[0]));+ if (p[0] == '?' && p[SKIP_ONE] == '\0') {+ return false; /* no type, or one longer than any */+ }+ r->nparams++;+ start = i + SKIP_ONE;+ }+ }+ return true;+}++/* `[module/]Type[#member[(params)]]`, `#member[(params)]`, `member(params)`. */+static bool jr_parse_java(const char *raw, jr_ref_t *r) {+ memset(r, 0, sizeof(*r));+ size_t len = strlen(raw);+ if (len == 0 || len > CBM_DOCLINK_JVM_REF_MAX) {+ return false; /* over-long: never resolve a truncated prefix */+ }+ memcpy(r->text, raw, len + SKIP_ONE);+ char *s = r->text;+ char *hash = strchr(s, '#');+ char *paren = strchr(s, '(');+ char *slash = strchr(s, '/');+ if (slash && (!hash || slash < hash) && (!paren || slash < paren)) {+ s = slash + SKIP_ONE; /* a module prefix */+ }+ char *type = s;+ char *member = NULL;+ if (hash) {+ *hash = '\0';+ member = hash + SKIP_ONE;+ } else if (paren) {+ member = s; /* `name(..)`: a member of the documented type */+ type = NULL;+ }+ if (member) {+ char *mp = strchr(member, '(');+ if (mp) {+ size_t ml = strlen(mp);+ if (mp[ml - SKIP_ONE] != ')' || !jr_parse_params(mp + SKIP_ONE, ml - PAIR_LEN, r)) {+ return false; /* a list that does not close, or is longer than any */+ }+ *mp = '\0';+ }+ if (!jr_ident(member)) {+ return false;+ }+ r->member = member;+ }+ if (type) {+ /* without type arguments and array brackets */+ char *lt = strchr(type, '<');+ if (lt) {+ *lt = '\0';+ }+ size_t tl = strlen(type);+ while (tl >= PAIR_LEN && type[tl - PAIR_LEN] == '[' && type[tl - SKIP_ONE] == ']') {+ tl -= PAIR_LEN;+ type[tl] = '\0';+ }+ if (!jr_split_path(type, r)) {+ return false;+ }+ }+ return r->nsegs > 0 || r->member != NULL;+}++/* A KDoc name: dotted, a segment may be backticked. */+static bool jr_parse_kotlin(const char *raw, jr_ref_t *r) {+ memset(r, 0, sizeof(*r));+ size_t len = strlen(raw);+ if (len == 0 || len > CBM_DOCLINK_JVM_REF_MAX) {+ return false;+ }+ /* copy without backticks; a dot inside backticks is no separator, and a+ * name that holds one cannot be a path segment here */+ size_t w = 0;+ bool quoted = false;+ for (size_t i = 0; i < len; i++) {+ if (raw[i] == '`') {+ quoted = !quoted;+ } else if (quoted && raw[i] == '.') {+ return false;+ } else {+ r->text[w++] = raw[i];+ }+ }+ r->text[w] = '\0';+ if (quoted) {+ return false;+ }+ if (w > PAIR_LEN && r->text[w - PAIR_LEN] == '(' && r->text[w - SKIP_ONE] == ')') {+ r->text[w - PAIR_LEN] = '\0'; /* `@see name()` */+ }+ r->nsegs = 0;+ for (char *p = r->text;;) {+ char *dot = strchr(p, '.');+ if (dot) {+ *dot = '\0';+ }+ if (r->nsegs >= JR_MAX_SEGS || !p[0] || strpbrk(p, "\t()#<>[]{}/\\:;,\"'")) {+ return false;+ }+ r->segs[r->nsegs++] = p;+ if (!dot) {+ break;+ }+ p = dot + SKIP_ONE;+ }+ return r->nsegs > 0;+}++/* ── Members of a type ───────────────────────────────────────────── */++enum {+ JR_SEL_VALUES = 1, /* fields, properties, enum constants, components */+ JR_SEL_CALLABLES = 2, /* methods and functions, no constructors */+ JR_SEL_CTORS = 4, /* constructors only */+ JR_SEL_SIG = 8, /* of the callables, those with the written signature */+};++typedef struct {+ int count; /* the selected members */+ bool several; /* ... are more than one thing: different signatures,+ or members of different owners */+ bool component; /* one is a record component or constructor property */+ bool invisible; /* members left out because product code may not bind+ what only test code declares */+ bool uncompared; /* callables left out because a Javadoc signature cannot+ be compared with a Kotlin declaration's */+ const char *sig; /* the first one's */+ const cbm_gbuf_node_t *node; /* the representative node of those that have one */+ int node_file;+ int node_order;+} jr_found_t;++/* Index of the first member of type `type` in `f` named `name` (the members+ * are sorted by owner, name, order); f->nmembers when there is none before+ * the end. */+static int jr_member_lower(const jr_file_t *f, int type, const char *name) {+ int lo = 0;+ int hi = f->nmembers;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ const jr_member_t *m = &f->members[mid];+ bool below = m->owner != type ? m->owner < type : strcmp(m->name, name) < 0;+ if (below) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo;+}++/* The suffix of a normalized type that says how many array levels it has. */+static size_t jr_array_suffix(const char *s, size_t n) {+ size_t e = n;+ while (e >= PAIR_LEN && s[e - PAIR_LEN] == '[' && s[e - SKIP_ONE] == ']') {+ e -= PAIR_LEN;+ }+ return e;+}++/* True when `name[0, n)` is a type variable in scope of a member of type+ * `owner` whose own type parameters are `mtparams`: the member's, its type's+ * or an enclosing type's. *bound / *blen: its first bound. */+static bool jr_is_tvar(const jr_file_t *f, const char *mtparams, int owner, const char *name,+ size_t n, const char **bound, size_t *blen) {+ if (n == 0) {+ return false;+ }+ if (jr_listed_n(mtparams, name, n, bound, blen)) {+ return true;+ }+ for (int t = owner; t != JR_NONE; t = f->types[t].outer) {+ if (jr_listed_n(f->types[t].tparams, name, n, bound, blen)) {+ return true;+ }+ }+ return false;+}++/* One written parameter type against one declared type: the same name, or+ * the erasure of a declared type variable (its first bound, Object when it+ * has none) with the same array rank. Nothing else: javadoc matches a+ * signature against the declared types and against their erasures. */+static bool jr_param_match(const jr_file_t *f, const char *mtparams, int owner, const char *written,+ const char *declared, size_t dn) {+ static const char object[] = "Object";+ size_t wn = strlen(written);+ if (wn == SKIP_ONE && written[0] == '?') {+ return false; /* a written type that is no type */+ }+ if (wn == dn && memcmp(written, declared, wn) == 0) {+ return true;+ }+ size_t wb = jr_array_suffix(written, wn);+ size_t db = jr_array_suffix(declared, dn);+ const char *bound = NULL;+ size_t blen = 0;+ if ((wn - wb) != (dn - db) || !jr_is_tvar(f, mtparams, owner, declared, db, &bound, &blen)) {+ return false;+ }+ if (blen == 0) {+ bound = object;+ blen = sizeof(object) - SKIP_ONE;+ }+ return wb == blen && memcmp(written, bound, blen) == 0;+}++/* True when the written parameter list is the canonical one of the record+ * `owner` declares: its components' types, in declaration order. The written+ * list is at most JR_MAX_PARAMS long, which bounds the passes over the+ * record's members. */+static bool jr_canonical_match(const jr_file_t *f, int owner, const jr_ref_t *r) {+ int first = jr_member_lower(f, owner, "");+ int components = 0;+ for (int i = first; i < f->nmembers && f->members[i].owner == owner; i++) {+ components += f->members[i].component;+ }+ if (components != r->nparams) {+ return false;+ }+ int last_order = JR_NONE;+ for (int k = 0; k < r->nparams; k++) {+ const jr_member_t *next = NULL; /* the component with the next larger order */+ for (int i = first; i < f->nmembers && f->members[i].owner == owner; i++) {+ const jr_member_t *x = &f->members[i];+ if (x->component && x->order > last_order && (!next || x->order < next->order)) {+ next = x;+ }+ }+ if (!next || !jr_param_match(f, "", owner, r->params[k], next->sig, strlen(next->sig))) {+ return false;+ }+ last_order = next->order;+ }+ return true;+}++/* The written parameter types against a declared signature. */+static bool jr_sig_match(const jr_file_t *f, const jr_member_t *m, const jr_ref_t *r) {+ if (m->ctor && strcmp(m->sig, "*") == 0) {+ return jr_canonical_match(f, m->owner, r);+ }+ const char *p = m->sig;+ for (int i = 0; i < r->nparams; i++) {+ if (!p || !*p) {+ return false; /* fewer declared than written */+ }+ const char *bar = strchr(p, '|');+ size_t dn = bar ? (size_t)(bar - p) : strlen(p);+ if (!jr_param_match(f, m->tparams, m->owner, r->params[i], p, dn)) {+ return false;+ }+ p = bar ? bar + SKIP_ONE : NULL;+ }+ return r->nparams == 0 ? m->sig[0] == '\0' : p == NULL;+}++/* Count member `m` of `file` among the selected ones. */+static void jr_found_take(const jr_ctx_t *c, jr_found_t *out, int file, const jr_member_t *m) {+ if (out->count == 0) {+ out->sig = m->sig;+ } else if (strcmp(out->sig, m->sig) != 0) {+ out->several = true;+ }+ out->count++;+ out->component = out->component || m->component;+ const cbm_gbuf_node_t *n = jr_member_node(c, file, m);+ if (n && (!out->node || jr_decl_better(c->ix, file, m->order, out->node_file, out->node_order,+ c->f->rel_path))) {+ out->node = n;+ out->node_file = file;+ out->node_order = m->order;+ }+}++/* Add to `out` the members named `name` that `sel` selects among those `type`+ * of `file` declares (JR_NONE: the file's top-level declarations). */+static void jr_members_in(const jr_ctx_t *c, int file, int type, const char *name, int sel,+ const jr_ref_t *r, jr_found_t *out) {+ const jr_file_t *f = &c->ix->files[file];+ for (int i = jr_member_lower(f, type, name); i < f->nmembers; i++) {+ const jr_member_t *m = &f->members[i];+ if (m->owner != type || strcmp(m->name, name) != 0) {+ break;+ }+ bool take = m->kind == 'v' ? (sel & JR_SEL_VALUES) != 0+ : (sel & (m->ctor ? JR_SEL_CTORS : JR_SEL_CALLABLES)) != 0;+ if (!take) {+ continue;+ }+ if (c->prod && f->is_test) {+ out->invisible = true;+ continue;+ }+ if ((sel & JR_SEL_SIG) && m->kind == 'c') {+ if (f->kotlin) {+ out->uncompared = true; /* Kotlin writes its types another way */+ continue;+ }+ if (!jr_sig_match(f, m, r)) {+ continue;+ }+ }+ jr_found_take(c, out, file, m);+ }+}++/* The members of entity `ent` named `name` that `sel` selects, across its+ * declarations. */+static jr_found_t jr_members(const jr_ctx_t *c, int ent, const char *name, int sel,+ const jr_ref_t *r) {+ const jr_entity_t *e = &c->ix->ents[ent];+ jr_found_t out = {0};+ for (int d = 0; d < e->ndecls; d++) {+ jr_members_in(c, e->decls[d].file, e->decls[d].type, name, sel, r, &out);+ }+ return out;+}++/* The top-level declarations named `name` of package `pkg`, across its+ * files. */+static jr_found_t jr_top_members(const jr_ctx_t *c, const char *pkg, const char *name, int sel) {+ jr_found_t out = {0};+ char key[JR_KEY_BUF];+ if (!jr_pair_key(pkg, name, key, sizeof(key))) {+ return out;+ }+ const jr_ilist_t *l = (const jr_ilist_t *)cbm_ht_get(c->ix->pkg_members, key);+ for (int i = 0; l && i < l->count; i++) {+ jr_members_in(c, l->items[i], JR_NONE, name, sel, NULL, &out);+ }+ return out;+}++/* Join the members found under one name in two places. Members of different+ * owners are different things, whatever their signatures. */+static void jr_found_add(const jr_ctx_t *c, jr_found_t *into, const jr_found_t *add,+ bool same_owner) {+ into->invisible = into->invisible || add->invisible;+ into->uncompared = into->uncompared || add->uncompared;+ if (add->count == 0) {+ return;+ }+ if (into->count == 0) {+ bool invisible = into->invisible;+ bool uncompared = into->uncompared;+ *into = *add;+ into->invisible = invisible;+ into->uncompared = uncompared;+ return;+ }+ into->several =+ into->several || add->several || !same_owner || strcmp(into->sig, add->sig) != 0;+ into->count += add->count;+ into->component = into->component || add->component;+ if (add->node &&+ (!into->node || jr_decl_better(c->ix, add->node_file, add->node_order, into->node_file,+ into->node_order, c->f->rel_path))) {+ into->node = add->node;+ into->node_file = add->node_file;+ into->node_order = add->node_order;+ }+}++/* The selected members as a result: their node, or a graph gap when the+ * source declares them and the graph has no node for them. */+static jr_res_t jr_found_result(const jr_found_t *found, bool exact) {+ return found->node ? jr_edge(found->node, exact) : jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+}++/* ── Type paths ──────────────────────────────────────────────────── */++typedef enum { JR_TP_OK = 0, JR_TP_PARTIAL, JR_TP_RES } jr_tp_kind_t;++typedef struct {+ jr_tp_kind_t st;+ int ent; /* OK: the type; PARTIAL: the last type reached */+ int failed_seg; /* PARTIAL: index of the segment that is no member type */+ bool exact;+ bool unfound; /* RES: no scope level has the head (the result says why not) */+ jr_res_t res; /* RES */+} jr_tp_t;++static jr_tp_t jr_tp_res(jr_res_t r) {+ return (jr_tp_t){.st = JR_TP_RES, .res = r};+}++static bool jr_join(char *const *segs, int from, int to, char *out, size_t cap) {+ size_t w = 0;+ out[0] = '\0';+ for (int i = from; i < to; i++) {+ int k = snprintf(out + w, cap - w, "%s%s", w ? "." : "", segs[i]);+ if (k < 0 || (size_t)k >= cap - w) {+ return false;+ }+ w += (size_t)k;+ }+ return true;+}++/* Walk segs[from, to) as member types of `cur` (own, then inherited). */+static jr_tp_t jr_walk_nested(const jr_ctx_t *c, int cur, char *const *segs, int from, int to,+ bool exact) {+ for (int i = from; i < to; i++) {+ int next = jr_member_type(c, cur, segs[i]);+ if (next == JR_NONE) {+ return (jr_tp_t){.st = JR_TP_PARTIAL, .ent = cur, .failed_seg = i, .exact = exact};+ }+ if (!jr_visible(c, next)) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_TEST_ONLY));+ }+ cur = next;+ }+ return (jr_tp_t){.st = JR_TP_OK, .ent = cur, .exact = exact};+}++/* The file's single import of the simple name `name` with one of `kinds`;+ * the next one after `prev` (the imports are sorted by alias). */+static const jr_import_t *jr_import_next(const jr_file_t *f, const char *name,+ const jr_import_t *prev) {+ int i;+ if (prev) {+ i = (int)(prev - f->imports) + SKIP_ONE;+ } else {+ int lo = 0;+ int hi = f->nimports;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (strcmp(f->imports[mid].alias, name) < 0) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ i = lo;+ }+ return (i < f->nimports && strcmp(f->imports[i].alias, name) == 0) ? &f->imports[i] : NULL;+}++/* True when the repository declares package `p`. */+static bool jr_is_package(const jr_index_t *ix, const char *p) {+ return p[0] && cbm_ht_get(ix->packages, p) != NULL;+}++/* The package part of a qualified name: everything before its last name.+ * false for a simple name. */+static bool jr_package_of(const char *fqn, char *out, size_t cap) {+ const char *dot = strrchr(fqn, '.');+ if (!dot || (size_t)(dot - fqn) >= cap) {+ return false;+ }+ memcpy(out, fqn, (size_t)(dot - fqn));+ out[dot - fqn] = '\0';+ return true;+}++/* True when the file's scope is open: an on-demand import of a package the+ * repository does not declare (or of a type it does not declare) can supply+ * any simple name. */+static bool jr_scope_open(const jr_ctx_t *c) {+ for (int i = 0; i < c->f->nwild; i++) {+ const char *target = c->f->wild[i].target;+ if (!jr_is_package(c->ix, target) && jr_ent(c->ix, target) == JR_NONE) {+ return true;+ }+ }+ return false;+}++/* True when package `pkg` lies in a directory the indexer never reads, below+ * a package the repository owns. A JVM package is a directory path, and+ * discovery skips some directory names wherever they occur (`env`, `target`,+ * `tmp` ...): what is declared there is on disk, but not in the graph. */+static bool jr_not_indexed(const jr_index_t *ix, const char *pkg) {+ char buf[JR_KEY_BUF];+ size_t n = strlen(pkg);+ if (n == 0 || n >= sizeof(buf)) {+ return false;+ }+ memcpy(buf, pkg, n + SKIP_ONE);+ bool owned = false; /* a prefix before this segment is the repository's */+ size_t seg = 0;+ for (size_t i = 0; i <= n; i++) {+ if (buf[i] != '.' && buf[i] != '\0') {+ continue;+ }+ char keep = buf[i];+ buf[i] = '\0'; /* buf: the prefix through this segment; buf + seg: the segment */+ if (owned && cbm_should_skip_dir(buf + seg, (cbm_index_mode_t)ix->mode)) {+ return true;+ }+ owned = owned || cbm_ht_get(ix->packages, buf) || cbm_ht_get(ix->pkg_prefixes, buf);+ buf[i] = keep;+ seg = i + SKIP_ONE;+ }+ return false;+}++/* What a name that no scope shows is, by its package: declared by the+ * repository without a scope record (G: generated code, a declaration the+ * scan does not see), in a part of it the indexer does not read (N), or+ * outside the repository (X). `pkg`: the package, or the type, the name is+ * said to be in. */+static char jr_unseen_kind(const jr_index_t *ix, const char *pkg) {+ if (pkg[0] && (jr_is_package(ix, pkg) || jr_ent(ix, pkg) != JR_NONE)) {+ return 'G';+ }+ return jr_not_indexed(ix, pkg) ? 'N' : 'X';+}++static int jr_kind_reason(char kind) {+ return kind == 'G' ? CBM_DOCLINK_REASON_GRAPH_GAP+ : kind == 'N' ? CBM_DOCLINK_REASON_NOT_INDEXED+ : CBM_DOCLINK_REASON_EXTERNAL;+}++/* What an explicit import of `fqn` names: the type, or what jr_unseen_kind+ * says of its package. */+static void jr_cand_import_type(const jr_ctx_t *c, jr_cands_t *out, const char *fqn) {+ int ent = jr_ent(c->ix, fqn);+ if (ent != JR_NONE) {+ jr_cand_type(c, out, ent);+ return;+ }+ char pkg[JR_KEY_BUF];+ if (!jr_package_of(fqn, pkg, sizeof(pkg))) {+ pkg[0] = '\0';+ }+ jr_cand(out, jr_unseen_kind(c->ix, pkg), JR_NONE);+}++/* ── Why a name was not found ────────────────────────────────────── */++/* A simple name no scope level has: the scope can still explain it. */+static jr_res_t jr_unfound_simple(const jr_ctx_t *c, const char *name) {+ if (!c->f->kotlin && JR_NAMED(JR_JAVA_PRIMITIVES, name)) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ if (jr_scope_open(c)) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ for (int i = 0; c->inherit && i < c->nchain; i++) {+ if (jr_open(c->ix, c->chain[i])) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL); /* a supertype outside may declare it */+ }+ }+ return jr_unres(CBM_DOCLINK_REASON_MISSING);+}++/* True when the file imports something of package `pkg` (or the package+ * itself on demand) and the repository does not declare that package. */+static bool jr_imports_outside(const jr_ctx_t *c, const char *pkg) {+ if (jr_is_package(c->ix, pkg)) {+ return false;+ }+ size_t pl = strlen(pkg);+ for (int i = 0; i < c->f->nwild; i++) {+ if (strcmp(c->f->wild[i].target, pkg) == 0) {+ return true;+ }+ }+ for (int i = 0; i < c->f->nimports; i++) {+ const char *t = c->f->imports[i].target;+ if (strncmp(t, pkg, pl) == 0 && t[pl] == '.') {+ return true;+ }+ }+ return false;+}++/* A qualified name that is no type, no member and no top-level declaration.+ * - a package of the repository (or the start of one): packages have no node+ * - `pkg.Type..` (a capitalized name after the package part): the type is+ * missing when the repository declares that package, else it is outside+ * - all lower case: the languages' own namespaces and what the file imports+ * from outside are external; anything else names nothing+ * - `Type.x` with an unknown head: as the simple name+ * The roots are the namespaces the two platforms define themselves (`java`,+ * `javax`, `kotlin`). A library family is none, however common: a path under+ * `kotlinx` or `org` is external only where the file imports from it. */+static jr_res_t jr_unfound_path(const jr_ctx_t *c, char *const *segs, int n) {+ static const char *const roots[] = {"java", "javax", "kotlin"};+ const jr_index_t *ix = c->ix;+ char buf[JR_KEY_BUF];+ if (!jr_join(segs, 0, n, buf, sizeof(buf))) {+ return jr_unres(CBM_DOCLINK_REASON_UNPARSEABLE);+ }+ if (cbm_ht_get(ix->packages, buf) || cbm_ht_get(ix->pkg_prefixes, buf)) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ if (n == SKIP_ONE) {+ return jr_unfound_simple(c, segs[0]);+ }+ int k = 0;+ while (k < n && !isupper((unsigned char)segs[k][0])) {+ k++;+ }+ if (k == 0) {+ return jr_unfound_simple(c, segs[0]);+ }+ if (k < n) {+ (void)jr_join(segs, 0, k, buf, sizeof(buf));+ if (jr_is_package(ix, buf)) {+ return jr_unres(CBM_DOCLINK_REASON_MISSING);+ }+ return jr_unres(jr_kind_reason(jr_unseen_kind(ix, buf)));+ }+ if (JR_NAMED(roots, segs[0])) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ if (jr_not_indexed(ix, buf)) {+ return jr_unres(CBM_DOCLINK_REASON_NOT_INDEXED); /* a package the indexer skips */+ }+ for (int i = n; i >= SKIP_ONE; i--) {+ (void)jr_join(segs, 0, i, buf, sizeof(buf));+ if (jr_imports_outside(c, buf)) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ }+ return jr_unres(CBM_DOCLINK_REASON_MISSING);+}++/* ── Members across supertypes ───────────────────────────────────── */++/* How many supertypes that declare a name are compared with the nearest one.+ * Past that the name is ambiguous: an unresolved outcome with its reason,+ * never a pick. */+enum { JR_CLASH_CHECKS = 16 };++typedef struct {+ jr_found_t found; /* the fields of the first type that has any */+ int ent; /* that type; JR_NONE when none has */+ bool gap; /* a type with members a parse error hides was reached before+ any was found: one of those may be the field */+ bool open; /* nothing found, and a supertype outside the repository */+ bool clash; /* a second type declares the name, and neither comes first */+ bool invisible;+} jr_msearch_t;++/* The fields `name` of `ent` (enum constants and record components among+ * them): its own, else those of the nearest supertype that declares any. A+ * second supertype with the name must be one the first extends (hidden);+ * else neither comes first: a clash. Methods are javadoc's search (jr_walk). */+static void jr_fields_in(const jr_ctx_t *c, int ent, const char *name, jr_msearch_t *out) {+ const jr_index_t *ix = c->ix;+ const jr_entity_t *e = &ix->ents[ent];+ memset(out, 0, sizeof(*out));+ out->ent = JR_NONE;+ jr_found_t own = jr_members(c, ent, name, JR_SEL_VALUES, NULL);+ out->invisible = own.invisible;+ if (own.count > 0) {+ out->found = own;+ out->ent = ent;+ return;+ }+ if (e->incomplete) {+ out->gap = true;+ return;+ }+ int checks = 0;+ for (int k = 0; k < e->nclosure; k++) {+ int sup = e->closure[k];+ jr_found_t inh = jr_members(c, sup, name, JR_SEL_VALUES, NULL);+ out->invisible = out->invisible || inh.invisible;+ if (inh.count == 0) {+ if (out->ent == JR_NONE && ix->ents[sup].incomplete) {+ out->gap = true;+ return;+ }+ continue;+ }+ if (out->ent == JR_NONE) {+ out->found = inh;+ out->ent = sup;+ } else if (!out->clash &&+ (++checks > JR_CLASH_CHECKS || !jr_is_or_extends(ix, out->ent, sup))) {+ out->clash = true;+ }+ }+ out->open = out->ent == JR_NONE && jr_open(ix, ent);+}++/* True when java.lang.Object has a method `name`. With `r`, a reference that+ * writes a parameter list: one with exactly that list. */+static bool jr_object_method(const char *name, const jr_ref_t *r) {+ for (size_t i = 0; i < sizeof(JR_OBJECT_METHODS) / sizeof(JR_OBJECT_METHODS[0]); i++) {+ const char *p = JR_OBJECT_METHODS[i].sig;+ bool same = strcmp(JR_OBJECT_METHODS[i].name, name) == 0;+ for (int k = 0; same && r && k < r->nparams; k++) {+ size_t n = strlen(r->params[k]);+ same = n > 0 && strncmp(p, r->params[k], n) == 0 && (p[n] == '|' || p[n] == '\0');+ p += same ? n + (p[n] == '|' ? SKIP_ONE : 0) : 0;+ }+ if (same && (!r || *p == '\0')) {+ return true;+ }+ }+ return false;+}++/* The members every type has without declaring them, in either language:+ * Object's, an enum's, an annotation's. By name alone, and wider than any one+ * language: it only tells `external` from `missing` once nothing was found. */+static bool jr_implicit_member(const jr_index_t *ix, int ent, const char *name) {+ char kind = ix->ents[ent].kind;+ if (jr_object_method(name, NULL)) {+ return true;+ }+ if (kind == 'e') {+ return JR_NAMED(JR_JAVA_ENUM_MEMBERS, name) || JR_NAMED(JR_KOTLIN_ENUM_MEMBERS, name);+ }+ return kind == 'a' && strcmp(name, "annotationType") == 0;+}++/* True when the type `ent`, a type around the documented definition of a+ * Kotlin file, has a member `name` without declaring it: a member of+ * kotlin.Any, at an enum class what an enum class has (the name alone+ * decides). Java's counterpart is javadoc's own search (jr_walk). */+static bool jr_given_member(const jr_ctx_t *c, int ent, const char *name) {+ char kind = c->ix->ents[ent].kind;+ return JR_NAMED(JR_ANY_MEMBERS, name) ||+ (kind == 'e' && JR_NAMED(JR_KOTLIN_ENUM_MEMBERS, name));+}++/* The fields `name` through the context's chain of types, innermost first: a+ * type and what it inherits before the type around it. *level is the chain+ * index of the hit. javadoc looks for a field in a type, then in the types+ * around it, then in its supertypes; where the two orders find different+ * fields, jr_java_member says ambiguous. */+static void jr_fields_around(const jr_ctx_t *c, const char *name, jr_msearch_t *out, int *level) {+ bool open = false;+ bool invisible = false;+ memset(out, 0, sizeof(*out));+ out->ent = JR_NONE;+ *level = 0;+ for (int i = 0; i < c->nchain; i++) {+ jr_msearch_t one;+ jr_fields_in(c, c->chain[i], name, &one);+ open = open || one.open;+ invisible = invisible || one.invisible;+ if (one.ent != JR_NONE || one.gap) {+ *out = one;+ *level = i;+ break;+ }+ }+ out->open = out->ent == JR_NONE && !out->gap && open;+ out->invisible = out->invisible || invisible;+}++/* ── Java: javadoc's search for a method ─────────────────────────── */++/* javadoc links `#m` and `Type#m` to the first method its own search finds+ * (JavacTrees.searchMethod; read in the JDK 21 source on 2026-10-04, stated+ * here in our words). It is not javac's scoping. From a type it looks at+ * 1. the type's own methods of the name; with a written parameter list,+ * one whose parameters match it;+ * 2. the superclass, by this whole search: the superclass's own methods,+ * its superclass, its interfaces and the type around the SUPERCLASS+ * all come before step 3;+ * 3. the interfaces, in the order written, each by this whole search;+ * 4. the type around it, by this whole search;+ * and at each type once. `#m` starts at the type of the documented+ * definition, `Type#m` at the type named. The steps of each type come from+ * its declarations (jr_walk_steps). java.lang.Object, java.lang.Enum and+ * java.lang.annotation.Annotation are steps whose methods the language+ * defines; an enum has values() and valueOf(String), a record equals,+ * hashCode and toString without declaring them. A type outside the+ * repository is a step the index cannot look into: a method there would be+ * the one linked. These lists are the language's, written from knowledge of+ * the Java SE API. */+static const char *const JR_ENUM_OWN_METHODS[] = {"values", "valueOf"};+static const char *const JR_RECORD_OWN_METHODS[] = {"equals", "hashCode", "toString"};+static const char *const JR_ENUM_CLASS_METHODS[] = {+ "name", "ordinal", "compareTo", "getDeclaringClass", "describeConstable",+ "valueOf", "equals", "hashCode", "toString", "clone",+ "finalize"};+static const char *const JR_ANNOTATION_METHODS[] = {"annotationType", "equals", "hashCode",+ "toString"};++/* How many types one search looks at, at most. A search that would look at+ * more ends as ambiguous (JR_WK_LIMIT): never cut short into a result. */+enum { JR_WALK_MAX = 512, JR_WALK_SLOTS = 1024 /* a power of two above twice the max */ };+static const unsigned JR_WALK_MIX = 2654435761U; /* multiplicative hashing */++typedef enum {+ JR_WK_NONE = 0, /* no type on the way has the method */+ JR_WK_FOUND, /* a type of the repository declares it */+ JR_WK_GIVEN, /* the language gives it */+ JR_WK_OUTSIDE, /* a type outside the repository comes first */+ JR_WK_GAP, /* a type whose members a parse error hides comes first */+ JR_WK_UNCOMPARED, /* a Kotlin declaration of the name comes first, which a written+ parameter list cannot be compared with: it may be the one */+ JR_WK_LIMIT, /* more than JR_WALK_MAX types */+} jr_wk_t;++typedef struct {+ jr_wk_t kind;+ /* FOUND, GAP, UNCOMPARED: the type; OUTSIDE: the type whose supertype+ * lies outside; GIVEN: the type that has the method without declaring+ * it, or JR_W_OBJECT, JR_W_ENUM, JR_W_ANNOTATION */+ int ent;+ jr_found_t found; /* FOUND */+ bool invisible; /* a declaration only test code holds was passed over */+ bool passed_outside; /* for a field: a step outside was passed (jr_walk_ends) */+ bool passed_gap; /* ... a type whose members a parse error hides */+} jr_walk_t;++enum { JR_WS_OWN = 0, JR_WS_SUPER, JR_WS_IFACES, JR_WS_DONE };++typedef struct {+ int ent;+ int stage; /* JR_WS_* */+ int next; /* JR_WS_IFACES: the next interface step */+} jr_wframe_t;++/* Marks type `ent` as looked at (`slots` holds ent + 1); false when it was.+ * The caller marks at most JR_WALK_MAX + 1 types, so a free slot is found. */+static bool jr_walk_mark(int *slots, int ent) {+ unsigned mask = (unsigned)JR_WALK_SLOTS - SKIP_ONE;+ unsigned h = ((unsigned)ent * JR_WALK_MIX) & mask;+ for (int i = 0; i < JR_WALK_SLOTS; i++) {+ if (slots[h] == ent + SKIP_ONE) {+ return false;+ }+ if (slots[h] == 0) {+ slots[h] = ent + SKIP_ONE;+ return true;+ }+ h = (h + SKIP_ONE) & mask;+ }+ return false;+}++/* Step 1 at a type of the repository: what the type itself has under the+ * name. True when that ends the step, as *out says. */+static bool jr_walk_own(const jr_ctx_t *c, int ent, const char *name, int sel, const jr_ref_t *r,+ jr_walk_t *out) {+ const jr_entity_t *e = &c->ix->ents[ent];+ jr_found_t own = jr_members(c, ent, name, sel, r);+ out->invisible = out->invisible || own.invisible;+ out->ent = ent;+ if (own.count > 0) {+ out->kind = JR_WK_FOUND;+ out->found = own;+ return true;+ }+ if (own.uncompared) {+ out->kind = JR_WK_UNCOMPARED;+ return true;+ }+ if (e->kind == 'r' && (!(sel & JR_SEL_SIG) || r->nparams == 0)) {+ jr_found_t comp = jr_members(c, ent, name, JR_SEL_VALUES, NULL);+ if (comp.count > 0 && comp.component) {+ /* a component's accessor: the record's own method, without a node */+ memset(&out->found, 0, sizeof(out->found));+ out->found.count = SKIP_ONE;+ out->kind = JR_WK_FOUND;+ return true;+ }+ }+ if ((e->kind == 'e' && JR_NAMED(JR_ENUM_OWN_METHODS, name)) ||+ (e->kind == 'r' && JR_NAMED(JR_RECORD_OWN_METHODS, name))) {+ out->kind = JR_WK_GIVEN;+ return true;+ }+ if (e->incomplete) {+ out->kind = JR_WK_GAP;+ return true;+ }+ out->ent = JR_NONE;+ return false;+}++/* A step that is no type of the repository, taken from type `owner`. True+ * when it ends the search, as *out says. With a written parameter list+ * Object's methods are matched by it; an enum's and an annotation's by name. */+static bool jr_walk_marker(int step, int owner, const char *name, int sel, const jr_ref_t *r,+ jr_walk_t *out) {+ const jr_ref_t *sig = (sel & JR_SEL_SIG) ? r : NULL;+ int given = JR_NONE;+ if (step == JR_W_OUTSIDE) {+ out->kind = JR_WK_OUTSIDE;+ out->ent = owner;+ return true;+ }+ if (step == JR_W_OBJECT && jr_object_method(name, sig)) {+ given = JR_W_OBJECT;+ } else if (step == JR_W_ENUM && JR_NAMED(JR_ENUM_CLASS_METHODS, name)) {+ given = JR_W_ENUM;+ } else if (step == JR_W_ENUM && jr_object_method(name, sig)) {+ given = JR_W_OBJECT;+ } else if (step == JR_W_ANNOTATION && JR_NAMED(JR_ANNOTATION_METHODS, name)) {+ given = JR_W_ANNOTATION;+ }+ if (given == JR_NONE) {+ return false;+ }+ out->kind = JR_WK_GIVEN;+ out->ent = given;+ return true;+}++/* Whether the search ends where *out says. A method is linked where it is+ * found. For a field of class `cf` (jr_java_field) a step outside the+ * repository, or a type whose members a parse error hides, does not end it+ * when `cf` is below the type the step belongs to: whatever method is there,+ * the field comes first, so the search goes on to what may come after it.+ * `peek`, for a count only, passes everything but a method of the+ * repository. */+static bool jr_walk_ends(const jr_index_t *ix, jr_walk_t *out, int cf, bool peek) {+ bool pass = false;+ if (peek) {+ pass = out->kind != JR_WK_FOUND;+ } else if (cf != JR_NONE && (out->kind == JR_WK_OUTSIDE || out->kind == JR_WK_GAP) &&+ jr_is_or_extends(ix, cf, out->ent)) {+ pass = true;+ if (out->kind == JR_WK_OUTSIDE) {+ out->passed_outside = true;+ } else {+ out->passed_gap = true;+ }+ }+ if (pass) {+ out->kind = JR_WK_NONE;+ out->ent = JR_NONE;+ }+ return !pass;+}++/* javadoc's search for a method `name` (`sel`, `r`: a written parameter+ * list) from type `start`, without recursion: an explicit stack, each type+ * once. `cf` and `peek`: jr_walk_ends. */+static void jr_walk(const jr_ctx_t *c, int start, const char *name, int sel, const jr_ref_t *r,+ int cf, bool peek, jr_walk_t *out) {+ const jr_index_t *ix = c->ix;+ int slots[JR_WALK_SLOTS];+ jr_wframe_t stack[JR_WALK_MAX];+ memset(slots, 0, sizeof(slots));+ memset(out, 0, sizeof(*out));+ out->ent = JR_NONE;+ (void)jr_walk_mark(slots, start);+ int marked = SKIP_ONE;+ int depth = 0;+ stack[depth++] = (jr_wframe_t){.ent = start, .stage = JR_WS_OWN, .next = 0};+ while (depth > 0) {+ jr_wframe_t *fr = &stack[depth - SKIP_ONE];+ const jr_entity_t *e = &ix->ents[fr->ent];+ int step = JR_W_NONE;+ if (fr->stage == JR_WS_OWN) {+ fr->stage = JR_WS_SUPER;+ if (jr_walk_own(c, fr->ent, name, sel, r, out) && jr_walk_ends(ix, out, cf, peek)) {+ return;+ }+ continue;+ }+ if (fr->stage == JR_WS_SUPER) {+ fr->stage = JR_WS_IFACES;+ step = e->wsuper;+ } else if (fr->stage == JR_WS_IFACES && fr->next < e->nwifaces) {+ step = e->wifaces[fr->next++];+ } else if (fr->stage == JR_WS_IFACES) {+ fr->stage = JR_WS_DONE;+ step = e->encl;+ } else {+ depth--;+ continue;+ }+ if (step < 0) {+ if (jr_walk_marker(step, fr->ent, name, sel, r, out) &&+ jr_walk_ends(ix, out, cf, peek)) {+ return;+ }+ continue;+ }+ if (!jr_walk_mark(slots, step)) {+ continue;+ }+ if (++marked > JR_WALK_MAX) {+ out->kind = JR_WK_LIMIT;+ out->ent = JR_NONE;+ return;+ }+ stack[depth++] = (jr_wframe_t){.ent = step, .stage = JR_WS_OWN, .next = 0};+ }+}++/* ── Java ────────────────────────────────────────────────────────── */++typedef enum { JR_LK_NONE = 0, JR_LK_FOUND, JR_LK_INVISIBLE, JR_LK_LOCAL } jr_lk_t;++/* Closes one scope level: true when it has a candidate, which then decides+ * the lookup. */+static bool jr_level_done(jr_cands_t *lv, jr_cands_t *out, bool *invisible) {+ if (lv->count > 0) {+ *out = *lv;+ return true;+ }+ *invisible = *invisible || lv->invisible;+ memset(lv, 0, sizeof(*lv));+ return false;+}++/* True when the type `ent` has a declaration in file `file`. */+static bool jr_declared_in(const jr_index_t *ix, int ent, int file) {+ const jr_entity_t *e = &ix->ents[ent];+ for (int d = 0; d < e->ndecls; d++) {+ if (e->decls[d].file == file) {+ return true;+ }+ }+ return false;+}++/* The member types an on-demand import of `target` offers under `name`. */+static void jr_java_on_demand(const jr_ctx_t *c, jr_cands_t *lv, const jr_import_t *imp,+ const char *name) {+ const jr_index_t *ix = c->ix;+ if (imp->kind == 'w' && jr_is_package(ix, imp->target)) {+ jr_cand_type(c, lv, jr_pkg_type(ix, imp->target, name));+ }+ int type = jr_ent(ix, imp->target); /* `import a.Outer.*;`, `import static a.B.*;` */+ if (type != JR_NONE) {+ jr_cand_type(c, lv, jr_member_type(c, type, name));+ }+}++/* A simple type name in a Java file, in javac's order. */+static jr_lk_t jr_java_type_lookup(const jr_ctx_t *c, const char *name, jr_cands_t *out) {+ const jr_index_t *ix = c->ix;+ const jr_file_t *f = c->f;+ jr_cands_t lv = {0};+ bool invisible = false;+ memset(out, 0, sizeof(*out));+ if (c->member && jr_listed(c->member->tparams, name)) {+ return JR_LK_LOCAL; /* the method's own type variable */+ }+ /* enclosing types, innermost first: the type and its member types, its+ * type variables, the member types it inherits */+ for (int i = 0; i < c->nchain; i++) {+ int ent = c->chain[i];+ if (strcmp(ix->ents[ent].name, name) == 0) {+ jr_cand_type(c, &lv, ent);+ }+ jr_cand_type(c, &lv, jr_nested(ix, ent, name));+ if (jr_level_done(&lv, out, &invisible)) {+ return JR_LK_FOUND;+ }+ if (jr_listed(c->chain_decl[i]->tparams, name)) {+ return JR_LK_LOCAL;+ }+ const jr_entity_t *e = &ix->ents[ent];+ for (int k = 0; c->inherit && k < e->nclosure && lv.count == 0; k++) {+ jr_cand_type(c, &lv, jr_nested(ix, e->closure[k], name));+ }+ if (jr_level_done(&lv, out, &invisible)) {+ return JR_LK_FOUND;+ }+ }+ /* the file's own top-level types and its single imports */+ int same = jr_pkg_type(ix, f->package, name);+ if (same != JR_NONE && jr_declared_in(ix, same, c->file)) {+ jr_cand_type(c, &lv, same);+ }+ for (const jr_import_t *imp = jr_import_next(f, name, NULL); imp;+ imp = jr_import_next(f, name, imp)) {+ if (imp->kind == 's') {+ jr_cand_import_type(c, &lv, imp->target);+ continue;+ }+ /* `import static a.B.name;` imports the member TYPE of that name too */+ int owner = jr_ent(ix, imp->target);+ if (owner != JR_NONE) {+ jr_cand_type(c, &lv, jr_member_type(c, owner, name));+ } else {+ /* a member of a type no scope shows: whatever it is, it is not+ * one of the repository's known declarations */+ char pkg[JR_KEY_BUF];+ if (!jr_package_of(imp->target, pkg, sizeof(pkg))) {+ pkg[0] = '\0';+ }+ jr_cand(&lv, jr_unseen_kind(ix, pkg), JR_NONE);+ }+ }+ if (lv.count > 0) {+ lv.exact = true;+ }+ if (jr_level_done(&lv, out, &invisible)) {+ return JR_LK_FOUND;+ }+ /* the file's package */+ jr_cand_type(c, &lv, same);+ if (jr_level_done(&lv, out, &invisible)) {+ return JR_LK_FOUND;+ }+ /* on-demand imports; java.lang is one of them */+ for (int i = 0; i < f->nwild; i++) {+ jr_java_on_demand(c, &lv, &f->wild[i], name);+ }+ int lang = jr_pkg_type(ix, "java.lang", name);+ if (lang != JR_NONE) {+ jr_cand_type(c, &lv, lang);+ } else if (JR_NAMED(JR_JAVA_LANG, name)) {+ jr_cand(&lv, 'X', JR_NONE);+ }+ if (jr_level_done(&lv, out, &invisible)) {+ return JR_LK_FOUND;+ }+ return invisible ? JR_LK_INVISIBLE : JR_LK_NONE;+}++/* A (qualified) type name in a Java file: the head through the scope, the+ * rest as member types; a head no scope level has is read from the root, as+ * packages and then a type. */+static jr_tp_t jr_java_type_path(const jr_ctx_t *c, char *const *segs, int n) {+ const jr_index_t *ix = c->ix;+ jr_cands_t cands;+ jr_lk_t lk = jr_java_type_lookup(c, segs[0], &cands);+ if (lk == JR_LK_LOCAL) {+ return jr_tp_res((jr_res_t){.st = JR_LOCAL});+ }+ if (lk == JR_LK_INVISIBLE) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_TEST_ONLY));+ }+ if (lk == JR_LK_FOUND) {+ if (cands.count > SKIP_ONE) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS));+ }+ if (cands.kind != 'T') {+ return jr_tp_res(jr_unres(jr_kind_reason(cands.kind)));+ }+ return jr_walk_nested(c, cands.ent, segs, SKIP_ONE, n, cands.exact);+ }+ for (int i = SKIP_ONE; i < n; i++) {+ char pkg[JR_KEY_BUF];+ if (!jr_join(segs, 0, i, pkg, sizeof(pkg))) {+ break;+ }+ int ent = jr_pkg_type(ix, pkg, segs[i]);+ if (ent == JR_NONE || ix->ents[ent].kind == 't') {+ continue;+ }+ if (!jr_visible(c, ent)) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_TEST_ONLY));+ }+ return jr_walk_nested(c, ent, segs, i + SKIP_ONE, n, true);+ }+ return jr_tp_res(jr_unfound_path(c, segs, n));+}++/* True when a record declaration of `ent` has exactly the written parameter+ * list as its components. */+static bool jr_record_canonical(const jr_ctx_t *c, int ent, const jr_ref_t *r) {+ const jr_index_t *ix = c->ix;+ const jr_entity_t *e = &ix->ents[ent];+ for (int d = 0; d < e->ndecls; d++) {+ const jr_file_t *f = &ix->files[e->decls[d].file];+ if (f->types[e->decls[d].type].kind == 'r' && !(c->prod && f->is_test) &&+ jr_canonical_match(f, e->decls[d].type, r)) {+ return true;+ }+ }+ return false;+}++/* `Type#Type(..)` and `#Type(..)`: the constructors of that type alone; none+ * is inherited. A constructor the type has without declaring it (the default+ * one, a record's canonical one) has no node. */+static jr_res_t jr_java_ctor(const jr_ctx_t *c, int ent, const jr_ref_t *r, bool exact) {+ const jr_entity_t *e = &c->ix->ents[ent];+ bool params = r->has_params;+ jr_found_t all = jr_members(c, ent, e->name, JR_SEL_CTORS, r);+ if (!params && all.count > 0) {+ return all.several ? jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS) : jr_found_result(&all, exact);+ }+ if (params) {+ jr_found_t sel = jr_members(c, ent, e->name, JR_SEL_CTORS | JR_SEL_SIG, r);+ if (sel.count > 0) {+ return jr_found_result(&sel, exact);+ }+ if (sel.uncompared) {+ return jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS);+ }+ }+ if (e->incomplete) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ if (all.count == 0 && all.invisible) {+ return jr_unres(CBM_DOCLINK_REASON_TEST_ONLY);+ }+ bool has_ctors = e->kind == 'c' || e->kind == 'e' || e->kind == 'r';+ if (has_ctors && params && jr_record_canonical(c, ent, r)) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ if (has_ctors && all.count == 0 && (!params || (r->nparams == 0 && e->kind != 'r'))) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ return jr_unres(CBM_DOCLINK_REASON_MISSING);+}++/* A method reference's outcome from javadoc's search `w` from `base`; `vs`:+ * the field search that came first, if any. A search that ended at a method+ * javadoc would link that the repository does not show is external; when a+ * method of the repository lies further on, the count says so. */+static jr_res_t jr_java_method(const jr_ctx_t *c, int base, const char *name, int sel,+ const jr_ref_t *r, const jr_walk_t *w, const jr_msearch_t *vs,+ bool exact) {+ if (w->kind == JR_WK_FOUND) {+ /* without a list, several signatures are an overload group */+ return (!(sel & JR_SEL_SIG) && w->found.several) ? jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS)+ : jr_found_result(&w->found, exact);+ }+ if (w->kind == JR_WK_GAP) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ if (w->invisible || (vs && vs->invisible)) {+ return jr_unres(CBM_DOCLINK_REASON_TEST_ONLY);+ }+ if (w->kind == JR_WK_UNCOMPARED || w->kind == JR_WK_LIMIT) {+ return jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS);+ }+ if (w->kind == JR_WK_GIVEN || w->kind == JR_WK_OUTSIDE) {+ jr_walk_t further;+ jr_walk(c, base, name, sel, r, JR_NONE, true, &further);+ if (further.kind == JR_WK_FOUND) {+ jr_stats_t *st = c->ix->stats;+ atomic_fetch_add(w->kind == JR_WK_GIVEN ? &st->java_given : &st->java_open, 1);+ }+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ if (jr_implicit_member(c->ix, base, name) || (vs && vs->open)) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ return jr_unres(CBM_DOCLINK_REASON_MISSING);+}++/* A field `vs` that javadoc's field search found for a reference without a+ * parameter list, weighed against javadoc's search for a METHOD of the name+ * from `start` (jr_walk). javadoc takes the field when no method is found, or+ * when the field's class is the method's class or below it+ * (JavacTrees.attributeDocReference, read in the JDK 21 source on+ * 2026-10-04). So the field binds only when that holds whatever the steps the+ * index cannot see hold:+ * - a step outside the repository may hold the method; the field's class+ * must be below the type the step belongs to (then it is below the+ * outside type as well), and the search goes on past it;+ * - a method the language gives is weighed like a declared one: Object's+ * never stops the field; Enum's or Annotation's only an enum's or an+ * annotation type's; a record's or an enum's own implicit one, a field+ * of that type or below it;+ * - against a method of the repository the field binds when its class is+ * below the method's class. Otherwise, with nothing the index cannot see+ * before that method, javadoc links the method, and so does the reference+ * (the lead's ruling of 2026-10-04: a certain binding), with the tier of+ * a member the search finds; an overload group without a list stays+ * ambiguous, as for any method. If a step outside was passed, the method+ * there may be the one: external;+ * - a type whose members a parse error hides may hold the method: a graph+ * gap, unless the field's class is below it (then it is passed, and only+ * a field outcome survives it).+ * *yielded: the field was not taken because of what lies outside. */+static jr_res_t jr_java_field(const jr_ctx_t *c, int start, const char *name, const jr_ref_t *r,+ const jr_msearch_t *vs, bool exact, bool *yielded) {+ const jr_index_t *ix = c->ix;+ int cf = vs->ent;+ char cf_kind = ix->ents[cf].kind;+ jr_walk_t w;+ jr_walk(c, start, name, JR_SEL_CALLABLES, r, cf, false, &w);+ bool field = false;+ int reason = CBM_DOCLINK_REASON_EXTERNAL;+ switch (w.kind) {+ case JR_WK_NONE:+ field = true;+ break;+ case JR_WK_FOUND:+ field = jr_is_or_extends(ix, cf, w.ent);+ if (!field && !w.passed_outside && !w.passed_gap) {+ return w.found.several ? jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS)+ : jr_found_result(&w.found, exact);+ }+ break;+ case JR_WK_GIVEN:+ field = w.ent == JR_W_OBJECT || (w.ent == JR_W_ENUM && cf_kind == 'e') ||+ (w.ent == JR_W_ANNOTATION && cf_kind == 'a') ||+ (w.ent >= 0 && jr_is_or_extends(ix, cf, w.ent));+ break;+ case JR_WK_OUTSIDE:+ break;+ case JR_WK_GAP:+ reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ break;+ default: /* a Kotlin declaration (only with a list), or too many types */+ reason = CBM_DOCLINK_REASON_AMBIGUOUS;+ break;+ }+ if (field) {+ return jr_found_result(&vs->found, exact);+ }+ if (w.passed_gap) {+ reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ }+ *yielded = reason == CBM_DOCLINK_REASON_EXTERNAL;+ return jr_unres(reason);+}++/* The scope of `Type#x`: the type named and the types around it, innermost+ * first. javadoc's field search goes through them as it does for `#x`. */+static void jr_ctx_named(jr_ctx_t *tc, const jr_ctx_t *c, int type) {+ *tc = *c;+ tc->nchain = 0;+ for (int t = type; t != JR_NONE && tc->nchain < JR_CHAIN_MAX; t = c->ix->ents[t].encl) {+ tc->chain[tc->nchain] = t;+ tc->chain_decl[tc->nchain] = NULL;+ tc->nchain++;+ }+}++/* A Javadoc member reference. `type` is the type it names, or JR_NONE for+ * `#member`, which starts at the type of the documented definition.+ * - a METHOD is javadoc's search (jr_walk): the first method it finds is the+ * one; a type outside the repository on the way, or a method the language+ * gives, ends it as external; a parameter list selects the overloads with+ * that signature, never another overload, and without one several+ * signatures are ambiguous+ * - without a list a FIELD comes first. javadoc looks for one in the type,+ * then in the types around it, then in the supertypes; javac scoping+ * takes the inherited one first: an inherited field binds only when no+ * type further out has one of that name (else ambiguous). The field is+ * then weighed against the method (jr_java_field)+ * - {@value} names a field and nothing else; for `Type#x` it searches the+ * type and its supertypes only, as before */+static jr_res_t jr_java_member(const jr_ctx_t *c, const char *name, const jr_ref_t *r, int type,+ bool params, bool exact, bool values_only) {+ const jr_index_t *ix = c->ix;+ bool in_scope = type == JR_NONE;+ int base = in_scope ? (c->nchain > 0 ? c->chain[0] : JR_NONE) : type;+ if (base == JR_NONE) {+ return jr_unres(CBM_DOCLINK_REASON_MISSING); /* no type to be a member of */+ }+ if (!values_only && strcmp(name, ix->ents[base].name) == 0) {+ return jr_java_ctor(c, base, r, exact);+ }+ int sel = JR_SEL_CALLABLES | (params ? JR_SEL_SIG : 0);+ jr_walk_t mw; /* the method, as javadoc searches for it */+ memset(&mw, 0, sizeof(mw));+ mw.ent = JR_NONE;+ if (params) {+ jr_walk(c, base, name, sel, r, JR_NONE, false, &mw);+ return jr_java_method(c, base, name, sel, r, &mw, NULL, exact);+ }+ jr_ctx_t named;+ const jr_ctx_t *fc = c; /* the chain the field is searched through */+ if (!in_scope && !values_only) {+ jr_ctx_named(&named, c, base);+ fc = &named;+ }+ bool chain = in_scope || !values_only;+ jr_msearch_t vs;+ int vlevel = 0;+ if (chain) {+ jr_fields_around(fc, name, &vs, &vlevel);+ } else {+ jr_fields_in(c, base, name, &vs);+ }+ if (vs.ent != JR_NONE) {+ for (int j = vlevel + SKIP_ONE;+ chain && vs.ent != fc->chain[vlevel] && !vs.clash && j < fc->nchain; j++) {+ jr_msearch_t outer;+ jr_fields_in(fc, fc->chain[j], name, &outer);+ vs.clash = outer.ent != JR_NONE || outer.gap;+ }+ if (vs.clash) {+ return jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS);+ }+ if (values_only) {+ return jr_found_result(&vs.found, exact);+ }+ bool yielded = false;+ jr_res_t res = jr_java_field(c, base, name, r, &vs, exact, &yielded);+ if (yielded) {+ atomic_fetch_add(in_scope ? &ix->stats->java_field : &ix->stats->java_field_named, 1);+ }+ return res;+ }+ if (vs.gap) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP); /* a hidden field would come first */+ }+ if (!values_only) {+ jr_walk(c, base, name, sel, r, JR_NONE, false, &mw);+ }+ return jr_java_method(c, base, name, sel, r, &mw, &vs, exact);+}++static jr_res_t jr_java_resolve(const jr_ctx_t *c, const jr_ref_t *r, bool values_only) {+ if (r->nsegs == 0) {+ return jr_java_member(c, r->member, r, JR_NONE, r->has_params, false, values_only);+ }+ jr_tp_t tp = jr_java_type_path(c, r->segs, r->nsegs);+ if (r->member) {+ if (tp.st == JR_TP_OK) {+ return jr_java_member(c, r->member, r, tp.ent, r->has_params, tp.exact, values_only);+ }+ /* a member type the named type does not have: javadoc finds no type */+ return tp.st == JR_TP_PARTIAL ? jr_unres(CBM_DOCLINK_REASON_MISSING) : tp.res;+ }+ if (tp.st == JR_TP_OK) {+ return values_only ? jr_unres(CBM_DOCLINK_REASON_MISSING)+ : jr_type_result(c, tp.ent, tp.exact);+ }+ if (tp.st == JR_TP_PARTIAL) {+ return jr_unres(CBM_DOCLINK_REASON_MISSING); /* `Type.member`: Javadoc wants a '#' */+ }+ if (r->nsegs == SKIP_ONE && tp.res.st == JR_UNRES &&+ tp.res.reason == CBM_DOCLINK_REASON_MISSING) {+ /* javadoc's own fixup: a bare identifier that is no type is read as+ * `#identifier`, a member in the enclosing types. Only where the scope+ * is closed: an open one may hold a type of that name, which comes+ * first. */+ jr_res_t m = jr_java_member(c, r->segs[0], r, JR_NONE, false, false, values_only);+ if (!(m.st == JR_UNRES && m.reason == CBM_DOCLINK_REASON_MISSING)) {+ return m;+ }+ }+ return tp.res;+}++/* ── Kotlin ──────────────────────────────────────────────────────── */++/* The packages every Kotlin file imports on demand. */+static const char *const JR_KOTLIN_DEFAULT_PKGS[] = {+ "kotlin", "kotlin.annotation", "kotlin.collections", "kotlin.comparisons", "kotlin.io",+ "kotlin.ranges", "kotlin.sequences", "kotlin.text", "java.lang", "kotlin.jvm"};++/* What one scope level holds under a name: types, properties, functions. */+typedef struct {+ jr_cands_t types;+ jr_found_t vals;+ jr_found_t calls;+ bool clash; /* two supertypes declare the name and neither comes first */+} jr_klevel_t;++static bool jr_kl_any(const jr_klevel_t *lv) {+ return lv->types.count > 0 || lv->vals.count > 0 || lv->calls.count > 0;+}++static bool jr_kl_invisible(const jr_klevel_t *lv) {+ return lv->types.invisible || lv->vals.invisible || lv->calls.invisible;+}++/* The members `name` of type `ent`, joined to the level. */+static void jr_kl_members(const jr_ctx_t *c, jr_klevel_t *lv, int ent, const char *name) {+ jr_found_t v = jr_members(c, ent, name, JR_SEL_VALUES, NULL);+ jr_found_t k = jr_members(c, ent, name, JR_SEL_CALLABLES, NULL);+ jr_found_add(c, &lv->vals, &v, false);+ jr_found_add(c, &lv->calls, &k, false);+}++/* The top-level declarations `name` of package `pkg`, joined to the level. */+static void jr_kl_top(const jr_ctx_t *c, jr_klevel_t *lv, const char *pkg, const char *name) {+ jr_found_t v = jr_top_members(c, pkg, name, JR_SEL_VALUES);+ jr_found_t k = jr_top_members(c, pkg, name, JR_SEL_CALLABLES);+ jr_found_add(c, &lv->vals, &v, false);+ jr_found_add(c, &lv->calls, &k, false);+}++/* The type `name` nested in `ent`; through a type alias, in the type it+ * names. */+static int jr_kotlin_nested(const jr_index_t *ix, int ent, const char *name) {+ int n = jr_nested(ix, ent, name);+ const jr_entity_t *e = &ix->ents[ent];+ if (n == JR_NONE && e->kind == 't' && e->nclosure > 0) {+ n = jr_nested(ix, e->closure[0], name);+ }+ return n;+}++/* What type `ent` holds under `name` itself: a nested type, its members, and+ * the same of its companion object. One level: a class's member scope and its+ * companion's are one scope to a KDoc name. */+static void jr_kl_type_scope(const jr_ctx_t *c, jr_klevel_t *lv, int ent, const char *name,+ bool members) {+ const jr_index_t *ix = c->ix;+ jr_cand_type(c, &lv->types, jr_kotlin_nested(ix, ent, name));+ if (members) {+ jr_kl_members(c, lv, ent, name);+ }+ int comp = ix->ents[ent].companion;+ if (comp != JR_NONE) {+ jr_cand_type(c, &lv->types, jr_nested(ix, comp, name));+ if (members) {+ jr_kl_members(c, lv, comp, name);+ }+ }+}++/* What the supertypes of `ent` hold under `name`: the nearest one that has+ * anything (`types`: nested types, `members`: properties and functions). A+ * further one that the nearest does not extend is a clash. *gap: a supertype+ * with members a parse error hides came before any hit. */+static void jr_kl_inherited(const jr_ctx_t *c, jr_klevel_t *lv, int ent, const char *name,+ bool types, bool members, bool *gap) {+ const jr_index_t *ix = c->ix;+ const jr_entity_t *e = &ix->ents[ent];+ int first = JR_NONE;+ int checks = 0;+ bool invisible = false;+ for (int k = 0; k < e->nclosure; k++) {+ int sup = e->closure[k];+ jr_klevel_t one;+ memset(&one, 0, sizeof(one));+ if (types) {+ jr_cand_type(c, &one.types, jr_nested(ix, sup, name));+ }+ if (members) {+ jr_kl_members(c, &one, sup, name);+ }+ if (!jr_kl_any(&one)) {+ invisible = invisible || jr_kl_invisible(&one);+ if (first == JR_NONE && members && ix->ents[sup].incomplete) {+ *gap = true;+ break;+ }+ continue;+ }+ if (first == JR_NONE) {+ *lv = one;+ first = sup;+ } else if (++checks > JR_CLASH_CHECKS || !jr_is_or_extends(ix, first, sup)) {+ lv->clash = true;+ break;+ }+ }+ lv->types.invisible = lv->types.invisible || invisible;+}++/* What an explicit import of `fqn` puts in scope: a type, the top-level+ * declarations of that name, a member of an object or an enum. When no scope+ * shows anything of that name it is either declared by the repository where+ * no scope sees it (its package or type is the repository's), or outside. */+static void jr_kl_import(const jr_ctx_t *c, jr_klevel_t *lv, const char *fqn, bool members) {+ const jr_index_t *ix = c->ix;+ const char *dot = strrchr(fqn, '.');+ const char *last = dot ? dot + SKIP_ONE : fqn;+ char pkg[JR_KEY_BUF];+ bool has_pkg = jr_package_of(fqn, pkg, sizeof(pkg));+ if (!has_pkg) {+ pkg[0] = '\0';+ }+ jr_klevel_t one;+ memset(&one, 0, sizeof(one));+ jr_cand_type(c, &one.types, jr_ent(ix, fqn));+ jr_kl_top(c, &one, pkg, last);+ int owner = has_pkg ? jr_ent(ix, pkg) : JR_NONE;+ if (owner != JR_NONE) {+ jr_kl_members(c, &one, owner, last);+ }+ if (!jr_kl_any(&one)) {+ if (jr_kl_invisible(&one)) {+ lv->types.invisible = true;+ return;+ }+ jr_cand(&lv->types, jr_unseen_kind(ix, pkg), JR_NONE);+ return;+ }+ if (one.types.count > 0) {+ jr_cand(&lv->types, one.types.kind, one.types.ent);+ }+ if (members) {+ jr_found_add(c, &lv->vals, &one.vals, false);+ jr_found_add(c, &lv->calls, &one.calls, false);+ }+}++/* True when the member scope of `ent` is not fully known: the type or its+ * companion object has a supertype outside the repository, directly or+ * further up. */+static bool jr_scope_unknown(const jr_index_t *ix, int ent) {+ int comp = ix->ents[ent].companion;+ return jr_open(ix, ent) || (comp != JR_NONE && jr_open(ix, comp));+}++/* Why a Kotlin lookup passed an enclosing type that may have the member+ * unseen (jr_kotlin_lookup). */+enum { JR_STOP_NO = 0, JR_STOP_GIVEN, JR_STOP_OPEN };++/* A simple name in a Kotlin file, level by level:+ * the documented definition's own parameters and type parameters, `this`+ * each enclosing type, innermost first: what it holds itself (with its+ * companion), its type parameters and constructor parameters, what it+ * inherits, what its companion inherits+ * explicit imports -> the file's package -> star imports -> default imports+ * `members` false: types only (the head of a qualified name, a supertype).+ * *gap: a type with members a parse error hides was passed without a hit; a+ * member found after it may be shadowed by one of those.+ * *stop (JR_STOP_*): an enclosing type was passed without a hit that may have+ * a member of the name unseen (jr_kotlin_simple); what the lookup returns+ * then lies further out than that type. */+static jr_lk_t jr_kotlin_lookup(const jr_ctx_t *c, const char *name, bool members, jr_klevel_t *out,+ bool *exact, bool *gap, int *stop) {+ const jr_index_t *ix = c->ix;+ const jr_file_t *f = c->f;+ jr_klevel_t lv;+ bool invisible = false;+ memset(out, 0, sizeof(*out));+ *exact = false;+ *gap = false;+ *stop = JR_STOP_NO;+ if (c->member &&+ (jr_listed(c->member->tparams, name) || (members && jr_listed(c->member->pnames, name)))) {+ return JR_LK_LOCAL;+ }+ /* a documented class: every parameter of its primary constructor is its+ * own, a `val` one included (seen from a member's doc that one is a+ * property of the class, further down) */+ if (c->type &&+ (jr_listed(c->type->tparams, name) || (members && jr_listed(c->type->pnames, name)))) {+ return JR_LK_LOCAL;+ }+ if (members && strcmp(name, "this") == 0) {+ return JR_LK_LOCAL;+ }+ for (int i = 0; i < c->nchain; i++) {+ int ent = c->chain[i];+ const jr_type_t *decl = c->chain_decl[i];+ memset(&lv, 0, sizeof(lv));+ if (strcmp(ix->ents[ent].name, name) == 0) {+ jr_cand_type(c, &lv.types, ent);+ }+ jr_kl_type_scope(c, &lv, ent, name, members);+ if (jr_kl_any(&lv)) {+ *out = lv;+ return JR_LK_FOUND;+ }+ invisible = invisible || jr_kl_invisible(&lv);+ if (jr_listed(decl->tparams, name) || (members && jr_listed(decl->pnames, name))) {+ return JR_LK_LOCAL;+ }+ if (members && ix->ents[ent].incomplete) {+ *gap = true;+ }+ if (!c->inherit) {+ continue;+ }+ memset(&lv, 0, sizeof(lv));+ jr_kl_inherited(c, &lv, ent, name, true, members, gap);+ if (jr_kl_any(&lv)) {+ *out = lv;+ return JR_LK_FOUND;+ }+ invisible = invisible || jr_kl_invisible(&lv);+ if (!members) {+ continue;+ }+ /* the companion's member scope is part of the class's, with what the+ * companion inherits */+ int comp = ix->ents[ent].companion;+ if (comp != JR_NONE) {+ memset(&lv, 0, sizeof(lv));+ jr_kl_inherited(c, &lv, comp, name, false, true, gap);+ if (jr_kl_any(&lv)) {+ *out = lv;+ return JR_LK_FOUND;+ }+ invisible = invisible || jr_kl_invisible(&lv);+ }+ if (*stop == JR_STOP_NO) {+ *stop = jr_given_member(c, ent, name) ? JR_STOP_GIVEN+ : jr_scope_unknown(ix, ent) ? JR_STOP_OPEN+ : JR_STOP_NO;+ }+ }+ /* explicit imports */+ memset(&lv, 0, sizeof(lv));+ for (const jr_import_t *imp = jr_import_next(f, name, NULL); imp;+ imp = jr_import_next(f, name, imp)) {+ jr_kl_import(c, &lv, imp->target, members);+ }+ if (jr_kl_any(&lv)) {+ *out = lv;+ *exact = true;+ return JR_LK_FOUND;+ }+ invisible = invisible || jr_kl_invisible(&lv);+ /* the file's package */+ memset(&lv, 0, sizeof(lv));+ jr_cand_type(c, &lv.types, jr_pkg_type(ix, f->package, name));+ if (members) {+ jr_kl_top(c, &lv, f->package, name);+ }+ if (jr_kl_any(&lv)) {+ *out = lv;+ return JR_LK_FOUND;+ }+ invisible = invisible || jr_kl_invisible(&lv);+ /* star imports: of a package, or of a type (its nested types and members) */+ memset(&lv, 0, sizeof(lv));+ for (int i = 0; i < f->nwild; i++) {+ const char *target = f->wild[i].target;+ if (jr_is_package(ix, target)) {+ jr_cand_type(c, &lv.types, jr_pkg_type(ix, target, name));+ if (members) {+ jr_kl_top(c, &lv, target, name);+ }+ }+ int type = jr_ent(ix, target);+ if (type != JR_NONE) {+ jr_cand_type(c, &lv.types, jr_kotlin_nested(ix, type, name));+ if (members) {+ jr_kl_members(c, &lv, type, name);+ }+ }+ }+ if (jr_kl_any(&lv)) {+ *out = lv;+ return JR_LK_FOUND;+ }+ invisible = invisible || jr_kl_invisible(&lv);+ /* default imports: the repository's own declarations there first */+ memset(&lv, 0, sizeof(lv));+ for (size_t i = 0; i < sizeof(JR_KOTLIN_DEFAULT_PKGS) / sizeof(JR_KOTLIN_DEFAULT_PKGS[0]);+ i++) {+ jr_cand_type(c, &lv.types, jr_pkg_type(ix, JR_KOTLIN_DEFAULT_PKGS[i], name));+ if (members) {+ jr_kl_top(c, &lv, JR_KOTLIN_DEFAULT_PKGS[i], name);+ }+ }+ if (!jr_kl_any(&lv) && (JR_NAMED(JR_KOTLIN_DEFAULT, name) || JR_NAMED(JR_JAVA_LANG, name))) {+ jr_cand(&lv.types, 'X', JR_NONE);+ }+ if (jr_kl_any(&lv)) {+ *out = lv;+ return JR_LK_FOUND;+ }+ invisible = invisible || jr_kl_invisible(&lv);+ return invisible ? JR_LK_INVISIBLE : JR_LK_NONE;+}++/* What a level with candidates is: one type, one property or one function.+ *+ * A type and a function of one name at one level (the factory-function+ * idiom, `class Json` beside `fun Json(..)`) are the TYPE. The order relied+ * on: KDoc's link resolution asks a scope for the classifier of a name before+ * it asks for functions and properties, and the documentation tool links the+ * first answer. That is stated from knowledge of the Kotlin documentation+ * tooling (the compiler's KDoc link resolver, which Dokka uses); it was not+ * checked online. The type binds with the tier the lookup gave. A type whose+ * node another declaration took (class and factory in one file share the+ * file-based qualified name, and the later one owns it) is a graph gap: the+ * function never stands in for it. However many overloads the function has+ * makes no difference. `@sample` names a function, so that order says nothing+ * about it: there a type and a function of one name stay ambiguous.+ *+ * Everything else with more than one candidate is ambiguous, never a pick: a+ * property and a function, a type and a property, a second type, an overload+ * group, members of two owners. */+static jr_res_t jr_kl_result(const jr_ctx_t *c, const jr_klevel_t *lv, bool exact) {+ int kinds = (lv->types.count > 0) + (lv->vals.count > 0) + (lv->calls.count > 0);+ if (!c->sample && lv->types.count == SKIP_ONE && lv->types.kind == 'T' && lv->calls.count > 0 &&+ lv->vals.count == 0 && !lv->clash) {+ jr_res_t type = jr_type_result(c, lv->types.ent, exact);+ atomic_fetch_add(&c->ix->stats->type_and_function, 1);+ if (type.st == JR_OK) {+ atomic_fetch_add(&c->ix->stats->type_and_function_node, 1);+ }+ return type;+ }+ if (kinds > SKIP_ONE || lv->types.count > SKIP_ONE || lv->clash) {+ return jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS);+ }+ if (lv->types.count == SKIP_ONE) {+ if (lv->types.kind == 'T') {+ return jr_type_result(c, lv->types.ent, exact);+ }+ return jr_unres(jr_kind_reason(lv->types.kind));+ }+ const jr_found_t *m = lv->vals.count > 0 ? &lv->vals : &lv->calls;+ return m->several ? jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS) : jr_found_result(m, exact);+}++/* A simple KDoc name.+ *+ * A function or a property further out than an enclosing type binds only when+ * that type is known not to have a member of the name. KDoc resolves a name+ * in the member scope of each enclosing class, inherited members included,+ * before it looks at the class around it, the file's imports or its package.+ * So when the lookup passed a type+ * - that has the name without declaring it (jr_given_member: a member of+ * kotlin.Any, of an enum class), or+ * - whose supertypes, or whose companion's, leave the repository+ * (jr_scope_unknown): one of them may declare the name,+ * a function or a property found further out is not taken: the reference is+ * `external`, and so is a name found nowhere. The order relied on is stated+ * from knowledge of the Kotlin documentation tooling (the compiler's KDoc+ * link resolver); it was not checked online.+ * A TYPE found further out binds as before: the guard is about the member+ * functions and properties a type has, not about nested types a supertype+ * outside the repository might lend. */+static jr_res_t jr_kotlin_simple(const jr_ctx_t *c, const char *name) {+ jr_klevel_t lv;+ bool exact = false;+ bool gap = false;+ int stop = JR_STOP_NO;+ jr_lk_t lk = jr_kotlin_lookup(c, name, true, &lv, &exact, &gap, &stop);+ if (lk == JR_LK_LOCAL) {+ return (jr_res_t){.st = JR_LOCAL};+ }+ if (lk == JR_LK_INVISIBLE) {+ return jr_unres(CBM_DOCLINK_REASON_TEST_ONLY);+ }+ if (lk == JR_LK_FOUND) {+ /* a member found past a type with hidden members: one of those may+ * be the one. A type is safe: a type declared where the scan lost its+ * place is quarantined by name. */+ if (gap && lv.types.count == 0) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ if (stop != JR_STOP_NO && lv.types.count == 0) {+ jr_stats_t *st = c->ix->stats;+ atomic_fetch_add(stop == JR_STOP_GIVEN ? &st->kotlin_given : &st->kotlin_open, 1);+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ return jr_kl_result(c, &lv, exact);+ }+ if (stop != JR_STOP_NO) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL); /* the member that type may have */+ }+ jr_res_t res = jr_unfound_simple(c, name);+ return (gap && res.reason == CBM_DOCLINK_REASON_MISSING)+ ? jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP)+ : res;+}++/* A (qualified) type name in a Kotlin file: the head through the scope or,+ * when no level has it, from the root as packages and then a type; the rest+ * as nested types. */+static jr_tp_t jr_kotlin_type_path(const jr_ctx_t *c, char *const *segs, int n) {+ const jr_index_t *ix = c->ix;+ jr_klevel_t lv;+ bool exact = false;+ bool gap = false;+ int stop = JR_STOP_NO; /* types only: nothing to hold back */+ jr_lk_t lk = jr_kotlin_lookup(c, segs[0], false, &lv, &exact, &gap, &stop);+ if (lk == JR_LK_LOCAL) {+ return jr_tp_res((jr_res_t){.st = JR_LOCAL});+ }+ if (lk == JR_LK_INVISIBLE) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_TEST_ONLY));+ }+ int cur = JR_NONE;+ int from = SKIP_ONE;+ if (lk == JR_LK_FOUND) {+ if (lv.types.count > SKIP_ONE) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS));+ }+ if (lv.types.kind != 'T') {+ return jr_tp_res(jr_unres(jr_kind_reason(lv.types.kind)));+ }+ cur = lv.types.ent;+ }+ for (int i = SKIP_ONE; cur == JR_NONE && i < n; i++) {+ char pkg[JR_KEY_BUF];+ if (!jr_join(segs, 0, i, pkg, sizeof(pkg))) {+ break;+ }+ int ent = jr_pkg_type(ix, pkg, segs[i]);+ if (ent == JR_NONE) {+ continue;+ }+ if (!jr_visible(c, ent)) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_TEST_ONLY));+ }+ cur = ent;+ from = i + SKIP_ONE;+ exact = true;+ }+ if (cur == JR_NONE) {+ jr_tp_t tp = jr_tp_res(jr_unfound_path(c, segs, n));+ tp.unfound = true;+ return tp;+ }+ for (int i = from; i < n; i++) {+ int next = jr_kotlin_nested(ix, cur, segs[i]);+ if (next == JR_NONE) {+ return (jr_tp_t){.st = JR_TP_PARTIAL, .ent = cur, .failed_seg = i, .exact = exact};+ }+ if (!jr_visible(c, next)) {+ return jr_tp_res(jr_unres(CBM_DOCLINK_REASON_TEST_ONLY));+ }+ cur = next;+ }+ return (jr_tp_t){.st = JR_TP_OK, .ent = cur, .exact = exact};+}++static bool jr_ext_key(int recv, const char *name, char *out, size_t cap) {+ int n = recv == JR_NONE ? snprintf(out, cap, "?\x1f%s", name)+ : snprintf(out, cap, "%d\x1f%s", recv, name);+ return n >= 0 && (size_t)n < cap;+}++/* True when the extension `m` of `file` is in scope of the source under its+ * simple name: declared in the source's package, imported, or a member of an+ * enclosing type. KDoc finds an extension for `Type.name` among the callables+ * in scope, nowhere else. */+static bool jr_ext_in_scope(const jr_ctx_t *c, int file, const jr_member_t *m) {+ const jr_file_t *xf = &c->ix->files[file];+ if (m->owner != JR_NONE) {+ int owner = xf->types[m->owner].entity;+ for (int i = 0; i < c->nchain; i++) {+ if (c->chain[i] == owner) {+ return true;+ }+ }+ return false;+ }+ if (strcmp(xf->package, c->f->package) == 0) {+ return true;+ }+ for (int i = 0; i < c->f->nwild; i++) {+ if (strcmp(c->f->wild[i].target, xf->package) == 0) {+ return true;+ }+ }+ size_t pl = strlen(xf->package);+ for (const jr_import_t *imp = jr_import_next(c->f, m->name, NULL); imp;+ imp = jr_import_next(c->f, m->name, imp)) {+ const char *t = imp->target;+ if (pl == 0 ? strcmp(t, m->name) == 0+ : (strncmp(t, xf->package, pl) == 0 && t[pl] == '.' &&+ strcmp(t + pl + SKIP_ONE, m->name) == 0)) {+ return true;+ }+ }+ return false;+}++/* The extensions `name` in scope whose receiver is `ent`, else one of its+ * supertypes (nearest first), else any type. false when there is none. */+static bool jr_kotlin_extension(const jr_ctx_t *c, int ent, const char *name, jr_res_t *res,+ bool *invisible) {+ const jr_index_t *ix = c->ix;+ const jr_entity_t *e = &ix->ents[ent];+ for (int k = -1; k <= e->nclosure; k++) {+ int recv = k < 0 ? ent : (k < e->nclosure ? e->closure[k] : JR_NONE);+ char key[JR_KEY_BUF];+ if (!jr_ext_key(recv, name, key, sizeof(key))) {+ return false;+ }+ const jr_ilist_t *l = (const jr_ilist_t *)cbm_ht_get(ix->extensions, key);+ jr_found_t found = {0};+ const char *package = NULL;+ for (int i = 0; l && i + SKIP_ONE < l->count; i += PAIR_LEN) {+ int file = l->items[i];+ const jr_member_t *m = &ix->files[file].members[l->items[i + SKIP_ONE]];+ if (!jr_ext_in_scope(c, file, m)) {+ continue;+ }+ if (c->prod && ix->files[file].is_test) {+ *invisible = true;+ continue;+ }+ /* the same name and signature in two packages are two functions */+ if (package && strcmp(package, ix->files[file].package) != 0) {+ found.several = true;+ }+ package = ix->files[file].package;+ jr_found_take(c, &found, file, m);+ }+ if (found.count > 0) {+ *res = found.several ? jr_unres(CBM_DOCLINK_REASON_AMBIGUOUS)+ : jr_found_result(&found, false);+ return true;+ }+ }+ return false;+}++/* `name` in the type `ent`, named explicitly: what the type holds itself+ * (with its companion), then what it inherits and what its companion+ * inherits, the members every type has, and the extensions in scope whose+ * receiver it is.+ *+ * An extension is taken only when the type is known not to have a member of+ * the name: a member comes before an extension. Where the supertypes of the+ * type, or of its companion, leave the repository (jr_scope_unknown), one of+ * them may declare the name: `external`, never the extension. Stated from+ * knowledge of the language and of the KDoc link resolver, which asks the+ * type's member scope before the extensions in scope; not checked online. */+static jr_res_t jr_kotlin_in_type(const jr_ctx_t *c, int ent, const char *name, bool exact) {+ const jr_index_t *ix = c->ix;+ jr_klevel_t lv;+ bool gap = false;+ memset(&lv, 0, sizeof(lv));+ jr_kl_type_scope(c, &lv, ent, name, true);+ if (jr_kl_any(&lv)) {+ return jr_kl_result(c, &lv, exact);+ }+ bool invisible = jr_kl_invisible(&lv);+ if (ix->ents[ent].incomplete) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ memset(&lv, 0, sizeof(lv));+ jr_kl_inherited(c, &lv, ent, name, true, true, &gap);+ if (jr_kl_any(&lv)) {+ return jr_kl_result(c, &lv, exact);+ }+ invisible = invisible || jr_kl_invisible(&lv);+ int comp = ix->ents[ent].companion;+ if (comp != JR_NONE && !gap) {+ memset(&lv, 0, sizeof(lv));+ jr_kl_inherited(c, &lv, comp, name, false, true, &gap);+ if (jr_kl_any(&lv)) {+ return jr_kl_result(c, &lv, exact);+ }+ invisible = invisible || jr_kl_invisible(&lv);+ }+ if (gap) {+ return jr_unres(CBM_DOCLINK_REASON_GRAPH_GAP);+ }+ if (jr_implicit_member(ix, ent, name)) {+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ jr_res_t ext;+ bool has_ext = jr_kotlin_extension(c, ent, name, &ext, &invisible);+ if (jr_scope_unknown(ix, ent)) {+ if (has_ext) {+ atomic_fetch_add(&ix->stats->kotlin_extension, 1);+ return jr_unres(CBM_DOCLINK_REASON_EXTERNAL);+ }+ return jr_unres(invisible ? CBM_DOCLINK_REASON_TEST_ONLY : CBM_DOCLINK_REASON_EXTERNAL);+ }+ if (has_ext) {+ return ext;+ }+ return jr_unres(invisible ? CBM_DOCLINK_REASON_TEST_ONLY : CBM_DOCLINK_REASON_MISSING);+}++/* True when `name` is a parameter or type parameter of the documented+ * definition or of a type around it. */+static bool jr_kotlin_local(const jr_ctx_t *c, const char *name) {+ if (c->member && (jr_listed(c->member->pnames, name) || jr_listed(c->member->tparams, name))) {+ return true;+ }+ for (int i = 0; i < c->nchain; i++) {+ if (jr_listed(c->chain_decl[i]->pnames, name) ||+ jr_listed(c->chain_decl[i]->tparams, name)) {+ return true;+ }+ }+ return strcmp(name, "this") == 0;+}++/* A dotted KDoc name. The qualifier is a type (found through the scope, or+ * from the root) and the last name what that type holds; or the qualifier is+ * a package and the last name one of its types or top-level declarations. */+static jr_res_t jr_kotlin_qualified(const jr_ctx_t *c, const jr_ref_t *r) {+ const jr_index_t *ix = c->ix;+ int n = r->nsegs;+ const char *last = r->segs[n - SKIP_ONE];+ if (jr_kotlin_local(c, r->segs[0])) {+ return (jr_res_t){.st = JR_LOCAL}; /* `param.member` names nothing elsewhere */+ }+ jr_tp_t qual = jr_kotlin_type_path(c, r->segs, n - SKIP_ONE);+ if (qual.st == JR_TP_OK) {+ return jr_kotlin_in_type(c, qual.ent, last, qual.exact);+ }+ if (qual.st == JR_TP_PARTIAL) {+ return jr_unres(CBM_DOCLINK_REASON_MISSING); /* a type without that nested type */+ }+ if (!qual.unfound) {+ return qual.res; /* the qualifier is known, and is no type of the repository */+ }+ char pkg[JR_KEY_BUF];+ if (!jr_join(r->segs, 0, n - SKIP_ONE, pkg, sizeof(pkg))) {+ return jr_unres(CBM_DOCLINK_REASON_UNPARSEABLE);+ }+ jr_klevel_t lv;+ memset(&lv, 0, sizeof(lv));+ jr_cand_type(c, &lv.types, jr_pkg_type(ix, pkg, last));+ jr_kl_top(c, &lv, pkg, last);+ if (jr_kl_any(&lv)) {+ return jr_kl_result(c, &lv, true);+ }+ if (jr_kl_invisible(&lv)) {+ return jr_unres(CBM_DOCLINK_REASON_TEST_ONLY);+ }+ return jr_unfound_path(c, r->segs, n);+}++static jr_res_t jr_kotlin_resolve(const jr_ctx_t *c, const jr_ref_t *r) {+ return r->nsegs == SKIP_ONE ? jr_kotlin_simple(c, r->segs[0]) : jr_kotlin_qualified(c, r);+}++/* ── Context ─────────────────────────────────────────────────────── */++/* True when a declaration with `slot` (see jr_type_t) is the definition whose+ * name below the module is `tail`. `path`: its logical path. */+static bool jr_slot_is(const char *slot, const char *owner_path, const char *name,+ const char *tail) {+ if (!slot) {+ return false;+ }+ if (strcmp(slot, "=") != 0) {+ return strcmp(slot, tail) == 0;+ }+ if (!owner_path) {+ return strcmp(name, tail) == 0;+ }+ size_t ol = strlen(owner_path);+ return strncmp(tail, owner_path, ol) == 0 && tail[ol] == '.' &&+ strcmp(tail + ol + SKIP_ONE, name) == 0;+}++/* The scope of the definition a reference is written on: the documented+ * member or type (found by its line and its name below the module), and the+ * types around it. */+static void jr_ctx_init(jr_ctx_t *c, const jr_index_t *ix, const cbm_gbuf_t *g, int file,+ const CBMDocLink *link) {+ memset(c, 0, sizeof(*c));+ c->ix = ix;+ c->g = g;+ c->file = file;+ c->f = &ix->files[file];+ c->prod = !c->f->is_test;+ c->inherit = true;+ if (link->flags & CBM_DOCLINK_FLAG_FILE) {+ return; /* a file-level doc: the file's scope alone */+ }+ const jr_file_t *f = c->f;+ uint32_t line = link->def_line;+ size_t ml = strlen(f->module_qn);+ const char *qn = link->source_qn;+ const char *tail =+ (qn && strncmp(qn, f->module_qn, ml) == 0 && qn[ml] == '.') ? qn + ml + SKIP_ONE : NULL;+ int lo = 0;+ int hi = f->nmembers;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (f->members[f->by_start[mid]].start < line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ for (int i = lo; tail && i < f->nmembers; i++) {+ const jr_member_t *m = &f->members[f->by_start[i]];+ if (m->start != line) {+ break;+ }+ if (jr_slot_is(m->slot, m->owner == JR_NONE ? NULL : f->types[m->owner].path, m->name,+ tail)) {+ c->member = m;+ jr_chain_from(c, m->owner);+ return;+ }+ }+ /* types are in source order: the last one that starts at or before the line */+ lo = 0;+ hi = f->ntypes;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (f->types[mid].start <= line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ int t = lo - SKIP_ONE;+ for (int k = t; tail && k >= 0 && f->types[k].start == line; k--) {+ if (jr_slot_is(f->types[k].slot, NULL, f->types[k].path, tail)) {+ c->type = &f->types[k];+ jr_chain_from(c, k);+ return;+ }+ }+ /* neither: a definition the scan has no record of. The innermost type+ * around its line is its scope. */+ while (t >= 0 && f->types[t].end < line) {+ t = f->types[t].outer;+ }+ if (t >= 0) {+ jr_chain_from(c, t);+ }+}++/* The scope of a type DECLARATION, for the names its header writes+ * (supertypes, an extension's receiver): the types around it. From structure+ * alone, since a stored scope has no lines. */+static void jr_ctx_decl(jr_ctx_t *c, const jr_index_t *ix, const cbm_gbuf_t *g, int file, int outer,+ bool inherit) {+ memset(c, 0, sizeof(*c));+ c->ix = ix;+ c->g = g;+ c->file = file;+ c->f = &ix->files[file];+ c->prod = false; /* a declared supertype is whatever the compiler bound */+ c->inherit = inherit;+ jr_chain_from(c, outer);+}++/* ── Supertypes, extensions ──────────────────────────────────────── */++/* Split a dotted name in place. Returns the number of names, 0 when there+ * are more than a reference may have. */+static int jr_split_dots(char *s, char **segs) {+ int n = 0;+ for (char *p = s;;) {+ char *dot = strchr(p, '.');+ if (dot) {+ *dot = '\0';+ }+ if (n >= JR_MAX_SEGS || !p[0]) {+ return 0;+ }+ segs[n++] = p;+ if (!dot) {+ return n;+ }+ p = dot + SKIP_ONE;+ }+}++/* The type a declaration header of `file` names with `name[0, len)`, in the+ * scope `c`; JR_NONE when the repository declares no such type. */+static int jr_header_type(const jr_ctx_t *c, const char *name, size_t len) {+ char buf[JR_KEY_BUF];+ char *segs[JR_MAX_SEGS];+ if (len == 0 || len >= sizeof(buf)) {+ return JR_NONE;+ }+ memcpy(buf, name, len);+ buf[len] = '\0';+ int n = jr_split_dots(buf, segs);+ if (n == 0) {+ return JR_NONE;+ }+ jr_tp_t tp = c->f->kotlin ? jr_kotlin_type_path(c, segs, n) : jr_java_type_path(c, segs, n);+ return tp.st == JR_TP_OK ? tp.ent : JR_NONE;+}++/* True when a declaration header of the context's file writes, with+ * `name[0, len)`, the root type every type has anyway: java.lang.Object,+ * kotlin.Any. Written out it adds no member (jr_given_member knows them), so+ * it does not leave the hierarchy open. The simple name counts only where+ * nothing else can supply it: no import of that name, no on-demand import of+ * a package the repository does not declare. */+static bool jr_root_super(const jr_ctx_t *c, const char *name, size_t len) {+ const char *full = c->f->kotlin ? "kotlin.Any" : "java.lang.Object";+ const char *simple = strrchr(full, '.') + SKIP_ONE;+ if (len == strlen(full) && memcmp(name, full, len) == 0) {+ return true;+ }+ return len == strlen(simple) && memcmp(name, simple, len) == 0 &&+ !jr_import_next(c->f, simple, NULL) && !jr_scope_open(c);+}++/* True when the repository's type `step` is an interface to javadoc (an+ * annotation type is one). */+static bool jr_walk_iface(const jr_index_t *ix, int step) {+ return step >= 0 && (ix->ents[step].kind == 'i' || ix->ents[step].kind == 'a');+}++/* The steps of javadoc's search for a method (jr_walk) at one declaration of+ * kind `kind`, from the supertypes its header writes, in the order written+ * (`steps[0, nd)`: types of the repository, JR_W_OBJECT for Object or Any+ * written out, JR_W_OUTSIDE for any other). Returns the superclass step and+ * leaves the interface steps, in order, in steps[0, *n).+ * - An interface has no superclass; an annotation type has the interface+ * java.lang.annotation.Annotation, an enum the superclass java.lang.Enum,+ * a record java.lang.Record (which adds nothing to what the record has+ * itself and Object's), any other class Object unless its header names+ * another.+ * - Java writes the superclass first: a first supertype that is no+ * interface of the repository is it. One outside the repository may be+ * the superclass or the first interface; it is taken as the superclass,+ * the earlier of the two places.+ * - Kotlin writes the superclass anywhere in the list: the one class of the+ * repository there is it. Without one, a supertype outside the+ * repository may be the superclass, which javadoc searches before every+ * interface: the superclass step is then outside.+ * - A Kotlin type alias is outside to this search. */+static int jr_walk_steps(const jr_index_t *ix, char kind, bool kotlin, int *steps, int nd, int *n) {+ int sup = JR_W_OBJECT;+ int skip = JR_NONE; /* the entry that is the superclass */+ for (int i = 0; i < nd; i++) {+ if (steps[i] >= 0 && ix->ents[steps[i]].kind == 't') {+ steps[i] = JR_W_OUTSIDE;+ }+ }+ *n = 0;+ if (kind == 'i') {+ sup = JR_W_NONE;+ } else if (kind == 'a') {+ sup = JR_W_ANNOTATION;+ } else if (kind == 'e') {+ sup = JR_W_ENUM;+ } else if (kind == 't') {+ return JR_W_OUTSIDE;+ } else if (kind != 'r' && !kotlin) {+ if (nd > 0 && steps[0] != JR_W_OBJECT && !jr_walk_iface(ix, steps[0])) {+ sup = steps[0];+ skip = 0;+ }+ } else if (kind != 'r') {+ int classes = 0;+ bool outside = false;+ for (int i = 0; i < nd; i++) {+ if (steps[i] >= 0 && !jr_walk_iface(ix, steps[i])) {+ classes++;+ skip = i;+ }+ outside = outside || steps[i] == JR_W_OUTSIDE;+ }+ if (classes > SKIP_ONE) {+ return JR_W_OUTSIDE; /* two superclasses: no order to follow */+ }+ if (classes == SKIP_ONE) {+ sup = steps[skip];+ } else if (outside) {+ sup = JR_W_OUTSIDE;+ }+ }+ int w = 0;+ for (int i = 0; i < nd; i++) {+ if (i != skip && steps[i] != JR_W_OBJECT) {+ steps[w++] = steps[i];+ }+ }+ *n = w;+ return sup;+}++/* One declaration's steps into its type's: the first declaration sets them,+ * a later one that has other steps or another order leaves the type's place+ * in javadoc's search unknown (its superclass step outside). */+static bool jr_walk_decl(jr_index_t *ix, jr_entity_t *e, const jr_type_t *t, bool kotlin,+ int *steps, int nd, bool merge) {+ int n = 0;+ int sup = jr_walk_steps(ix, t->kind, kotlin, steps, nd, &n);+ if (!merge) {+ e->wsuper = sup;+ if (n > 0) {+ e->wifaces = (int *)jr_alloc(ix, (size_t)n * sizeof(int));+ if (!e->wifaces) {+ return false;+ }+ memcpy(e->wifaces, steps, (size_t)n * sizeof(int));+ e->nwifaces = n;+ }+ return true;+ }+ if (sup != e->wsuper || n != e->nwifaces ||+ (n > 0 && memcmp(steps, e->wifaces, (size_t)n * sizeof(int)) != 0)) {+ e->wsuper = JR_W_OUTSIDE;+ e->nwifaces = 0;+ }+ return true;+}++/* The type around declaration `t` of `f`, as the scope chain has it. */+static int jr_walk_encl(const jr_file_t *f, const jr_type_t *t) {+ int o = t->outer;+ while (o != JR_NONE && f->types[o].entity < 0) {+ o = f->types[o].outer;+ }+ return o == JR_NONE ? JR_NONE : f->types[o].entity;+}++/* The direct supertypes of every type (each declaration's list, bound in that+ * declaration's own scope), then every type's closure: breadth-first, the+ * nearest first, each supertype once. A supertype that is no type of the+ * repository leaves the hierarchy open. Alongside, each type's steps of+ * javadoc's search for a method (jr_walk_steps). */+static bool jr_resolve_supers(jr_index_t *ix, const cbm_gbuf_t *g) {+ size_t n = (size_t)(ix->nents ? ix->nents : SKIP_ONE);+ int *seen = (int *)cbm_calloc(CBM_MEM_CLASS_OTHER, n * sizeof(int));+ int *queue = (int *)cbm_alloc(CBM_MEM_CLASS_OTHER, n * sizeof(int));+ int *steps = NULL; /* one declaration's supertypes, as javadoc's search sees them */+ int scap = 0;+ bool ok = seen && queue;+ for (int ei = 0; ok && ei < ix->nents; ei++) {+ jr_entity_t *e = &ix->ents[ei];+ int stamp = ei + SKIP_ONE;+ int nb = 0;+ for (int d = 0; ok && d < e->ndecls; d++) {+ int file = e->decls[d].file;+ const jr_type_t *t = &ix->files[file].types[e->decls[d].type];+ jr_ctx_t c;+ if (t->supers[0]) {+ jr_ctx_decl(&c, ix, g, file, t->outer, false);+ }+ int nd = 0;+ for (const char *p = t->supers; ok && p && *p;) {+ const char *bar = strchr(p, '|');+ size_t len = bar ? (size_t)(bar - p) : strlen(p);+ int base = jr_header_type(&c, p, len);+ int step = base;+ if (base == ei) {+ e->open = true;+ step = JR_W_OUTSIDE;+ } else if (base == JR_NONE) {+ bool root = jr_root_super(&c, p, len);+ e->open = e->open || !root;+ step = root ? JR_W_OBJECT : JR_W_OUTSIDE;+ } else if (seen[base] != stamp) {+ seen[base] = stamp;+ queue[nb++] = base;+ }+ if (nd >= scap) {+ int ncap = scap ? scap * PAIR_LEN : CBM_SZ_16;+ int *grown = (int *)cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)ncap * sizeof(int));+ ok = grown != NULL;+ if (ok && nd > 0) {+ memcpy(grown, steps, (size_t)nd * sizeof(int));+ }+ cbm_free(CBM_MEM_CLASS_OTHER, steps);+ steps = grown;+ scap = ok ? ncap : 0;+ }+ if (ok) {+ steps[nd++] = step;+ }+ p = bar ? bar + SKIP_ONE : NULL;+ }+ ok = ok && jr_walk_decl(ix, e, t, ix->files[file].kotlin, steps, nd, d > 0);+ if (d == 0) {+ e->encl = jr_walk_encl(&ix->files[file], t);+ }+ }+ if (ok && nb > 0) {+ e->bases = (int *)jr_alloc(ix, (size_t)nb * sizeof(int));+ ok = e->bases != NULL;+ if (ok) {+ memcpy(e->bases, queue, (size_t)nb * sizeof(int));+ e->nbases = nb;+ }+ }+ }+ memset(seen, 0, ok ? n * sizeof(int) : 0);+ for (int ei = 0; ok && ei < ix->nents; ei++) {+ jr_entity_t *e = &ix->ents[ei];+ int stamp = ei + SKIP_ONE;+ int head = 0;+ int tail = 0;+ seen[ei] = stamp; /* a cycle does not come back to the type itself */+ for (int b = 0; b < e->nbases; b++) {+ if (seen[e->bases[b]] != stamp) {+ seen[e->bases[b]] = stamp;+ queue[tail++] = e->bases[b];+ }+ }+ while (head < tail) {+ const jr_entity_t *s = &ix->ents[queue[head++]];+ for (int b = 0; b < s->nbases; b++) {+ if (seen[s->bases[b]] != stamp) {+ seen[s->bases[b]] = stamp;+ queue[tail++] = s->bases[b];+ }+ }+ }+ if (tail > 0) {+ e->closure = (int *)jr_alloc(ix, (size_t)tail * sizeof(int));+ ok = e->closure != NULL;+ if (ok) {+ memcpy(e->closure, queue, (size_t)tail * sizeof(int));+ e->nclosure = tail;+ }+ }+ }+ cbm_free(CBM_MEM_CLASS_OTHER, seen);+ cbm_free(CBM_MEM_CLASS_OTHER, queue);+ cbm_free(CBM_MEM_CLASS_OTHER, steps);+ return ok;+}++/* The receiver of every Kotlin extension, bound in its file's scope, and the+ * extensions of each receiver type by name. */+static bool jr_build_extensions(jr_index_t *ix, const cbm_gbuf_t *g) {+ for (int fi = 0; fi < ix->nfiles; fi++) {+ jr_file_t *f = &ix->files[fi];+ for (int mi = 0; f->kotlin && mi < f->nmembers; mi++) {+ jr_member_t *m = &f->members[mi];+ if (!m->recv[0]) {+ continue;+ }+ if (strcmp(m->recv, "?") != 0) {+ jr_ctx_t c;+ jr_ctx_decl(&c, ix, g, fi, m->owner, true);+ m->recv_entity = jr_header_type(&c, m->recv, strlen(m->recv));+ if (m->recv_entity == JR_NONE) {+ continue; /* a receiver outside the repository: nobody names it */+ }+ }+ char key[JR_KEY_BUF];+ if (!jr_ext_key(m->recv_entity, m->name, key, sizeof(key))) {+ continue;+ }+ jr_ilist_t *l = jr_ht_ilist(ix, ix->extensions, key, true);+ if (!l || !jr_ilist_push(ix, l, fi) || !jr_ilist_push(ix, l, mi)) {+ return false;+ }+ }+ }+ return true;+}++/* ── Index lifecycle and the resolver hooks ──────────────────────── */++static void jr_destroy(void *index) {+ jr_index_t *ix = (jr_index_t *)index;+ if (!ix) {+ return;+ }+ if (ix->stats) {+ const jr_stats_t *st = ix->stats;+ const _Atomic int64_t *vals[] = {&st->source_gaps, &st->plain_text,+ &st->type_and_function, &st->type_and_function_node,+ &st->java_given, &st->java_open,+ &st->kotlin_given, &st->kotlin_open,+ &st->kotlin_extension, &st->java_field,+ &st->java_field_named};+ char b[sizeof(vals) / sizeof(vals[0])][CBM_SZ_32];+ for (size_t i = 0; i < sizeof(vals) / sizeof(vals[0]); i++) {+ snprintf(b[i], sizeof(b[i]), "%lld", (long long)atomic_load(vals[i]));+ }+ cbm_log_info("doc_links.jvm.done", "source_without_node", b[0], "kdoc_plain_text", b[1],+ "type_and_function", b[2], "type_and_function_with_node", b[3],+ "not_taken_java_given", b[4], "not_taken_java_open", b[5],+ "not_taken_kotlin_given", b[6], "not_taken_kotlin_open", b[7],+ "not_taken_kotlin_extension", b[8], "not_taken_java_field", b[9],+ "not_taken_java_field_named", b[10]);+ cbm_free(CBM_MEM_CLASS_OTHER, ix->stats);+ }+ cbm_ht_free(ix->ent_by_fqn);+ cbm_ht_free(ix->pkg_types);+ cbm_ht_free(ix->packages);+ cbm_ht_free(ix->pkg_prefixes);+ cbm_ht_free(ix->pkg_members);+ cbm_ht_free(ix->extensions);+ cbm_ht_free(ix->quarantine);+ cbm_ht_free(ix->quarantine_test);+ cbm_free(CBM_MEM_CLASS_OTHER, ix->ents);+ cbm_free(CBM_MEM_CLASS_OTHER, ix->run_to_file);+ cbm_arena_destroy(&ix->arena);+ cbm_free(CBM_MEM_CLASS_OTHER, ix);+}++static void *jr_build_fail(jr_index_t *ix, const char *step) {+ cbm_log_error("doc_links.jvm.error", "step", step, "reason", "alloc");+ jr_destroy(ix);+ return NULL;+}++static bool jr_has_suffix(const char *s, const char *sfx) {+ size_t n = strlen(s);+ size_t sl = strlen(sfx);+ return n >= sl && strcmp(s + n - sl, sfx) == 0;+}++static void *jr_build(const cbm_doclink_build_in_t *in) {+ jr_index_t *ix = (jr_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->mode = in->ctx->mode;+ ix->ent_by_fqn = cbm_ht_create(CBM_SZ_4K);+ ix->pkg_types = cbm_ht_create(CBM_SZ_4K);+ ix->packages = cbm_ht_create(CBM_SZ_1K);+ ix->pkg_prefixes = cbm_ht_create(CBM_SZ_1K);+ ix->pkg_members = cbm_ht_create(CBM_SZ_1K);+ ix->extensions = cbm_ht_create(CBM_SZ_256);+ ix->quarantine = cbm_ht_create(CBM_SZ_64);+ ix->quarantine_test = cbm_ht_create(CBM_SZ_64);+ ix->nfiles = in->file_count;+ ix->files = (jr_file_t *)jr_alloc(ix, (size_t)(in->file_count ? in->file_count : SKIP_ONE) *+ sizeof(jr_file_t));+ 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));+ ix->stats = (jr_stats_t *)cbm_calloc(CBM_MEM_CLASS_OTHER, sizeof(*ix->stats));+ if (!ix->ent_by_fqn || !ix->pkg_types || !ix->packages || !ix->pkg_prefixes ||+ !ix->pkg_members || !ix->extensions || !ix->quarantine || !ix->quarantine_test ||+ !ix->files || !ix->run_to_file || !ix->stats) {+ return jr_build_fail(ix, "tables");+ }+ for (int i = 0; i < in->run_file_count; i++) {+ ix->run_to_file[i] = JR_NONE;+ }+ int bad_scopes = 0;+ for (int i = 0; i < in->file_count; i++) {+ const cbm_doclink_file_t *src = &in->files[i];+ jr_file_t *f = &ix->files[i];+ memset(f, 0, sizeof(*f));+ f->rel_path = src->rel_path; /* stays valid until destroy */+ f->is_test = jr_is_test_path(src->rel_path);+ f->scoped = src->scope && jr_parse_scope(ix, f, src->scope);+ if (!f->scoped) {+ bad_scopes += src->scope != NULL;+ f->nimports = f->nwild = f->ntypes = f->nmembers = f->nunplaced = 0;+ }+ f->kotlin = !jr_has_suffix(src->rel_path, ".java");+ if (!f->package) {+ f->package = "";+ }+ f->module_qn = cbm_fqn_module_source_lang(&ix->arena, ix->project, src->rel_path,+ f->kotlin ? CBM_LANG_KOTLIN : CBM_LANG_JAVA);+ if (!f->module_qn) {+ ix->oom = true;+ }+ if (src->run_file >= 0 && src->run_file < in->run_file_count) {+ ix->run_to_file[src->run_file] = i;+ }+ }+ if (ix->oom) {+ return jr_build_fail(ix, "scopes");+ }+ if (bad_scopes > 0) {+ char b[CBM_SZ_32];+ snprintf(b, sizeof(b), "%d", bad_scopes);+ cbm_log_warn("doc_links.jvm.bad_scope", "files", b);+ }+ int skipped = 0;+ if (!jr_build_entities(ix, &skipped) || ix->oom) {+ return jr_build_fail(ix, "entities");+ }+ if (!jr_resolve_supers(ix, in->graph) || ix->oom) {+ return jr_build_fail(ix, "supertypes");+ }+ if (!jr_build_extensions(ix, in->graph) || ix->oom) {+ return jr_build_fail(ix, "extensions");+ }+ int incomplete = 0;+ for (int i = 0; i < ix->nents; i++) {+ incomplete += ix->ents[i].incomplete;+ }+ char b[5][CBM_SZ_32];+ snprintf(b[0], sizeof(b[0]), "%d", ix->nfiles);+ snprintf(b[1], sizeof(b[1]), "%d", ix->nents);+ snprintf(b[2], sizeof(b[2]), "%d", skipped);+ snprintf(b[3], sizeof(b[3]), "%d", incomplete);+ snprintf(b[4], sizeof(b[4]), "%u",+ (unsigned)(cbm_ht_count(ix->quarantine) + cbm_ht_count(ix->quarantine_test)));+ cbm_log_info("doc_links.jvm.index", "files", b[0], "types", b[1], "skipped_types", b[2],+ "incomplete_types", b[3], "quarantined_names", b[4]);+ return ix;+}++/* True when the documented definition has a node of its own (or shares the+ * node of its overload group). One node per qualified name: a definition+ * whose name another declaration took (a Kotlin class and the factory+ * function named like it, two classes' properties of one name in one file)+ * has none, and an edge written for it would leave from that other+ * declaration. A definition the scan has no record of is checked against the+ * node itself: the source file is extracted in this run, so its nodes carry+ * their lines. */+static bool jr_source_has_node(const jr_ctx_t *c, const CBMDocLink *link) {+ if (link->flags & CBM_DOCLINK_FLAG_FILE) {+ return true; /* the File node: the core finds it */+ }+ if (c->member) {+ return jr_member_node(c, c->file, c->member) != NULL;+ }+ if (c->type) {+ jr_decl_t d = {.file = c->file, .type = (int)(c->type - c->f->types)};+ return jr_type_node(c, d) != NULL;+ }+ const cbm_gbuf_node_t *n = link->source_qn ? cbm_gbuf_find_by_qn(c->g, link->source_qn) : NULL;+ return n && n->file_path && strcmp(n->file_path, c->f->rel_path) == 0 &&+ n->start_line == (int)link->def_line;+}++/* True when `line` lies in a part of the file the scan could not place. */+static bool jr_unplaced_line(const jr_file_t *f, uint32_t line) {+ int lo = 0;+ int hi = f->nunplaced;+ while (lo < hi) {+ int mid = lo + ((hi - lo) / PAIR_LEN);+ if (f->unplaced[mid].to < line) {+ lo = mid + SKIP_ONE;+ } else {+ hi = mid;+ }+ }+ return lo < f->nunplaced && f->unplaced[lo].from <= line;+}++static void jr_resolve(const void *index, void *state, int run_file, const CBMDocLink *link,+ const cbm_gbuf_t *graph, cbm_doclink_outcome_t *out) {+ (void)state; /* Java and Kotlin keep no per-file working state */+ const jr_index_t *ix = (const jr_index_t *)index;+ out->kind = CBM_DOCLINK_UNRESOLVED;+ out->reason = CBM_DOCLINK_REASON_MISSING;+ out->target = NULL;+ out->exact = false;+ if (!ix || !link || run_file < 0 || run_file >= ix->run_count ||+ ix->run_to_file[run_file] < 0) {+ return;+ }+ int file = ix->run_to_file[run_file];+ const jr_file_t *f = &ix->files[file];+ if (!f->scoped) {+ out->reason = CBM_DOCLINK_REASON_GRAPH_GAP; /* no scope to resolve in: never a guess */+ return;+ }+ jr_ref_t r;+ if (!link->raw ||+ !(f->kotlin ? jr_parse_kotlin(link->raw, &r) : jr_parse_java(link->raw, &r))) {+ out->reason = CBM_DOCLINK_REASON_UNPARSEABLE;+ return;+ }+ /* What could not be placed is not resolved around: a definition in a part+ * of its file where the scan lost its place has no known scope, and a+ * name some file declares at an unknown place could be that declaration.+ * Both are declared-but-unplaced: graph gaps. */+ bool sample = link->syntax == CBM_DOCLINK_KT_SAMPLE;+ bool unplaced = !(link->flags & CBM_DOCLINK_FLAG_FILE) && jr_unplaced_line(f, link->def_line);+ for (int i = 0; !unplaced && i < r.nsegs; i++) {+ unplaced = cbm_ht_get(ix->quarantine, r.segs[i]) != NULL ||+ ((f->is_test || sample) && cbm_ht_get(ix->quarantine_test, r.segs[i]) != NULL);+ }+ if (unplaced) {+ out->reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ return;+ }+ jr_ctx_t c;+ jr_ctx_init(&c, ix, graph, file, link);+ if (sample) {+ c.prod = false; /* samples live in test sources */+ c.sample = true;+ }+ jr_res_t res = f->kotlin ? jr_kotlin_resolve(&c, &r)+ : jr_java_resolve(&c, &r, link->syntax == CBM_DOCLINK_JAVA_VALUE);+ /* KDoc `[name]` is Markdown: a name that resolves to nothing is rendered+ * as the plain text it is, so it is no reference. A block tag (@see,+ * @throws, @sample) names its subject and keeps its row. */+ bool plain_text = link->syntax == CBM_DOCLINK_KT_KDOC_LINK && res.st == JR_UNRES &&+ res.reason == CBM_DOCLINK_REASON_MISSING;+ if (res.st == JR_LOCAL || plain_text) {+ if (plain_text) {+ atomic_fetch_add(&ix->stats->plain_text, 1);+ }+ out->kind = CBM_DOCLINK_LOCAL;+ return;+ }+ if (res.st == JR_OK && res.node) {+ if (!jr_source_has_node(&c, link)) {+ /* resolved, with nowhere to leave from: the documented definition+ * is the one without a node */+ atomic_fetch_add(&ix->stats->source_gaps, 1);+ out->reason = CBM_DOCLINK_REASON_GRAPH_GAP;+ return;+ }+ out->kind = CBM_DOCLINK_EDGE;+ out->target = res.node;+ out->exact = res.exact;+ return;+ }+ out->reason = res.reason;+}++/* ── Incremental scope rules ─────────────────────────────────────── */++/* Scope record fields (0-based, the tag is field 0; internal/cbm/+ * doclink_jvm.c): `I kind alias target`, `T .. supers(6) ..` and+ * `M start kind flags(3) owner name(5) tparams sig recv(8) ..`. */+enum {+ JR_F_I_KIND = 1,+ JR_F_I_ALIAS = 2,+ JR_F_T_SUPERS = 6,+ JR_F_M_FLAGS = 3,+ JR_F_M_NAME = 5,+ JR_F_M_RECV = 8,+ JR_DELTA_IMPORTS = 16, /* changed imports compared by name; more: any name */+};++typedef struct {+ const char *p;+ size_t n;+} jr_span_t;++static jr_span_t jr_delta_field(jr_span_t line, int idx) {+ int f = 0;+ size_t s = 0;+ for (size_t i = 0; i <= line.n; i++) {+ if (i == line.n || line.p[i] == '\t') {+ if (f == idx) {+ return (jr_span_t){.p = line.p + s, .n = i - s};+ }+ f++;+ s = i + SKIP_ONE;+ }+ }+ return (jr_span_t){0};+}++/* The next record; with `imports` the next import record, without it the+ * next record that is none. false at the end. */+static bool jr_delta_next(const char **cursor, jr_span_t *line, bool imports) {+ for (const char *p = *cursor; p && *p;) {+ const char *nl = strchr(p, '\n');+ size_t n = nl ? (size_t)(nl - p) : strlen(p);+ const char *next = nl ? nl + SKIP_ONE : p + n;+ if (n > 0 && (p[0] == 'I') == imports) {+ *line = (jr_span_t){.p = p, .n = n};+ *cursor = next;+ return true;+ }+ p = next;+ }+ *cursor = NULL;+ return false;+}++static bool jr_span_eq(jr_span_t a, jr_span_t b) {+ return a.n == b.n && memcmp(a.p, b.p, a.n) == 0;+}++/* The import records of a scope, in order. Returns the count, -1 when memory+ * ran out. */+static int jr_delta_imports(const char *scope, jr_span_t **out) {+ int n = 0;+ jr_span_t line;+ for (const char *p = scope; jr_delta_next(&p, &line, true);) {+ n++;+ }+ *out =+ (jr_span_t *)cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)(n ? n : SKIP_ONE) * sizeof(jr_span_t));+ if (!*out) {+ return CBM_NOT_FOUND;+ }+ int w = 0;+ for (const char *p = scope; jr_delta_next(&p, &line, true);) {+ (*out)[w++] = line;+ }+ return n;+}++/* True when a changed import can change what the '|'-joined type names in+ * `names` bind to: an on-demand import can supply any name, a single import+ * the one it is known by. */+static bool jr_delta_names_hit(jr_span_t names, const jr_span_t *changed, int nchanged,+ bool any_name) {+ for (size_t i = 0; i < names.n;) {+ size_t e = i;+ while (e < names.n && names.p[e] != '|') {+ e++;+ }+ size_t head = i;+ while (head < e && names.p[head] != '.') {+ head++;+ }+ bool named = head > i && !(head - i == SKIP_ONE && names.p[i] == '?');+ if (named && any_name) {+ return true;+ }+ for (int k = 0; named && k < nchanged; k++) {+ jr_span_t alias = jr_delta_field(changed[k], JR_F_I_ALIAS);+ if (alias.n == head - i && memcmp(alias.p, names.p + i, alias.n) == 0) {+ return true;+ }+ }+ i = e + SKIP_ONE;+ }+ return false;+}++/* Imports scope the file itself, which is re-extracted anyway -- except for+ * the names its declaration headers write: a supertype and an extension's+ * receiver are bound in the file's scope, and references in OTHER files+ * resolve through them. A changed import that can re-bind one of those is not+ * repairable file by file. */+static int jr_delta_import_change(const char *stored, const char *fresh) {+ jr_span_t *si = NULL;+ jr_span_t *fi = NULL;+ int ns = jr_delta_imports(stored, &si);+ int nf = jr_delta_imports(fresh, &fi);+ int result = CBM_DOCLINK_DELTA_LOCAL;+ if (ns < 0 || nf < 0) {+ result = CBM_NOT_FOUND;+ } else {+ /* what is left between the common start and the common end changed */+ int a = 0;+ while (a < ns && a < nf && jr_span_eq(si[a], fi[a])) {+ a++;+ }+ int es = ns;+ int ef = nf;+ while (es > a && ef > a && jr_span_eq(si[es - SKIP_ONE], fi[ef - SKIP_ONE])) {+ es--;+ ef--;+ }+ int nchanged = (es - a) + (ef - a);+ bool any_name = nchanged > JR_DELTA_IMPORTS;+ jr_span_t changed[JR_DELTA_IMPORTS];+ int w = 0;+ for (int i = a; !any_name && i < es; i++) {+ changed[w++] = si[i];+ }+ for (int i = a; !any_name && i < ef; i++) {+ changed[w++] = fi[i];+ }+ for (int i = 0; i < w; i++) {+ jr_span_t kind = jr_delta_field(changed[i], JR_F_I_KIND);+ any_name = any_name || (kind.n == SKIP_ONE && (kind.p[0] == 'w' || kind.p[0] == 'n'));+ }+ jr_span_t line;+ for (const char *p = fresh; nchanged > 0 && result == CBM_DOCLINK_DELTA_LOCAL &&+ jr_delta_next(&p, &line, false);) {+ int field = line.p[0] == 'T' ? JR_F_T_SUPERS : (line.p[0] == 'M' ? JR_F_M_RECV : 0);+ if (field && jr_delta_names_hit(jr_delta_field(line, field), changed, w, any_name)) {+ result = CBM_DOCLINK_DELTA_GLOBAL;+ }+ }+ }+ cbm_free(CBM_MEM_CLASS_OTHER, si);+ cbm_free(CBM_MEM_CLASS_OTHER, fi);+ return result;+}++/* Compare a changed file's stored and fresh scopes record by record, in+ * order. Two differences leave every other file's resolution alone:+ * - a member the fresh scope no longer has (a method, a constructor, a+ * field, a property, an enum constant): a reference that depended on it+ * either bound it (an edge into this file) or names it in its unresolved+ * row, so the name is reported;+ * - the file's own imports, unless one can re-bind a supertype or an+ * extension receiver the file declares (jr_delta_import_change).+ * Everything else is GLOBAL: a new or changed record (a type, a member, a+ * signature, the package), a removed type (it may be another type's+ * supertype), a removed record component or constructor property (a record's+ * canonical constructor is matched against them without naming them), a+ * quarantined name or unplaced range that came or went, and a changed order+ * (declarations of one name own their node by order). */+static int jr_scope_delta(const char *stored, const char *fresh, cbm_doclink_name_fn removed,+ void *ud) {+ const char *sp = stored;+ const char *fp = fresh;+ jr_span_t sl = {0};+ jr_span_t fl = {0};+ bool hs = jr_delta_next(&sp, &sl, false);+ bool hf = jr_delta_next(&fp, &fl, false);+ while (hs || hf) {+ if (hs && hf && jr_span_eq(sl, fl)) {+ hs = jr_delta_next(&sp, &sl, false);+ hf = jr_delta_next(&fp, &fl, false);+ continue;+ }+ if (!hs || sl.p[0] != 'M') {+ return CBM_DOCLINK_DELTA_GLOBAL;+ }+ jr_span_t flags = jr_delta_field(sl, JR_F_M_FLAGS);+ jr_span_t name = jr_delta_field(sl, JR_F_M_NAME);+ if (!flags.p || !name.p || name.n == 0) {+ return CBM_NOT_FOUND; /* not a member record this code wrote */+ }+ if (memchr(flags.p, 'p', flags.n)) {+ return CBM_DOCLINK_DELTA_GLOBAL;+ }+ if (!removed || !removed(ud, name.p, name.n)) {+ return CBM_NOT_FOUND;+ }+ hs = jr_delta_next(&sp, &sl, false);+ }+ return jr_delta_import_change(stored, fresh);+}++const cbm_doclink_resolver_t cbm_doclink_jvm_resolver = {+ .langs = {CBM_LANG_JAVA, CBM_LANG_KOTLIN},+ .lang_count = 2,+ .scope_tag = CBM_DOCLINK_JVM_SCOPE_TAG,+ .build = jr_build,+ .destroy = jr_destroy,+ .resolve = jr_resolve,+ .scope_delta = jr_scope_delta,+};diff --git a/tests/test_doc_mentions_helpers.h b/tests/test_doc_mentions_helpers.hindex 7756b4947..1053912c9 100644--- a/tests/test_doc_mentions_helpers.h+++ b/tests/test_doc_mentions_helpers.h@@ -430,9 +430,15 @@ static inline int dm_reason_lines(const char *db, const char *block) {* so it is the resolution an audit would ship; doc_links_md_ship_gate tests* the production gate itself. */static const int DM_HELD_FAMILIES[] = {- CBM_DOCLINK_MD_BARE_PATH, CBM_DOCLINK_MD_SUPERSEDES_PROSE, CBM_DOCLINK_RST_INCLUDE,- CBM_DOCLINK_RST_KERNEL_DOC, CBM_DOCLINK_ADOC_ATTRIBUTE, CBM_DOCLINK_ADOC_CODE_PATH,+ CBM_DOCLINK_MD_BARE_PATH, CBM_DOCLINK_MD_SUPERSEDES_PROSE,+ CBM_DOCLINK_RST_INCLUDE, CBM_DOCLINK_RST_KERNEL_DOC,+ CBM_DOCLINK_ADOC_ATTRIBUTE, CBM_DOCLINK_ADOC_CODE_PATH,CBM_DOCLINK_ADOC_CODE_NAME, CBM_DOCLINK_GO_DOC_LINK,+ CBM_DOCLINK_JAVA_LINK, CBM_DOCLINK_JAVA_LINKPLAIN,+ 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,};static inline void dm_ship_held_families(void) {diff --git a/tests/test_doc_mentions_jvm.c b/tests/test_doc_mentions_jvm.cnew file mode 100644index 000000000..31602e942--- /dev/null+++ b/tests/test_doc_mentions_jvm.c@@ -0,0 +1,3669 @@+/*+ * test_doc_mentions_jvm.c — doc-comment references of Java and Kotlin+ * (internal/cbm/doclink_jvm.c, src/pipeline/doc_links_jvm.c).+ *+ * Extraction is tested on source text (tokens, scope blobs, hostile input);+ * resolution through the pipeline on fixture repositories, read back from+ * the published database: every family and reason of both languages, the+ * lookup order of each level by level with a decoy one level further out,+ * references across the two languages, test code, parse errors, the scope+ * changes an incremental run repairs file by file, incremental == full and+ * one worker == several.+ */+#include "test_framework.h"+#include "test_doc_mentions_helpers.h"++/* ── extraction: tokens ──────────────────────────────────────────── */++/* The token written as `raw`, or a stand-in that fails every check. */+static const CBMDocLink *jt_token(const CBMFileResult *r, const char *raw) {+ static const CBMDocLink none = {.raw = "", .syntax = CBM_DOCLINK_NONE};+ const CBMDocLink *l = dm_find_token(r, raw);+ return l ? l : &none;+}++TEST(doc_mentions_jvm_java_tokens) {+ const char *src =+ "package a;\n" /* 1 */+ "\n" /* 2 */+ "/**\n" /* 3 */+ " * See {@link Gadget} and {@linkplain Gadget#spin() spin it},\n" /* 4 */+ " * {@link Helper#run(int, String) label text}, {@value #MAX}.\n" /* 5 */+ " * A tag over two lines {@link\n" /* 6 */+ " * Wrapped#name}. {@code {@link InCode}} {@literal {@link InLiteral}}\n" /* 7 */+ " * <!-- {@link InComment} --> <![CDATA[ {@link InCdata} ]]>\n" /* 8 */+ " * {@linkage NotATag} {@link Open\n" /* 9 */+ " * @see Gadget#spin()\n" /* 10 */+ " * @see <a href=\"https://example.org/x\">site</a>\n" /* 11 */+ " * @see \"The Book\"\n" /* 12 */+ " * @throws IllegalStateException never\n" /* 13 */+ " * @exception a.CustomError worse\n" /* 14 */+ " * @param <T> the type {@link T}\n" /* 15 */+ " * @return {@value} nothing, {@value \"%x\" Helper#MASK}\n" /* 16 */+ " */\n" /* 17 */+ "public class Widget<T> {\n" /* 18 */+ " /** Max {@value}. {@link Widget#MAX} */\n" /* 19 */+ " public static final int MAX = 10;\n" /* 20 */+ " /**\n" /* 21 */+ " * <pre>{@code\n" /* 22 */+ " * @Override {@link InSample}\n" /* 23 */+ " * }</pre> after {@link AfterSample}\n" /* 24 */+ " */\n" /* 25 */+ " void sample() {}\n" /* 26 */+ "}\n";+ CBMFileResult *r = dm_extract(src, CBM_LANG_JAVA, "a/Widget.java");+ ASSERT_NOT_NULL(r);+ /* every family, with the line the reference is written on */+ const CBMDocLink *t = jt_token(r, "Gadget");+ ASSERT_EQ(t->syntax, CBM_DOCLINK_JAVA_LINK);+ ASSERT_EQ(t->line, 4);+ ASSERT_EQ(t->def_line, 18);+ ASSERT_STR_EQ(t->source_qn, "p.a.Widget");+ ASSERT_EQ(dm_count_tokens(r, "Gadget#spin()"), 2);+ ASSERT_EQ(jt_token(r, "Gadget#spin()")->syntax, CBM_DOCLINK_JAVA_LINKPLAIN);+ /* the label is not part of the reference; blanks inside it are one */+ ASSERT_EQ(jt_token(r, "Helper#run(int, String)")->line, 5);+ ASSERT_EQ(jt_token(r, "#MAX")->syntax, CBM_DOCLINK_JAVA_VALUE);+ ASSERT_EQ(jt_token(r, "Wrapped#name")->line, 7);+ ASSERT_EQ(jt_token(r, "IllegalStateException")->syntax, CBM_DOCLINK_JAVA_THROWS);+ ASSERT_EQ(jt_token(r, "a.CustomError")->syntax, CBM_DOCLINK_JAVA_THROWS);+ ASSERT_EQ(jt_token(r, "a.CustomError")->line, 14);+ ASSERT_EQ(jt_token(r, "https://example.org/x")->syntax, CBM_DOCLINK_HREF);+ ASSERT_EQ(jt_token(r, "https://example.org/x")->line, 11);+ /* a format string is not the reference of {@value} */+ ASSERT_EQ(jt_token(r, "Helper#MASK")->syntax, CBM_DOCLINK_JAVA_VALUE);+ /* a reference to the definition's own type parameter is still a token:+ * the resolver, which knows the scope, calls it local */+ ASSERT_EQ(jt_token(r, "T")->line, 15);+ /* not references: code, literal, HTML comment, CDATA, another tag whose+ * name only starts like one, a quoted title, a bare {@value} */+ ASSERT_NULL(dm_find_token(r, "InCode"));+ ASSERT_NULL(dm_find_token(r, "InLiteral"));+ ASSERT_NULL(dm_find_token(r, "InComment"));+ ASSERT_NULL(dm_find_token(r, "InCdata"));+ ASSERT_NULL(dm_find_token(r, "NotATag"));+ ASSERT_NULL(dm_find_token(r, "\"The"));+ /* an inline tag that a block tag cuts off never closed: javadoc reports+ * it, and it links nothing */+ ASSERT_NULL(dm_find_token(r, "Open"));+ /* the field's doc is harvested once, on the Field (its package-level+ * Variable twin carries the same doc) */+ ASSERT_EQ(dm_count_tokens(r, "Widget#MAX"), 1);+ ASSERT_STR_EQ(jt_token(r, "Widget#MAX")->source_qn, "p.a.Widget.MAX");+ /* `@` at the start of a line inside {@code} is sample code, not a block+ * tag, and what follows inside the block is still code */+ ASSERT_NULL(dm_find_token(r, "InSample"));+ ASSERT_EQ(jt_token(r, "AfterSample")->line, 24);+ cbm_free_result(r);+ PASS();+}++TEST(doc_mentions_jvm_kotlin_tokens) {+ const char *src =+ "package k\n" /* 1 */+ "\n" /* 2 */+ "/**\n" /* 3 */+ " * A [Gadget], [the helper][Helper.run], [text](https://x.org), `[InCode]`.\n" /* 4 */+ " * ``double `tick` [InDouble]`` then [Outer.Inner] and [`quoted name`].\n" /* 5 */+ " * [label]: https://example.org\n" /* 6 */+ " * <!-- [InComment] --> ![image][ImgLabel] \\[Escaped]\n" /* 7 */+ " * Nested /* comment [StillDoc] */ goes on to [AfterNested].\n" /* 8 */+ " *\n" /* 9 */+ " * [IndentedCode]\n" /* 10 */+ " *\n" /* 11 */+ " * ```\n" /* 12 */+ " * [Fenced]\n" /* 13 */+ " * ```\n" /* 14 */+ " * @param name the [name] of [T]\n" /* 15 */+ " * @property size the size\n" /* 16 */+ " * @see Gadget.spin\n" /* 17 */+ " * @see https://example.org\n" /* 18 */+ " * @throws IllegalStateException never\n" /* 19 */+ " * @exception CustomError worse\n" /* 20 */+ " * @sample k.samples.widgetSample\n" /* 21 */+ " * @return [Result] of [0] and [two words]\n" /* 22 */+ " */\n" /* 23 */+ "class Widget<T>(val name: String, size: Int)\n"; /* 24 */+ CBMFileResult *r = dm_extract(src, CBM_LANG_KOTLIN, "k/Widget.kt");+ ASSERT_NOT_NULL(r);+ const CBMDocLink *t = jt_token(r, "Gadget");+ ASSERT_EQ(t->syntax, CBM_DOCLINK_KT_KDOC_LINK);+ ASSERT_EQ(t->line, 4);+ ASSERT_EQ(t->def_line, 24);+ ASSERT_STR_EQ(t->source_qn, "p.k.Widget.Widget");+ /* [text][Name]: the second bracket names the code */+ ASSERT_EQ(jt_token(r, "Helper.run")->syntax, CBM_DOCLINK_KT_KDOC_LINK);+ ASSERT_NULL(dm_find_token(r, "the helper"));+ ASSERT_EQ(jt_token(r, "Outer.Inner")->line, 5);+ ASSERT_EQ(jt_token(r, "`quoted name`")->line, 5);+ /* a block comment inside the doc is part of its text: Kotlin comments+ * nest, and the doc goes on after it */+ ASSERT_EQ(jt_token(r, "StillDoc")->line, 8);+ ASSERT_EQ(jt_token(r, "AfterNested")->line, 8);+ ASSERT_EQ(jt_token(r, "Gadget.spin")->syntax, CBM_DOCLINK_KT_SEE);+ ASSERT_EQ(jt_token(r, "IllegalStateException")->syntax, CBM_DOCLINK_KT_THROWS);+ ASSERT_EQ(jt_token(r, "CustomError")->syntax, CBM_DOCLINK_KT_THROWS);+ ASSERT_EQ(jt_token(r, "CustomError")->line, 20);+ ASSERT_EQ(jt_token(r, "k.samples.widgetSample")->syntax, CBM_DOCLINK_KT_SAMPLE);+ ASSERT_EQ(jt_token(r, "Result")->line, 22);+ /* own parameter and type parameter: tokens, local to the resolver */+ ASSERT_EQ(jt_token(r, "name")->line, 15);+ ASSERT_EQ(jt_token(r, "T")->line, 15);+ /* not references: a Markdown link, code spans, a link definition, an+ * HTML comment, an image's label, an escaped bracket, an indented and a+ * fenced code block, a URL, and brackets that hold no name */+ ASSERT_NULL(dm_find_token(r, "text"));+ ASSERT_NULL(dm_find_token(r, "InCode"));+ ASSERT_NULL(dm_find_token(r, "InDouble"));+ ASSERT_NULL(dm_find_token(r, "label"));+ ASSERT_NULL(dm_find_token(r, "InComment"));+ ASSERT_NULL(dm_find_token(r, "image"));+ ASSERT_NULL(dm_find_token(r, "ImgLabel"));+ ASSERT_NULL(dm_find_token(r, "Escaped"));+ ASSERT_NULL(dm_find_token(r, "IndentedCode"));+ ASSERT_NULL(dm_find_token(r, "Fenced"));+ ASSERT_NULL(dm_find_token(r, "https://example.org"));+ ASSERT_NULL(dm_find_token(r, "0"));+ ASSERT_NULL(dm_find_token(r, "two words"));+ ASSERT_NULL(dm_find_token(r, "size"));+ cbm_free_result(r);+ PASS();+}++/* ── extraction: hostile input ───────────────────────────────────── */++enum { JT_BIG = 200000, JT_MEGA = 1100000 };++/* Extract `head` + `count` copies of `unit` + `tail` as one doc comment on a+ * class; the result, or NULL when memory ran out. */+static CBMFileResult *jt_extract_repeated(CBMLanguage lang, const char *head, const char *unit,+ int count, const char *tail) {+ size_t ul = strlen(unit);+ size_t cap = strlen(head) + (ul * (size_t)count) + strlen(tail) + 64;+ char *src = malloc(cap);+ if (!src) {+ return NULL;+ }+ size_t w = (size_t)snprintf(src, cap, "/**\n * %s", head);+ for (int i = 0; i < count; i++) {+ memcpy(src + w, unit, ul);+ w += ul;+ }+ snprintf(src + w, cap - w, "%s\n */\n%s", tail,+ lang == CBM_LANG_JAVA ? "public class C {}\n" : "class C\n");+ CBMFileResult *r = dm_extract(src, lang, lang == CBM_LANG_JAVA ? "C.java" : "C.kt");+ free(src);+ return r;+}++TEST(doc_mentions_jvm_malformed_and_oversized) {+ /* a reference longer than any name (here: over a megabyte) is kept just+ * past the limit, which is how the resolver knows it was cut: it never+ * resolves a prefix */+ CBMFileResult *r = jt_extract_repeated(CBM_LANG_JAVA, "{@link ", "A", JT_MEGA, "}");+ ASSERT_NOT_NULL(r);+ ASSERT_EQ(r->doc_links.count, 1);+ ASSERT_GT(strlen(r->doc_links.items[0].raw), (size_t)CBM_DOCLINK_JVM_REF_MAX);+ ASSERT(strlen(r->doc_links.items[0].raw) < (size_t)CBM_DOCLINK_JVM_REF_MAX + 16);+ cbm_free_result(r);+ r = jt_extract_repeated(CBM_LANG_KOTLIN, "[", "A", JT_MEGA, "]");+ ASSERT_NOT_NULL(r);+ ASSERT_EQ(r->doc_links.count, 1);+ ASSERT_GT(strlen(r->doc_links.items[0].raw), (size_t)CBM_DOCLINK_JVM_REF_MAX);+ ASSERT(strlen(r->doc_links.items[0].raw) < (size_t)CBM_DOCLINK_JVM_REF_MAX + 16);+ cbm_free_result(r);+ /* tags that never close, nested deeper than any text nests */+ r = jt_extract_repeated(CBM_LANG_JAVA, "", "{@link A ", JT_BIG, "");+ ASSERT_NOT_NULL(r);+ ASSERT_EQ(r->doc_links.count, 0);+ cbm_free_result(r);+ /* ... and closed again: the innermost ones are references, no more than+ * the parser keeps open at once, and nothing overflows */+ r = jt_extract_repeated(CBM_LANG_JAVA, "", "{@link A ", 100, "}}}}}}}}}}");+ ASSERT_NOT_NULL(r);+ ASSERT(r->doc_links.count <= 10);+ cbm_free_result(r);+ /* brackets, backticks and comment openers by the hundred thousand on one+ * line: one pass, no token */+ r = jt_extract_repeated(CBM_LANG_KOTLIN, "", "[", JT_BIG, "");+ ASSERT_NOT_NULL(r);+ ASSERT_EQ(r->doc_links.count, 0);+ cbm_free_result(r);+ r = jt_extract_repeated(CBM_LANG_KOTLIN, "", "` `` ", JT_BIG, " [After]");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ r = jt_extract_repeated(CBM_LANG_KOTLIN, "[Before] ", "<!-- ", JT_BIG, " [Hidden]");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(dm_find_token(r, "Before"));+ ASSERT_NULL(dm_find_token(r, "Hidden")); /* the comment never ends */+ cbm_free_result(r);+ /* bytes that are no UTF-8, a NUL in the middle of the comment */+ const char bad[] = "/**\n * {@link Caf\xC3} {@link \xFF\xFE#x} [x\x80y]\n */\nclass C {}\n";+ r = dm_extract(bad, CBM_LANG_JAVA, "C.java");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ r = dm_extract(bad, CBM_LANG_KOTLIN, "C.kt");+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ const char nul[] = "/**\n * {@link Before} \0 {@link After}\n */\nclass C {}\n";+ r = cbm_extract_file(nul, (int)sizeof(nul) - 1, CBM_LANG_JAVA, "p", "C.java", 0, NULL, NULL);+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ r = cbm_extract_file(nul, (int)sizeof(nul) - 1, CBM_LANG_KOTLIN, "p", "C.kt", 0, NULL, NULL);+ ASSERT_NOT_NULL(r);+ cbm_free_result(r);+ PASS();+}++TEST(doc_mentions_jvm_java_norm_type) {+ static const struct {+ const char *in;+ const char *want;+ } cases[] = {+ {"int", "int"},+ {"final String s", "String"},+ {"java.util.List<String>", "List"},+ {"Map.Entry<K, V>", "Entry"},+ {"Map<String, List<int[]>>[]", "Map[]"},+ {"String...", "String[]"},+ {"int[] xs", "int[]"},+ {"int xs[]", "int[]"},+ {"int [] xs", "int[]"},+ {"@NonNull String", "String"},+ {"@Size(max = 3) java.lang.String name", "String"},+ {" T ", "T"},+ {"", "?"},+ {"<>", "?"},+ };+ char out[64];+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ cbm_doclink_java_norm_type(cases[i].in, strlen(cases[i].in), out, sizeof(out));+ if (strcmp(out, cases[i].want) != 0) {+ printf(" norm_type(\"%s\") = \"%s\", expected \"%s\"\n", cases[i].in, out,+ cases[i].want);+ }+ ASSERT_STR_EQ(out, cases[i].want);+ }+ /* a name that does not fit is no type: never a truncated one, which+ * could equal another type's name */+ char small[8];+ cbm_doclink_java_norm_type("LongTypeName", strlen("LongTypeName"), small, sizeof(small));+ ASSERT_STR_EQ(small, "?");+ PASS();+}++/* ── extraction: scope blobs ─────────────────────────────────────── */++/* True when the scope blob has the record `line` (tab-separated, a whole+ * line). */+static bool jt_has_line(const char *scope, const char *line) {+ size_t n = strlen(line);+ for (const char *p = scope; 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_jvm_java_scope_blob) {+ const char *src =+ "package com.acme.core;\n" /* 1 */+ "import com.acme.util.Helper;\n" /* 2 */+ "import com.acme.util.*;\n" /* 3 */+ "import static com.acme.util.Helper.once;\n" /* 4 */+ "import static com.acme.util.Helper.*;\n" /* 5 */+ "public class Widget<T, U extends Comparable<U>> extends Base implements Runnable {\n" /* 6+ */+ " public static final int MAX = 10;\n" /* 7 */+ " private int size, other;\n" /* 8 */+ " public Widget() {}\n" /* 9 */+ " public Widget(int size) {}\n" /* 10 */+ " public <V extends Number> int size(V scale, java.util.List<String> xs, int... rest) "+ "{ return 0; }\n" /* 11 */+ " public void run() {}\n" /* 12 */+ " public static class Inner {\n" /* 13 */+ " public int deep;\n" /* 14 */+ " }\n" /* 15 */+ " public enum Mode { FAST, SLOW; public Mode flip() { return this; } }\n" /* 16 */+ " public record Point(int x, String y) { public Point { } }\n" /* 17 */+ " public interface Shape { int SIDES = 4; double area(); }\n" /* 18 */+ " public @interface Marker { String value() default \"\"; }\n" /* 19 */+ "}\n";+ CBMFileResult *r = dm_extract(src, CBM_LANG_JAVA, "com/acme/core/Widget.java");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ const char *s = r->doc_scope;+ ASSERT(strncmp(s, CBM_DOCLINK_JVM_SCOPE_TAG "\n", strlen(CBM_DOCLINK_JVM_SCOPE_TAG) + 1) == 0);+ ASSERT(jt_has_line(s, "L\tj"));+ ASSERT(jt_has_line(s, "P\tcom.acme.core"));+ ASSERT(jt_has_line(s, "I\ts\tHelper\tcom.acme.util.Helper"));+ ASSERT(jt_has_line(s, "I\tw\t-\tcom.acme.util"));+ ASSERT(jt_has_line(s, "I\tm\tonce\tcom.acme.util.Helper"));+ ASSERT(jt_has_line(s, "I\tn\t-\tcom.acme.util.Helper"));+ /* a type: lines, kind, path, type parameters (a Java one with its first+ * bound, its erasure), supertypes, where its node is, whether it owns it */+ ASSERT(jt_has_line(s, "T\t6\t20\tc\tWidget\tT,U:Comparable\tBase|Runnable\t=\t1\t"));+ /* a field's node is named by the field; one named like a method of its+ * class has <Owner>.<name>#field; a second declarator has no definition */+ ASSERT(jt_has_line(s, "M\t7\tv\t\t0\tMAX\t\t-\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "M\t8\tv\t\t0\tsize\t\t-\t\tWidget.size#field\t1\t"));+ ASSERT(jt_has_line(s, "M\t8\tv\t\t0\tother\t\t-\t\t-\t0\t"));+ /* constructors, overloads of one name: one node, owned by the last */+ ASSERT(jt_has_line(s, "M\t9\tc\tK\t0\tWidget\t\t\t\t=\t0\t"));+ ASSERT(jt_has_line(s, "M\t10\tc\tK\t0\tWidget\t\tint\t\t=\t1\t"));+ /* a signature: simple names, no type arguments, an ellipsis is an array */+ ASSERT(jt_has_line(s, "M\t11\tc\t\t0\tsize\tV:Number\tV|List|int[]\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "T\t13\t15\tc\tWidget.Inner\t\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "M\t14\tv\t\t1\tdeep\t\t-\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "T\t16\t16\te\tWidget.Mode\t\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "M\t16\tv\tn\t2\tFAST\t\t-\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "M\t16\tc\t\t2\tflip\t\t\t\t=\t1\t"));+ /* a record: its components and its compact constructor (whose signature+ * is the components' types) are declared, and have no definition */+ ASSERT(jt_has_line(s, "T\t17\t17\tr\tWidget.Point\t\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "M\t17\tv\tp\t3\tx\t\tint\t\t-\t0\t"));+ ASSERT(jt_has_line(s, "M\t17\tv\tp\t3\ty\t\tString\t\t-\t0\t"));+ ASSERT(jt_has_line(s, "M\t17\tc\tK\t3\tPoint\t\t*\t\t-\t0\t"));+ /* an interface constant and an annotation element: declared, no node */+ ASSERT(jt_has_line(s, "M\t18\tv\t\t4\tSIDES\t\t-\t\t-\t0\t"));+ ASSERT(jt_has_line(s, "M\t19\tc\t\t5\tvalue\t\t\t\t-\t0\t"));+ /* the persisted form: no line numbers, nothing else changed */+ char *portable = cbm_doclink_portable_scope(s);+ ASSERT_NOT_NULL(portable);+ ASSERT(jt_has_line(portable, "T\t0\t0\tc\tWidget\tT,U:Comparable\tBase|Runnable\t=\t1\t"));+ ASSERT(jt_has_line(portable, "M\t0\tc\tK\t0\tWidget\t\tint\t\t=\t1\t"));+ ASSERT(jt_has_line(portable, "I\ts\tHelper\tcom.acme.util.Helper"));+ cbm_free(CBM_MEM_CLASS_OTHER, portable);+ cbm_free_result(r);+ PASS();+}++TEST(doc_mentions_jvm_kotlin_scope_blob) {+ const char *src =+ "package com.acme.kt\n" /* 1 */+ "import com.acme.core.Gadget\n" /* 2 */+ "import com.acme.far.Far as Farther\n" /* 3 */+ "import com.acme.far.*\n" /* 4 */+ "class Alias<T>(val delegate: T, name: String) : Base<T>(), Marker {\n" /* 5 */+ " val bodyProp: Int = 1\n" /* 6 */+ " fun member(param: Int): Int {\n" /* 7 */+ " return param\n" /* 8 */+ " }\n" /* 9 */+ " fun member(param: String): Int {\n" /* 10 */+ " return 0\n" /* 11 */+ " }\n" /* 12 */+ " class Nested\n" /* 13 */+ " companion object {\n" /* 14 */+ " val LIMIT = 3\n" /* 15 */+ " }\n" /* 16 */+ " constructor(x: Int) : this(x as T, \"n\")\n" /* 17 */+ "}\n" /* 18 */+ "fun <T : Base<*>> T.alias(name: String): Int {\n" /* 19 */+ " return 1\n" /* 20 */+ "}\n" /* 21 */+ "fun <T> T.anything(): Int {\n" /* 22 */+ " return 1\n" /* 23 */+ "}\n" /* 24 */+ "val com.acme.far.Far.ext: Int get() = 1\n" /* 25 */+ "enum class Color { RED, GREEN }\n" /* 26 */+ "typealias Name = com.acme.far.Far\n" /* 27 */+ "typealias Handler = (Int) -> Unit\n"; /* 28 */+ CBMFileResult *r = dm_extract(src, CBM_LANG_KOTLIN, "com/acme/kt/Alias.kt");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ const char *s = r->doc_scope;+ ASSERT(jt_has_line(s, "L\tk"));+ ASSERT(jt_has_line(s, "P\tcom.acme.kt"));+ ASSERT(jt_has_line(s, "I\ts\tGadget\tcom.acme.core.Gadget"));+ ASSERT(jt_has_line(s, "I\ts\tFarther\tcom.acme.far.Far")); /* an import alias */+ ASSERT(jt_has_line(s, "I\tw\t-\tcom.acme.far"));+ /* a class: its constructor's parameter names are its own (the last+ * field; the persisted form drops them) */+ ASSERT(jt_has_line(s, "T\t5\t18\tc\tAlias\tT\tBase|Marker\t=\t1\tdelegate,name"));+ /* a `val` constructor parameter is a property without a definition */+ ASSERT(jt_has_line(s, "M\t5\tv\tp\t0\tdelegate\t\t-\t\t-\t0\t"));+ /* a class-body property: its node is named below the FILE's module */+ ASSERT(jt_has_line(s, "M\t6\tv\t\t0\tbodyProp\t\t-\t\tbodyProp\t1\t"));+ ASSERT(jt_has_line(s, "M\t7\tc\t\t0\tmember\t\tInt\t\t=\t0\tparam"));+ ASSERT(jt_has_line(s, "M\t10\tc\t\t0\tmember\t\tString\t\t=\t1\tparam"));+ /* a nested type's node is flat: named below the file's module */+ ASSERT(jt_has_line(s, "T\t13\t13\tc\tAlias.Nested\t\t\tNested\t1\t"));+ /* an unnamed companion and its members: declared, no definitions */+ ASSERT(jt_has_line(s, "T\t14\t16\tC\tAlias.Companion\t\t\t-\t0\t"));+ ASSERT(jt_has_line(s, "M\t15\tv\t\t2\tLIMIT\t\t-\t\t-\t0\t"));+ ASSERT(jt_has_line(s, "M\t17\tc\tK\t0\tAlias\t\tInt\t\t=\t1\tx"));+ /* an extension: its receiver as written; a type parameter stands for its+ * bound, one without a bound for any type */+ ASSERT(jt_has_line(s, "M\t19\tc\t\t-\talias\tT\tR=T|String\tBase\t=\t1\tname"));+ ASSERT(jt_has_line(s, "M\t22\tc\t\t-\tanything\tT\tR=T\t?\t=\t1\t"));+ ASSERT(jt_has_line(s, "M\t25\tv\t\t-\text\t\tR=com.acme.far.Far\tcom.acme.far.Far\t=\t1\t"));+ ASSERT(jt_has_line(s, "T\t26\t26\te\tColor\t\t\t=\t1\t"));+ ASSERT(jt_has_line(s, "M\t26\tv\tn\t3\tRED\t\t-\t\t-\t0\t"));+ /* a type alias: the type it names stands where a supertype does */+ ASSERT(jt_has_line(s, "T\t27\t27\tt\tName\t\tcom.acme.far.Far\t=\t1\t"));+ ASSERT(jt_has_line(s, "T\t28\t28\tt\tHandler\t\t?\t=\t1\t"));+ char *portable = cbm_doclink_portable_scope(s);+ ASSERT_NOT_NULL(portable);+ ASSERT(jt_has_line(portable, "T\t0\t0\tc\tAlias\tT\tBase|Marker\t=\t1\t"));+ ASSERT(jt_has_line(portable, "M\t0\tc\t\t0\tmember\t\tString\t\t=\t1\t"));+ cbm_free(CBM_MEM_CLASS_OTHER, portable);+ cbm_free_result(r);+ PASS();+}++/* ── the published database ──────────────────────────────────────── */++/* A fixture repository in a temporary directory, and its index. */+typedef struct {+ char tmp[256];+ char repo[400];+ char db[512];+} jt_repo_t;++static bool jt_begin(jt_repo_t *r, const char *tag) {+ snprintf(r->tmp, sizeof(r->tmp), "/tmp/cbm_dm_jvm_%s_XXXXXX", tag);+ if (!cbm_mkdtemp(r->tmp)) {+ return false;+ }+ snprintf(r->repo, sizeof(r->repo), "%s/repo", r->tmp);+ snprintf(r->db, sizeof(r->db), "%s/index.db", r->tmp);+ return true;+}++static void jt_write(const jt_repo_t *r, const char *rel, const char *content) {+ th_write_file(TH_PATH(r->repo, rel), content);+}++static void jt_end(jt_repo_t *r) {+ dm_unlink_db(r->db);+ th_rmtree(r->tmp);+}++/* Number of MENTIONS edges between the definitions whose qualified names end+ * with these paths; their properties are left in jt_props. */+static char jt_props[512];++static int jt_edge(const char *db, const char *src, const char *tgt) {+ int n = 0;+ dm_edge(db, src, tgt, jt_props, sizeof(jt_props), &n);+ return n;+}++/* Reason of the unresolved row with this raw text in this file; "" when the+ * reference has no row. */+static const char *jt_reason(const char *db, const char *rel, const char *raw) {+ static char reason[64];+ dm_row(db, rel, raw, reason, sizeof(reason), NULL, 0);+ return reason;+}++/* ── Java: every family, every reason ────────────────────────────── */++#define JT_GADGET \+ "package a;\n" \+ "public class Gadget {\n" \+ " public int count;\n" \+ " public static final String NAME = \"g\";\n" \+ " public void spin() {}\n" \+ " public void spin(int times) {}\n" \+ " public void stop() {}\n" \+ "}\n" \+ "class Gr\xC3\xB6\xC3\x9F" \+ "e {\n" \+ " public int l\xC3\xA4nge = 1;\n" \+ "}\n"++#define JT_HELPER \+ "package b;\n" \+ "public class Helper {\n" \+ " public static final int MASK = 255;\n" \+ " public void run(int n, String s) {}\n" \+ "}\n"++#define JT_SHAPES \+ "package a;\n" \+ "public class Shapes {\n" \+ " public record Point(int x, int y) {}\n" \+ " public interface Shape { int SIDES = 4; double area(); }\n" \+ " public @interface Marker { String value() default \"\"; }\n" \+ " public static class Sized {\n" \+ " private int size;\n" \+ " public int size() { return size; }\n" \+ " }\n" \+ " public static class Made {\n" \+ " public Made(int n) {}\n" \+ " }\n" \+ "}\n"++#define JT_WIDGET \+ "package a;\n" /* 1 */ \+ "\n" /* 2 */ \+ "import b.Helper;\n" /* 3 */ \+ "import a.env.Config;\n" /* 4 */ \+ "import java.util.List;\n" /* 5 */ \+ "import b.Generated;\n" /* 6 */ \+ "/**\n" /* 7 */ \+ " * {@link Gadget} {@linkplain Gadget#spin(int) spin} {@link Helper#run(int, String)}\n" /* 8 \+ */ \+ " * {@value Helper#MASK} {@link List} {@link String} {@link T} {@link Gadget#spin}\n" /* 9 */ \+ " * {@link NoSuchType} {@link Gadget#nope} {@link GadgetTests} {@link Config}\n" /* 10 */ \+ " * {@link a.env.Other} {@link b} {@link Shapes.Point#x} {@link Shapes.Shape#SIDES}\n" /* 11 \+ */ \+ " * {@link Shapes.Marker#value()} {@link Shapes.Sized#size} {@link Shapes.Sized#size()}\n" /* 12 */ \+ " * {@link Gadget#Gadget()} {@link Shapes.Made#Made(int)} {@link Shapes.Made#Made(String)}\n" /* 13 */ \+ " * {@link Gadget#a#b} {@link Gadget#spin(int} {@link Gr\xC3\xB6\xC3\x9F" \+ "e#l\xC3\xA4nge}\n" /* 14 */ \+ " * {@link org.outside.Thing} {@link b.Missing} {@link Gadget.stop} {@link Generated}\n" /* 15 \+ */ \+ " * {@link Gadget#spin(int, int)} {@link Gadget#spin(long)} {@link Shapes#Sized}\n" /* 16 */ \+ " * {@value Gadget#stop}\n" /* 17 */ \+ " * @see Gadget#count\n" /* 18 */ \+ " * @see <a href=\"https://example.org\">site</a>\n" /* 19 */ \+ " * @throws CustomError never\n" /* 20 */ \+ " * @throws java.io.IOException bad\n" /* 21 */ \+ " */\n" /* 22 */ \+ "public class Widget<T> {\n" /* 23 */ \+ "}\n"++TEST(doc_mentions_jvm_java_families_and_reasons) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jfam"));+ jt_write(&r, "src/main/java/a/Gadget.java", JT_GADGET);+ jt_write(&r, "src/main/java/a/CustomError.java",+ "package a;\npublic class CustomError extends RuntimeException {}\n");+ jt_write(&r, "src/main/java/b/Helper.java", JT_HELPER);+ jt_write(&r, "src/main/java/a/Shapes.java", JT_SHAPES);+ jt_write(&r, "src/main/java/a/Widget.java", JT_WIDGET);+ /* a real package in a directory the indexer skips by name */+ jt_write(&r, "src/main/java/a/env/Config.java", "package a.env;\npublic class Config {}\n");+ jt_write(&r, "src/test/java/a/GadgetTests.java",+ "package a;\n/** Tests {@link Gadget}. */\npublic class GadgetTests {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ const char *w = "src/main/java/a/Widget.java";++ /* link: a type of the file's package, unique at its first level */+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Gadget"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"via\":\"doc_comment\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"link\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"unique\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"line\":8"));+ /* linkplain, with a signature that selects one overload (overloads of a+ * type share a node) */+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Gadget.spin"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"linkplain\""));+ /* ... and nothing is relaxed: another parameter count, another parameter+ * type, a nested type named as a member and a method named as a value+ * bind nothing (that edge counts the one reference) */+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1"));+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#spin(int, int)"), "missing");+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#spin(long)"), "missing");+ ASSERT_STR_EQ(jt_reason(db, w, "Shapes#Sized"), "missing");+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Shapes.Sized"), 0);+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#stop"), "missing");+ /* a type named by a single import: exact */+ ASSERT_EQ(jt_edge(db, "a.Widget", "b.Helper.run"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"exact\""));+ /* value: a field, whose node is named by its declarator */+ ASSERT_EQ(jt_edge(db, "a.Widget", "b.Helper.MASK"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"value\""));+ /* see */+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Gadget.count"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"see\""));+ /* throws */+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.CustomError"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"throws\""));++ /* external: a single import of a package the repository does not declare,+ * java.lang, a qualified name of such a package, a URL */+ ASSERT_STR_EQ(jt_reason(db, w, "List"), "external");+ ASSERT_STR_EQ(jt_reason(db, w, "String"), "external");+ ASSERT_STR_EQ(jt_reason(db, w, "java.io.IOException"), "external");+ ASSERT_STR_EQ(jt_reason(db, w, "org.outside.Thing"), "external");+ ASSERT_STR_EQ(jt_reason(db, w, "https://example.org"), "external");+ /* local: the class's own type parameter is neither an edge nor a row */+ ASSERT_STR_EQ(jt_reason(db, w, "T"), "");+ /* ambiguous: an overload group named without a parameter list */+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#spin"), "ambiguous");+ /* missing: nothing of that name anywhere; a member the type does not+ * have; a type the repository's own package does not declare */+ ASSERT_STR_EQ(jt_reason(db, w, "NoSuchType"), "missing");+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#nope"), "missing");+ ASSERT_STR_EQ(jt_reason(db, w, "b.Missing"), "missing");+ /* `Type.member` is no Javadoc reference (it wants a '#'): no binding of+ * the method that happens to have that name */+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget.stop"), "missing");+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Gadget.stop"), 0);+ /* test_only_target: product code names a declaration only tests hold */+ ASSERT_STR_EQ(jt_reason(db, w, "GadgetTests"), "test_only_target");+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.GadgetTests"), 0);+ /* ... while test code binds product code */+ ASSERT_EQ(jt_edge(db, "a.GadgetTests", "a.Gadget"), 1);+ /* not_indexed: a package of the repository in a directory discovery+ * skips, named by an import and by its qualified name */+ ASSERT_STR_EQ(jt_reason(db, w, "Config"), "not_indexed");+ ASSERT_STR_EQ(jt_reason(db, w, "a.env.Other"), "not_indexed");+ /* graph_gap: a package (no node), a record component, an interface+ * constant and an annotation element (declared, no definition), a+ * constructor the class has without declaring it */+ ASSERT_STR_EQ(jt_reason(db, w, "b"), "graph_gap");+ /* ... and a type the file imports from a package of the repository that+ * no indexed file declares (generated code): the import vouches for it,+ * where the same name written out without one is missing (b.Missing) */+ ASSERT_STR_EQ(jt_reason(db, w, "Generated"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, w, "Shapes.Point#x"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, w, "Shapes.Shape#SIDES"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, w, "Shapes.Marker#value()"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#Gadget()"), "graph_gap");+ /* a field named like its accessor has a node of its own+ * (<Owner>.<name>#field): the field reference binds it */+ ASSERT_STR_EQ(jt_reason(db, w, "Shapes.Sized#size"), "");+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Shapes.Sized.size#field"), 1);+ /* ... while the accessor itself, named as a method, binds */+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Shapes.Sized.size"), 1);+ /* a constructor reference: the declared one binds, another signature is+ * missing (never the constructor that is there) */+ ASSERT_EQ(jt_edge(db, "a.Widget", "a.Shapes.Made.Made"), 1);+ ASSERT_STR_EQ(jt_reason(db, w, "Shapes.Made#Made(String)"), "missing");+ /* unparseable: two '#', a parameter list that does not close */+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#a#b"), "unparseable");+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget#spin(int"), "unparseable");+ /* identifiers are Unicode */+ ASSERT_EQ(jt_edge(db, "a.Widget", "l\xC3\xA4nge"), 1);+ jt_end(&r);+ PASS();+}++/* An oversized reference is unparseable in both languages: the resolver+ * never resolves the prefix that was kept. */+TEST(doc_mentions_jvm_oversized_reference) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "big"));+ enum { JT_LONG = 3000 };+ char *java = malloc(JT_LONG + 256);+ char *kotlin = malloc(JT_LONG + 256);+ ASSERT_NOT_NULL(java);+ ASSERT_NOT_NULL(kotlin);+ size_t w = (size_t)snprintf(java, 128, "package a;\n/** {@link Target");+ memset(java + w, 'x', JT_LONG);+ snprintf(java + w + JT_LONG, 100, "} */\npublic class Big {}\n");+ w = (size_t)snprintf(kotlin, 128, "package a\n/** [Target");+ memset(kotlin + w, 'x', JT_LONG);+ snprintf(kotlin + w + JT_LONG, 100, "] */\nclass BigK\n");+ jt_write(&r, "src/main/java/a/Big.java", java);+ jt_write(&r, "src/main/kotlin/a/BigK.kt", kotlin);+ /* the prefix that survives the cut names a real class */+ jt_write(&r, "src/main/java/a/Target.java", "package a;\npublic class Target {}\n");+ free(java);+ free(kotlin);+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ ASSERT_EQ(dm_count(r.db, "SELECT COUNT(*) FROM edges WHERE type = 'MENTIONS'"), 0);+ ASSERT_EQ(dm_count(r.db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE reason = "+ "'unparseable'"),+ 2);+ ASSERT_EQ(dm_count(r.db, "SELECT COUNT(*) FROM doc_link_unresolved"), 2);+ jt_end(&r);+ PASS();+}++/* ── Java: the lookup order, level by level ──────────────────────── */++/* One class per boundary of javac's order for a simple type name. Each binds+ * at the nearer level although the same name exists one level further out. */+TEST(doc_mentions_jvm_java_type_levels) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jlvl"));+ jt_write(&r, "src/main/java/far/Thing.java",+ "package far;\npublic class Thing { public void go() {} }\n");+ jt_write(&r, "src/main/java/far/Tool.java", "package far;\npublic class Tool {}\n");+ jt_write(&r, "src/main/java/far/Dup.java", "package far;\npublic class Dup {}\n");+ jt_write(&r, "src/main/java/far/Iterable.java", "package far;\npublic class Iterable {}\n");+ jt_write(&r, "src/main/java/near/Dup.java", "package near;\npublic class Dup {}\n");+ jt_write(&r, "src/main/java/lv/Thing.java", "package lv;\npublic class Thing {}\n");+ jt_write(&r, "src/main/java/lv/Tool.java", "package lv;\npublic class Tool {}\n");+ /* 1. a method's own type variable, before a member type of its class */+ jt_write(&r, "src/main/java/lv/B1.java",+ "package lv;\n"+ "public class B1 {\n"+ " public static class T {}\n"+ " /** {@link T} */\n"+ " public <T> void m(T x) {}\n"+ "}\n");+ /* 2. a class's own member type, before its type variable of that name */+ jt_write(&r, "src/main/java/lv/B2.java",+ "package lv;\n"+ "public class B2<Part> {\n"+ " public static class Part {}\n"+ " /** {@link Part} */\n"+ " public void m() {}\n"+ "}\n");+ /* 3. a class's type variable, before a member type it inherits */+ jt_write(&r, "src/main/java/lv/B3.java",+ "package lv;\n"+ "public class B3<Item> extends B3Base {\n"+ " /** {@link Item} */\n"+ " public void m() {}\n"+ "}\n"+ "class B3Base {\n"+ " public static class Item {}\n"+ "}\n");+ /* 4. what the inner type inherits, before a member type of the type+ * around it */+ jt_write(&r, "src/main/java/lv/B4.java",+ "package lv;\n"+ "public class B4 {\n"+ " public static class Piece {}\n"+ " public static class Inner extends B4Base {\n"+ " /** {@link Piece} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n"+ "class B4Base {\n"+ " public static class Piece {}\n"+ "}\n");+ /* 5. a member type of an enclosing type, before a single import */+ jt_write(&r, "src/main/java/lv/B5.java",+ "package lv;\n"+ "import far.Thing;\n"+ "public class B5 {\n"+ " public static class Thing {}\n"+ " /** {@link Thing} */\n"+ " public void m() {}\n"+ "}\n");+ /* 6. a single import, before the file's package */+ jt_write(&r, "src/main/java/lv/B6.java",+ "package lv;\n"+ "import far.Thing;\n"+ "/** {@link Thing} */\n"+ "public class B6 {}\n");+ /* 7. the file's package, before an on-demand import */+ jt_write(&r, "src/main/java/lv/B7.java",+ "package lv;\n"+ "import far.*;\n"+ "/** {@link Tool} */\n"+ "public class B7 {}\n");+ /* 8. on-demand imports are one level, java.lang among them: two+ * suppliers of a name are ambiguous, never a pick */+ jt_write(&r, "src/main/java/lv/B8.java",+ "package lv;\n"+ "import far.*;\n"+ "import near.*;\n"+ "/** {@link Dup} {@link Iterable} {@link Runnable} */\n"+ "public class B8 {}\n");+ /* 9. a qualified name: the head through the scope, else from the root */+ jt_write(&r, "src/main/java/lv/B9.java",+ "package lv;\n"+ "/**\n"+ " * {@link B5.Thing} {@link far.Thing} {@link B5.Nope} {@link far.Thing.go}\n"+ " * {@link lv.B4.Inner}\n"+ " */\n"+ "public class B9 {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* 1: local, neither an edge nor a row */+ ASSERT_EQ(dm_mentions_from(db, "lv.B1.m"), 0);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/lv/B1.java", "T"), "");+ /* 2: the member type */+ ASSERT_EQ(jt_edge(db, "lv.B2.m", "lv.B2.Part"), 1);+ /* 3: local, not the inherited member type */+ ASSERT_EQ(dm_mentions_from(db, "lv.B3.m"), 0);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/lv/B3.java", "Item"), "");+ /* 4: the inherited one, not the outer type's */+ ASSERT_EQ(jt_edge(db, "lv.B4.Inner.m", "lv.B4Base.Piece"), 1);+ ASSERT_EQ(jt_edge(db, "lv.B4.Inner.m", "lv.B4.Piece"), 0);+ /* 5: the member type, not the import */+ ASSERT_EQ(jt_edge(db, "lv.B5.m", "lv.B5.Thing"), 1);+ ASSERT_EQ(jt_edge(db, "lv.B5.m", "far.Thing"), 0);+ /* 6: the import (exact), not the package's type */+ ASSERT_EQ(jt_edge(db, "lv.B6", "far.Thing"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"exact\""));+ ASSERT_EQ(jt_edge(db, "lv.B6", "lv.Thing"), 0);+ /* 7: the package's type (unique), not the on-demand import's */+ ASSERT_EQ(jt_edge(db, "lv.B7", "lv.Tool"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"unique\""));+ ASSERT_EQ(jt_edge(db, "lv.B7", "far.Tool"), 0);+ /* 8 */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/lv/B8.java", "Dup"), "ambiguous");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/lv/B8.java", "Iterable"), "ambiguous");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/lv/B8.java", "Runnable"), "external");+ ASSERT_EQ(dm_mentions_from(db, "lv.B8"), 0);+ /* 9 */+ ASSERT_EQ(jt_edge(db, "lv.B9", "lv.B5.Thing"), 1);+ ASSERT_EQ(jt_edge(db, "lv.B9", "far.Thing"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"exact\""));+ ASSERT_EQ(jt_edge(db, "lv.B9", "lv.B4.Inner"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/lv/B9.java", "B5.Nope"), "missing");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/lv/B9.java", "far.Thing.go"), "missing");+ ASSERT_EQ(jt_edge(db, "lv.B9", "far.Thing.go"), 0);+ jt_end(&r);+ PASS();+}++/* Member references: the order of the levels, the kind rule, and no+ * relaxation across overloads, arities, kinds or constructors. */+TEST(doc_mentions_jvm_java_member_levels) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jmem"));+ jt_write(&r, "src/main/java/far/Thing.java",+ "package far;\npublic class Thing { public static void go() {} }\n");+ /* 1. the type's own method, before the one it inherits */+ jt_write(&r, "src/main/java/mv/M1.java",+ "package mv;\n"+ "public class M1 extends M1Base {\n"+ " public void go() {}\n"+ " /** {@link #go()} */\n"+ " public void m() {}\n"+ "}\n"+ "class M1Base {\n"+ " public void go() {}\n"+ "}\n");+ /* 2. what the inner type inherits, before the type around it */+ jt_write(&r, "src/main/java/mv/M2.java",+ "package mv;\n"+ "public class M2 {\n"+ " public void go() {}\n"+ " public class Inner extends M2Base {\n"+ " /** {@link #go()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n"+ "class M2Base {\n"+ " public void go() {}\n"+ "}\n");+ /* 3. a FIELD: javadoc looks in the enclosing types before the+ * supertypes, javac scoping the other way round. Where both have one+ * the reference binds neither; with only the inherited one it binds */+ jt_write(&r, "src/main/java/mv/M3.java",+ "package mv;\n"+ "public class M3 {\n"+ " public int level = 1;\n"+ " public class Inner extends M3Base {\n"+ " /** {@link #level} {@link #depth} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n"+ "class M3Base {\n"+ " public int level = 2;\n"+ " public int depth = 3;\n"+ "}\n");+ /* 4. `Type#m` is javadoc's search from the type named: its supertypes,+ * then the types around it (JDK source, JavacTrees.searchMethod) */+ jt_write(&r, "src/main/java/mv/M4.java",+ "package mv;\n"+ "public class M4 {\n"+ " public void outer() {}\n"+ " public static class Inner {}\n"+ "}\n"+ "/** {@link M4.Inner#outer()} */\n"+ "class M4User {}\n");+ /* 5. kinds: a field comes first when its class is the method's or below+ * it; for a field ABOVE the method javadoc links the method */+ jt_write(&r, "src/main/java/mv/M5.java",+ "package mv;\n"+ "public class M5 extends M5Base {\n"+ " public int size = 0;\n"+ " public int size() { return size; }\n"+ " public int total() { return 0; }\n"+ " /** {@link #size} {@link #size()} {@link #total} {@link #total()} */\n"+ " public void m() {}\n"+ "}\n"+ "class M5Base {\n"+ " public int total = 1;\n"+ "}\n");+ /* 6. signatures */+ jt_write(&r, "src/main/java/mv/M6.java",+ "package mv;\n"+ "public class M6 extends M6Base {\n"+ " public void put(int a) {}\n"+ " public <T> void take(T item) {}\n"+ " public <N extends Number> void add(N n) {}\n"+ " public static M6 of(int... xs) { return null; }\n"+ " /**\n"+ " * {@link #put(int)} {@link #put(long)} {@link #put(String)} {@link #put()}\n"+ " * {@link #take(Object)} {@link #take(String)} {@link #add(Number)}\n"+ " * {@link #add(Object)} {@link #of(int...)} {@link #of(int[])} {@link #of(int)}\n"+ " */\n"+ " public void m() {}\n"+ "}\n"+ "class M6Base {\n"+ " public void put(long a) {}\n"+ "}\n");+ /* 7. constructors: of the named type only, none inherited */+ jt_write(&r, "src/main/java/mv/M7.java",+ "package mv;\n"+ "public class M7 {\n"+ " public M7(int n) {}\n"+ " /** {@link #M7(int)} {@link #M7(String)} {@link M7Sub#M7Sub(int)} */\n"+ " public void m() {}\n"+ "}\n"+ "class M7Sub extends M7 {\n"+ " M7Sub() { super(1); }\n"+ "}\n");+ /* 8. a record: its component's accessor is its own method (no node);+ * the interface method of that name does not stand in */+ jt_write(&r, "src/main/java/mv/M8.java",+ "package mv;\n"+ "/** {@link M8#x()} {@link M8#x} {@link M8#M8(int, String)} {@link M8#M8(int)} */\n"+ "public record M8(int x, String y) implements M8Shape {}\n"+ "interface M8Shape {\n"+ " int x();\n"+ "}\n");+ /* 9. among supertypes a class's method comes before an interface's,+ * wherever the interface sits */+ jt_write(&r, "src/main/java/mv/M9.java",+ "package mv;\n"+ "public class M9 extends M9Mid implements M9Api {\n"+ " /** {@link #name()} */\n"+ " public void m() {}\n"+ "}\n"+ "interface M9Api {\n"+ " String name();\n"+ "}\n"+ "class M9Mid extends M9Base {}\n"+ "class M9Base {\n"+ " public String name() { return null; }\n"+ "}\n");+ /* 10. javadoc reads a bare identifier that is no type as `#identifier`;+ * not where an on-demand import of an unknown package may hold a type+ * of that name, which would come first */+ jt_write(&r, "src/main/java/mv/M10.java",+ "package mv;\n"+ "public class M10 {\n"+ " public void helper() {}\n"+ " /** {@link helper} */\n"+ " public void m() {}\n"+ "}\n");+ jt_write(&r, "src/main/java/mv/M10b.java",+ "package mv;\n"+ "import org.outside.*;\n"+ "public class M10b {\n"+ " public void helper() {}\n"+ " /** {@link helper} */\n"+ " public void m() {}\n"+ "}\n");+ /* 11. a static import is no level for a member reference */+ jt_write(&r, "src/main/java/mv/M11.java",+ "package mv;\n"+ "import static far.Thing.go;\n"+ "public class M11 {\n"+ " /** {@link #go()} */\n"+ " public void m() {}\n"+ "}\n");+ /* 12. {@value} names a field: a method of that name is no target */+ jt_write(&r, "src/main/java/mv/M12.java",+ "package mv;\n"+ "public class M12 {\n"+ " public static final int LIMIT = 3;\n"+ " public int count() { return 0; }\n"+ " /** {@value #LIMIT} {@value #count} */\n"+ " public void m() {}\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* 1 */+ ASSERT_EQ(jt_edge(db, "mv.M1.m", "mv.M1.go"), 1);+ ASSERT_EQ(jt_edge(db, "mv.M1.m", "mv.M1Base.go"), 0);+ /* 2 */+ ASSERT_EQ(jt_edge(db, "mv.M2.Inner.m", "mv.M2Base.go"), 1);+ ASSERT_EQ(jt_edge(db, "mv.M2.Inner.m", "mv.M2.go"), 0);+ /* 3 */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M3.java", "#level"), "ambiguous");+ ASSERT_EQ(jt_edge(db, "mv.M3.Inner.m", "mv.M3Base.depth"), 1);+ ASSERT_EQ(dm_mentions_from(db, "mv.M3.Inner.m"), 1);+ /* 4 */+ ASSERT_EQ(jt_edge(db, "mv.M4User", "mv.M4.outer"), 1);+ ASSERT_EQ(dm_mentions_from(db, "mv.M4User"), 1);+ /* 5 */+ ASSERT_EQ(jt_edge(db, "mv.M5.m", "mv.M5.size"), 1); /* the field */+ ASSERT_EQ(jt_edge(db, "mv.M5.m", "mv.M5.size"), 1); /* the method, by its list */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M5.java", "#total"), ""); /* no row */+ ASSERT_EQ(jt_edge(db, "mv.M5.m", "mv.M5.total"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":2")); /* `#total` and `#total()` */+ ASSERT_EQ(jt_edge(db, "mv.M5.m", "mv.M5Base.total"), 0);+ /* 6 */+ ASSERT_EQ(jt_edge(db, "mv.M6.m", "mv.M6.put"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1")); /* put(int) only */+ ASSERT_EQ(jt_edge(db, "mv.M6.m", "mv.M6Base.put"), 1); /* put(long): the supertype's */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M6.java", "#put(String)"), "missing");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M6.java", "#put()"), "missing");+ ASSERT_EQ(jt_edge(db, "mv.M6.m", "mv.M6.take"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1")); /* take(Object), the erasure */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M6.java", "#take(String)"), "missing");+ ASSERT_EQ(jt_edge(db, "mv.M6.m", "mv.M6.add"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M6.java", "#add(Object)"), "missing");+ ASSERT_EQ(jt_edge(db, "mv.M6.m", "mv.M6.of"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":2")); /* of(int...) and of(int[]) */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M6.java", "#of(int)"), "missing");+ /* 7 */+ ASSERT_EQ(jt_edge(db, "mv.M7.m", "mv.M7.M7"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M7.java", "#M7(String)"), "missing");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M7.java", "M7Sub#M7Sub(int)"), "missing");+ /* 8 */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M8.java", "M8#x()"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M8.java", "M8#x"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M8.java", "M8#M8(int, String)"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M8.java", "M8#M8(int)"), "missing");+ ASSERT_EQ(jt_edge(db, "mv.M8", "mv.M8Shape.x"), 0);+ /* 9 */+ ASSERT_EQ(jt_edge(db, "mv.M9.m", "mv.M9Base.name"), 1);+ ASSERT_EQ(jt_edge(db, "mv.M9.m", "mv.M9Api.name"), 0);+ /* 10 */+ ASSERT_EQ(jt_edge(db, "mv.M10.m", "mv.M10.helper"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M10b.java", "helper"), "external");+ ASSERT_EQ(dm_mentions_from(db, "mv.M10b.m"), 0);+ /* 11 */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M11.java", "#go()"), "missing");+ ASSERT_EQ(dm_mentions_from(db, "mv.M11.m"), 0);+ /* 12 */+ ASSERT_EQ(jt_edge(db, "mv.M12.m", "mv.M12.LIMIT"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/mv/M12.java", "#count"), "missing");+ ASSERT_EQ(jt_edge(db, "mv.M12.m", "mv.M12.count"), 0);+ jt_end(&r);+ PASS();+}++/* ── Kotlin: every family, every reason ──────────────────────────── */++#define JT_K_GADGET \+ "package k\n" \+ "\n" \+ "class Gadget {\n" \+ " val count: Int = 0\n" \+ " fun spin() {}\n" \+ " fun turn(times: Int) {}\n" \+ " fun turn(name: String) {}\n" \+ " val both: Int = 1\n" \+ " fun both() {}\n" \+ " companion object Factory {\n" \+ " fun create(): Gadget = Gadget()\n" \+ " }\n" \+ "}\n" \+ "enum class Color { RED, GREEN }\n" \+ "class CustomError : RuntimeException()\n" \+ "typealias Alias = Gadget\n"++#define JT_K_WIDGET \+ "package k\n" /* 1 */ \+ "\n" /* 2 */ \+ "import far.Helper\n" /* 3 */ \+ "import java.sql.SQLException\n" /* 4 */ \+ "\n" /* 5 */ \+ "/**\n" /* 6 */ \+ " * A [Gadget], [the count][Gadget.count], [Gadget.spin], [Helper], [String], [T],\n" /* 7 */ \+ " * [name], [Gadget.turn], [Gadget.both], [Color.RED], [NoSuchThing], [Gadget.nope],\n" /* 8 \+ */ \+ " * [GadgetTests], [Gadget.create], [Alias], [Alias.spin], [far.Helper.run], [far.sub],\n" /* 9 */ \+ " * [org.outside.Thing], [far.Missing], [k.env.Config]\n" /* 10 */ \+ " * @see Gadget.spin\n" /* 11 */ \+ " * @see NoSuchThing\n" /* 12 */ \+ " * @throws CustomError never\n" /* 13 */ \+ " * @throws SQLException bad\n" /* 14 */ \+ " * @throws IllegalStateException worse\n" /* 15 */ \+ " * @sample k.samples.widgetSample\n" /* 16 */ \+ " * @sample k.samples.noSuchSample\n" /* 17 */ \+ " * @see Gadget..spin\n" /* 18 */ \+ " */\n" /* 19 */ \+ "class Widget<T>(val name: String)\n"++TEST(doc_mentions_jvm_kotlin_families_and_reasons) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "kfam"));+ jt_write(&r, "src/main/kotlin/k/Gadget.kt", JT_K_GADGET);+ jt_write(&r, "src/main/kotlin/k/Widget.kt", JT_K_WIDGET);+ jt_write(&r, "src/main/kotlin/far/Helper.kt",+ "package far\n\nclass Helper {\n fun run() {}\n}\n");+ jt_write(&r, "src/main/kotlin/far/sub/Deep.kt", "package far.sub\n\nclass Deep\n");+ /* a real package in a directory the indexer skips by name */+ jt_write(&r, "src/main/kotlin/k/env/Config.kt", "package k.env\n\nclass Config\n");+ jt_write(&r, "src/test/kotlin/k/GadgetTests.kt", "package k\n\nclass GadgetTests\n");+ jt_write(&r, "src/test/kotlin/k/samples/Samples.kt",+ "package k.samples\n\nfun widgetSample() {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ const char *w = "src/main/kotlin/k/Widget.kt";+ const char *widget = "k.Widget.Widget";++ /* kdoc_link: a type of the file's package */+ ASSERT_EQ(jt_edge(db, widget, "k.Gadget.Gadget"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"kdoc_link\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"unique\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"line\":7"));+ /* [text][Type.member]: a property (its node is named below the file) */+ ASSERT_EQ(jt_edge(db, widget, "k.Gadget.count"), 1);+ /* a member function, named twice: once in the text, once by @see */+ ASSERT_EQ(jt_edge(db, widget, "k.Gadget.Gadget.spin"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":3")); /* ... and once through the alias */+ /* an explicit import: exact */+ ASSERT_EQ(jt_edge(db, widget, "far.Helper.Helper"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"exact\""));+ ASSERT_EQ(jt_edge(db, widget, "far.Helper.Helper.run"), 1);+ /* a member of the companion object, named through its class */+ ASSERT_EQ(jt_edge(db, widget, "k.Gadget.Factory.create"), 1);+ /* a type alias has a node of its own */+ ASSERT_EQ(jt_edge(db, widget, "k.Gadget.Alias"), 1);+ /* throws */+ ASSERT_EQ(jt_edge(db, widget, "k.Gadget.CustomError"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"throws\""));+ /* sample: a function in test sources binds although Widget is product+ * code (samples live in tests) */+ ASSERT_EQ(jt_edge(db, widget, "k.samples.Samples.widgetSample"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"sample\""));++ /* external: a default import, an import of a package the repository+ * does not declare, a qualified name of such a package */+ ASSERT_STR_EQ(jt_reason(db, w, "String"), "external");+ ASSERT_STR_EQ(jt_reason(db, w, "SQLException"), "external");+ ASSERT_STR_EQ(jt_reason(db, w, "IllegalStateException"), "external");+ ASSERT_STR_EQ(jt_reason(db, w, "org.outside.Thing"), "external");+ /* local: the class's own type parameter and constructor parameter */+ ASSERT_STR_EQ(jt_reason(db, w, "T"), "");+ ASSERT_STR_EQ(jt_reason(db, w, "name"), "");+ /* ambiguous: an overload group; a property and a function of one name */+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget.turn"), "ambiguous");+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget.both"), "ambiguous");+ /* graph_gap: an enum entry (declared, no node), a package (no node) */+ ASSERT_STR_EQ(jt_reason(db, w, "Color.RED"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, w, "far.sub"), "graph_gap");+ /* test_only_target */+ ASSERT_STR_EQ(jt_reason(db, w, "GadgetTests"), "test_only_target");+ /* not_indexed: a package of the repository in a directory discovery skips */+ ASSERT_STR_EQ(jt_reason(db, w, "k.env.Config"), "not_indexed");+ /* unparseable: a path with an empty name in it */+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget..spin"), "unparseable");+ /* a `[name]` that names nothing is Markdown text to KDoc: no row. The+ * block tags name their subject: missing */+ ASSERT_STR_EQ(jt_reason(db, w, "Gadget.nope"), "");+ ASSERT_STR_EQ(jt_reason(db, w, "far.Missing"), "");+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE raw = 'NoSuchThing'"),+ 1);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE raw = 'NoSuchThing' "+ "AND syntax = 'see' AND reason = 'missing' AND line = 12"),+ 1);+ ASSERT_STR_EQ(jt_reason(db, w, "k.samples.noSuchSample"), "missing");+ jt_end(&r);+ PASS();+}++/* ── Kotlin: the lookup order, level by level ────────────────────── */++TEST(doc_mentions_jvm_kotlin_levels) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "klvl"));+ jt_write(&r, "src/main/kotlin/far/Thing.kt", "package far\n\nclass Thing\n");+ jt_write(&r, "src/main/kotlin/far/Tool.kt", "package far\n\nclass Tool\n");+ jt_write(&r, "src/main/kotlin/far/List.kt", "package far\n\nclass List\n");+ jt_write(&r, "src/main/kotlin/far/Funs.kt", "package far\n\nfun topFun() {}\n");+ jt_write(&r, "src/main/kotlin/far/Ext.kt", "package far\n\nfun Thing.shine() {}\n");+ jt_write(&r, "src/main/kotlin/kl/Thing.kt", "package kl\n\nclass Thing\n");+ jt_write(&r, "src/main/kotlin/kl/Tool.kt", "package kl\n\nclass Tool\n");+ /* 1. the definition's own parameter, before a member of its class */+ jt_write(&r, "src/main/kotlin/kl/K1.kt",+ "package kl\n"+ "\n"+ "class K1 {\n"+ " val label: Int = 0\n"+ " /** The [label]. */\n"+ " fun m(label: String) {}\n"+ "}\n");+ /* 2. a constructor parameter is the class's own in the class's doc. In+ * a member's doc a `val` one is a property of the class (declared, no+ * node): it shadows the package's property of that name */+ jt_write(&r, "src/main/kotlin/kl/K2.kt",+ "package kl\n"+ "\n"+ "val shade: Int = 1\n"+ "\n"+ "/** Uses [shade] and [plain]. */\n"+ "class K2(val shade: Int, plain: Int) {\n"+ " /** Reads [shade], also [plain]. */\n"+ " fun m() {}\n"+ "}\n");+ /* 3. what the type holds itself and in its companion (one scope), then+ * what it inherits: its own override, not the supertype's */+ jt_write(&r, "src/main/kotlin/kl/K3.kt",+ "package kl\n"+ "\n"+ "open class K3Base {\n"+ " fun inherited() {}\n"+ " open fun shared() {}\n"+ "}\n"+ "\n"+ "class K3 : K3Base() {\n"+ " fun own() {}\n"+ " override fun shared() {}\n"+ " companion object Tools {\n"+ " fun make() {}\n"+ " }\n"+ " /** [own], [make], [inherited], [shared] */\n"+ " fun m() {}\n"+ "}\n"+ "\n"+ "fun K3Base.glow() {}\n"+ "\n"+ "fun <T> T.anyExt() {}\n");+ /* 4. a type nested in an enclosing type, before an explicit import */+ jt_write(&r, "src/main/kotlin/kl/K4.kt",+ "package kl\n"+ "\n"+ "import far.Thing\n"+ "\n"+ "class K4 {\n"+ " class Thing\n"+ " /** [Thing] */\n"+ " fun m() {}\n"+ "}\n");+ /* 5. an explicit import, before the file's package */+ jt_write(&r, "src/main/kotlin/kl/K5.kt",+ "package kl\n"+ "\n"+ "import far.Thing\n"+ "\n"+ "/** [Thing] */\n"+ "class K5\n");+ /* 6. the file's package, before a star import */+ jt_write(&r, "src/main/kotlin/kl/K6.kt",+ "package kl\n"+ "\n"+ "import far.*\n"+ "\n"+ "/** [Tool] */\n"+ "class K6\n");+ /* 7. a star import, before the default imports; 8. the default imports */+ jt_write(&r, "src/main/kotlin/kl/K7.kt",+ "package kl\n"+ "\n"+ "import far.*\n"+ "\n"+ "/** [List] */\n"+ "class K7\n");+ jt_write(&r, "src/main/kotlin/kl/K8.kt",+ "package kl\n"+ "\n"+ "/** [List], [listOf], [Runnable] */\n"+ "class K8\n");+ /* 9. dotted names */+ jt_write(+ &r, "src/main/kotlin/kl/K9.kt",+ "package kl\n"+ "\n"+ "/** [K4.Thing], [far.Thing], [far.topFun], [K3.make], [K3.inherited], [K3.shared] */\n"+ "class K9\n");+ /* 10. an extension is found for `Type.name` among the callables in+ * scope, by its receiver: imported, declared in the file's package (on a+ * supertype, on any type), and not when nothing brings it into scope */+ jt_write(&r, "src/main/kotlin/kl/K10.kt",+ "package kl\n"+ "\n"+ "import far.Thing\n"+ "import far.shine\n"+ "\n"+ "/** [Thing.shine], [K3.glow], [K3.anyExt] */\n"+ "class K10\n");+ jt_write(&r, "src/main/kotlin/kl/K10b.kt",+ "package kl\n"+ "\n"+ "/** @see far.Thing.shine */\n"+ "class K10b\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* 1 */+ ASSERT_EQ(dm_mentions_from(db, "kl.K1.K1.m"), 0);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/kl/K1.kt", "label"), "");+ /* 2: the class's doc leaves no row; the member's doc one gap for the+ * property and nothing for the plain parameter */+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/main/kotlin/kl/K2.kt'"),+ 1);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/main/kotlin/kl/K2.kt' AND raw = 'shade' AND line = 7 AND "+ "reason = 'graph_gap'"),+ 1);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM edges e JOIN nodes t ON t.id = e.target_id "+ "WHERE e.type = 'MENTIONS' AND t.qualified_name LIKE '%.kl.K2.shade'"),+ 0);+ /* 3 */+ ASSERT_EQ(jt_edge(db, "kl.K3.K3.m", "kl.K3.K3.own"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K3.K3.m", "kl.K3.Tools.make"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K3.K3.m", "kl.K3.K3Base.inherited"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K3.K3.m", "kl.K3.K3.shared"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K3.K3.m", "kl.K3.K3Base.shared"), 0);+ /* 4 */+ ASSERT_EQ(jt_edge(db, "kl.K4.K4.m", "kl.K4.Thing"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K4.K4.m", "far.Thing.Thing"), 0);+ /* 5 */+ ASSERT_EQ(jt_edge(db, "kl.K5.K5", "far.Thing.Thing"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"exact\""));+ ASSERT_EQ(jt_edge(db, "kl.K5.K5", "kl.Thing.Thing"), 0);+ /* 6 */+ ASSERT_EQ(jt_edge(db, "kl.K6.K6", "kl.Tool.Tool"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K6.K6", "far.Tool.Tool"), 0);+ /* 7 */+ ASSERT_EQ(jt_edge(db, "kl.K7.K7", "far.List.List"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/kl/K7.kt", "List"), "");+ /* 8 */+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/kl/K8.kt", "List"), "external");+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/kl/K8.kt", "listOf"), "external");+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/kl/K8.kt", "Runnable"), "external");+ /* 9 */+ ASSERT_EQ(jt_edge(db, "kl.K9.K9", "kl.K4.Thing"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K9.K9", "far.Thing.Thing"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"exact\""));+ ASSERT_EQ(jt_edge(db, "kl.K9.K9", "far.Funs.topFun"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K9.K9", "kl.K3.Tools.make"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K9.K9", "kl.K3.K3Base.inherited"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K9.K9", "kl.K3.K3.shared"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K9.K9", "kl.K3.K3Base.shared"), 0);+ /* 10 */+ ASSERT_EQ(jt_edge(db, "kl.K10.K10", "far.Ext.shine"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K10.K10", "kl.K3.glow"), 1);+ ASSERT_EQ(jt_edge(db, "kl.K10.K10", "kl.K3.anyExt"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/kl/K10b.kt", "far.Thing.shine"), "missing");+ ASSERT_EQ(dm_mentions_from(db, "kl.K10b.K10b"), 0);+ jt_end(&r);+ PASS();+}++/* ── a member a nearer type may have unseen ──────────────────────── */++/* Both languages resolve a member name in a type, with what the type+ * inherits, before they look at the type around it (or, in Kotlin, at the+ * file's imports and package). A member found further out binds only when the+ * nearer type is KNOWN not to have one: not where the language gives every+ * type a member of that name, and not where a supertype outside the+ * repository may declare it. Those references are external rows. */++/* Number of unresolved rows of file `rel` with this raw text and reason. */+static int jt_rows(const char *db, const char *rel, const char *raw, const char *reason) {+ char sql[700];+ snprintf(sql, sizeof(sql),+ "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = '%s' AND raw = '%s' "+ "AND reason = '%s'",+ rel, raw, reason);+ return dm_count(db, sql);+}++/* Java: a method every class has (java.lang.Object's), or every enum, is the+ * documented class's own. `#toString()` in a nested class never names the+ * method of the class around it. */+TEST(doc_mentions_jvm_java_given_members) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jgiv"));+ const char *g1 = "src/main/java/gj/G1.java";+ jt_write(&r, g1,+ "package gj;\n"+ "public class G1 {\n"+ " public int hashCode = 2;\n"+ " public String toString() { return \"\"; }\n"+ " public boolean equals(String key, int n) { return false; }\n"+ " public void helper() {}\n"+ " public static class Bare {\n"+ " /**\n"+ " * {@link #toString()} {@link #toString} {@link #equals(Object)}\n"+ " * {@link #wait(long)} {@link #equals(String, int)} {@link #helper()}\n"+ " * {@link #hashCode}\n"+ " */\n"+ " public void m() {}\n"+ " }\n"+ " public static class Own {\n"+ " public String toString() { return \"\"; }\n"+ " /** {@link #toString()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ const char *g2 = "src/main/java/gj/G2.java";+ jt_write(&r, g2,+ "package gj;\n"+ "public class G2 {\n"+ " public static void values() {}\n"+ " public void helper() {}\n"+ " public enum Mode {\n"+ " ON;\n"+ " /** {@link #values()} {@link #helper()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* Object's methods, with one of their own parameter lists or with none+ * written: external, and no edge to the method of the class around */+ ASSERT_EQ(jt_rows(db, g1, "#toString()", "external"), 1);+ ASSERT_EQ(jt_rows(db, g1, "#toString", "external"), 1);+ ASSERT_EQ(jt_rows(db, g1, "#equals(Object)", "external"), 1);+ ASSERT_EQ(jt_rows(db, g1, "#wait(long)", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G1.Bare.m", "gj.G1.toString"), 0);+ /* decoys: another parameter list is no method of Object; another name is+ * none at all; a FIELD of such a name keeps javadoc's order for fields */+ ASSERT_EQ(jt_edge(db, "gj.G1.Bare.m", "gj.G1.equals"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G1.Bare.m", "gj.G1.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G1.Bare.m", "gj.G1.hashCode"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gj.G1.Bare.m"), 3);+ /* ... and a class that declares the method binds its own */+ ASSERT_EQ(jt_edge(db, "gj.G1.Own.m", "gj.G1.Own.toString"), 1);+ /* what an enum has, and beside it a name it does not have */+ ASSERT_EQ(jt_rows(db, g2, "#values()", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G2.Mode.m", "gj.G2.values"), 0);+ ASSERT_EQ(jt_edge(db, "gj.G2.Mode.m", "gj.G2.helper"), 1);+ jt_end(&r);+ PASS();+}++/* The supertypes the Java cases share: one whose own hierarchy leaves the+ * repository, one without members, one with them. */+static void jt_guard_java_bases(const jt_repo_t *r) {+ jt_write(r, "src/main/java/gj/Mid.java",+ "package gj;\n"+ "public class Mid extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ "}\n");+ jt_write(r, "src/main/java/gj/Plain.java", "package gj;\npublic class Plain {}\n");+ jt_write(r, "src/main/java/gj/Has.java",+ "package gj;\n"+ "public class Has {\n"+ " public void close() {}\n"+ " public void helper() {}\n"+ "}\n");+}++/* Java: a method of the class around a nested class binds only when every+ * supertype of the nested class is in the repository and none has it. A+ * supertype outside the repository, directly or further up, may declare it,+ * and then javadoc links that one. */+TEST(doc_mentions_jvm_java_open_supertypes) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jopen"));+ jt_guard_java_bases(&r);+ const char *g3 = "src/main/java/gj/G3.java";+ jt_write(&r, g3,+ "package gj;\n"+ "public class G3 {\n"+ " public int count = 1;\n"+ " public void close() {}\n"+ " public void helper() {}\n"+ " public static class Stream extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ " /** {@link #close()} {@link #helper} {@link #count} {@link #read()} */\n"+ " public void m() {}\n"+ " }\n"+ " public static class Deep extends Mid {\n"+ " /** {@link #close()} {@link #count} */\n"+ " public void m() {}\n"+ " }\n"+ " public static class Wrap extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ " public class In {\n"+ " /** {@link #helper()} {@link #read()} */\n"+ " public void m() {}\n"+ " }\n"+ " }\n"+ "}\n");+ const char *g4 = "src/main/java/gj/G4.java";+ jt_write(&r, g4,+ "package gj;\n"+ "public class G4 {\n"+ " public int count = 1;\n"+ " public void close() {}\n"+ " public void helper() {}\n"+ " public void extra() {}\n"+ " public static class Lacks extends Plain {\n"+ " /** {@link #close()} {@link #helper} {@link #count} */\n"+ " public void m() {}\n"+ " }\n"+ " public static class Gets extends Has {\n"+ " /** {@link #close()} {@link #helper} {@link #extra()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ const char *g5 = "src/main/java/gj/G5.java";+ jt_write(&r, g5,+ "package gj;\n"+ "public class G5 {\n"+ " public int total() { return 0; }\n"+ " public class Mid5 extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ " public class In {\n"+ " public int total = 1;\n"+ " /** {@link #total} */\n"+ " public void m() {}\n"+ " }\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* a supertype outside the repository, written on the class (Stream) and+ * one level up (Deep, through Mid): java.io.InputStream may declare+ * close() and helper() */+ ASSERT_EQ(jt_rows(db, g3, "#close()", "external"), 2);+ ASSERT_EQ(jt_rows(db, g3, "#helper", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G3.Stream.m", "gj.G3.close"), 0);+ ASSERT_EQ(jt_edge(db, "gj.G3.Stream.m", "gj.G3.helper"), 0);+ ASSERT_EQ(jt_edge(db, "gj.G3.Deep.m", "gj.G3.close"), 0);+ /* the class's own method is found before the lookup would leave it */+ ASSERT_EQ(jt_edge(db, "gj.G3.Stream.m", "gj.G3.Stream.read"), 1);+ /* a FIELD of the class around, through the same shapes: the supertype+ * outside may have a METHOD count(), which javadoc would link instead */+ ASSERT_EQ(jt_rows(db, g3, "#count", "external"), 2);+ ASSERT_EQ(jt_edge(db, "gj.G3.Stream.m", "gj.G3.count"), 0);+ ASSERT_EQ(dm_mentions_from(db, "gj.G3.Stream.m"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gj.G3.Deep.m"), 0);+ /* the type that leaves the repository need not be the innermost one */+ ASSERT_EQ(jt_rows(db, g3, "#helper()", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G3.Wrap.In.m", "gj.G3.Wrap.read"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gj.G3.Wrap.In.m"), 1);+ /* every supertype in the repository and none has the method: the class+ * around it, as before */+ ASSERT_EQ(jt_edge(db, "gj.G4.Lacks.m", "gj.G4.close"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G4.Lacks.m", "gj.G4.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G4.Lacks.m", "gj.G4.count"), 1);+ /* a supertype in the repository has it: that one */+ ASSERT_EQ(jt_edge(db, "gj.G4.Gets.m", "gj.Has.close"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G4.Gets.m", "gj.Has.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G4.Gets.m", "gj.G4.close"), 0);+ ASSERT_EQ(jt_edge(db, "gj.G4.Gets.m", "gj.G4.extra"), 1);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/main/java/gj/G4.java'"),+ 0);+ /* the field of In against javadoc's search for a method: it passes Mid5,+ * whose supertype lies outside, before it reaches total() of G5. In is+ * not below Mid5: a method total() there would win, and so would G5's+ * (In is not below G5 either): external */+ ASSERT_EQ(jt_rows(db, g5, "#total", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gj.G5.Mid5.In.m"), 0);+ jt_end(&r);+ PASS();+}++/* Java: a Kotlin declaration of the name cannot be compared with a written+ * Javadoc parameter list. It may be the method meant, so the lookup does not+ * go on to the class around it. */+TEST(doc_mentions_jvm_java_uncompared_level) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "juncmp"));+ jt_write(&r, "src/main/kotlin/gj/KBase.kt",+ "package gj\n"+ "\n"+ "open class KBase {\n"+ " fun send(x: Int) {}\n"+ "}\n"+ "\n"+ "open class KPlain\n");+ const char *g6 = "src/main/java/gj/G6.java";+ jt_write(&r, g6,+ "package gj;\n"+ "public class G6 {\n"+ " public void send(int x) {}\n"+ " public static class Sub extends KBase {\n"+ " /** {@link #send(int)} */\n"+ " public void m() {}\n"+ " }\n"+ " public static class Sub2 extends KPlain {\n"+ " /** {@link #send(int)} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_rows(db, g6, "#send(int)", "ambiguous"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gj.G6.Sub.m"), 0);+ /* decoy: a Kotlin supertype without the name is known not to have it */+ ASSERT_EQ(jt_edge(db, "gj.G6.Sub2.m", "gj.G6.send"), 1);+ jt_end(&r);+ PASS();+}++/* Kotlin: a member of kotlin.Any, or of an enum class, is the documented+ * class's own. `[toString]` in a class is neither the package's function of+ * that name nor plain text. */+TEST(doc_mentions_jvm_kotlin_given_members) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "kgiv"));+ jt_write(&r, "src/main/kotlin/gk/Top.kt",+ "package gk\n"+ "\n"+ "fun toString(x: Int): String = \"\"\n"+ "\n"+ "fun values() {}\n"+ "\n"+ "fun helper() {}\n");+ const char *k1 = "src/main/kotlin/gk/K1.kt";+ jt_write(&r, k1,+ "package gk\n"+ "\n"+ "/** [toString], [hashCode], [helper] */\n"+ "class Bare\n"+ "\n"+ "class Own {\n"+ " override fun toString(): String = \"\"\n"+ " /** [toString] */\n"+ " fun m() {}\n"+ "}\n"+ "\n"+ "enum class Color {\n"+ " RED;\n"+ " /** [values], [helper] */\n"+ " fun m() {}\n"+ "}\n"+ "\n"+ "/** [toString] */\n"+ "fun free() {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* external: with a function of that name in the package, and with+ * nothing of that name anywhere */+ ASSERT_EQ(jt_rows(db, k1, "toString", "external"), 1);+ ASSERT_EQ(jt_rows(db, k1, "hashCode", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K1.Bare", "gk.Top.toString"), 0);+ /* decoys: another name; a class that declares the member; a definition+ * with no class around it */+ ASSERT_EQ(jt_edge(db, "gk.K1.Bare", "gk.Top.helper"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K1.Bare"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K1.Own.m", "gk.K1.Own.toString"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K1.free", "gk.Top.toString"), 1);+ /* what an enum class has, and beside it a name it does not have (the+ * graph names a method of an enum class below the file) */+ ASSERT_EQ(jt_rows(db, k1, "values", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K1.m", "gk.Top.helper"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K1.m"), 1);+ jt_end(&r);+ PASS();+}++/* Kotlin: a function or property of the package, or of the class around,+ * binds only when every supertype of the class (and of its companion) is in+ * the repository and none has the name. A type found further out binds as+ * before. */+TEST(doc_mentions_jvm_kotlin_open_supertypes) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "kopen"));+ jt_write(&r, "src/main/kotlin/gk/Top.kt",+ "package gk\n"+ "\n"+ "fun close() {}\n"+ "\n"+ "fun helper() {}\n"+ "\n"+ "val depth: Int = 0\n"+ "\n"+ "class Thing\n");+ jt_write(&r, "src/main/kotlin/gk/Bases.kt",+ "package gk\n"+ "\n"+ "open class Mid : java.io.InputStream() {\n"+ " override fun read(): Int = 0\n"+ "}\n"+ "\n"+ "open class Plain\n"+ "\n"+ "open class Has {\n"+ " fun helper() {}\n"+ "}\n");+ const char *k2 = "src/main/kotlin/gk/K2.kt";+ jt_write(&r, k2,+ "package gk\n"+ "\n"+ "/** [close], [helper], [depth], [read], [Thing] */\n"+ "class Stream : java.io.InputStream() {\n"+ " override fun read(): Int = 0\n"+ "}\n"+ "\n"+ "/** [close], [Thing] */\n"+ "class Deep : Mid()\n");+ const char *k3 = "src/main/kotlin/gk/K3.kt";+ jt_write(&r, k3,+ "package gk\n"+ "\n"+ "/** [close], [helper], [depth] */\n"+ "class Lacks : Plain()\n"+ "\n"+ "/** [close], [helper] */\n"+ "class Gets : Has()\n");+ const char *k4 = "src/main/kotlin/gk/K4.kt";+ jt_write(&r, k4,+ "package gk\n"+ "\n"+ "class Outer {\n"+ " fun aid() {}\n"+ "\n"+ " inner class Wrapped : java.io.InputStream() {\n"+ " override fun read(): Int = 0\n"+ " /** [aid] */\n"+ " fun m() {}\n"+ " }\n"+ "\n"+ " inner class Simple {\n"+ " /** [aid] */\n"+ " fun m() {}\n"+ " }\n"+ "}\n"+ "\n"+ "class Locked {\n"+ " companion object Lock : java.io.Closeable {\n"+ " override fun close() {}\n"+ " }\n"+ " /** [helper], [close] */\n"+ " fun m() {}\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* a supertype outside the repository, written on the class (Stream) and+ * one level up (Deep, through Mid): no function or property of the+ * package */+ ASSERT_EQ(jt_rows(db, k2, "close", "external"), 2);+ ASSERT_EQ(jt_rows(db, k2, "helper", "external"), 1);+ ASSERT_EQ(jt_rows(db, k2, "depth", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K2.Stream", "gk.Top.close"), 0);+ ASSERT_EQ(jt_edge(db, "gk.K2.Deep", "gk.Top.close"), 0);+ /* the class's own member, and a TYPE of the package, bind */+ ASSERT_EQ(jt_edge(db, "gk.K2.Stream", "gk.K2.Stream.read"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K2.Stream", "gk.Top.Thing"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K2.Stream"), 2);+ ASSERT_EQ(jt_edge(db, "gk.K2.Deep", "gk.Top.Thing"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K2.Deep"), 1);+ /* every supertype in the repository and none has the name: the package,+ * as before */+ ASSERT_EQ(jt_edge(db, "gk.K3.Lacks", "gk.Top.close"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K3.Lacks", "gk.Top.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K3.Lacks", "gk.Top.depth"), 1);+ /* a supertype in the repository has it: that one */+ ASSERT_EQ(jt_edge(db, "gk.K3.Gets", "gk.Bases.Has.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K3.Gets", "gk.Top.helper"), 0);+ ASSERT_EQ(jt_edge(db, "gk.K3.Gets", "gk.Top.close"), 1);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/main/kotlin/gk/K3.kt'"),+ 0);+ /* the class around instead of the package: the same rule */+ ASSERT_EQ(jt_rows(db, k4, "aid", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K4.Wrapped.m"), 0);+ ASSERT_EQ(jt_edge(db, "gk.K4.Simple.m", "gk.K4.Outer.aid"), 1);+ /* the companion object's supertypes count: its members are in the+ * class's scope. What the companion declares itself binds */+ ASSERT_EQ(jt_rows(db, k4, "helper", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K4.Locked.m", "gk.K4.Lock.close"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K4.Locked.m"), 1);+ jt_end(&r);+ PASS();+}++/* Kotlin: what the companion object inherits is in the class's scope, before+ * the package. */+TEST(doc_mentions_jvm_kotlin_companion_inherits) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "kcomp"));+ jt_write(&r, "src/main/kotlin/gk/Top.kt",+ "package gk\n"+ "\n"+ "fun create() {}\n"+ "\n"+ "fun helper() {}\n");+ jt_write(&r, "src/main/kotlin/gk/K5.kt",+ "package gk\n"+ "\n"+ "open class Maker {\n"+ " fun create() {}\n"+ "}\n"+ "\n"+ "class Entity {\n"+ " companion object : Maker()\n"+ " /** [create], [helper] */\n"+ " fun m() {}\n"+ "}\n"+ "\n"+ "/** [Entity.create] */\n"+ "class User\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_edge(db, "gk.K5.Entity.m", "gk.K5.Maker.create"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K5.Entity.m", "gk.Top.create"), 0);+ /* decoy: a name the companion's hierarchy does not have is the package's */+ ASSERT_EQ(jt_edge(db, "gk.K5.Entity.m", "gk.Top.helper"), 1);+ /* the same member, named through the class */+ ASSERT_EQ(jt_edge(db, "gk.K5.User", "gk.K5.Maker.create"), 1);+ jt_end(&r);+ PASS();+}++/* Kotlin `Type.name`: a member comes before an extension. Where a supertype+ * of the type lies outside the repository it may declare the name, so the+ * extension in scope is not taken. */+TEST(doc_mentions_jvm_kotlin_extension_guard) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "kext"));+ jt_write(&r, "src/main/kotlin/gk/Types.kt",+ "package gk\n"+ "\n"+ "class Shut : java.io.Closeable {\n"+ " override fun close() {}\n"+ "}\n"+ "\n"+ "open class Plain\n"+ "\n"+ "class Calm : Plain()\n");+ jt_write(&r, "src/main/kotlin/gk/ExtA.kt", "package gk\n\nfun Shut.shine() {}\n");+ jt_write(&r, "src/main/kotlin/gk/ExtB.kt", "package gk\n\nfun Calm.glow() {}\n");+ const char *k6 = "src/main/kotlin/gk/K6.kt";+ jt_write(&r, k6,+ "package gk\n"+ "\n"+ "/** [Shut.shine], [Calm.glow], [Shut.close] */\n"+ "class ExtUser\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_rows(db, k6, "Shut.shine", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K6.ExtUser", "gk.ExtA.shine"), 0);+ /* decoys: a receiver whose supertypes are all in the repository; a+ * member the open type declares itself */+ ASSERT_EQ(jt_edge(db, "gk.K6.ExtUser", "gk.ExtB.glow"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K6.ExtUser", "gk.Types.Shut.close"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K6.ExtUser"), 2);+ jt_end(&r);+ PASS();+}++/* java.lang.Object and kotlin.Any written out as a supertype are no supertype+ * outside the repository: every type has them, and their members are known. */+TEST(doc_mentions_jvm_root_supertype_written) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "groot"));+ jt_write(&r, "src/main/java/gj/G7.java",+ "package gj;\n"+ "public class G7 {\n"+ " public void helper() {}\n"+ " public static class Rooted extends Object {\n"+ " /** {@link #helper()} */\n"+ " public void m() {}\n"+ " }\n"+ " public static class Full extends java.lang.Object {\n"+ " /** {@link #helper()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ jt_write(&r, "src/main/kotlin/gk/Top.kt", "package gk\n\nfun helper() {}\n");+ jt_write(&r, "src/main/kotlin/gk/K7.kt",+ "package gk\n"+ "\n"+ "/** [helper] */\n"+ "class Rooted : Any()\n"+ "\n"+ "/** [helper] */\n"+ "class Full : kotlin.Any()\n");+ /* decoy: where an import supplies the simple name, the supertype is+ * whatever that import names */+ const char *k7b = "src/main/kotlin/gk/K7b.kt";+ jt_write(&r, k7b,+ "package gk\n"+ "\n"+ "import org.outside.Any\n"+ "\n"+ "/** [helper] */\n"+ "class Other : Any()\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_edge(db, "gj.G7.Rooted.m", "gj.G7.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gj.G7.Full.m", "gj.G7.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K7.Rooted", "gk.Top.helper"), 1);+ ASSERT_EQ(jt_edge(db, "gk.K7.Full", "gk.Top.helper"), 1);+ ASSERT_EQ(jt_rows(db, k7b, "helper", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gk.K7b.Other"), 0);+ jt_end(&r);+ PASS();+}++/* The guard reads supertypes that OTHER files declare: what a file's own+ * references bind changes when a supertype elsewhere loses a member, or gains+ * or loses a supertype outside the repository. Incremental equals full. */+TEST(doc_mentions_jvm_guard_incremental_equals_full) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "ginc"));+ const char *base = "src/main/java/gi/Base.java";+ const char *outer = "src/main/java/gi/Outer.java";+ jt_write(&r, base, "package gi;\npublic class Base {\n public void near() {}\n}\n");+ jt_write(&r, outer,+ "package gi;\n"+ "public class Outer {\n"+ " public void near() {}\n"+ " public void far() {}\n"+ " public class In extends Base {\n"+ " /** {@link #near()} {@link #far()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ char full_db[600];+ snprintf(full_db, sizeof(full_db), "%s/full.db", r.tmp);+ const char *db = r.db;+ ASSERT_EQ(dm_index(r.repo, db, NULL), 0);+ ASSERT_EQ(jt_edge(db, "gi.Outer.In.m", "gi.Base.near"), 1);+ ASSERT_EQ(jt_edge(db, "gi.Outer.In.m", "gi.Outer.far"), 1);+ /* the supertype loses the member: the class around has one */+ jt_write(&r, base, "package gi;\npublic class Base {\n}\n");+ ASSERT_EQ(dm_step(r.repo, db, full_db, "supertype member removed",+ CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR),+ 0);+ ASSERT_EQ(jt_edge(db, "gi.Outer.In.m", "gi.Outer.near"), 1);+ /* the supertype leaves the repository: no method of the class around */+ jt_write(&r, base,+ "package gi;\n"+ "public class Base extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ "}\n");+ ASSERT_EQ(dm_step(r.repo, db, full_db, "supertype opened", CBM_INCREMENTAL_ROUTE_FORCED_FULL),+ 0);+ ASSERT_EQ(dm_mentions_from(db, "gi.Outer.In.m"), 0);+ ASSERT_EQ(jt_rows(db, outer, "#far()", "external"), 1);+ /* ... and comes back into it */+ jt_write(&r, base, "package gi;\npublic class Base {\n}\n");+ ASSERT_EQ(dm_step(r.repo, db, full_db, "supertype closed", CBM_INCREMENTAL_ROUTE_FORCED_FULL),+ 0);+ ASSERT_EQ(jt_edge(db, "gi.Outer.In.m", "gi.Outer.near"), 1);+ ASSERT_EQ(jt_edge(db, "gi.Outer.In.m", "gi.Outer.far"), 1);+ dm_unlink_db(full_db);+ jt_end(&r);+ PASS();+}++/* ── both languages in one index ─────────────────────────────────── */++/* A package is one namespace whatever language declares into it: a KDoc name+ * finds a Java class, a Javadoc link a Kotlin class. What cannot be compared+ * across the two (a Javadoc signature against a Kotlin declaration, a type+ * alias seen from Java) is a row, never a guess. */+TEST(doc_mentions_jvm_cross_language) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "cross"));+ jt_write(&r, "src/main/java/x/JBox.java",+ "package x;\n"+ "public class JBox {\n"+ " public int size = 1;\n"+ " public void open() {}\n"+ " public void open(int n) {}\n"+ " public void shut() {}\n"+ "}\n");+ jt_write(&r, "src/main/kotlin/x/KBox.kt",+ "package x\n"+ "\n"+ "class KBox {\n"+ " fun close() {}\n"+ " val lid: Int = 0\n"+ "}\n"+ "\n"+ "typealias KAlias = KBox\n");+ jt_write(&r, "src/main/kotlin/x/KUser.kt",+ "package x\n"+ "\n"+ "/** [JBox], [JBox.size], [JBox.shut], [JBox.open] */\n"+ "class KUser\n");+ jt_write(&r, "src/main/java/x/JUser.java",+ "package x;\n"+ "/**\n"+ " * {@link KBox} {@link KBox#close} {@link KBox#lid} {@link KBox#close()}\n"+ " * {@link KAlias}\n"+ " */\n"+ "public class JUser {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* Kotlin -> Java */+ ASSERT_EQ(jt_edge(db, "x.KUser.KUser", "x.JBox"), 1);+ ASSERT_EQ(jt_edge(db, "x.KUser.KUser", "x.JBox.size"), 1);+ ASSERT_EQ(jt_edge(db, "x.KUser.KUser", "x.JBox.shut"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/x/KUser.kt", "JBox.open"), "ambiguous");+ /* Java -> Kotlin */+ ASSERT_EQ(jt_edge(db, "x.JUser", "x.KBox.KBox"), 1);+ ASSERT_EQ(jt_edge(db, "x.JUser", "x.KBox.KBox.close"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1")); /* `#close`, not `#close()` */+ ASSERT_EQ(jt_edge(db, "x.JUser", "x.KBox.lid"), 1);+ /* a Javadoc parameter list cannot be compared with a Kotlin signature */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/x/JUser.java", "KBox#close()"), "ambiguous");+ /* Java does not see a Kotlin type alias */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/x/JUser.java", "KAlias"), "missing");+ ASSERT_EQ(jt_edge(db, "x.JUser", "x.KBox.KAlias"), 0);+ jt_end(&r);+ PASS();+}++/* ── one node per qualified name ─────────────────────────────────── */++/* Several declarations can have one qualified name, and the graph keeps one+ * node. A reference binds only the declaration that owns the node, and an+ * edge leaves only from a definition that owns its own: a doc written on a+ * definition whose name another declaration took has nowhere to leave from. */+TEST(doc_mentions_jvm_node_ownership) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "own"));+ /* Kotlin: a class and the factory function named like it share the+ * file-based name; the later declaration owns the node */+ jt_write(&r, "src/main/kotlin/c/Maker.kt",+ "package c\n"+ "\n"+ "/** Makes a [Part], takes [T] and [String]. */\n"+ "class Maker<T>\n"+ "\n"+ "class Part\n"+ "\n"+ "/** Factory of a [Part]. */\n"+ "fun Maker(): Maker<Int> = Maker()\n");+ /* Kotlin: two classes' properties of one name in one file */+ jt_write(&r, "src/main/kotlin/c/Twins.kt",+ "package c\n"+ "\n"+ "class First {\n"+ " /** In [First]. */\n"+ " val id: Int = 1\n"+ "}\n"+ "\n"+ "class Second {\n"+ " /** In [Second]. */\n"+ " val id: Int = 2\n"+ "}\n"+ "\n"+ "/** [First.id] and [Second.id] */\n"+ "class TwinUser\n");+ /* Java: a field and its accessor share `Holder.value`; the method,+ * declared later, owns the node */+ jt_write(&r, "src/main/java/c/Holder.java",+ "package c;\n"+ "public class Holder {\n"+ " /** The {@link Other}. */\n"+ " private int value;\n"+ " /** Reads {@link Other}, see {@link #value} and {@link #value()}. */\n"+ " public int value() { return value; }\n"+ "}\n"+ "class Other {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ const char *maker = "src/main/kotlin/c/Maker.kt";+ /* the function's doc: an edge from the node the function owns */+ ASSERT_EQ(jt_edge(db, "c.Maker.Maker", "c.Maker.Part"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1"));+ ASSERT_NOT_NULL(strstr(jt_props, "\"line\":8"));+ /* the class's doc: what would be an edge is a gap; what is local or+ * external anyway keeps its own outcome */+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/main/kotlin/c/Maker.kt' AND raw = 'Part' AND line = 3 AND "+ "reason = 'graph_gap'"),+ 1);+ ASSERT_STR_EQ(jt_reason(db, maker, "T"), "");+ ASSERT_STR_EQ(jt_reason(db, maker, "String"), "external");+ /* the property that owns `id` is the later one: Second's */+ ASSERT_EQ(jt_edge(db, "c.Twins.id", "c.Twins.Second"), 1);+ ASSERT_EQ(jt_edge(db, "c.Twins.id", "c.Twins.First"), 0);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/main/kotlin/c/Twins.kt' AND raw = 'First' AND reason = "+ "'graph_gap'"),+ 1);+ ASSERT_EQ(jt_edge(db, "c.Twins.TwinUser", "c.Twins.id"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1")); /* Second.id only */+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/c/Twins.kt", "First.id"), "graph_gap");+ /* Java: a field named like its accessor has a node of its own+ * (<Owner>.<name>#field), so its doc is a source too; `#value` is the+ * field, `#value()` the method itself */+ ASSERT_EQ(jt_edge(db, "c.Holder.value", "c.Other"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1"));+ ASSERT_NOT_NULL(strstr(jt_props, "\"line\":5"));+ ASSERT_EQ(jt_edge(db, "c.Holder.value#field", "c.Other"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"line\":3"));+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE rel_path = "+ "'src/main/java/c/Holder.java' AND raw = 'Other' AND line = 3"),+ 0);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/c/Holder.java", "#value"), "");+ ASSERT_EQ(jt_edge(db, "c.Holder.value", "c.Holder.value#field"), 1);+ jt_end(&r);+ PASS();+}++/* A Kotlin class and a function of its name at one scope level (the factory+ * idiom, `class Json` beside `fun Json(..)`): KDoc resolves the classifier+ * first, so the name is the CLASS, with the tier the lookup gives. A class+ * without a node of its own is a graph gap. The function never stands in for+ * the class, with a node or without. */+TEST(doc_mentions_jvm_kotlin_type_and_function) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "tfun"));+ /* class and factory in different files: each has its node. Two factory+ * overloads: the function side is a group, which changes nothing */+ jt_write(&r, "src/main/kotlin/f/Json.kt",+ "package f\n\nclass Json {\n fun encode() {}\n}\n");+ jt_write(&r, "src/main/kotlin/f/Builders.kt",+ "package f\n"+ "\n"+ "fun Json(strict: Boolean): Json = Json()\n"+ "\n"+ "fun Json(name: String): Json = Json()\n");+ /* class and factory in ONE file share the file-based qualified name+ * `f.Alias.Alias`; the function, declared later, owns the node, and the+ * class has none */+ jt_write(&r, "src/main/kotlin/f/Alias.kt",+ "package f\n"+ "\n"+ "class Alias {\n"+ " fun name() {}\n"+ "}\n"+ "\n"+ "fun Alias(text: String): Alias = Alias()\n");+ /* the same idiom inside a type: a nested class and a member function */+ jt_write(&r, "src/main/kotlin/f/Holder.kt",+ "package f\n"+ "\n"+ "class Holder {\n"+ " class Part\n"+ " fun Part(size: Int): Part = Part()\n"+ "}\n");+ /* not the idiom: a class and a PROPERTY of one name stay ambiguous */+ jt_write(&r, "src/main/kotlin/f/Mode.kt", "package f\n\nclass Mode\n");+ jt_write(&r, "src/main/kotlin/f/Modes.kt", "package f\n\nval Mode: Int = 1\n");+ jt_write(&r, "src/main/kotlin/f/User.kt",+ "package f\n"+ "\n"+ "/** A [Json] with [Json.encode], a [Holder.Part], a [Mode]. */\n"+ "class User\n");+ jt_write(&r, "src/main/kotlin/f/GapUser.kt",+ "package f\n"+ "\n"+ "/** An [Alias]. */\n"+ "class GapUser\n");+ /* the block tags that name code resolve like a link ... */+ jt_write(&r, "src/main/kotlin/f/TagUser.kt",+ "package f\n"+ "\n"+ "/**\n"+ " * @see Json\n"+ " * @throws Json never\n"+ " * @see Alias\n"+ " */\n"+ "class TagUser\n");+ /* ... but a sample is a function: there the two stay ambiguous */+ jt_write(&r, "src/main/kotlin/f/SampleUser.kt",+ "package f\n"+ "\n"+ "/** @sample f.Json */\n"+ "class SampleUser\n");+ /* an explicit import brings the class and the function: the class, exact */+ jt_write(&r, "src/main/kotlin/g/Importer.kt",+ "package g\n"+ "\n"+ "import f.Json\n"+ "\n"+ "/** A [Json]. */\n"+ "class Importer\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* the class has a node: an edge to the class, with the tier of the level+ * that found it (the file's package: unique), and no row */+ ASSERT_EQ(jt_edge(db, "f.User.User", "f.Json.Json"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"kdoc_link\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"unique\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":1"));+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/f/User.kt", "Json"), "");+ /* ... never to the function */+ ASSERT_EQ(jt_edge(db, "f.User.User", "f.Builders.Json"), 0);+ /* a qualifier is a type: the function is no candidate there */+ ASSERT_EQ(jt_edge(db, "f.User.User", "f.Json.Json.encode"), 1);+ /* inside a type: the nested class, not the member function */+ ASSERT_EQ(jt_edge(db, "f.User.User", "f.Holder.Part"), 1);+ ASSERT_EQ(jt_edge(db, "f.User.User", "f.Holder.Holder.Part"), 0);+ /* a class and a property: ambiguous, as before */+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/f/User.kt", "Mode"), "ambiguous");+ ASSERT_EQ(jt_edge(db, "f.User.User", "f.Mode.Mode"), 0);+ ASSERT_EQ(dm_mentions_from(db, "f.User.User"), 3);+ /* the class has NO node: a graph gap, and no edge at all -- the node at+ * `f.Alias.Alias` is the function's */+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/f/GapUser.kt", "Alias"), "graph_gap");+ ASSERT_EQ(jt_edge(db, "f.GapUser.GapUser", "f.Alias.Alias"), 0);+ ASSERT_EQ(dm_mentions_from(db, "f.GapUser.GapUser"), 0);+ /* @see and @throws: the class (one edge for both references), and the gap */+ ASSERT_EQ(jt_edge(db, "f.TagUser.TagUser", "f.Json.Json"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"see\""));+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":2"));+ ASSERT_EQ(jt_edge(db, "f.TagUser.TagUser", "f.Builders.Json"), 0);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/f/TagUser.kt", "Alias"), "graph_gap");+ ASSERT_EQ(dm_mentions_from(db, "f.TagUser.TagUser"), 1);+ /* @sample: neither */+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/f/SampleUser.kt", "f.Json"), "ambiguous");+ ASSERT_EQ(dm_mentions_from(db, "f.SampleUser.SampleUser"), 0);+ /* through an explicit import: the class, exact */+ ASSERT_EQ(jt_edge(db, "g.Importer.Importer", "f.Json.Json"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"tier\":\"exact\""));+ ASSERT_EQ(jt_edge(db, "g.Importer.Importer", "f.Builders.Json"), 0);+ ASSERT_EQ(dm_mentions_from(db, "g.Importer.Importer"), 1);+ jt_end(&r);+ PASS();+}++/* ── parse errors ────────────────────────────────────────────────── */++TEST(doc_mentions_jvm_scope_parse_errors) {+ /* an error inside a method's own block: the type is complete */+ CBMFileResult *r = dm_extract("package pe;\n"+ "public class InBody {\n"+ " public void before() {}\n"+ " public void bad() {\n"+ " int x = ;\n"+ " foo(;\n"+ " }\n"+ " public void after() {}\n"+ "}\n",+ CBM_LANG_JAVA, "pe/InBody.java");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT(jt_has_line(r->doc_scope, "T\t2\t9\tc\tInBody\t\t\t=\t1\t"));+ ASSERT(jt_has_line(r->doc_scope, "M\t4\tc\t\t0\tbad\t\t\t\t=\t1\t"));+ ASSERT(jt_has_line(r->doc_scope, "M\t8\tc\t\t0\tafter\t\t\t\t=\t1\t"));+ cbm_free_result(r);+ /* an error among the members: the type does not show all of them ('!'),+ * and the member the error hit is not listed */+ r = dm_extract("package pe;\n"+ "public class Among {\n"+ " public void before() {}\n"+ " public void bad( { }\n"+ " public void after() {}\n"+ "}\n",+ CBM_LANG_JAVA, "pe/Among.java");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT(jt_has_line(r->doc_scope, "T\t2\t6\tc!\tAmong\t\t\t=\t1\t"));+ ASSERT(jt_has_line(r->doc_scope, "M\t3\tc\t\t0\tbefore\t\t\t\t=\t1\t"));+ ASSERT_NULL(strstr(r->doc_scope, "\tbad\t"));+ cbm_free_result(r);+ /* braces that do not pair: nothing behind the first one is placed. The+ * names declared there are kept apart (Q), the lines marked (X) */+ r = dm_extract("package pe;\n"+ "public class Open {\n"+ " public void before() {}\n"+ " public static class Lost {\n"+ " public void inLost() {\n"+ " }\n"+ " public void after() {}\n"+ "}\n",+ CBM_LANG_JAVA, "pe/Open.java");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT_NULL(strstr(r->doc_scope, "\nT\t"));+ ASSERT(jt_has_line(r->doc_scope, "Q\tOpen"));+ ASSERT(jt_has_line(r->doc_scope, "Q\tLost"));+ ASSERT_NOT_NULL(strstr(r->doc_scope, "\nX\t2\t"));+ cbm_free_result(r);+ /* Kotlin: an error held by braces inside a member (an accessor's body, a+ * `when`) does not reach past the member: the type is complete */+ r = dm_extract("package pe\n"+ "\n"+ "class Getter {\n"+ " val ok: Int = 1\n"+ " val broken: Int\n"+ " get() {\n"+ " val x = when (this) {\n"+ " is Getter if true -> 1\n"+ " else -> 2\n"+ " }\n"+ " return x\n"+ " }\n"+ " fun bad(e: Any): Int = when (e) {\n"+ " is String if e.isEmpty() -> 1\n"+ " else -> 2\n"+ " }\n"+ " fun after() {}\n"+ "}\n",+ CBM_LANG_KOTLIN, "pe/Getter.kt");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT(jt_has_line(r->doc_scope, "T\t3\t18\tc\tGetter\t\t\t=\t1\t"));+ ASSERT(jt_has_line(r->doc_scope, "M\t5\tv\t\t0\tbroken\t\t-\t\tbroken\t1\t"));+ ASSERT(jt_has_line(r->doc_scope, "M\t13\tc\t\t0\tbad\t\tAny\t\t=\t1\te"));+ ASSERT(jt_has_line(r->doc_scope, "M\t17\tc\t\t0\tafter\t\t\t\t=\t1\t"));+ cbm_free_result(r);+ /* ... while one among the members leaves it incomplete */+ r = dm_extract("package pe\n"+ "\n"+ "class KStray {\n"+ " fun before() {}\n"+ " ) ) )\n"+ " fun after() {}\n"+ "}\n",+ CBM_LANG_KOTLIN, "pe/KStray.kt");+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT(jt_has_line(r->doc_scope, "T\t3\t7\tc!\tKStray\t\t\t=\t1\t"));+ ASSERT(jt_has_line(r->doc_scope, "X\t5\t5"));+ cbm_free_result(r);+ /* types nested deeper than any program nests them: the scan stops+ * descending, marks the rest unplaced, and does not overflow */+ enum { JT_DEEP = 400 };+ size_t deep_cap = (size_t)JT_DEEP * 40 + 64;+ char *deep = malloc(deep_cap);+ ASSERT_NOT_NULL(deep);+ size_t w = (size_t)snprintf(deep, deep_cap, "package pe;\n");+ for (int i = 0; i < JT_DEEP; i++) {+ w += (size_t)snprintf(deep + w, deep_cap - w, "class D%d {\n", i);+ }+ for (int i = 0; i < JT_DEEP; i++) {+ w += (size_t)snprintf(deep + w, deep_cap - w, "}\n");+ }+ r = dm_extract(deep, CBM_LANG_JAVA, "pe/Deep.java");+ free(deep);+ ASSERT_NOT_NULL(r);+ ASSERT_NOT_NULL(r->doc_scope);+ ASSERT_NOT_NULL(strstr(r->doc_scope, "\tD0.D1.D2\t"));+ ASSERT_NULL(strstr(r->doc_scope,+ "\tD0.D1.D2.D3.D4.D5.D6.D7.D8.D9.D10.D11.D12.D13.D14.D15.D16."+ "D17.D18.D19.D20.D21.D22.D23.D24.D25.D26.D27.D28.D29.D30.D31."+ "D32.D33.D34.D35.D36.D37.D38.D39.D40.D41.D42.D43.D44.D45.D46."+ "D47.D48.D49.D50.D51.D52.D53.D54.D55.D56.D57.D58.D59.D60.D61."+ "D62.D63.D64.D65.D66.D67.D68.D69.D70.D71.D72.D73.D74.D75.D76."+ "D77.D78.D79.D80.D81.D82.D83.D84.D85.D86.D87.D88.D89.D90.D91."+ "D92.D93.D94.D95.D96.D97.D98.D99.D100.D101.D102.D103.D104.D105."+ "D106.D107.D108.D109.D110.D111.D112.D113.D114.D115.D116.D117."+ "D118.D119.D120.D121.D122.D123.D124.D125.D126.D127.D128\t"));+ ASSERT_NOT_NULL(strstr(r->doc_scope, "\nQ\tD128\n"));+ cbm_free_result(r);+ PASS();+}++/* What the resolver does with those scopes: a member a parse error may hide+ * is a graph gap (never "missing", never an outer declaration of that name);+ * a name declared where the scan lost its place is not resolved around. */+TEST(doc_mentions_jvm_resolver_parse_errors) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "perr"));+ jt_write(&r, "src/main/java/pe/Among.java",+ "package pe;\n"+ "public class Among {\n"+ " /** {@link #bad()} {@link #after()} {@link Whole#gone()} */\n"+ " public void before() {}\n"+ " public void bad( { }\n"+ " public void after() {}\n"+ "}\n");+ jt_write(&r, "src/main/java/pe/Whole.java",+ "package pe;\n"+ "/** {@link Among#bad()} {@link Among#before()} {@link Open} {@link Lost} */\n"+ "public class Whole {}\n");+ jt_write(&r, "src/main/java/pe/Open.java",+ "package pe;\n"+ "public class Open {\n"+ " public void before() {}\n"+ " public static class Lost {\n"+ " public void inLost() {\n"+ " }\n"+ " public void after() {}\n"+ "}\n");+ /* the same simple name, placed, in a package imported on demand: the+ * unplaced declaration could be the one meant, so it does not bind */+ jt_write(&r, "src/main/java/other/Lost.java", "package other;\npublic class Lost {}\n");+ jt_write(&r, "src/main/java/pe/Importer.java",+ "package pe;\n"+ "import other.*;\n"+ "/** {@link Lost} */\n"+ "public class Importer {}\n");+ jt_write(&r, "src/main/kotlin/pk/Getter.kt",+ "package pk\n"+ "\n"+ "class Getter {\n"+ " val ok: Int = 1\n"+ " val broken: Int\n"+ " get() {\n"+ " val x = when (this) {\n"+ " is Getter if true -> 1\n"+ " else -> 2\n"+ " }\n"+ " return x\n"+ " }\n"+ " /**\n"+ " * [ok], [broken]\n"+ " * @see Getter.nope\n"+ " */\n"+ " fun after() {}\n"+ "}\n");+ jt_write(&r, "src/main/kotlin/pk/KStray.kt",+ "package pk\n"+ "\n"+ "fun topLevel() {}\n"+ "\n"+ "class KStray {\n"+ " fun own() {}\n"+ " /**\n"+ " * [own], [topLevel], [Getter]\n"+ " * @see KStray.hidden\n"+ " */\n"+ " fun documented() {}\n"+ " ) ) )\n"+ " fun after() {}\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* Java, inside the incomplete type: its parsed members bind; the one the+ * error hid is a gap; a complete type's absent member is missing */+ ASSERT_EQ(jt_edge(db, "pe.Among.before", "pe.Among.after"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/pe/Among.java", "#bad()"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/pe/Among.java", "Whole#gone()"), "missing");+ /* ... and named from outside */+ ASSERT_EQ(jt_edge(db, "pe.Whole", "pe.Among.before"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/pe/Whole.java", "Among#bad()"), "graph_gap");+ /* names declared where the braces do not pair */+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/pe/Whole.java", "Open"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/pe/Whole.java", "Lost"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, "src/main/java/pe/Importer.java", "Lost"), "graph_gap");+ ASSERT_EQ(jt_edge(db, "pe.Importer", "other.Lost"), 0);+ /* Kotlin: errors held inside a member's braces leave the type whole */+ ASSERT_EQ(jt_edge(db, "pk.Getter.Getter.after", "pk.Getter.ok"), 1);+ ASSERT_EQ(jt_edge(db, "pk.Getter.Getter.after", "pk.Getter.broken"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/pk/Getter.kt", "Getter.nope"), "missing");+ /* Kotlin, inside an incomplete type: its own parsed member binds, a TYPE+ * further out binds (a type the scan lost is kept apart by name), a+ * MEMBER further out does not (a hidden member could shadow it) */+ ASSERT_EQ(jt_edge(db, "pk.KStray.KStray.documented", "pk.KStray.KStray.own"), 1);+ ASSERT_EQ(jt_edge(db, "pk.KStray.KStray.documented", "pk.Getter.Getter"), 1);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/pk/KStray.kt", "topLevel"), "graph_gap");+ ASSERT_EQ(jt_edge(db, "pk.KStray.KStray.documented", "pk.KStray.topLevel"), 0);+ ASSERT_STR_EQ(jt_reason(db, "src/main/kotlin/pk/KStray.kt", "KStray.hidden"), "graph_gap");+ jt_end(&r);+ PASS();+}++/* ── test code ───────────────────────────────────────────────────── */++/* Where a build puts test code, in the layouts the two languages use. In+ * each a product class names a test-only class (a row) and the test class+ * names the product class (an edge). */+TEST(doc_mentions_jvm_test_only_layouts) {+ static const struct {+ const char *dir; /* the directory of the test class */+ const char *name;+ bool test;+ } cases[] = {+ {"src/test/kotlin/t", "InSrcTest", true},+ {"src/jvmTest/kotlin/t", "InSourceSet", true},+ {"src/testFixtures/kotlin/t", "InFixtures", true},+ {"core/commonTest/src/t", "SetBeforeSrc", true},+ {"core/common/test/t", "PlainTestDir", true},+ {"json-tests/src/main/kotlin/t", "TestProject", true},+ {"samples/app/src/main/kotlin/t", "InSamples", true},+ /* a directory BELOW the source set is a package, and a name that+ * merely contains the letters is no test directory */+ {"src/main/kotlin/t/test", "PackageNamedTest", false},+ {"latest/src/main/kotlin/t", "InLatest", false},+ };+ jt_repo_t r;+ ASSERT(jt_begin(&r, "tonly"));+ char doc[2048] = "package t\n\n/**";+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ char path[512];+ char body[512];+ snprintf(path, sizeof(path), "%s/%s.kt", cases[i].dir, cases[i].name);+ snprintf(body, sizeof(body), "package t\n\n/** Tests [Product]. */\nclass %s\n",+ cases[i].name);+ jt_write(&r, path, body);+ size_t used = strlen(doc);+ snprintf(doc + used, sizeof(doc) - used, " [%s]", cases[i].name);+ }+ size_t used = strlen(doc);+ snprintf(doc + used, sizeof(doc) - used, " */\nclass Product\n");+ jt_write(&r, "src/main/kotlin/t/Product.kt", doc);+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ char sql[512];+ snprintf(sql, sizeof(sql),+ "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id = e.source_id "+ "JOIN nodes t ON t.id = e.target_id WHERE e.type = 'MENTIONS' "+ "AND s.name = 'Product' AND t.name = '%s'",+ cases[i].name);+ const char *reason = jt_reason(r.db, "src/main/kotlin/t/Product.kt", cases[i].name);+ if (dm_count(r.db, sql) != (cases[i].test ? 0 : 1) ||+ strcmp(reason, cases[i].test ? "test_only_target" : "") != 0) {+ printf(" %s/%s: edges %d, reason '%s'\n", cases[i].dir, cases[i].name,+ dm_count(r.db, sql), reason);+ }+ ASSERT_EQ(dm_count(r.db, sql), cases[i].test ? 0 : 1);+ ASSERT_STR_EQ(reason, cases[i].test ? "test_only_target" : "");+ /* every one of them, test or not, may name the product class */+ snprintf(sql, sizeof(sql),+ "SELECT COUNT(*) FROM edges e JOIN nodes s ON s.id = e.source_id "+ "JOIN nodes t ON t.id = e.target_id WHERE e.type = 'MENTIONS' "+ "AND s.name = '%s' AND t.name = 'Product'",+ cases[i].name);+ ASSERT_EQ(dm_count(r.db, sql), 1);+ }+ jt_end(&r);+ PASS();+}++/* ── the family table ────────────────────────────────────────────── */++/* The families' names are public surface (the "syntax" edge property and+ * column); each belongs to its language and ships. */+TEST(doc_mentions_jvm_family_names) {+ static const struct {+ int syntax;+ CBMLanguage lang;+ const char *name;+ } families[] = {+ {CBM_DOCLINK_JAVA_LINK, CBM_LANG_JAVA, "link"},+ {CBM_DOCLINK_JAVA_LINKPLAIN, CBM_LANG_JAVA, "linkplain"},+ {CBM_DOCLINK_JAVA_SEE, CBM_LANG_JAVA, "see"},+ {CBM_DOCLINK_JAVA_THROWS, CBM_LANG_JAVA, "throws"},+ {CBM_DOCLINK_JAVA_VALUE, CBM_LANG_JAVA, "value"},+ {CBM_DOCLINK_KT_KDOC_LINK, CBM_LANG_KOTLIN, "kdoc_link"},+ {CBM_DOCLINK_KT_SEE, CBM_LANG_KOTLIN, "see"},+ {CBM_DOCLINK_KT_THROWS, CBM_LANG_KOTLIN, "throws"},+ {CBM_DOCLINK_KT_SAMPLE, CBM_LANG_KOTLIN, "sample"},+ };+ /* both languages have a doc-reference parser */+ ASSERT_TRUE(cbm_doclink_lang_supported(CBM_LANG_JAVA));+ ASSERT_TRUE(cbm_doclink_lang_supported(CBM_LANG_KOTLIN));+ for (size_t i = 0; i < sizeof(families) / sizeof(families[0]); i++) {+ const CBMDocLinkFamily *f = cbm_doclink_family(families[i].syntax);+ ASSERT_NOT_NULL(f);+ ASSERT_EQ(f->lang, families[i].lang);+ ASSERT_STR_EQ(f->name, families[i].name);+ ASSERT_STR_EQ(cbm_doclink_syntax_name(families[i].syntax), families[i].name);+ ASSERT_FALSE(cbm_doclink_syntax_is_external(families[i].syntax));+ }+ /* held in production until their held-out audit passes; the suite ships them */+ cbm_doclink_test_reset_ships();+ int shipping_in_production = 0;+ for (size_t i = 0; i < sizeof(families) / sizeof(families[0]); i++) {+ shipping_in_production += cbm_doclink_syntax_ships(families[i].syntax) ? 1 : 0;+ }+ dm_ship_held_families();+ ASSERT_EQ(shipping_in_production, 0);+ for (size_t i = 0; i < sizeof(families) / sizeof(families[0]); i++) {+ ASSERT_TRUE(cbm_doclink_syntax_ships(families[i].syntax));+ }+ PASS();+}++/* ── which scope changes are repairable file by file ─────────────── */++#define JT_DJ_HEAD "package n;\nimport acme.local.Base;\nimport acme.util.Tool;\n"+#define JT_DJ_OPEN "public class W extends Base {\n"+#define JT_DJ_RUN_INT " public void run(int n) {}\n"+#define JT_DJ_RUN_STR " public void run(String s) {}\n"+#define JT_DJ_SIZE " public int size;\n"+#define JT_DJ_CLOSE "}\nclass Other {}\n"+#define JT_DJ_BODY JT_DJ_RUN_INT JT_DJ_RUN_STR JT_DJ_SIZE+#define JT_DJ_TYPES JT_DJ_OPEN JT_DJ_BODY JT_DJ_CLOSE+#define JT_DJ_BASE JT_DJ_HEAD JT_DJ_TYPES+/* no declaration header of this file names a type */+#define JT_DJ_PLAIN "public class Plain {\n public void go() {}\n}\n"++#define JT_DK_HEAD "package n\n\nimport acme.local.Base\nimport acme.util.Tool\n\n"+#define JT_DK_OPEN "class W(val id: Int) : Base() {\n"+#define JT_DK_RUN_INT " fun run(n: Int) {}\n"+#define JT_DK_RUN_STR " fun run(s: String) {}\n"+#define JT_DK_SIZE " val size: Int = 0\n"+#define JT_DK_CLOSE "}\n\nfun Base.ext() {}\n\nclass Other\n"+#define JT_DK_BODY JT_DK_RUN_INT JT_DK_RUN_STR JT_DK_SIZE+#define JT_DK_TYPES JT_DK_OPEN JT_DK_BODY JT_DK_CLOSE+#define JT_DK_BASE JT_DK_HEAD JT_DK_TYPES+#define JT_DK_PLAIN "class Plain {\n fun go() {}\n}\n"++TEST(doc_mentions_jvm_scope_delta_rules) {+ const int local = CBM_DOCLINK_DELTA_LOCAL;+ const int global = CBM_DOCLINK_DELTA_GLOBAL;+ const CBMLanguage java = CBM_LANG_JAVA;+ const CBMLanguage kotlin = CBM_LANG_KOTLIN;+ struct {+ const char *what;+ CBMLanguage lang;+ const char *before;+ const char *after;+ int want;+ const char *names; /* NULL: any */+ } cases[] = {+ /* ── Java ── */+ {"java unchanged", java, JT_DJ_BASE, JT_DJ_BASE, local, ""},+ /* nothing of the persisted scope carries a line number, a body or a+ * doc comment */+ {"java lines moved", java, JT_DJ_BASE, "// moved\n\n" JT_DJ_BASE, local, ""},+ {"java body edit", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN+ " public void run(int n) { n++; }\n" JT_DJ_RUN_STR JT_DJ_SIZE JT_DJ_CLOSE,+ local, ""},+ {"java doc edit", java, JT_DJ_BASE, JT_DJ_HEAD "/** {@link Other} */\n" JT_DJ_TYPES, local,+ ""},+ /* imports scope the file itself ... */+ {"java import added", java, JT_DJ_BASE, JT_DJ_HEAD "import acme.more.Thing;\n" JT_DJ_TYPES,+ local, ""},+ {"java import removed", java, JT_DJ_BASE,+ "package n;\nimport acme.local.Base;\n" JT_DJ_TYPES, local, ""},+ {"java static import added", java, JT_DJ_BASE,+ JT_DJ_HEAD "import static acme.S.max;\n" JT_DJ_TYPES, local, ""},+ {"java on-demand import, no header names a type", java, "package n;\n" JT_DJ_PLAIN,+ "package n;\nimport acme.more.*;\n" JT_DJ_PLAIN, local, ""},+ /* ... except for the names its declaration headers write: other files+ * resolve inherited members through the supertype they bind */+ {"java supertype's import changed", java, JT_DJ_BASE,+ "package n;\nimport acme.other.Base;\nimport acme.util.Tool;\n" JT_DJ_TYPES, global, NULL},+ {"java supertype's import removed", java, JT_DJ_BASE,+ "package n;\nimport acme.util.Tool;\n" JT_DJ_TYPES, global, NULL},+ {"java on-demand import added", java, JT_DJ_BASE,+ JT_DJ_HEAD "import acme.more.*;\n" JT_DJ_TYPES, global, NULL},+ {"java static on-demand import added", java, JT_DJ_BASE,+ JT_DJ_HEAD "import static acme.S.*;\n" JT_DJ_TYPES, global, NULL},+ {"java static import of the supertype's name", java, JT_DJ_BASE,+ JT_DJ_HEAD "import static acme.S.Base;\n" JT_DJ_TYPES, global, NULL},+ /* a removed member is reported by name */+ {"java overload removed", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_RUN_STR JT_DJ_SIZE JT_DJ_CLOSE, local, "run"},+ {"java field removed", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_RUN_INT JT_DJ_RUN_STR JT_DJ_CLOSE, local, "size"},+ {"java two members removed", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_RUN_STR JT_DJ_CLOSE, local, "run,size"},+ {"java constructor removed", java,+ "package n;\npublic class C {\n public C(int n) {}\n public void m() {}\n}\n",+ "package n;\npublic class C {\n public void m() {}\n}\n", local, "C"},+ {"java enum constant removed", java, "package n;\npublic enum Color { RED, GREEN }\n",+ "package n;\npublic enum Color { RED }\n", local, "GREEN"},+ /* ... unless the overloads' one node was its own: the node moves to+ * the declaration that stays */+ {"java node owner removed", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_RUN_INT JT_DJ_SIZE JT_DJ_CLOSE, global, NULL},+ /* everything else can re-route references of files with no edge here */+ {"java member added", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_BODY " public int more;\n" JT_DJ_CLOSE, global, NULL},+ {"java signature changed", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN+ " public void run(long n) {}\n" JT_DJ_RUN_STR JT_DJ_SIZE JT_DJ_CLOSE,+ global, NULL},+ {"java members reordered", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_RUN_STR JT_DJ_RUN_INT JT_DJ_SIZE JT_DJ_CLOSE, global, NULL},+ /* the first line of a field's declarator is part of its node's name */+ /* a field's node is named by the field alone: a new initializer+ * declares the same names */+ {"java field initializer", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_RUN_INT JT_DJ_RUN_STR " public int size = 1;\n" JT_DJ_CLOSE,+ local, ""},+ {"java type removed", java, JT_DJ_BASE, JT_DJ_HEAD JT_DJ_OPEN JT_DJ_BODY "}\n", global,+ NULL},+ {"java type added", java, JT_DJ_BASE, JT_DJ_BASE "class New {}\n", global, NULL},+ {"java supertype changed", java, JT_DJ_BASE,+ JT_DJ_HEAD "public class W extends Tool {\n" JT_DJ_BODY JT_DJ_CLOSE, global, NULL},+ {"java type parameter bound", java, JT_DJ_BASE,+ JT_DJ_HEAD "public class W<T extends Other> extends Base {\n" JT_DJ_BODY JT_DJ_CLOSE,+ global, NULL},+ {"java package renamed", java, JT_DJ_BASE,+ "package m;\nimport acme.local.Base;\nimport acme.util.Tool;\n" JT_DJ_TYPES, global, NULL},+ /* a record's canonical constructor is matched against its components */+ {"java record component removed", java, "package n;\npublic record P(int x, int y) {}\n",+ "package n;\npublic record P(int x) {}\n", global, NULL},+ /* a member the parser can no longer show makes its type incomplete */+ {"java member hidden", java, JT_DJ_BASE,+ JT_DJ_HEAD JT_DJ_OPEN JT_DJ_BODY " public void bad( { }\n" JT_DJ_CLOSE, global, NULL},+ {"java file deleted", java, JT_DJ_BASE, NULL, global, NULL},+ {"java file added", java, NULL, JT_DJ_BASE, global, NULL},+ /* ── Kotlin ── */+ {"kotlin unchanged", kotlin, JT_DK_BASE, JT_DK_BASE, local, ""},+ {"kotlin lines moved", kotlin, JT_DK_BASE, "// moved\n\n" JT_DK_BASE, local, ""},+ {"kotlin body edit", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN+ " fun run(n: Int) { println(n) }\n" JT_DK_RUN_STR JT_DK_SIZE JT_DK_CLOSE,+ local, ""},+ {"kotlin property initializer", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN JT_DK_RUN_INT JT_DK_RUN_STR " val size: Int = 1\n" JT_DK_CLOSE,+ local, ""},+ {"kotlin import added", kotlin, JT_DK_BASE,+ "package n\n\nimport acme.local.Base\nimport acme.more.Thing\nimport "+ "acme.util.Tool\n\n" JT_DK_TYPES,+ local, ""},+ {"kotlin import alias that no header writes", kotlin, JT_DK_BASE,+ "package n\n\nimport acme.local.Base\nimport acme.more.Thing as Renamed\n"+ "import acme.util.Tool\n\n" JT_DK_TYPES,+ local, ""},+ {"kotlin star import, no header names a type", kotlin, "package n\n\n" JT_DK_PLAIN,+ "package n\n\nimport acme.more.*\n\n" JT_DK_PLAIN, local, ""},+ /* a supertype and an extension's receiver are bound in the file's scope */+ {"kotlin import alias equal to the supertype", kotlin, JT_DK_BASE,+ "package n\n\nimport acme.other.Thing as Base\nimport acme.util.Tool\n\n" JT_DK_TYPES,+ global, NULL},+ {"kotlin star import added", kotlin, JT_DK_BASE,+ "package n\n\nimport acme.local.Base\nimport acme.more.*\nimport "+ "acme.util.Tool\n\n" JT_DK_TYPES,+ global, NULL},+ {"kotlin receiver's import changed", kotlin,+ "package n\n\nimport acme.local.Recv\n\nfun Recv.ext() {}\n",+ "package n\n\nimport acme.other.Recv\n\nfun Recv.ext() {}\n", global, NULL},+ {"kotlin overload removed", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN JT_DK_RUN_STR JT_DK_SIZE JT_DK_CLOSE, local, "run"},+ {"kotlin property removed", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN JT_DK_RUN_INT JT_DK_RUN_STR JT_DK_CLOSE, local, "size"},+ {"kotlin extension removed", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN JT_DK_BODY "}\n\nclass Other\n", local, "ext"},+ /* a constructor property goes with the constructor's signature */+ {"kotlin constructor property removed", kotlin, JT_DK_BASE,+ JT_DK_HEAD "class W() : Base() {\n" JT_DK_BODY JT_DK_CLOSE, global, NULL},+ {"kotlin member added", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN JT_DK_BODY " val more: Int = 0\n" JT_DK_CLOSE, global, NULL},+ {"kotlin signature changed", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN " fun run(n: Long) {}\n" JT_DK_RUN_STR JT_DK_SIZE JT_DK_CLOSE,+ global, NULL},+ {"kotlin receiver changed", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN JT_DK_BODY "}\n\nfun Other.ext() {}\n\nclass Other\n", global, NULL},+ {"kotlin type removed", kotlin, JT_DK_BASE,+ JT_DK_HEAD JT_DK_OPEN JT_DK_BODY "}\n\nfun Base.ext() {}\n", global, NULL},+ {"kotlin type added", kotlin, JT_DK_BASE, JT_DK_BASE "\nclass New\n", global, NULL},+ {"kotlin supertype changed", kotlin, JT_DK_BASE,+ JT_DK_HEAD "class W(val id: Int) : Tool() {\n" JT_DK_BODY JT_DK_CLOSE, global, NULL},+ {"kotlin package renamed", kotlin, JT_DK_BASE,+ "package m\n\nimport acme.local.Base\nimport acme.util.Tool\n\n" JT_DK_TYPES, global,+ NULL},+ {"kotlin type alias target", kotlin, "package n\n\nclass A\nclass B\ntypealias N = A\n",+ "package n\n\nclass A\nclass B\ntypealias N = B\n", global, NULL},+ {"kotlin file deleted", kotlin, JT_DK_BASE, NULL, global, NULL},+ {"kotlin file added", kotlin, NULL, JT_DK_BASE, global, NULL},+ };+ char names[256];+ for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) {+ const char *rel = cases[i].lang == java ? "n/W.java" : "n/W.kt";+ int got = dm_scope_delta(cases[i].lang, rel, cases[i].before, 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");+ }+ }+ PASS();+}++/* ── incremental == full ─────────────────────────────────────────── */++#define JT_I_MAIN_IMPORTS \+ "package app;\n" \+ "import lib.Ov;\n" \+ "import lib.Sig;\n" \+ "import lib.Target;\n" \+ "import p.*;\n" \+ "import q.*;\n"+#define JT_I_MAIN_DOC \+ "/**\n" \+ " * {@link Target}, {@link Target#go(int)}, {@link Target#LIMIT}, {@link Ov#run},\n" \+ " * {@link Dup}, {@link Extra}, {@link Sig#go(int)}, {@link d.Derived#inherited()},\n" \+ " * {@link kt.KHelper}, {@link lib.Gone#m()}"+#define JT_I_MAIN_END "\n */\npublic class Main {}\n"+static const char JT_I_MAIN[] = JT_I_MAIN_IMPORTS JT_I_MAIN_DOC JT_I_MAIN_END;+static const char JT_I_MAIN_EDITED[] =+ JT_I_MAIN_IMPORTS JT_I_MAIN_DOC ", {@link Ov#run(String)}" JT_I_MAIN_END;+static const char JT_I_MAIN_IMPORT[] =+ JT_I_MAIN_IMPORTS "import s.Extra;\n" JT_I_MAIN_DOC ", {@link Ov#run(String)}" JT_I_MAIN_END;+static const char JT_I_TARGET[] = "package lib;\n"+ "public class Target {\n"+ " public static final int LIMIT = 10;\n"+ " public void go(int n) {}\n"+ "}\n";+static const char JT_I_TARGET_INIT[] = "package lib;\n"+ "public class Target {\n"+ " public static final int LIMIT = 20;\n"+ " public void go(int n) {}\n"+ "}\n";+static const char JT_I_TARGET_RENAMED[] = "package lib;\n"+ "public class Renamed {\n"+ " public static final int LIMIT = 20;\n"+ " public void go(int n) {}\n"+ "}\n";+/* one node for both overloads; it belongs to the later declaration */+static const char JT_I_OV[] = "package lib;\n"+ "public class Ov {\n"+ " public void run(int n) {}\n"+ " public void run(String s) {}\n"+ "}\n";+static const char JT_I_OV_ONE[] = "package lib;\n"+ "public class Ov {\n"+ " public void run(String s) {}\n"+ "}\n";+static const char JT_I_SIG[] = "package lib;\n"+ "public class Sig {\n"+ " public void go(int n) {}\n"+ "}\n";+static const char JT_I_SIG_BODY[] = "package lib;\n"+ "public class Sig {\n"+ " public void go(int n) { n++; }\n"+ "}\n";+static const char JT_I_SIG_MOVED[] = "// moved\n"+ "\n"+ "package lib;\n"+ "\n"+ "public class Sig {\n"+ "\n"+ " public void go(int n) { n++; }\n"+ "}\n";+static const char JT_I_P[] = "package p;\n"+ "public class Dup {}\n"+ "class Keep {}\n";+static const char JT_I_P_NO_DUP[] = "package p;\n"+ "class Keep {}\n";+static const char JT_I_DERIVED[] = "package d;\n"+ "import lib.Base;\n"+ "public class Derived extends Base {}\n";+static const char JT_I_DERIVED_ALT[] = "package d;\n"+ "import alt.Base;\n"+ "public class Derived extends Base {}\n";+static const char JT_I_KHELPER[] = "package kt\n"+ "\n"+ "import lib.Target\n"+ "\n"+ "/**\n"+ " * [Target], [Target.go], [help]\n"+ " * @see lib.Ov.run\n"+ " * @see KOther.gone\n"+ " */\n"+ "class KHelper {\n"+ " fun help() {}\n"+ "}\n";+static const char JT_I_KHELPER_RENAMED[] = "package kt\n"+ "\n"+ "import lib.Target\n"+ "\n"+ "/**\n"+ " * [Target], [Target.go], [help]\n"+ " * @see lib.Ov.run\n"+ " * @see KOther.gone\n"+ " */\n"+ "class KHelp {\n"+ " fun help() {}\n"+ "}\n";+static const char JT_I_KOTHER[] = "package kt\n"+ "\n"+ "/** [KHelper.help] */\n"+ "class KOther {\n"+ " fun gone() {}\n"+ " fun stays() {}\n"+ "}\n";+static const char JT_I_KOTHER_EDITED[] = "package kt\n"+ "\n"+ "/** [KHelper.help], [KHelper] */\n"+ "class KOther {\n"+ " fun gone() {}\n"+ " fun stays() {}\n"+ "}\n";+static const char JT_I_KOTHER_NO_GONE[] = "package kt\n"+ "\n"+ "/** [KHelper.help], [KHelper] */\n"+ "class KOther {\n"+ " fun stays() {}\n"+ "}\n";+/* an extension function: the import decides which `Recv` is its receiver */+static const char JT_I_EXT[] = "package kt\n"+ "\n"+ "import recv.one.Recv\n"+ "\n"+ "fun Recv.shine() {}\n";+static const char JT_I_EXT_OTHER[] = "package kt\n"+ "\n"+ "import recv.two.Recv\n"+ "\n"+ "fun Recv.shine() {}\n";+static const char JT_I_EXTUSER[] = "package kt\n"+ "\n"+ "import recv.one.Recv\n"+ "\n"+ "/** @see Recv.shine */\n"+ "class ExtUser\n";++TEST(doc_mentions_jvm_incremental_equals_full) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "inc"));+ const char *main_java = "src/main/java/app/Main.java";+ const char *khelper_kt = "src/main/kotlin/kt/KHelper.kt";+ jt_write(&r, main_java, JT_I_MAIN);+ jt_write(&r, "src/main/java/lib/Target.java", JT_I_TARGET);+ jt_write(&r, "src/main/java/lib/Ov.java", JT_I_OV);+ jt_write(&r, "src/main/java/lib/Sig.java", JT_I_SIG);+ jt_write(&r, "src/main/java/lib/Gone.java",+ "package lib;\npublic class Gone {\n public void m() {}\n}\n");+ jt_write(&r, "src/main/java/lib/Base.java",+ "package lib;\npublic class Base {\n public void inherited() {}\n}\n");+ jt_write(&r, "src/main/java/alt/Base.java",+ "package alt;\npublic class Base {\n public void other() {}\n}\n");+ jt_write(&r, "src/main/java/d/Derived.java", JT_I_DERIVED);+ jt_write(&r, "src/main/java/p/Types.java", JT_I_P);+ jt_write(&r, "src/main/java/q/Dup.java", "package q;\npublic class Dup {}\n");+ jt_write(&r, "src/main/java/s/Extra.java", "package s;\npublic class Extra {}\n");+ jt_write(&r, khelper_kt, JT_I_KHELPER);+ jt_write(&r, "src/main/kotlin/kt/KOther.kt", JT_I_KOTHER);+ const char *ext_kt = "src/main/kotlin/kt/Ext.kt";+ const char *extuser_kt = "src/main/kotlin/kt/ExtUser.kt";+ jt_write(&r, "src/main/kotlin/recv/one/Recv.kt", "package recv.one\n\nclass Recv\n");+ jt_write(&r, "src/main/kotlin/recv/two/Recv.kt", "package recv.two\n\nclass Recv\n");+ jt_write(&r, ext_kt, JT_I_EXT);+ jt_write(&r, extuser_kt, JT_I_EXTUSER);+ char full_db[600];+ snprintf(full_db, sizeof(full_db), "%s/full.db", r.tmp);+ const char *db = r.db;+ const cbm_incremental_route_t repair = CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR;+ const cbm_incremental_route_t forced = CBM_INCREMENTAL_ROUTE_FORCED_FULL;+ ASSERT_EQ(dm_index(r.repo, db, NULL), 0);+ /* the preconditions the steps below move away from */+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Target"), 1);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Target.go"), 1);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Target.LIMIT"), 1);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Sig.go"), 1);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Gone.m"), 1);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Base.inherited"), 1); /* through d.Derived */+ ASSERT_EQ(jt_edge(db, "app.Main", "kt.KHelper.KHelper"), 1); /* a Kotlin class */+ ASSERT_STR_EQ(jt_reason(db, main_java, "Ov#run"), "ambiguous"); /* an overload group */+ ASSERT_STR_EQ(jt_reason(db, main_java, "Dup"), "ambiguous"); /* p.* and q.* */+ ASSERT_STR_EQ(jt_reason(db, main_java, "Extra"), "missing"); /* s is not imported */+ ASSERT_EQ(jt_edge(db, "kt.KHelper.KHelper", "lib.Target"), 1); /* a Java class */+ ASSERT_EQ(jt_edge(db, "kt.KHelper.KHelper", "lib.Target.go"), 1);+ ASSERT_EQ(jt_edge(db, "kt.KHelper.KHelper", "kt.KOther.KOther.gone"), 1);+ ASSERT_STR_EQ(jt_reason(db, khelper_kt, "lib.Ov.run"), "ambiguous");+ ASSERT_EQ(jt_edge(db, "kt.KOther.KOther", "kt.KHelper.KHelper.help"), 1);+ ASSERT_EQ(jt_edge(db, "kt.ExtUser.ExtUser", "kt.Ext.shine"), 1); /* an extension of Recv */++ /* a doc-comment edit re-extracts the file alone */+ jt_write(&r, main_java, JT_I_MAIN_EDITED);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "doc edit", repair), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Ov.run"), 1);++ /* a body edit in a TARGET file: its scope is unchanged, and the edges+ * into it stand */+ jt_write(&r, "src/main/java/lib/Sig.java", JT_I_SIG_BODY);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "target body edit", repair), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Sig.go"), 1);++ /* moving every declaration of a target file to another line changes no+ * scope: the stored scopes carry no line numbers */+ jt_write(&r, "src/main/java/lib/Sig.java", JT_I_SIG_MOVED);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "lines moved", repair), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Sig.go"), 1);++ /* an import no declaration header of the file writes scopes the file+ * alone */+ jt_write(&r, main_java, JT_I_MAIN_IMPORT);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "import added", repair), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "s.Extra"), 1);++ /* ... but the import that binds a supertype decides what OTHER files+ * inherit through the type: Main has no edge into Derived.java */+ jt_write(&r, "src/main/java/d/Derived.java", JT_I_DERIVED_ALT);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "supertype re-bound by an import", forced), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Base.inherited"), 0);+ ASSERT_STR_EQ(jt_reason(db, main_java, "d.Derived#inherited()"), "missing");++ /* the same for the import that binds an extension's RECEIVER: of which+ * type `shine` is an extension decides what other files find under+ * `Recv.shine`. Away from the type ExtUser names ... */+ jt_write(&r, ext_kt, JT_I_EXT_OTHER);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "receiver re-bound by an import", forced), 0);+ ASSERT_EQ(jt_edge(db, "kt.ExtUser.ExtUser", "kt.Ext.shine"), 0);+ ASSERT_STR_EQ(jt_reason(db, extuser_kt, "Recv.shine"), "missing");+ /* ... and back to it. ExtUser has no edge into Ext.kt now and Ext.kt+ * removed no name, so no file-by-file repair would look at ExtUser again */+ jt_write(&r, ext_kt, JT_I_EXT);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "receiver bound back by an import", forced), 0);+ ASSERT_EQ(jt_edge(db, "kt.ExtUser.ExtUser", "kt.Ext.shine"), 1);+ ASSERT_STR_EQ(jt_reason(db, extuser_kt, "Recv.shine"), "");++ /* a removed member (an overload group shrinks to one) re-resolves the+ * files whose rows name it, of either language, although they have no+ * edge into the changed file */+ jt_write(&r, "src/main/java/lib/Ov.java", JT_I_OV_ONE);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "member removed", repair), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Ov.run"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":2"));+ ASSERT_STR_EQ(jt_reason(db, main_java, "Ov#run"), "");+ ASSERT_EQ(jt_edge(db, "kt.KHelper.KHelper", "lib.Ov.run"), 1);++ /* a Java field's node is named by the field alone: a changed initializer+ * keeps the node, and the edge stays on it */+ jt_write(&r, "src/main/java/lib/Target.java", JT_I_TARGET_INIT);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "field initializer", repair), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Target.LIMIT"), 1);++ /* a removed TYPE is not repaired file by file (it may be another type's+ * supertype): one of two ambiguous candidates goes, the other binds */+ jt_write(&r, "src/main/java/p/Types.java", JT_I_P_NO_DUP);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "type removed", forced), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "q.Dup"), 1);++ /* renaming a target, named from both languages. Both files still import+ * the old name: an import of a type that the repository's own package+ * does not show vouches for a declaration the graph lacks */+ jt_write(&r, "src/main/java/lib/Target.java", JT_I_TARGET_RENAMED);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "rename", forced), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Target"), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Target.go"), 0);+ ASSERT_STR_EQ(jt_reason(db, main_java, "Target"), "graph_gap");+ ASSERT_STR_EQ(jt_reason(db, main_java, "Target#go(int)"), "graph_gap");+ ASSERT_EQ(jt_edge(db, "kt.KHelper.KHelper", "lib.Target"), 0);+ ASSERT_STR_EQ(jt_reason(db, khelper_kt, "Target"), "graph_gap");++ /* Kotlin: a doc-comment edit */+ jt_write(&r, "src/main/kotlin/kt/KOther.kt", JT_I_KOTHER_EDITED);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "kotlin doc edit", repair), 0);+ ASSERT_EQ(jt_edge(db, "kt.KOther.KOther", "kt.KHelper.KHelper"), 1);++ /* Kotlin: a removed member takes the edge into it along */+ jt_write(&r, "src/main/kotlin/kt/KOther.kt", JT_I_KOTHER_NO_GONE);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "kotlin member removed", repair), 0);+ ASSERT_EQ(jt_edge(db, "kt.KHelper.KHelper", "kt.KOther.KOther.gone"), 0);+ ASSERT_STR_EQ(jt_reason(db, khelper_kt, "KOther.gone"), "missing");++ /* a deleted file takes its types along: the name Main writes out in full+ * (no import vouches for it) is now missing in a package that stays */+ ASSERT_EQ(unlink(TH_PATH(r.repo, "src/main/java/lib/Gone.java")), 0);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "delete file", forced), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "lib.Gone.m"), 0);+ ASSERT_STR_EQ(jt_reason(db, main_java, "lib.Gone#m()"), "missing");++ /* Kotlin: renaming a target a Java file names */+ jt_write(&r, khelper_kt, JT_I_KHELPER_RENAMED);+ ASSERT_EQ(dm_step(r.repo, db, full_db, "kotlin rename", forced), 0);+ ASSERT_EQ(jt_edge(db, "app.Main", "kt.KHelper.KHelper"), 0);+ ASSERT_STR_EQ(jt_reason(db, main_java, "kt.KHelper"), "missing");++ dm_unlink_db(full_db);+ jt_end(&r);+ PASS();+}++/* ── the parallel path == the sequential path ────────────────────── */++enum { JT_RING = 32 }; /* per language: above MIN_FILES_FOR_PARALLEL together */++/* A ring of Java classes and a ring of Kotlin classes. Every class documents+ * its successor, its counterpart in the other language, a shared target (by+ * name, by overload group and by signature) and a name nothing declares. */+static void jt_write_ring_fixture(const jt_repo_t *r) {+ for (int i = 0; i < JT_RING; i++) {+ char path[128];+ char body[1024];+ int next = (i + 1) % JT_RING;+ snprintf(path, sizeof(path), "src/main/java/ring/J%02d.java", i);+ snprintf(body, sizeof(body),+ "package ring;\n"+ "import ring.shared.Hub;\n"+ "/**\n"+ " * Next {@link J%02d}, shared {@linkplain Hub the hub}, {@link Hub#run},\n"+ " * {@link Nothing%02d}, in Kotlin {@link ringk.K%02d}.\n"+ " * @see Hub#run(String)\n"+ " */\n"+ "public class J%02d {}\n",+ next, i, i, i);+ jt_write(r, path, body);+ snprintf(path, sizeof(path), "src/main/kotlin/ringk/K%02d.kt", i);+ snprintf(body, sizeof(body),+ "package ringk\n"+ "\n"+ "import ring.shared.Hub\n"+ "\n"+ "/**\n"+ " * Next [K%02d], shared [Hub], in Java [ring.J%02d].\n"+ " * @see Hub.run\n"+ " * @see Nothing%02d\n"+ " */\n"+ "class K%02d\n",+ next, i, i, i);+ jt_write(r, path, body);+ }+ jt_write(r, "src/main/java/ring/shared/Hub.java",+ "package ring.shared;\n"+ "public class Hub {\n"+ " public void run(int n) {}\n"+ " public void run(String s) {}\n"+ "}\n");+}++/* The worker pipeline (extract workers, resolve workers, per-file rows merged+ * at the end) and the sequential passes publish the same edges and rows. */+TEST(doc_mentions_jvm_parallel_equals_sequential) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "par"));+ jt_write_ring_fixture(&r);+ char seq_db[600];+ snprintf(seq_db, sizeof(seq_db), "%s/seq.db", r.tmp);+ ASSERT_EQ(dm_workers_agree(r.repo, r.db, seq_db), 0);+ /* per Java class: successor, Hub, Hub.run(String), its Kotlin counterpart;+ * per Kotlin class: successor, Hub, its Java counterpart */+ ASSERT_EQ(dm_count(r.db, "SELECT COUNT(*) FROM edges WHERE type = 'MENTIONS'"),+ JT_RING * 4 + JT_RING * 3);+ /* per class of either language: the overload group and the undeclared+ * name */+ ASSERT_EQ(dm_count(r.db, "SELECT COUNT(*) FROM doc_link_unresolved"), JT_RING * 4);+ ASSERT_EQ(dm_count(r.db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE reason = 'ambiguous'"),+ JT_RING * 2);+ ASSERT_EQ(dm_count(r.db, "SELECT COUNT(*) FROM doc_link_unresolved WHERE reason = 'missing'"),+ JT_RING * 2);+ dm_unlink_db(seq_db);+ jt_end(&r);+ PASS();+}++/* ── the platforms' own namespaces ───────────────────────────────── */++/* An all-lower-case path that nothing declares is external under the+ * namespaces the two platforms define themselves: `java`, `javax`, `kotlin`.+ * No library family is such a root. A path under `kotlinx` is external only+ * where the file imports from that package (which the repository does not+ * declare); without an import it names nothing, like any other path. */+TEST(doc_mentions_jvm_platform_roots) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "roots"));+ const char *with = "src/main/kotlin/rt/WithImport.kt";+ jt_write(&r, with,+ "package rt\n"+ "\n"+ "import kotlinx.coroutines.flow.map\n"+ "\n"+ "/**\n"+ " * @see java.util.concurrent\n"+ " * @see javax.annotation.processing\n"+ " * @see kotlin.collections.map\n"+ " * @see kotlinx.coroutines.flow.onEach\n"+ " */\n"+ "class WithImport\n");+ const char *without = "src/main/kotlin/rt/NoImport.kt";+ jt_write(&r, without,+ "package rt\n"+ "\n"+ "/**\n"+ " * [kotlinx.coroutines.flow.map]\n"+ " * @see kotlinx.coroutines.flow.onEach\n"+ " * @see org.outside.lib.helper\n"+ " */\n"+ "class NoImport\n");+ const char *java = "src/main/java/rt/JRoots.java";+ jt_write(&r, java,+ "package rt;\n"+ "/** {@link java.util.concurrent} {@link kotlinx.coroutines.flow} */\n"+ "public class JRoots {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* the three roots */+ ASSERT_EQ(jt_rows(db, with, "java.util.concurrent", "external"), 1);+ ASSERT_EQ(jt_rows(db, with, "javax.annotation.processing", "external"), 1);+ ASSERT_EQ(jt_rows(db, with, "kotlin.collections.map", "external"), 1);+ ASSERT_EQ(jt_rows(db, java, "java.util.concurrent", "external"), 1);+ /* `kotlinx` with an import of that package: external by the import */+ ASSERT_EQ(jt_rows(db, with, "kotlinx.coroutines.flow.onEach", "external"), 1);+ /* ... and without one: a block tag keeps its row as missing, a `[name]`+ * is plain text, exactly as for any other library's path */+ ASSERT_EQ(jt_rows(db, without, "kotlinx.coroutines.flow.onEach", "missing"), 1);+ ASSERT_EQ(jt_rows(db, without, "org.outside.lib.helper", "missing"), 1);+ ASSERT_STR_EQ(jt_reason(db, without, "kotlinx.coroutines.flow.map"), "");+ ASSERT_EQ(jt_rows(db, java, "kotlinx.coroutines.flow", "missing"), 1);+ ASSERT_EQ(dm_count(db, "SELECT COUNT(*) FROM edges WHERE type = 'MENTIONS'"), 0);+ jt_end(&r);+ PASS();+}++/* ── a field against a method from outside ───────────────────────── */++/* A bare Javadoc `#x` that finds a FIELD. javadoc looks for a method of the+ * name as well and takes the field only when its class is the method's class+ * or below it. The index cannot see the methods of a supertype outside the+ * repository, or what an enum has from the language; where one of those may+ * come first, the reference is external. */++/* A type consulted BEFORE the field's level that may have the method unseen:+ * the field of the class around is not below that type's supertypes. */+TEST(doc_mentions_jvm_java_field_before_level) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jfbef"));+ const char *f1 = "src/main/java/gf/F1.java";+ jt_write(&r, f1,+ "package gf;\n"+ "public class F1 {\n"+ " public int available = 1;\n"+ " public int hashCode = 2;\n"+ " public int name = 3;\n"+ " public int other = 4;\n"+ " public class In extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ " /** {@link #available} {@link #hashCode} */\n"+ " public void m() {}\n"+ " }\n"+ " public class Closed {\n"+ " /** {@link #available} {@link #hashCode} */\n"+ " public void m() {}\n"+ " }\n"+ " public enum Mode {\n"+ " ON;\n"+ " /** {@link #name} {@link #other} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* java.io.InputStream may declare available(); it may also override+ * hashCode(), and then the method is no longer Object's */+ ASSERT_EQ(jt_rows(db, f1, "#available", "external"), 1);+ ASSERT_EQ(jt_rows(db, f1, "#hashCode", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gf.F1.In.m"), 0);+ /* decoy: a nested class without a supertype outside binds both. Object's+ * own hashCode() is no reason to yield: every class is below Object */+ ASSERT_EQ(jt_edge(db, "gf.F1.Closed.m", "gf.F1.available"), 1);+ ASSERT_EQ(jt_edge(db, "gf.F1.Closed.m", "gf.F1.hashCode"), 1);+ /* an enum has name() from the language, and the class around is not+ * below java.lang.Enum; a name the enum does not have binds */+ ASSERT_EQ(jt_rows(db, f1, "#name", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gf.F1.Mode.m", "gf.F1.other"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gf.F1.Mode.m"), 1);+ jt_end(&r);+ PASS();+}++/* At the field's OWN level: the field binds when every supertype outside the+ * repository of that level's type is a supertype of the field's class too. A+ * field the type declares itself always is; an inherited one only when the+ * type adds no supertype from outside of its own. The same for the type a+ * reference names (`Type#x`). */+TEST(doc_mentions_jvm_java_field_at_open_level) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jflvl"));+ jt_write(&r, "src/main/java/gf/F2.java",+ "package gf;\n"+ "public class F2 extends java.io.InputStream {\n"+ " public int own = 1;\n"+ " public int read() { return 0; }\n"+ " /** {@link #own} */\n"+ " public void m() {}\n"+ "}\n");+ const char *f3 = "src/main/java/gf/F3.java";+ jt_write(&r, f3,+ "package gf;\n"+ "public class F3 extends F3Base implements java.io.Closeable {\n"+ " public void close() {}\n"+ " /** {@link #LIMIT} */\n"+ " public void m() {}\n"+ "}\n"+ "class F3Base {\n"+ " public static final int LIMIT = 1;\n"+ "}\n");+ jt_write(&r, "src/main/java/gf/F4.java",+ "package gf;\n"+ "public class F4 extends F4Base {\n"+ " /** {@link #shared} */\n"+ " public void m() {}\n"+ "}\n"+ "class F4Base extends java.io.InputStream {\n"+ " public int shared = 1;\n"+ " public int read() { return 0; }\n"+ "}\n");+ const char *f5 = "src/main/java/gf/F5.java";+ jt_write(&r, f5,+ "package gf;\n"+ "/** {@link F2#own} {@link F3#LIMIT} {@link F4#shared} {@value F3#LIMIT} */\n"+ "public class F5 {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* declared by the type itself: below everything the type is below */+ ASSERT_EQ(jt_edge(db, "gf.F2.m", "gf.F2.own"), 1);+ /* inherited, and F3 itself adds java.io.Closeable, which is no supertype+ * of F3Base: a method LIMIT() there would be what javadoc links */+ ASSERT_EQ(jt_rows(db, f3, "#LIMIT", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gf.F3.m"), 0);+ /* inherited from the one type of the hierarchy that leaves the+ * repository: its supertypes are the field's class's own */+ ASSERT_EQ(jt_edge(db, "gf.F4.m", "gf.F4Base.shared"), 1);+ /* the same three at a type the reference names */+ ASSERT_EQ(jt_edge(db, "gf.F5", "gf.F2.own"), 1);+ ASSERT_EQ(jt_rows(db, f5, "F3#LIMIT", "external"), 1);+ ASSERT_EQ(jt_edge(db, "gf.F5", "gf.F4Base.shared"), 1);+ /* {@value} names a field and nothing else: as before */+ ASSERT_EQ(jt_edge(db, "gf.F5", "gf.F3Base.LIMIT"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"syntax\":\"value\""));+ ASSERT_EQ(dm_mentions_from(db, "gf.F5"), 3);+ jt_end(&r);+ PASS();+}++/* ── javadoc's search for a method (JavacTrees.searchMethod in the JDK) ──+ *+ * From a type: its own methods, its superclass by the whole search (with the+ * superclass's own interfaces and the type around the superclass), its+ * interfaces in the order written, then the type around it; each type once.+ * A type outside the repository on the way makes the reference external. */++/* Step 2 takes in the type around the SUPERCLASS, before the type around the+ * documented one. */+TEST(doc_mentions_jvm_java_search_superclass_around) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jsenc"));+ jt_write(&r, "src/main/java/sa/Base2.java",+ "package sa;\n"+ "public class Base2 {\n"+ " public void go() {}\n"+ " public static class Inner {}\n"+ "}\n");+ jt_write(&r, "src/main/java/sa/Plain2.java", "package sa;\npublic class Plain2 {}\n");+ jt_write(&r, "src/main/java/sa/Holder.java",+ "package sa;\n"+ "public class Holder {\n"+ " public void go() {}\n"+ " public static class Sub extends Base2.Inner {\n"+ " /** {@link #go()} */\n"+ " public void m() {}\n"+ " }\n"+ " public static class Sub2 extends Plain2 {\n"+ " /** {@link #go()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* Base2.Inner is searched with Base2 around it, before Holder */+ ASSERT_EQ(jt_edge(db, "sa.Holder.Sub.m", "sa.Base2.go"), 1);+ ASSERT_EQ(jt_edge(db, "sa.Holder.Sub.m", "sa.Holder.go"), 0);+ /* decoy: a superclass nested in nothing: the type around Sub2 */+ ASSERT_EQ(jt_edge(db, "sa.Holder.Sub2.m", "sa.Holder.go"), 1);+ jt_end(&r);+ PASS();+}++/* Step 2 before step 3: a superclass outside the repository comes before an+ * interface of the repository. */+TEST(doc_mentions_jvm_java_search_outside_superclass) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jsout"));+ const char *s1 = "src/main/java/sb/S1.java";+ jt_write(&r, s1,+ "package sb;\n"+ "public abstract class S1 extends java.io.InputStream implements Api {\n"+ " /** {@link #close()} */\n"+ " public void m() {}\n"+ "}\n"+ "interface Api {\n"+ " void close();\n"+ "}\n"+ "class Plain {}\n"+ "abstract class S2 extends Plain implements Api {\n"+ " /** {@link #close()} */\n"+ " public void m() {}\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* java.io.InputStream is searched first; its close() is the one */+ ASSERT_EQ(jt_rows(db, s1, "#close()", "external"), 1);+ ASSERT_EQ(jt_edge(db, "sb.S1.m", "sb.Api.close"), 0);+ /* decoy: a superclass of the repository without the method */+ ASSERT_EQ(jt_edge(db, "sb.S2.m", "sb.Api.close"), 1);+ jt_end(&r);+ PASS();+}++/* Step 3: the interfaces in the order written; the first with the method is+ * the one. */+TEST(doc_mentions_jvm_java_search_interface_order) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jsord"));+ jt_write(&r, "src/main/java/sc/Both.java",+ "package sc;\n"+ "public abstract class Both implements First, Second {\n"+ " /** {@link #run()} */\n"+ " public void m() {}\n"+ "}\n"+ "interface First {\n"+ " void run();\n"+ "}\n"+ "interface Second {\n"+ " void run();\n"+ "}\n"+ "abstract class Other implements Second, First {\n"+ " /** {@link #run()} */\n"+ " public void m() {}\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_edge(db, "sc.Both.m", "sc.First.run"), 1);+ ASSERT_EQ(jt_edge(db, "sc.Both.m", "sc.Second.run"), 0);+ /* decoy: the other order */+ ASSERT_EQ(jt_edge(db, "sc.Other.m", "sc.Second.run"), 1);+ ASSERT_EQ(jt_edge(db, "sc.Other.m", "sc.First.run"), 0);+ jt_end(&r);+ PASS();+}++/* An interface has no superclass step: Object's methods are not searched at+ * it, and the search goes on to the type around it. */+TEST(doc_mentions_jvm_java_search_interface_no_object) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jsifc"));+ const char *h = "src/main/java/sd/Host.java";+ jt_write(&r, h,+ "package sd;\n"+ "public class Host {\n"+ " public String toString() { return \"\"; }\n"+ " public interface Shape {\n"+ " /** {@link #toString()} */\n"+ " void m();\n"+ " }\n"+ " public static class Box {\n"+ " /** {@link #toString()} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_edge(db, "sd.Host.Shape.m", "sd.Host.toString"), 1);+ /* decoy: a class has the superclass Object, whose toString() comes first */+ ASSERT_EQ(jt_rows(db, h, "#toString()", "external"), 1);+ ASSERT_EQ(jt_edge(db, "sd.Host.Box.m", "sd.Host.toString"), 0);+ jt_end(&r);+ PASS();+}++/* A Kotlin class on the way writes its superclass anywhere in its list: the+ * class among its supertypes is searched before its interfaces. */+TEST(doc_mentions_jvm_java_search_kotlin_superclass) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jskt"));+ jt_write(&r, "src/main/kotlin/se/KApi.kt",+ "package se\n\ninterface KApi {\n fun run()\n}\n");+ jt_write(&r, "src/main/kotlin/se/KBase.kt",+ "package se\n\nopen class KBase {\n fun run() {}\n}\n");+ jt_write(&r, "src/main/kotlin/se/KMix.kt", "package se\n\nopen class KMix : KApi, KBase()\n");+ jt_write(&r, "src/main/kotlin/se/KOnly.kt", "package se\n\nabstract class KOnly : KApi\n");+ jt_write(&r, "src/main/java/se/J.java",+ "package se;\n"+ "public class J extends KMix {\n"+ " /** {@link #run} */\n"+ " public void m() {}\n"+ "}\n"+ "abstract class J2 extends KOnly {\n"+ " /** {@link #run} */\n"+ " public void m() {}\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_edge(db, "se.J.m", "se.KBase.KBase.run"), 1);+ ASSERT_EQ(jt_edge(db, "se.J.m", "se.KApi.KApi.run"), 0);+ /* decoy: no class among the supertypes: the interface */+ ASSERT_EQ(jt_edge(db, "se.J2.m", "se.KApi.KApi.run"), 1);+ jt_end(&r);+ PASS();+}++/* ── The field rule against that search ───────────────────────────────+ *+ * A field javadoc's field search finds binds only when its class is below+ * every type outside the repository that the search for a METHOD passes+ * before a type of the repository that declares one, and below that method's+ * class. */++/* A field of the innermost type; the class AROUND it leaves the repository. */+TEST(doc_mentions_jvm_java_field_outer_outside) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jfout"));+ const char *o = "src/main/java/ga/Outer.java";+ jt_write(&r, o,+ "package ga;\n"+ "public class Outer extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ " public class In {\n"+ " public int available = 1;\n"+ " /** {@link #available} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ jt_write(&r, "src/main/java/ga/Shut.java",+ "package ga;\n"+ "public class Shut {\n"+ " public class In2 {\n"+ " public int available = 1;\n"+ " /** {@link #available} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* the search passes In, then Outer and java.io.InputStream, whose+ * available() would win: In is not below it */+ ASSERT_EQ(jt_rows(db, o, "#available", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "ga.Outer.In.m"), 0);+ /* decoy: the class around stays in the repository */+ ASSERT_EQ(jt_edge(db, "ga.Shut.In2.m", "ga.Shut.In2.available"), 1);+ jt_end(&r);+ PASS();+}++/* The type's OWN field, the type leaving the repository itself and a class+ * further out as well: the field is below the first, not the second. */+TEST(doc_mentions_jvm_java_field_own_far_outside) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jfown"));+ const char *far = "src/main/java/gb/Far.java";+ jt_write(&r, far,+ "package gb;\n"+ "public class Far extends java.io.InputStream {\n"+ " public int read() { return 0; }\n"+ " public abstract class Near extends java.io.Reader {\n"+ " public int level = 1;\n"+ " /** {@link #level} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ jt_write(&r, "src/main/java/gb/Far2.java",+ "package gb;\n"+ "public class Far2 {\n"+ " public abstract class Near2 extends java.io.Reader {\n"+ " public int level = 1;\n"+ " /** {@link #level} */\n"+ " public void m() {}\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_rows(db, far, "#level", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gb.Far.Near.m"), 0);+ /* decoy: only the type's own supertype leaves the repository */+ ASSERT_EQ(jt_edge(db, "gb.Far2.Near2.m", "gb.Far2.Near2.level"), 1);+ jt_end(&r);+ PASS();+}++/* Past a step outside the repository the field's class is below, a method of+ * the repository the field's class is NOT below: javadoc links that method,+ * or one the step outside holds (then the field): external. Without the step+ * outside, javadoc links the method, and so does the reference. */+TEST(doc_mentions_jvm_java_field_method_past_outside) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jfpast"));+ const char *top = "src/main/java/gc/Top.java";+ jt_write(&r, top,+ "package gc;\n"+ "public class Top {\n"+ " public int count() { return 0; }\n"+ " public class Mid extends java.io.InputStream {\n"+ " public int count = 1;\n"+ " public int read() { return 0; }\n"+ " public class Doc {\n"+ " /** {@link #count} */\n"+ " public void m() {}\n"+ " }\n"+ " }\n"+ " public class Mid2 {\n"+ " public int count = 1;\n"+ " public class Doc2 {\n"+ " /** {@link #count} */\n"+ " public void m() {}\n"+ " }\n"+ " }\n"+ "}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ ASSERT_EQ(jt_rows(db, top, "#count", "external"), 1);+ ASSERT_EQ(dm_mentions_from(db, "gc.Top.Mid.Doc.m"), 0);+ /* decoy: no step outside on the way: the method of Top */+ ASSERT_EQ(jt_edge(db, "gc.Top.Mid2.Doc2.m", "gc.Top.count"), 1);+ ASSERT_EQ(jt_rows(db, top, "#count", "ambiguous"), 0);+ jt_end(&r);+ PASS();+}++/* `Type#x`: javadoc's field search goes through the types around the type+ * named, as its method search does. A field there comes first when its class+ * is below the method's class. */+TEST(doc_mentions_jvm_java_field_named_around) {+ jt_repo_t r;+ ASSERT(jt_begin(&r, "jfnam"));+ jt_write(&r, "src/main/java/ge/Base3.java",+ "package ge;\n"+ "public class Base3 {\n"+ " public int x() { return 0; }\n"+ "}\n");+ jt_write(&r, "src/main/java/ge/E.java",+ "package ge;\n"+ "public class E extends Base3 {\n"+ " public int x = 1;\n"+ " public static class T {}\n"+ "}\n");+ jt_write(&r, "src/main/java/ge/User.java",+ "package ge;\n"+ "/** {@link E.T#x} {@link E#x} */\n"+ "public class User {}\n");+ ASSERT_EQ(dm_index(r.repo, r.db, NULL), 0);+ const char *db = r.db;+ /* the method search from E.T reaches Base3.x() through E; the field+ * search reaches E.x first, and E is below Base3 */+ ASSERT_EQ(jt_edge(db, "ge.User", "ge.E.x"), 1);+ ASSERT_NOT_NULL(strstr(jt_props, "\"count\":2"));+ ASSERT_EQ(jt_edge(db, "ge.User", "ge.Base3.x"), 0);+ jt_end(&r);+ PASS();+}++SUITE(doc_mentions_jvm) {+ dm_ship_held_families();+ RUN_TEST(doc_mentions_jvm_java_tokens);+ RUN_TEST(doc_mentions_jvm_kotlin_tokens);+ RUN_TEST(doc_mentions_jvm_malformed_and_oversized);+ RUN_TEST(doc_mentions_jvm_java_norm_type);+ RUN_TEST(doc_mentions_jvm_java_scope_blob);+ RUN_TEST(doc_mentions_jvm_kotlin_scope_blob);+ RUN_TEST(doc_mentions_jvm_scope_parse_errors);+ RUN_TEST(doc_mentions_jvm_resolver_parse_errors);+ RUN_TEST(doc_mentions_jvm_java_families_and_reasons);+ RUN_TEST(doc_mentions_jvm_oversized_reference);+ RUN_TEST(doc_mentions_jvm_java_type_levels);+ RUN_TEST(doc_mentions_jvm_java_member_levels);+ RUN_TEST(doc_mentions_jvm_kotlin_families_and_reasons);+ RUN_TEST(doc_mentions_jvm_kotlin_levels);+ RUN_TEST(doc_mentions_jvm_java_given_members);+ RUN_TEST(doc_mentions_jvm_java_open_supertypes);+ RUN_TEST(doc_mentions_jvm_java_uncompared_level);+ RUN_TEST(doc_mentions_jvm_kotlin_given_members);+ RUN_TEST(doc_mentions_jvm_kotlin_open_supertypes);+ RUN_TEST(doc_mentions_jvm_kotlin_companion_inherits);+ RUN_TEST(doc_mentions_jvm_kotlin_extension_guard);+ RUN_TEST(doc_mentions_jvm_root_supertype_written);+ RUN_TEST(doc_mentions_jvm_guard_incremental_equals_full);+ RUN_TEST(doc_mentions_jvm_cross_language);+ RUN_TEST(doc_mentions_jvm_node_ownership);+ RUN_TEST(doc_mentions_jvm_kotlin_type_and_function);+ RUN_TEST(doc_mentions_jvm_test_only_layouts);+ RUN_TEST(doc_mentions_jvm_family_names);+ RUN_TEST(doc_mentions_jvm_scope_delta_rules);+ RUN_TEST(doc_mentions_jvm_incremental_equals_full);+ RUN_TEST(doc_mentions_jvm_parallel_equals_sequential);+ RUN_TEST(doc_mentions_jvm_platform_roots);+ RUN_TEST(doc_mentions_jvm_java_field_before_level);+ RUN_TEST(doc_mentions_jvm_java_field_at_open_level);+ RUN_TEST(doc_mentions_jvm_java_search_superclass_around);+ RUN_TEST(doc_mentions_jvm_java_search_outside_superclass);+ RUN_TEST(doc_mentions_jvm_java_search_interface_order);+ RUN_TEST(doc_mentions_jvm_java_search_interface_no_object);+ RUN_TEST(doc_mentions_jvm_java_search_kotlin_superclass);+ RUN_TEST(doc_mentions_jvm_java_field_outer_outside);+ RUN_TEST(doc_mentions_jvm_java_field_own_far_outside);+ RUN_TEST(doc_mentions_jvm_java_field_method_past_outside);+ RUN_TEST(doc_mentions_jvm_java_field_named_around);+}diff --git a/tests/test_main.c b/tests/test_main.cindex d465ba98d..746ee2bc3 100644--- a/tests/test_main.c+++ b/tests/test_main.c@@ -1826,6 +1826,7 @@ extern void suite_doc_links_pdf(void);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_infrascan(void);extern void suite_cli(void);extern void suite_agent_clients(void);@@ -2298,6 +2299,7 @@ int main(int argc, char **argv) {RUN_SELECTED_SUITE(doc_links_rst);RUN_SELECTED_SUITE(doc_links_adoc);RUN_SELECTED_SUITE(doc_mentions_go);+ RUN_SELECTED_SUITE(doc_mentions_jvm);/* Infrastructure scanning */RUN_SELECTED_SUITE(infrascan);