diff --git a/src/pipeline/include_path.c b/src/pipeline/include_path.c index f45755280..ee7c77af5 100644 --- a/src/pipeline/include_path.c +++ b/src/pipeline/include_path.c @@ -12,6 +12,7 @@ #include "foundation/arena.h" #include "foundation/compat_fs.h" +#include "foundation/compat_thread.h" #include "foundation/constants.h" #include "foundation/hash_table.h" #include "foundation/log.h" @@ -20,17 +21,117 @@ #include "graph_buffer/graph_buffer.h" #include "pipeline/pipeline_internal.h" +#include #include #include #include -enum { IP_PATH_MAX = 1024, IP_UP_LEN = 3 /* "../" */ }; +enum { + IP_PATH_MAX = 1024, + IP_UP_LEN = 3, /* "../" */ + IP_DART_SCHEME_LEN = 5, /* "dart:" */ + IP_PACKAGE_SCHEME_LEN = 8, /* "package:" */ + IP_SEGS_MAX = 512, /* segments of one Dart URI path */ + IP_WS_DEPTH = 16, /* nested pub workspaces followed */ +}; + +/* Test seams (include_path.h): the work the rule counts, an insert dropped. */ +#if defined(CBM_MEM_TEST_API) && CBM_MEM_TEST_API +static _Thread_local uint64_t ip_test_steps; +static _Thread_local int ip_test_drop_at; +static _Thread_local bool ip_test_dropped; +static _Thread_local int ip_test_read_fail_at; +static _Thread_local bool ip_test_read_failed; + +void cbm_include_path_test_fail_insert(int nth) { + ip_test_drop_at = nth; + ip_test_dropped = false; +} + +bool cbm_include_path_test_reset_insert_failure(void) { + bool fired = ip_test_dropped; + ip_test_drop_at = 0; + ip_test_dropped = false; + return fired; +} + +void cbm_include_path_test_fail_read(int nth) { + ip_test_read_fail_at = nth; + ip_test_read_failed = false; +} + +bool cbm_include_path_test_reset_read_failure(void) { + bool fired = ip_test_read_failed; + ip_test_read_fail_at = 0; + ip_test_read_failed = false; + return fired; +} + +static bool ip_test_read_fail(void) { + if (ip_test_read_fail_at > 0 && --ip_test_read_fail_at == 0) { + ip_test_read_failed = true; + return true; + } + return false; +} + +uint64_t cbm_include_path_test_steps(void) { + return ip_test_steps; +} + +static bool ip_test_drop(void) { + if (ip_test_drop_at > 0 && --ip_test_drop_at == 0) { + ip_test_dropped = true; + return true; + } + return false; +} + +static _Thread_local int ip_test_answers_fail_at; +static _Thread_local bool ip_test_answers_failed; +static _Thread_local uint64_t ip_test_probes; + +void cbm_include_path_test_fail_answers(int nth) { + ip_test_answers_fail_at = nth; + ip_test_answers_failed = false; +} + +bool cbm_include_path_test_reset_answers_failure(void) { + bool fired = ip_test_answers_failed; + ip_test_answers_fail_at = 0; + ip_test_answers_failed = false; + return fired; +} + +static bool ip_test_answers_fail(void) { + if (ip_test_answers_fail_at > 0 && --ip_test_answers_fail_at == 0) { + ip_test_answers_failed = true; + return true; + } + return false; +} + +uint64_t cbm_include_path_test_probes(void) { + return ip_test_probes; +} +#define IP_COUNT() (ip_test_steps++) +#define IP_PROBE() (ip_test_probes++) +#else +#define ip_test_drop() false +#define ip_test_read_fail() false +#define ip_test_answers_fail() false +#define IP_COUNT() ((void)0) +#define IP_PROBE() ((void)0) +#endif /* ── Rows ────────────────────────────────────────────────────────────── */ static const char *const IP_PROTO_SUFFIXES[] = {".proto", NULL}; static const char *const IP_MAKE_SUFFIXES[] = {".mk", ".make", NULL}; static const char *const IP_MAKE_PREFIXES[] = {"Makefile", "makefile", "GNUmakefile", NULL}; +static const char *const IP_DART_SUFFIXES[] = {".dart", NULL}; +static const char *const IP_DART_ROOTS[] = {"pubspec.yaml", "pubspec_overrides.yaml", NULL}; +static const char IP_PUB_OVERRIDES[] = "pubspec_overrides.yaml"; static const cbm_include_path_row_t IP_ROWS[] = { /* Protobuf: `import "a/b.proto"` names the one indexed file that is that @@ -57,6 +158,14 @@ static const cbm_include_path_row_t IP_ROWS[] = { * uses a server mapping, so use Protobuf's unique whole-path tail rule. * The fallback filter passes CFML: templates are always decided, other imports are no path. */ {.lang = CBM_LANG_CFML, .base_file_dir = true, .whole_path_tail = true}, + /* Dart: `import 'package:dio/dio.dart'` names lib/dio.dart of the package + * dio as the importer's own pubspec.yaml resolves it; `import 'src/a.dart'` + * the file relative to the importing library; `dart:` an SDK library, + * never a repository file. */ + {.lang = CBM_LANG_DART, + .suffixes = IP_DART_SUFFIXES, + .root_names = IP_DART_ROOTS, + .dart_uri = true}, }; const cbm_include_path_row_t *cbm_include_path_row(CBMLanguage lang) { @@ -85,6 +194,11 @@ static bool ip_row_names(const cbm_include_path_row_t *row, const char *name) { return true; } } + for (const char *const *r = row->root_names; r && *r; r++) { + if (strcmp(name, *r) == 0) { + return true; + } + } return false; } @@ -97,6 +211,47 @@ bool cbm_include_path_listed_name(const char *name) { return false; } +/* A root name of some row ("pubspec.yaml"). */ +static bool ip_root_name(const char *name) { + for (size_t i = 0; name && i < sizeof(IP_ROWS) / sizeof(IP_ROWS[0]); i++) { + for (const char *const *r = IP_ROWS[i].root_names; r && *r; r++) { + if (strcmp(name, *r) == 0) { + return true; + } + } + } + return false; +} + +bool cbm_include_path_root_file(const char *rel) { + const char *base = rel ? strrchr(rel, '/') : NULL; + base = base ? base + SKIP_ONE : rel; + return base && ip_root_name(base); +} + +/* A name a row other than Dart's keeps: a Protobuf or Make suffix or prefix + * (CFML keeps none of its own). This is main's set of listed names: the Make + * and Protobuf candidates are gated by it, and only its paths go into the + * suffix tables. Not a Dart file or a pubspec: the Dart row lists those for its + * own answers, and no Make or Protobuf answer may change because it does. */ +static bool ip_path_row_name(const char *name) { + for (size_t i = 0; name && i < sizeof(IP_ROWS) / sizeof(IP_ROWS[0]); i++) { + if (!IP_ROWS[i].dart_uri && ip_row_names(&IP_ROWS[i], name)) { + return true; + } + } + return false; +} + +/* A listed name whose indexed SET decides an answer for other paths: a name a + * base or tail row keeps (Protobuf, Make: a file elsewhere can make a tail + * ambiguous or a base exist), or a root name. Not a Dart file: a Dart URI + * names one exact path, so deleting a Dart file changes only the answers that + * named that file, whose importers had their edges into it. */ +static bool ip_keyed_name(const char *name) { + return ip_path_row_name(name) || ip_root_name(name); +} + /* ── Paths ───────────────────────────────────────────────────────────── */ /* `rel` (./ and ../ allowed) inside repository directory `base` ("" = the @@ -167,6 +322,119 @@ typedef struct { int n; } ip_tail_t; +/* Where a pubspec says a dependency comes from. */ +typedef enum { + IP_SRC_PLAIN = 0, /* a version constraint, or none: pub's default host */ + IP_SRC_PATH, /* `path:` a directory */ + IP_SRC_EXTERNAL, /* `git:`, `hosted:` with a URL, `sdk:` */ + IP_SRC_UNKNOWN, /* a form the reader does not take */ +} ip_src_t; + +enum { IP_SEC_DEPS = 0, IP_SEC_DEV = 1, IP_SEC_OVERRIDES = 2, IP_SEC_COUNT = 3 }; + +typedef struct ip_dep { + const char *name; + const char *path; /* IP_SRC_PATH: as written */ + ip_src_t src; + bool hosted_open; /* `hosted:` with nested keys, no `url:` seen yet */ + struct ip_dep *next; +} ip_dep_t; + +typedef struct ip_str { + const char *s; + struct ip_str *next; +} ip_str_t; + +typedef struct ip_pkg ip_pkg_t; + +/* The package one name stands for in a resolution. */ +typedef enum { + IP_RES_DIR, /* a package of the repository */ + IP_RES_EXTERNAL, /* git, a hosted URL, the SDK */ + IP_RES_PLAIN, /* a version constraint: pub's default host (the convention class) */ + IP_RES_UNDECIDED, /* two sources, a form the reader does not take, a path it cannot follow */ + IP_RES_ABSENT, /* listed by no package the walk reached */ +} ip_res_kind_t; + +typedef enum { + IP_VIA_MEMBER = 0, /* a package of the resolution itself (the root, a workspace member) */ + IP_VIA_PATH, /* a path dependency of one of those */ + IP_VIA_TRANSITIVE, /* a path dependency of a path dependency */ +} ip_via_t; + +typedef struct { + ip_res_kind_t kind; + ip_via_t via; + const ip_pkg_t *pkg; /* IP_RES_DIR */ + bool whole; /* IP_RES_ABSENT: every package the walk reached was read */ +} ip_res_t; + +/* One name's answer in a root's resolution, kept after the walk: the name + * (a universe string), its package, its kind and how it was reached. */ +typedef struct { + const char *name; /* NULL: an empty slot */ + const ip_pkg_t *pkg; + uint32_t h; + uint8_t kind; /* ip_res_kind_t */ + uint8_t via; /* ip_via_t */ +} ip_answer_t; + +/* A resolution root's parts, made on its first question (under the + * universe's lock): the packages of the resolution itself (the root and its + * workspace members), their overrides, and its answers. The first question + * walks the root's closure once, level by level, keeping the walk's state (a + * name table with the sources found per name, the packages reached, the next + * level) in an arena of that question; when the walk is done, only the + * answers are kept (an open-addressed array, one slot per name of the + * closure) and the walk's state is freed. */ +typedef struct ip_root { + const ip_pkg_t **self; /* the root first */ + int n_self; + int cap_self; + bool unread; /* a package of the resolution itself not read whole: every answer NONE */ + bool whole; /* every member listed is indexed and named */ + CBMHashTable *ov; /* override name -> ip_ovr_t */ + CBMHashTable *names; /* during the walk: name -> ip_name_t, every name it has met */ + CBMHashTable *seen; /* during the walk: package directory -> package reached */ + CBMArena *walk; /* during the walk: the arena of its name entries */ + const ip_pkg_t **level; /* the walk's next level */ + int n_level; + int cap_level; + int depth; /* the level the walk takes next */ + bool lost; /* a package reached was not read, or an entry could not be followed */ + bool done; /* the walk has reached the whole closure */ + bool clash; /* a name has two known sources: pub refuses the resolution, every answer NONE */ + ip_res_t absent; /* when done: the answer for a name the walk never met */ + ip_answer_t *ans; /* when done: the answers, cap_ans slots (a power of two), or NULL */ + uint32_t cap_ans; + ip_res_t res; /* the last answer looked up (read under the universe's lock) */ +} ip_root_t; + +/* The indexed pubspecs that carry one name. */ +typedef struct { + int n; + const ip_pkg_t *first; +} ip_pubname_t; + +/* One indexed pubspec.yaml: its package, read once. */ +struct ip_pkg { + const char *dir; /* "." at the repository root */ + const char *lib; /* "lib" at the root, else "/lib" */ + const char *name; /* NULL when `name:` is no identifier */ + bool name_seen; /* a `name:` line was read */ + bool name_unsure; /* ... with a value the reader cannot decode (pub may read a name) */ + bool read; /* every line the rule needs was read */ + bool member; /* `resolution: workspace` */ + bool members_whole; /* every `workspace:` entry is a directory the rule reads */ + ip_str_t *members; /* `workspace:` entries, as repository directories */ + ip_dep_t *secs[IP_SEC_COUNT]; + bool ovfile; /* a pubspec_overrides.yaml (read into a package of its own) */ + bool has_ov_key; /* ... that holds a `dependency_overrides:` key */ + ip_pkg_t *root; /* the package whose resolution it shares; NULL: unknown */ + ip_root_t *rs; /* at a resolution root: its parts, made on the first question */ + uint64_t walk; /* the walk that reached it last (under the universe's lock) */ +}; + struct cbm_include_universe { CBMArena arena; CBMHashTable *listed; /* rel -> non-NULL */ @@ -174,13 +442,54 @@ struct cbm_include_universe { /* the same suffixes in lower case: a path that matches one only when case * is ignored is not known absent (a case-insensitive disk opens it) */ CBMHashTable *ftails; - /* false when an indexed path did not fit the rule's buffers: then no - * uniqueness and no absence is proven */ + CBMHashTable *pkgs; /* package directory -> ip_pkg_t */ + CBMHashTable *ws_of; /* workspace member directory -> the ip_pkg_t listing it */ + /* package directory -> ip_pkg_t of its pubspec_overrides.yaml (its + * dependency_overrides replace the pubspec's) */ + CBMHashTable *ovfiles; + CBMHashTable *pub_names; /* package name -> ip_pubname_t (the convention class) */ + ip_pkg_t **pkg_list; + int n_pkgs; + int cap_pkgs; + /* indexed pubspecs whose path did not fit: a directory that long may hold + * the package of a file below it */ + int long_pubs; + /* indexed pubspec.yaml files whose name the reader did not take (unread + * before `name:`, larger than 1 MB, a path that did not fit, a name it + * does not take): each may carry any name, so while one is indexed no name + * is known to have exactly one package, or none, in the repository */ + int unnamed_pubs; + /* false when an indexed path of a keyed name (ip_keyed_name) did not fit + * the rule's buffers: then no uniqueness and no absence is proven for the + * tail and base rows. A Dart file that does not fit changes nothing: no + * URI the rule reads can name it (its candidate does not fit either). */ bool complete; - bool all_paths; /* CFML templates can name any indexed file */ + bool all_paths; /* CFML templates can name any indexed file */ + /* an insert into a table failed (no memory): every answer is NONE. Atomic: + * a Dart walk may set it (under the lock) while any question reads it + * (without the lock); only ip_fail and ip_failed touch it */ + _Atomic bool failed; + /* a Dart manifest could not be read at all (opened, or no memory): every + * Dart answer is NONE; the Protobuf, Make and CFML answers read no + * manifest and stay decided */ + bool dart_failed; uint64_t tail_steps; /* suffix keys made while building */ + /* the resolutions are made on demand: their parts and the walk counter + * are written under this lock (a question may come from any worker) */ + cbm_mutex_t lock; + uint64_t walks; }; +/* The failed flag (relaxed: it only turns answers into NONE; what a walk wrote + * is read under the lock that ordered it). */ +static void ip_fail(cbm_include_universe_t *u) { + atomic_store_explicit(&u->failed, true, memory_order_relaxed); +} + +static bool ip_failed(const cbm_include_universe_t *u) { + return atomic_load_explicit(&u->failed, memory_order_relaxed); +} + static bool ip_has_cfml(const cbm_file_info_t *files, int count) { for (int i = 0; files && i < count; i++) { if (files[i].language == CBM_LANG_CFML) { @@ -194,14 +503,29 @@ void cbm_include_universe_free(cbm_include_universe_t *u) { if (!u) { return; } - if (u->listed) { - cbm_ht_free(u->listed); + for (int i = 0; i < u->n_pkgs; i++) { + ip_root_t *rs = u->pkg_list[i]->rs; + if (rs) { + cbm_ht_free(rs->ov); + if (rs->names) { + cbm_ht_free(rs->names); + } + if (rs->seen) { + cbm_ht_free(rs->seen); + } + cbm_free(CBM_MEM_CLASS_OTHER, (void *)rs->self); + cbm_free(CBM_MEM_CLASS_OTHER, (void *)rs->level); + cbm_free(CBM_MEM_CLASS_OTHER, rs->ans); + } } - if (u->tails) { - cbm_ht_free(u->tails); - } - if (u->ftails) { - cbm_ht_free(u->ftails); + cbm_mutex_destroy(&u->lock); + cbm_free(CBM_MEM_CLASS_OTHER, (void *)u->pkg_list); + CBMHashTable *tables[] = {u->listed, u->tails, u->ftails, u->pkgs, + u->ws_of, u->pub_names, u->ovfiles}; + for (size_t i = 0; i < sizeof(tables) / sizeof(tables[0]); i++) { + if (tables[i]) { + cbm_ht_free(tables[i]); + } } cbm_arena_destroy(&u->arena); cbm_free(CBM_MEM_CLASS_OTHER, u); @@ -211,6 +535,20 @@ uint64_t cbm_include_universe_tail_steps(const cbm_include_universe_t *u) { return u ? u->tail_steps : 0; } +/* One insert, checked: cbm_ht_set reports no failed allocation, so the value + * is read back. A failed insert marks the universe failed (every answer + * NONE: a lost key would read as an absent file or package). */ +static bool ip_set(cbm_include_universe_t *u, CBMHashTable *ht, const char *key, void *val) { + if (!ip_test_drop()) { + (void)cbm_ht_set(ht, key, val); + } + if (cbm_ht_get(ht, key) != val) { + ip_fail(u); + return false; + } + return true; +} + /* "a/B.proto" -> "a/b.proto" (ASCII) into out; false when it does not fit. */ static bool ip_fold_into(char *out, size_t sz, const char *p) { size_t n = strlen(p); @@ -224,32 +562,41 @@ static bool ip_fold_into(char *out, size_t sz, const char *p) { return true; } -/* One indexed path: into the set and the suffix indexes (building only). */ -static bool ip_list_add(cbm_include_universe_t *u, const char *path, bool listed_name) { +/* One indexed path, building only: into the set; into the exact suffix index + * (`tails`) for a name a base or tail row keeps and for any path a CFML + * template may name (a repository with a CFML file); into the case-folded + * suffix index (`folded`) for a base or tail row's name only (CFML consults + * the exact index, so its additional paths stay out of the absence proof). A + * Dart path or a pubspec goes into the set only, unless a CFML template may + * name it: a Dart answer reads the exact listed path. */ +static bool ip_list_add(cbm_include_universe_t *u, const char *path, bool tails, bool folded) { const char *rel = cbm_arena_strdup(&u->arena, path); if (!rel) { return false; } - /* The older rows use case-folded tails to prove absence. CFML only - * consults the exact index, so keep its additional paths out of that proof. */ - if (listed_name) { + if (folded) { char fold[IP_PATH_MAX]; if (!ip_fold_into(fold, sizeof(fold), rel)) { return false; } - const char *folded = cbm_arena_strdup(&u->arena, fold); - if (!folded) { + const char *f = cbm_arena_strdup(&u->arena, fold); + if (!f) { return false; } - for (const char *p = folded; p;) { - cbm_ht_set(u->ftails, p, (void *)folded); + for (const char *p = f; p;) { + if (!ip_set(u, u->ftails, p, (void *)f)) { + return true; /* failed: marked */ + } const char *slash = strchr(p, '/'); p = slash ? slash + SKIP_ONE : NULL; } } - cbm_ht_set(u->listed, rel, (void *)rel); + if (!ip_set(u, u->listed, rel, (void *)rel) || !tails) { + return true; /* failed: marked; or the set only */ + } for (const char *p = rel; p;) { u->tail_steps++; + IP_COUNT(); ip_tail_t *e = cbm_ht_get(u->tails, p); if (!e) { e = cbm_arena_alloc(&u->arena, sizeof(*e)); @@ -258,7 +605,9 @@ static bool ip_list_add(cbm_include_universe_t *u, const char *path, bool listed } e->path = rel; e->n = 0; - cbm_ht_set(u->tails, p, e); /* p points into rel: arena-owned */ + if (!ip_set(u, u->tails, p, e)) { /* p points into rel: arena-owned */ + return true; + } } e->n++; const char *slash = strchr(p, '/'); @@ -267,6 +616,1152 @@ static bool ip_list_add(cbm_include_universe_t *u, const char *path, bool listed return true; } +enum { IP_READ_OK = 0, IP_READ_TOO_BIG = 1, IP_READ_FAILED = 2 }; + +/* The bytes of an indexed manifest (1 MB at most, as the package map reads + * it; "" for an empty file), core-owned, into *out. IP_READ_TOO_BIG: larger; + * IP_READ_FAILED: it could not be opened or read, or no memory. */ +static int ip_read_manifest(const char *path, char **out) { + *out = NULL; + FILE *f = path && !ip_test_read_fail() ? cbm_fopen(path, "rb") : NULL; + if (!f) { + return IP_READ_FAILED; + } + long size = fseek(f, 0, SEEK_END) == 0 ? ftell(f) : -1; + int rc = size < 0 || fseek(f, 0, SEEK_SET) != 0 ? IP_READ_FAILED : IP_READ_OK; + if (rc == IP_READ_OK && size > (long)CBM_SZ_1K * CBM_SZ_1K) { + rc = IP_READ_TOO_BIG; + } + char *buf = rc == IP_READ_OK ? cbm_alloc(CBM_MEM_CLASS_OTHER, (size_t)size + SKIP_ONE) : NULL; + if (rc == IP_READ_OK && (!buf || fread(buf, SKIP_ONE, (size_t)size, f) != (size_t)size)) { + rc = IP_READ_FAILED; + } + if (rc == IP_READ_OK) { + buf[size] = '\0'; + *out = buf; + } else { + cbm_free(CBM_MEM_CLASS_OTHER, buf); + } + (void)fclose(f); + return rc; +} + +/* ── Dart packages: the pubspec reader ───────────────────────────────── */ + +/* A Dart package name: an identifier, bare or in one pair of matching quotes, + * into out. False for anything else. */ +static bool ip_pub_name(const char *raw, char *out, size_t out_sz) { + size_t n = strlen(raw); + if (n >= PAIR_LEN + SKIP_ONE && (raw[0] == '"' || raw[0] == '\'') && + raw[n - SKIP_ONE] == raw[0]) { + raw++; + n -= PAIR_LEN; + } + if (n == 0 || n >= out_sz || (raw[0] >= '0' && raw[0] <= '9')) { + return false; + } + for (size_t i = 0; i < n; i++) { + char c = raw[i]; + if (!((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9') || + c == '_')) { + return false; + } + } + memcpy(out, raw, n); + out[n] = '\0'; + return true; +} + +/* A scalar without its one pair of quotes, in place. */ +static char *ip_unquote(char *v) { + size_t n = strlen(v); + if (n >= PAIR_LEN && (v[0] == '"' || v[0] == '\'') && v[n - SKIP_ONE] == v[0]) { + v[n - SKIP_ONE] = '\0'; + return v + SKIP_ONE; + } + return v; +} + +/* A value the reader cannot take as a plain scalar: a flow collection, a + * block scalar, an anchor, alias or tag. */ +static bool ip_yaml_complex(const char *v) { + return v[0] == '{' || v[0] == '[' || v[0] == '|' || v[0] == '>' || v[0] == '&' || v[0] == '*' || + v[0] == '!'; +} + +/* A value that opens a quote, `[` or `{` and does not close it on its own + * line (its comment cut): the lines after it belong to the value, so no key + * on them can be told from it. The Dart SDK 3.14.1's `dart pub get` takes a + * quoted value continued over the next lines, at column 0 too, as one value + * (a `dependency_overrides:` line inside it is no key), and refuses a `[` or + * `{` continued at column 0; a line reader would take that line as a key. A + * quote opens only where a scalar starts; `\` escapes in double quotes, a + * doubled quote in single ones. A plain scalar opens nothing. */ +static bool ip_yaml_open(const char *v) { + if (v[0] != '"' && v[0] != '\'' && v[0] != '[' && v[0] != '{') { + return false; + } + int depth = 0; + char q = 0; + for (const char *s = v; *s; s++) { + if (q == '"') { + if (*s == '\\' && s[1]) { + s++; + } else if (*s == '"') { + q = 0; + } + } else if (q == '\'') { + if (*s == '\'' && s[1] == '\'') { + s++; + } else if (*s == '\'') { + q = 0; + } + } else if ((*s == '"' || *s == '\'') && (s == v || strchr("[{,: ", s[-1]))) { + q = *s; + } else if (*s == '[' || *s == '{') { + depth++; + } else if (*s == ']' || *s == '}') { + depth--; + } + } + return q != 0 || depth > 0; +} + +typedef struct { + int indent; + bool item; /* `- value` */ + char *key; /* NULL for an item or a line with no key */ + char *val; /* "" when none */ +} ip_yline_t; + +/* One line (in place): its indent, `key: value` or `- value`, the comment + * cut. 0: blank or a comment; 1: a key or an item; 2: some other content + * (a continued scalar); -1: a tab in the indent. */ +static int ip_yaml_line(char *line, ip_yline_t *out) { + int ind = 0; + while (line[ind] == ' ') { + ind++; + } + if (line[ind] == '\t') { + return -1; + } + char *c = line + ind; + char q = 0; + for (char *s = c; *s; s++) { + if (q) { + q = *s == q ? 0 : q; + } else if ((*s == '"' || *s == '\'') && (s == c || s[-1] == ' ' || s[-1] == ':')) { + q = *s; + } else if (*s == '#' && (s == c || s[-1] == ' ' || s[-1] == '\t')) { + *s = '\0'; + break; + } + } + size_t n = strlen(c); + while (n > 0 && (c[n - 1] == ' ' || c[n - 1] == '\t' || c[n - 1] == '\r')) { + c[--n] = '\0'; + } + if (n == 0) { + return 0; + } + out->indent = ind; + out->item = false; + out->key = NULL; + out->val = c + n; + if (c[0] == '-' && (c[1] == ' ' || c[1] == '\0')) { + out->item = true; + out->val = c[1] ? c + PAIR_LEN : c + SKIP_ONE; + while (*out->val == ' ') { + out->val++; + } + return 1; + } + char *colon = NULL; + if (c[0] == '"' || c[0] == '\'') { + char *close = strchr(c + SKIP_ONE, c[0]); + colon = close && close[1] == ':' ? close + SKIP_ONE : NULL; + } else { + for (char *s = c; *s && !colon; s++) { + colon = *s == ':' && (s[1] == ' ' || s[1] == '\0') ? s : NULL; + } + } + if (!colon || colon == c) { + return PAIR_LEN; + } + *colon = '\0'; + /* `key :` names key: pub reads `dependency_overrides :` as the section + * (a blank before the colon of a section or an entry key) */ + for (char *e = colon; e > c && (e[-1] == ' ' || e[-1] == '\t'); e--) { + e[-1] = '\0'; + } + out->key = ip_unquote(c); + out->val = colon + SKIP_ONE; + while (*out->val == ' ') { + out->val++; + } + return 1; +} + +enum { IP_URI_LEAVES = -1, IP_URI_DIR = 0, IP_URI_FILE = 1 }; + +static int ip_uri_join(char *out, size_t sz, const char *base, const char *ref, bool clamp, + bool *clamped); + +/* `rel` of a pubspec (a dependency's `path:`, a `workspace:` entry) from the + * package directory `dir` ("." at the root), normalized into out ("." for + * the root); false when it is absolute, leaves the repository, or does not + * fit. */ +static bool ip_pkg_join(char *out, size_t sz, const char *dir, const char *rel) { + if (!rel[0] || rel[0] == '/' || strpbrk(rel, "\\:") || sz < PAIR_LEN) { + return false; + } + bool clamped = false; + if (ip_uri_join(out, sz, strcmp(dir, ".") == 0 ? "" : dir, rel, false, &clamped) == + IP_URI_LEAVES) { + return false; + } + if (!out[0]) { + memcpy(out, ".", PAIR_LEN); /* the root itself */ + } + return true; +} + +typedef struct { + cbm_include_universe_t *u; + ip_pkg_t *pk; + int sec; /* -1 none, else IP_SEC_*; IP_SEC_COUNT: `workspace:` */ + int entry_indent; /* the indent of a section's entries */ + int sub_indent; /* the indent of an entry's keys */ + ip_dep_t *cur; + bool map_open; /* the entry's last key opened a map (`git:`, `hosted:`) */ + bool entry_scalar; /* the entry's line held a value (`foo: ^1.0.0`): nothing may follow below */ + unsigned keys; /* the entry's keys seen (IP_KEY_*), a map's under it in the high bits */ + CBMHashTable *names[IP_SEC_COUNT]; /* each section's entry names (a name twice: not read) */ + CBMHashTable *root_keys; /* the root's keys (a key twice: not read) */ + bool ok; /* no allocation failed */ +} ip_yread_t; + +/* An entry's keys and the keys of a `git:` or `hosted:` map under it, each + * allowed once (YAML refuses a mapping key twice: pub "Duplicate mapping key"). */ +enum { + IP_KEY_VERSION = 1U << 0, + IP_KEY_PATH = 1U << 1, + IP_KEY_GIT = 1U << 2, + IP_KEY_SDK = 1U << 3, + IP_KEY_HOSTED = 1U << 4, + IP_KEY_MAP_URL = 1U << 8, + IP_KEY_MAP_REF = 1U << 9, + IP_KEY_MAP_PATH = 1U << 10, + IP_KEY_MAP_NAME = 1U << 11, +}; + +/* The bit of a key, of the entry or of the map under it; 0 for another key. */ +static unsigned ip_key_bit(const char *key, bool in_map) { + static const struct { + const char *k; + unsigned entry; + unsigned map; + } bits[] = {{"version", IP_KEY_VERSION, 0}, {"path", IP_KEY_PATH, IP_KEY_MAP_PATH}, + {"git", IP_KEY_GIT, 0}, {"sdk", IP_KEY_SDK, 0}, + {"hosted", IP_KEY_HOSTED, 0}, {"url", 0, IP_KEY_MAP_URL}, + {"ref", 0, IP_KEY_MAP_REF}, {"name", 0, IP_KEY_MAP_NAME}}; + for (size_t i = 0; i < sizeof(bits) / sizeof(bits[0]); i++) { + if (strcmp(key, bits[i].k) == 0) { + return in_map ? bits[i].map : bits[i].entry; + } + } + return 0; +} + +/* `key` taken once in the table `*ht` (made on first use); false when it is + * there already (a key twice) or the table cannot be made (r->ok false). */ +static bool ip_key_once(ip_yread_t *r, CBMHashTable **ht, const char *key) { + if (!*ht && !(*ht = cbm_ht_create(CBM_SZ_16))) { + r->ok = false; + return false; + } + if (cbm_ht_get(*ht, key)) { + return false; + } + (void)cbm_ht_set(*ht, key, (void *)key); + if (cbm_ht_get(*ht, key) != key) { + r->ok = false; + return false; + } + return true; +} + +/* A plain root key: letters, digits and underscores, and a hyphen after the + * first (no known key has one, YAML reads a hyphenated plain scalar as + * itself, and dart reads a pubspec with such a key), after the one pair of + * quotes an exact key may have. */ +static bool ip_plain_key(const char *k) { + if (!k || !k[0] || k[0] == '-') { + return false; + } + for (const char *s = k; *s; s++) { + if (!((*s >= 'a' && *s <= 'z') || (*s >= 'A' && *s <= 'Z') || (*s >= '0' && *s <= '9') || + *s == '_' || *s == '-')) { + return false; + } + } + return true; +} + +static void ip_dep_close(ip_yread_t *r) { + if (r->cur && r->sec >= 0 && r->sec < IP_SEC_COUNT) { + r->cur->next = r->pk->secs[r->sec]; + r->pk->secs[r->sec] = r->cur; + } + r->cur = NULL; +} + +/* A key line at the root of the pubspec. */ +static void ip_yaml_root(ip_yread_t *r, const ip_yline_t *l, unsigned *seen) { + static const char *const keys[] = {"dependencies", "dev_dependencies", "dependency_overrides"}; + ip_pkg_t *pk = r->pk; + r->sec = -1; + r->entry_indent = -1; + if (pk->ovfile && strcmp(l->key, keys[IP_SEC_OVERRIDES]) != 0) { + pk->read = false; /* pub refuses another key there */ + return; + } + if (strcmp(l->key, "name") == 0) { + char pname[IP_PATH_MAX]; + pk->read = pk->read && !(*seen & (1U << IP_SEC_COUNT)); /* `name:` twice */ + *seen |= 1U << IP_SEC_COUNT; + pk->name = NULL; + if (ip_pub_name(l->val, pname, sizeof(pname))) { + pk->name = cbm_arena_strdup(&r->u->arena, pname); + r->ok = r->ok && pk->name; + } + /* a value the reader cannot decode may still be an identifier to pub: + * none on this line (an indented one may follow), a tag, anchor, + * alias, block scalar, an escape in double quotes. A plain scalar, + * single quotes, double quotes without an escape, a flow map or list + * (a template's `{{name}}`) are read as written: no package name */ + const char *v = l->val; + pk->name_seen = true; + pk->name_unsure = + !pk->name && (!v[0] || strchr("!&*|>", v[0]) || (v[0] == '"' && strchr(v, '\\'))); + return; + } + if (strcmp(l->key, "resolution") == 0) { + char v[CBM_SZ_64]; + snprintf(v, sizeof(v), "%s", l->val); + pk->read = pk->read && !ip_yaml_complex(l->val) && !(*seen & (1U << (IP_SEC_COUNT + 1))); + *seen |= 1U << (IP_SEC_COUNT + 1); + pk->member = strcmp(ip_unquote(v), "workspace") == 0; + return; + } + if (strcmp(l->key, "workspace") == 0) { + /* a flow list, or the key twice: not read */ + pk->read = pk->read && !l->val[0] && !(*seen & (1U << (IP_SEC_COUNT + PAIR_LEN))); + *seen |= 1U << (IP_SEC_COUNT + PAIR_LEN); + r->sec = IP_SEC_COUNT; + return; + } + for (int s = 0; s < IP_SEC_COUNT; s++) { + if (strcmp(l->key, keys[s]) == 0) { + /* a key twice, or a section the reader cannot take as a block map */ + pk->read = + pk->read && !(*seen & (1U << s)) && (!l->val[0] || strcmp(l->val, "{}") == 0); + *seen |= 1U << s; + pk->has_ov_key = pk->has_ov_key || s == IP_SEC_OVERRIDES; + r->sec = l->val[0] ? -1 : s; + return; + } + } +} + +/* A `workspace:` entry. */ +static void ip_yaml_member(ip_yread_t *r, const ip_yline_t *l) { + char raw[IP_PATH_MAX]; + char dir[IP_PATH_MAX]; + snprintf(raw, sizeof(raw), "%s", l->val); + const char *v = ip_unquote(raw); + if (!l->item || !v[0] || ip_yaml_complex(v) || strpbrk(v, "*?[]{}") || + !ip_pkg_join(dir, sizeof(dir), r->pk->dir, v)) { + r->pk->read = false; /* a glob, or a form the reader does not take */ + return; + } + /* pub refuses a member outside the workspace's own directory + * ("\"workspace\" members must be subdirectories", for two workspaces + * both listing ../m), and the member then finds no workspace + * root among its parent directories: that workspace is not read, so no + * two pubspecs of one directory depth can be a member's workspace */ + size_t dl = strlen(r->pk->dir); + bool below = strcmp(r->pk->dir, ".") == 0 ? strcmp(dir, ".") != 0 + : strncmp(dir, r->pk->dir, dl) == 0 && dir[dl] == '/'; + if (!below) { + r->pk->read = false; + return; + } + ip_str_t *m = cbm_arena_alloc(&r->u->arena, sizeof(*m)); + const char *s = cbm_arena_strdup(&r->u->arena, dir); + if (!m || !s) { + r->ok = false; + return; + } + m->s = s; + m->next = r->pk->members; + r->pk->members = m; +} + +/* A nested line of a dependency section. */ +static void ip_yaml_dep_line(ip_yread_t *r, const ip_yline_t *l) { + if (r->entry_indent < 0) { + r->entry_indent = l->indent; + } + if (l->indent < r->entry_indent) { + r->pk->read = false; + return; + } + if (l->indent == r->entry_indent) { + ip_dep_close(r); + if (!l->key) { + r->pk->read = false; + return; + } + char pname[IP_PATH_MAX]; + if (!ip_pub_name(l->key, pname, sizeof(pname)) || strcmp(pname, l->key) != 0 || + ip_yaml_complex(l->val)) { + /* no package name (a merge key `<<`, a quoted key), a flow map, an + * anchor, alias or tag: the pubspec is not read */ + r->pk->read = false; + return; + } + ip_dep_t *d = cbm_arena_calloc(&r->u->arena, sizeof(*d)); + const char *name = cbm_arena_strdup(&r->u->arena, l->key); + if (!d || !name) { + r->ok = false; + return; + } + if (!ip_key_once(r, &r->names[r->sec], name)) { + r->pk->read = false; /* an entry twice: pub "Duplicate mapping key" */ + return; + } + d->name = name; + d->src = IP_SRC_PLAIN; + r->cur = d; + r->sub_indent = -1; + r->map_open = false; + r->entry_scalar = l->val[0] != '\0'; + r->keys = 0; + return; + } + ip_dep_t *d = r->cur; + if (!d || r->entry_scalar) { + /* a line below an entry whose own line held a value (`foo: ^1.0.0`, + * then `path: foo_a` deeper): pub "Mapping values are not allowed + * here" */ + r->pk->read = false; + return; + } + if (r->sub_indent < 0) { + r->sub_indent = l->indent; + } + if (l->indent > r->sub_indent) { + /* below a key of the entry: only a `git:` or `hosted:` map has lines + * there (`url:`, `ref:`, `path:`, `name:`); `hosted:`'s `url:` decides */ + unsigned bit = l->key ? ip_key_bit(l->key, true) : 0; + if (!r->map_open || !l->key || ip_yaml_complex(l->val) || (r->keys & bit)) { + r->pk->read = false; + return; + } + r->keys |= bit; + if (d->hosted_open && strcmp(l->key, "url") == 0 && d->src == IP_SRC_PLAIN) { + d->src = IP_SRC_EXTERNAL; + } + return; + } + bool empty = !l->val[0]; + bool complex = !empty && ip_yaml_complex(l->val); + unsigned bit = l->key ? ip_key_bit(l->key, false) : 0; + if (l->indent < r->sub_indent || !l->key || complex || d->src == IP_SRC_UNKNOWN || + (r->keys & bit)) { + r->pk->read = false; /* a flow map on its own line, an anchor, a key twice: not read */ + return; + } + r->keys = + (r->keys & ~(IP_KEY_MAP_URL | IP_KEY_MAP_REF | IP_KEY_MAP_PATH | IP_KEY_MAP_NAME)) | bit; + r->map_open = empty && (strcmp(l->key, "git") == 0 || strcmp(l->key, "hosted") == 0); + if (strcmp(l->key, "version") == 0) { + return; /* a version constraint: the source stays */ + } + if (strcmp(l->key, "path") == 0 && d->src == IP_SRC_PLAIN && !empty && !d->hosted_open) { + char raw[IP_PATH_MAX]; + snprintf(raw, sizeof(raw), "%s", l->val); + d->path = cbm_arena_strdup(&r->u->arena, ip_unquote(raw)); + d->src = d->path ? IP_SRC_PATH : IP_SRC_UNKNOWN; + r->ok = r->ok && d->path; + } else if ((strcmp(l->key, "git") == 0 || strcmp(l->key, "sdk") == 0) && + d->src == IP_SRC_PLAIN && !d->hosted_open) { + d->src = IP_SRC_EXTERNAL; + } else if (strcmp(l->key, "hosted") == 0 && d->src == IP_SRC_PLAIN && !d->hosted_open) { + d->hosted_open = empty; + d->src = empty ? IP_SRC_PLAIN : IP_SRC_EXTERNAL; /* `hosted: ` */ + } else { + r->pk->read = false; /* another key, or two sources: not read */ + } +} + +/* Reads one pubspec (src, in place) into pk: `name:`, `resolution:`, + * `workspace:` and the three dependency sections. The reader is a whitelist. + * At the root, a line is blank, a comment, or a PLAIN key (letters, digits, + * underscore, then a colon); a plain key the reader does not know is skipped + * with its section. ANY other root line makes the pubspec unread: a key + * starting with `&`, `!`, `?`, `*`, a quote with an escape, `[`, `{`, `<<`, a + * byte-order mark, a tab, a document marker after content, `...` (the Dart + * SDK 3.14.1's `dart pub get` reads most of them). Inside the sections it + * takes, an entry key twice, a key of an entry twice, a scalar entry followed + * by a deeper line, a flow map, an anchor, alias or tag, a merge key, a tab in the + * indent, a glob in a workspace list make it unread. CRLF line ends and a + * quoted key without an escape are read (dart reads them: CRLF line ends, a + * double- or single-quoted root key, entry key or sub-key); a CR alone is not + * (dart reads a pubspec broken by lone CRs; this reader does not). Block scalars + * are skipped whole, so an indented line of one is never a key. A value that + * opens a quote, `[` or `{` and does not close it on its line makes the + * pubspec unread, at the root and in any section (ip_yaml_open). False on + * allocation failure. */ +static bool ip_yaml_read(cbm_include_universe_t *u, ip_pkg_t *pk, char *src) { + ip_yread_t r = {.u = u, .pk = pk, .sec = -1, .entry_indent = -1, .sub_indent = -1, .ok = true}; + unsigned seen = 0; + int block = -1; /* the indent of the key that opened a block scalar */ + bool content = false; + /* a CR that ends no CRLF is a line break to YAML (pub reads such a file) + * that this reader does not split on: not read */ + for (const char *s = strchr(src, '\r'); s && pk->read; s = strchr(s + SKIP_ONE, '\r')) { + pk->read = s[1] == '\n'; + } + for (char *line = src; line && pk->read;) { + char *nl = strchr(line, '\n'); + if (nl) { + *nl = '\0'; /* the CR of a CRLF is cut with the line's trailing blanks */ + } + char *next = nl ? nl + SKIP_ONE : NULL; + int ind = 0; + while (line[ind] == ' ') { + ind++; + } + if (block >= 0 && (line[ind] == '\0' || line[ind] == '\r' || ind > block)) { + line = next; + continue; + } + block = -1; + ip_yline_t l; + int k = ip_yaml_line(line, &l); + if (k == 0) { + line = next; + continue; + } + if (k < 0 || ip_yaml_open(k == 1 ? l.val : line + ind)) { + pk->read = false; /* a tab in the indent; a value open past its line */ + break; + } + if (k == PAIR_LEN && ind == 0 && strcmp(line, "---") == 0 && !content) { + line = next; + continue; + } + content = true; + if (l.indent == 0) { + ip_dep_close(&r); + /* the root is a whitelist: a line is blank, a comment or a plain + * key; any other root line makes the pubspec unread */ + if (k != 1 || l.item || !ip_plain_key(l.key) || !ip_key_once(&r, &r.root_keys, l.key)) { + pk->read = false; /* a second document, a list, a continued root scalar, an + * anchor, tag, explicit or merge key, an escaped key, a + * byte-order mark, a key twice */ + break; + } + if (l.val[0] == '|' || l.val[0] == '>') { + block = 0; + } + ip_yaml_root(&r, &l, &seen); + if (block == 0 && r.sec >= 0) { + pk->read = false; + } + } else if (r.sec == IP_SEC_COUNT) { + if (k == 1 && l.item) { + ip_yaml_member(&r, &l); + } else { + pk->read = false; + } + } else if (r.sec >= 0) { + if (k != 1) { + pk->read = false; + break; + } + ip_yaml_dep_line(&r, &l); + } else if (k == 1 && (l.val[0] == '|' || l.val[0] == '>')) { + block = l.indent; /* a block scalar in a section the rule skips */ + } + line = next; + } + ip_dep_close(&r); + for (int s = 0; s < IP_SEC_COUNT; s++) { + if (r.names[s]) { + cbm_ht_free(r.names[s]); + } + } + if (r.root_keys) { + cbm_ht_free(r.root_keys); + } + return r.ok; +} + +/* One indexed pubspec.yaml (rel fits): its package read and kept under its + * directory; or a pubspec_overrides.yaml, kept under its directory for the + * package beside it (building only). False on allocation failure. */ +static bool ip_pkg_add(cbm_include_universe_t *u, const cbm_file_info_t *fi) { + char dir[IP_PATH_MAX]; + if (!ip_dirname(dir, sizeof(dir), fi->rel_path)) { + return true; + } + const char *base = strrchr(fi->rel_path, '/'); + bool ovfile = strcmp(base ? base + SKIP_ONE : fi->rel_path, IP_PUB_OVERRIDES) == 0; + ip_pkg_t *pk = cbm_arena_calloc(&u->arena, sizeof(*pk)); + char lib[IP_PATH_MAX + 4]; + snprintf(lib, sizeof(lib), "%s%slib", dir, dir[0] ? "/" : ""); + if (!pk || !(pk->dir = cbm_arena_strdup(&u->arena, dir[0] ? dir : ".")) || + !(pk->lib = cbm_arena_strdup(&u->arena, lib))) { + return false; + } + pk->members_whole = true; + pk->ovfile = ovfile; + char *src = NULL; + int rc = ip_read_manifest(fi->path, &src); + if (rc == IP_READ_FAILED) { + u->dart_failed = true; /* a Dart answer would read it as absent or unnamed */ + return true; + } + pk->read = src != NULL; + bool ok = !src || ip_yaml_read(u, pk, src); + cbm_free(CBM_MEM_CLASS_OTHER, src); + if (!ok) { + return false; + } + if (ovfile) { + (void)ip_set(u, u->ovfiles, pk->dir, pk); + return true; + } + /* a name not taken: unread before its `name:` line, too big, or a value the + * reader cannot decode; a pubspec with no `name:` line, or with a value that + * is no identifier as written, names nothing */ + u->unnamed_pubs += !pk->name && (pk->name_unsure || (!pk->read && !pk->name_seen)); + if (u->n_pkgs == u->cap_pkgs) { + int cap = u->cap_pkgs ? u->cap_pkgs * PAIR_LEN : CBM_SZ_16; + ip_pkg_t **grown = + cbm_realloc(CBM_MEM_CLASS_OTHER, (void *)u->pkg_list, (size_t)cap * sizeof(*grown)); + if (!grown) { + return false; + } + u->pkg_list = grown; + u->cap_pkgs = cap; + } + u->pkg_list[u->n_pkgs++] = pk; + if (!ip_set(u, u->pkgs, pk->dir, pk)) { + return true; + } + ip_pubname_t *pn = pk->name ? cbm_ht_get(u->pub_names, pk->name) : NULL; + if (pk->name && !pn) { + pn = cbm_arena_calloc(&u->arena, sizeof(*pn)); + if (!pn) { + return false; + } + pn->first = pk; + if (!ip_set(u, u->pub_names, pk->name, pn)) { + return true; + } + } + if (pn) { + pn->n++; + } + for (const ip_str_t *m = pk->members; m && !ip_failed(u); m = m->next) { + /* the nearest workspace listing a directory is its workspace */ + const ip_pkg_t *had = cbm_ht_get(u->ws_of, m->s); + if (!had || strlen(had->dir) < strlen(pk->dir)) { + (void)ip_set(u, u->ws_of, m->s, pk); + } + } + return true; +} + +/* ── Dart packages: the resolution of a root package ─────────────────── */ + +/* An override of the resolution and the package whose pubspec states it. */ +typedef struct { + const ip_dep_t *dep; + const ip_pkg_t *decl; /* NULL: two packages override the name */ +} ip_ovr_t; + +static bool ip_grow(cbm_include_universe_t *u, const ip_pkg_t ***arr, int *n, int *cap, + const ip_pkg_t *pk) { + if (*n == *cap) { + int c = *cap ? *cap * PAIR_LEN : CBM_SZ_16; + const ip_pkg_t **g = cbm_realloc(CBM_MEM_CLASS_OTHER, (void *)*arr, (size_t)c * sizeof(*g)); + if (!g) { + ip_fail(u); + return false; + } + *arr = g; + *cap = c; + } + (*arr)[(*n)++] = pk; + return true; +} + +/* The package a path dependency `e` of `decl` names: its indexed, read + * pubspec of that name; NULL otherwise (no indexed pubspec there, one the + * rule cannot read, or another name: pub refuses it). */ +static const ip_pkg_t *ip_path_target(const cbm_include_universe_t *u, const ip_dep_t *e, + const ip_pkg_t *decl, const char *name) { + char dir[IP_PATH_MAX]; + const ip_pkg_t *tp = e->path && ip_pkg_join(dir, sizeof(dir), decl->dir, e->path) + ? cbm_ht_get(u->pkgs, dir) + : NULL; + return tp && tp->read && tp->name && strcmp(tp->name, name) == 0 ? tp : NULL; +} + +/* The root's own parts (once): the root and its workspace members (nested + * workspaces included), and the overrides they state. */ +static ip_root_t *ip_root_parts(cbm_include_universe_t *u, ip_pkg_t *r) { + if (r->rs) { + return r->rs; + } + ip_root_t *rs = cbm_arena_calloc(&u->arena, sizeof(*rs)); + if (!rs || !(rs->ov = cbm_ht_create(CBM_SZ_16))) { + ip_fail(u); + return NULL; + } + r->rs = rs; + rs->whole = true; + uint64_t walk = ++u->walks; + r->walk = walk; + if (!ip_grow(u, &rs->self, &rs->n_self, &rs->cap_self, r)) { + return NULL; + } + for (int i = 0; i < rs->n_self; i++) { + IP_COUNT(); + const ip_pkg_t *p = rs->self[i]; + rs->unread = rs->unread || !p->read; + rs->whole = rs->whole && p->name != NULL; + for (const ip_str_t *m = p->members; m; m = m->next) { + ip_pkg_t *mp = cbm_ht_get(u->pkgs, m->s); + if (!mp) { + rs->whole = false; /* a member the index does not hold */ + } else if (mp->walk != walk) { + mp->walk = walk; + if (!ip_grow(u, &rs->self, &rs->n_self, &rs->cap_self, mp)) { + return NULL; + } + } + } + for (const ip_dep_t *o = p->secs[IP_SEC_OVERRIDES]; o; o = o->next) { + IP_COUNT(); + ip_ovr_t *had = cbm_ht_get(rs->ov, o->name); + if (had) { + had->decl = NULL; + continue; + } + ip_ovr_t *e = cbm_arena_alloc(&u->arena, sizeof(*e)); + if (!e) { + ip_fail(u); + return NULL; + } + e->dep = o; + e->decl = p; + if (!ip_set(u, rs->ov, o->name, e)) { + return NULL; + } + } + } + return rs; +} + +/* The sources found for a name anywhere in a root's closure: pub takes one + * source per name for the whole closure. */ +typedef struct { + ip_res_kind_t kind; + const ip_pkg_t *pkg; + int n; + bool conflict; /* two sources differ (one of them perhaps unknown): the name is undecided */ + /* two sources both known (a directory, pub's host, git, a hosted URL, the + * SDK) and different: pub refuses the root's whole resolution ("version + * solving failed", whether the second source is one level deeper or more) */ + bool clash; + bool has_known; + ip_res_kind_t known_kind; + const ip_pkg_t *known_pkg; +} ip_found_t; + +static void ip_found_add(ip_found_t *f, ip_res_kind_t kind, const ip_pkg_t *pkg) { + if (f->n > 0 && (f->kind != kind || f->pkg != pkg)) { + f->conflict = true; + } + if (kind != IP_RES_UNDECIDED) { + f->clash = f->clash || (f->has_known && (f->known_kind != kind || f->known_pkg != pkg)); + f->has_known = true; + f->known_kind = kind; + f->known_pkg = pkg; + } + f->kind = kind; + f->pkg = pkg; + f->n++; +} + +/* The source a dependency entry stands for, an override of its name applied; + * *next: the package a path source names (NULL otherwise or when it cannot be + * followed, *lost then true). */ +static ip_res_kind_t ip_source(const cbm_include_universe_t *u, const ip_root_t *rs, + const ip_dep_t *d, const ip_pkg_t *decl, const ip_pkg_t **next, + bool *lost) { + const ip_ovr_t *o = cbm_ht_get(rs->ov, d->name); + const ip_dep_t *e = o && o->decl ? o->dep : d; + const ip_pkg_t *edecl = o && o->decl ? o->decl : decl; + *next = NULL; + if (o && !o->decl) { + *lost = true; + return IP_RES_UNDECIDED; /* two overrides of one name */ + } + switch (e->src) { + case IP_SRC_PLAIN: { + /* A version constraint (`^1.0.0`, `any`, none) on a name exactly one + * package of the repository carries: that package, by the + * project's decision (the working setup; by the committed + * files pub takes the published copy, and refuses the resolution + * when a path entry of the same name is in it). Two or more + * namesakes, or none: pub's host, as before. Not for an entry + * written with `hosted:`, git or the SDK, nor while a pubspec whose + * name the reader did not take is indexed (it may be a namesake). */ + const ip_pubname_t *pn = e->hosted_open ? NULL : cbm_ht_get(u->pub_names, d->name); + if (!pn || pn->n != SKIP_ONE || u->unnamed_pubs > 0) { + return IP_RES_PLAIN; + } + if (!pn->first->read) { + *lost = true; /* the namesake's own dependencies are unknown */ + return IP_RES_UNDECIDED; + } + *next = pn->first; + return IP_RES_DIR; + } + case IP_SRC_EXTERNAL: + return IP_RES_EXTERNAL; + case IP_SRC_UNKNOWN: + *lost = true; + return IP_RES_UNDECIDED; + case IP_SRC_PATH: + break; + } + *next = ip_path_target(u, e, edecl, d->name); + if (!*next) { + *lost = true; /* what it depends on is unknown */ + return IP_RES_UNDECIDED; + } + return IP_RES_DIR; +} + +/* One name of a root's table: every source found for it in the root's + * closure, and where it was first met (IP_LEVEL_SELF: a package of the + * resolution itself; IP_LEVEL_OVERRIDE: an override of a name that is not its + * own; else the walk level that first lists it: the class of the answer). */ +enum { IP_LEVEL_SELF = -2, IP_LEVEL_OVERRIDE = -1 }; + +typedef struct { + ip_res_t res; + ip_found_t f; + int level; +} ip_name_t; + +/* The entry of `name` (an arena string) in rs's table, made at `level` when it + * has none. NULL on allocation failure (the universe marked failed). */ +static ip_name_t *ip_name_at(cbm_include_universe_t *u, ip_root_t *rs, const char *name, int level, + ip_via_t via) { + ip_name_t *nm = cbm_ht_get(rs->names, name); + if (nm) { + return nm; + } + nm = cbm_arena_calloc(rs->walk, sizeof(*nm)); /* the walk's state: freed when it is done */ + if (!nm) { + ip_fail(u); + return NULL; + } + nm->level = level; + nm->res.via = via; + return ip_set(u, rs->names, name, nm) ? nm : NULL; +} + +/* A package the root's walk reaches: taken once (its directory into rs->seen) + * and put on the level `*arr`. False when it was reached before or on + * allocation failure (the universe marked failed). */ +static bool ip_reach(cbm_include_universe_t *u, ip_root_t *rs, const ip_pkg_t ***arr, int *n, + int *cap, const ip_pkg_t *pk) { + if (cbm_ht_get(rs->seen, pk->dir)) { + return false; + } + return ip_set(u, rs->seen, pk->dir, (void *)pk) && ip_grow(u, arr, n, cap, pk); +} + +/* The start of root r's name table, on its first question: the root's own + * packages first, then an override of a name that is not their own (it + * enters the resolution even when nothing depends on it, as pub reads an + * override no entry uses); the walk's first level is the root's own packages. + * False on allocation failure (the universe marked failed). */ +static bool ip_names_start(cbm_include_universe_t *u, ip_pkg_t *r, ip_root_t *rs) { + if (!(rs->names = cbm_ht_create(CBM_SZ_64)) || !(rs->seen = cbm_ht_create(CBM_SZ_64))) { + ip_fail(u); + return false; + } + for (int i = 0; i < rs->n_self; i++) { + IP_COUNT(); + const ip_pkg_t *p = rs->self[i]; + ip_name_t *nm = p->name ? ip_name_at(u, rs, p->name, IP_LEVEL_SELF, IP_VIA_MEMBER) : NULL; + if (p->name && !nm) { + return false; + } + if (nm) { + ip_found_add(&nm->f, IP_RES_DIR, p); + rs->clash = rs->clash || nm->f.clash; + } + (void)ip_reach(u, rs, &rs->level, &rs->n_level, &rs->cap_level, p); + } + for (int i = 0; i < rs->n_self && !ip_failed(u); i++) { + for (const ip_dep_t *o = rs->self[i]->secs[IP_SEC_OVERRIDES]; o; o = o->next) { + IP_COUNT(); + if (cbm_ht_get(rs->names, o->name)) { + continue; /* a name of the resolution itself, or overridden twice: made once */ + } + const ip_ovr_t *ov = cbm_ht_get(rs->ov, o->name); + ip_name_t *nm = ip_name_at(u, rs, o->name, IP_LEVEL_OVERRIDE, IP_VIA_PATH); + if (!ov || !nm) { + ip_fail(u); + return false; + } + /* Two statements, not one call: ip_source sets `next`, and the + * order in which a call's arguments are evaluated is unspecified. + * Passed in the same call, `next` may be read before it is set, + * and the override then clashes with its own source (DIR with no + * package against DIR with the package), which refuses the root's + * whole resolution. */ + const ip_pkg_t *next = NULL; + ip_res_kind_t k = ip_source(u, rs, ov->dep, ov->decl ? ov->decl : r, &next, &rs->lost); + ip_found_add(&nm->f, k, next); + } + } + return !ip_failed(u); +} + +/* One level of root r's walk (the dependencies and dev_dependencies of the + * root's own packages at level 0, then the dependencies of each path + * dependency reached): every entry's source is added to its name's, at any + * level, since pub takes one source per name for the whole closure (two + * sources: the name undecided; two known ones: pub refuses the resolution, + * rs->clash). The next level is the path dependencies reached for the first + * time. When none is, the walk is done and a name it never met is absent, + * decided only when every package it reached was read. Work: the level's + * packages and entries, once per root. */ +static void ip_names_step(cbm_include_universe_t *u, ip_root_t *rs) { + const ip_pkg_t **deeper = NULL; + int n_deeper = 0; + int cap_deeper = 0; + int depth = rs->depth; + ip_via_t via = depth == 0 ? IP_VIA_PATH : IP_VIA_TRANSITIVE; + for (int i = 0; i < rs->n_level && !ip_failed(u); i++) { + const ip_pkg_t *p = rs->level[i]; + IP_COUNT(); + rs->lost = rs->lost || !p->read; + int secs = depth == 0 ? IP_SEC_DEV + SKIP_ONE : SKIP_ONE; + for (int s = 0; s < secs && !ip_failed(u); s++) { + for (const ip_dep_t *d = p->secs[s]; d && !ip_failed(u); d = d->next) { + IP_COUNT(); + const ip_pkg_t *next = NULL; + ip_res_kind_t k = ip_source(u, rs, d, p, &next, &rs->lost); + ip_name_t *nm = ip_name_at(u, rs, d->name, depth, via); + /* a package of the resolution itself is that name whatever an + * entry says (a workspace member listed by version) */ + if (nm && nm->level != IP_LEVEL_SELF) { + ip_found_add(&nm->f, k, next); + rs->clash = rs->clash || nm->f.clash; + } + if (next) { + (void)ip_reach(u, rs, &deeper, &n_deeper, &cap_deeper, next); + } + } + } + } + cbm_free(CBM_MEM_CLASS_OTHER, (void *)rs->level); + rs->level = deeper; + rs->n_level = n_deeper; + rs->cap_level = cap_deeper; + rs->depth = depth + 1; + if (rs->n_level == 0) { + rs->done = true; + rs->absent = (ip_res_t){.kind = IP_RES_ABSENT, .whole = rs->whole && !rs->lost}; + } +} + +/* murmur3's 32-bit finaliser. FNV-1a's low bits depend only on the low bits + * of the bytes, and an answer's slot is the low bits of its key (the capacity + * is a power of two): names that agree there would all share one probe run. + * The finaliser mixes every bit of the value into the low ones. */ +static uint32_t ip_slot_mix(uint32_t h) { + enum { IP_MIX_A = 16, IP_MIX_B = 13 }; + h ^= h >> IP_MIX_A; + h *= 0x85ebca6bU; + h ^= h >> IP_MIX_B; + h *= 0xc2b2ae35U; + h ^= h >> IP_MIX_A; + return h; +} + +/* The key of a package name's answer, whose low bits are its slot: FNV-1a, + * mixed. */ +static uint32_t ip_answer_key(const char *s) { + uint32_t h = 2166136261U; + for (; *s; s++) { + h = (h ^ (uint8_t)*s) * 16777619U; + } + return ip_slot_mix(h); +} + +/* One name of the finished walk into the answers (cbm_ht_foreach). + * WHY: the parameters are cbm_ht_iter_fn's; `value` is only read here. */ +// cppcheck-suppress constParameterCallback +static void ip_answer_put(const char *name, void *value, void *ctx) { + ip_root_t *rs = ctx; + const ip_name_t *nm = value; + uint32_t h = ip_answer_key(name); + uint32_t i = h & (rs->cap_ans - SKIP_ONE); + IP_PROBE(); + while (rs->ans[i].name) { + IP_PROBE(); + i = (i + SKIP_ONE) & (rs->cap_ans - SKIP_ONE); + } + rs->ans[i] = (ip_answer_t){.name = name, + .pkg = nm->f.conflict ? NULL : nm->f.pkg, + .h = h, + .kind = (uint8_t)(nm->f.conflict ? IP_RES_UNDECIDED : nm->f.kind), + .via = (uint8_t)nm->res.via}; +} + +/* The answers of a finished walk: one slot per name, at most three quarters + * of the slots filled. False on allocation failure (the universe marked failed). */ +static bool ip_answers_make(cbm_include_universe_t *u, ip_root_t *rs) { + uint32_t n = cbm_ht_count(rs->names); + if (n == 0) { + return true; + } + uint32_t cap = CBM_SZ_4; + while (cap - cap / CBM_SZ_4 < n + SKIP_ONE) { + cap *= PAIR_LEN; + } + rs->ans = ip_test_answers_fail() + ? NULL + : cbm_calloc(CBM_MEM_CLASS_OTHER, (size_t)cap * sizeof(*rs->ans)); + if (!rs->ans) { + ip_fail(u); + return false; + } + rs->cap_ans = cap; + cbm_ht_foreach(rs->names, ip_answer_put, rs); + return true; +} + +/* The walk's state, freed: the name table and its entries, the packages + * reached, the next level. */ +static void ip_walk_free(ip_root_t *rs) { + if (rs->names) { + cbm_ht_free(rs->names); + rs->names = NULL; + } + if (rs->seen) { + cbm_ht_free(rs->seen); + rs->seen = NULL; + } + cbm_free(CBM_MEM_CLASS_OTHER, (void *)rs->level); + rs->level = NULL; + rs->n_level = 0; + rs->cap_level = 0; + if (rs->walk) { + cbm_arena_destroy(rs->walk); + rs->walk = NULL; + } +} + +/* What `name` stands for in the resolution of root r: one lookup in the + * root's answers. The root's first question walks its closure once, + * completely (an answer is right only when no second source of the name, and + * none of any other name, lies deeper), keeps one answer + * per name and frees the walk's state; every later question is one lookup. A + * root costs its closure once; roots that share a subgraph each walk it. + * Under u->lock. NULL on allocation failure (the universe marked failed). */ +static const ip_res_t *ip_res_get(cbm_include_universe_t *u, ip_pkg_t *r, const char *name) { + ip_root_t *rs = ip_root_parts(u, r); + if (!rs || ip_failed(u)) { + return NULL; + } + if (!rs->done) { + CBMArena walk; + cbm_arena_init_lazy(&walk, CBM_ARENA_APPEND_BLOCK); + rs->walk = &walk; + if (ip_names_start(u, r, rs)) { + while (!rs->done && !ip_failed(u)) { + ip_names_step(u, rs); + } + } + if (!ip_failed(u)) { + (void)ip_answers_make(u, rs); + } + ip_walk_free(rs); + if (ip_failed(u)) { + return NULL; + } + } + IP_COUNT(); + uint32_t h = ip_answer_key(name); + for (uint32_t i = h & (rs->cap_ans - SKIP_ONE); rs->ans && rs->ans[i].name; + i = (i + SKIP_ONE) & (rs->cap_ans - SKIP_ONE)) { + IP_PROBE(); + const ip_answer_t *a = &rs->ans[i]; + if (a->h == h && strcmp(a->name, name) == 0) { + rs->res = + (ip_res_t){.kind = (ip_res_kind_t)a->kind, .via = (ip_via_t)a->via, .pkg = a->pkg}; + return &rs->res; + } + } + return &rs->absent; +} + +/* Every package's resolution root (a workspace member: its workspace's), and + * the overrides file beside it (building only). No resolution is made here: + * each is made on its first question (ip_res_get). */ +static bool ip_res_all(cbm_include_universe_t *u) { + for (int i = 0; i < u->n_pkgs; i++) { + ip_pkg_t *pk = u->pkg_list[i]; + /* a pubspec_overrides.yaml beside it: its dependency_overrides + * replace the pubspec's; without that key (a comment, an empty file) + * the pubspec's stay; another key makes pub refuse it */ + const ip_pkg_t *ov = cbm_ht_get(u->ovfiles, pk->dir); + if (ov) { + IP_COUNT(); + pk->read = pk->read && ov->read; + if (ov->has_ov_key) { + pk->secs[IP_SEC_OVERRIDES] = ov->secs[IP_SEC_OVERRIDES]; + } + } + } + for (int i = 0; i < u->n_pkgs; i++) { + ip_pkg_t *pk = u->pkg_list[i]; + ip_pkg_t *at = pk; + for (int depth = 0; at && at->member && depth < IP_WS_DEPTH; depth++) { + IP_COUNT(); + at = cbm_ht_get(u->ws_of, at->dir); /* NULL: no workspace lists it */ + } + pk->root = at && !at->member ? at : NULL; + } + return true; +} + cbm_include_universe_t *cbm_include_universe_new(const cbm_file_info_t *files, int count) { cbm_include_universe_t *u = cbm_alloc(CBM_MEM_CLASS_OTHER, sizeof(*u)); if (!u) { @@ -274,10 +1769,16 @@ cbm_include_universe_t *cbm_include_universe_new(const cbm_file_info_t *files, i } memset(u, 0, sizeof(*u)); cbm_arena_init(&u->arena); + cbm_mutex_init(&u->lock); u->listed = cbm_ht_create(CBM_SZ_4K); u->tails = cbm_ht_create(CBM_SZ_4K); u->ftails = cbm_ht_create(CBM_SZ_4K); - if (!u->listed || !u->tails || !u->ftails) { + u->pkgs = cbm_ht_create(CBM_SZ_64); + u->ws_of = cbm_ht_create(CBM_SZ_16); + u->ovfiles = cbm_ht_create(CBM_SZ_16); + u->pub_names = cbm_ht_create(CBM_SZ_64); + if (!u->listed || !u->tails || !u->ftails || !u->pkgs || !u->ws_of || !u->pub_names || + !u->ovfiles) { cbm_include_universe_free(u); return NULL; } @@ -285,7 +1786,7 @@ cbm_include_universe_t *cbm_include_universe_new(const cbm_file_info_t *files, i bool has_cfml = ip_has_cfml(files, count); u->complete = true; u->all_paths = has_cfml; - for (int i = 0; files && i < count; i++) { + for (int i = 0; files && i < count && !ip_failed(u); i++) { const char *rel = files[i].rel_path; if (!rel || !rel[0]) { continue; @@ -296,19 +1797,38 @@ cbm_include_universe_t *cbm_include_universe_new(const cbm_file_info_t *files, i if ((!has_cfml && !listed_name) || cbm_ht_get(u->listed, rel)) { continue; /* a name no row's import names, or listed already */ } + /* a base or tail row's name (not a Dart file or a pubspec) */ + bool keyed = ip_path_row_name(base); if (strlen(rel) >= IP_PATH_MAX) { - u->complete = u->complete && !listed_name; + /* a path the rule cannot hold: a pubspec whose package may hold a + * file below it, or a keyed name the tail and base rows cannot + * account for */ + if (ip_root_name(base)) { + u->long_pubs++; + u->unnamed_pubs += strcmp(base, IP_DART_ROOTS[0]) == 0; + } else if (ip_path_row_name(base)) { + u->complete = false; + } if (!has_cfml) { continue; } - /* CFML still counts long paths when checking tail uniqueness. */ - listed_name = false; + /* CFML still counts long paths when checking tail uniqueness: + * the set and the exact suffix index, not the folded one */ + if (!ip_list_add(u, rel, true, false)) { + cbm_include_universe_free(u); + return NULL; + } + continue; } - if (!ip_list_add(u, rel, listed_name)) { + if (!ip_list_add(u, rel, keyed || has_cfml, keyed) || + (ip_root_name(base) && !ip_pkg_add(u, &files[i]))) { cbm_include_universe_free(u); return NULL; } } + if (!ip_failed(u)) { + (void)ip_res_all(u); + } return u; } @@ -318,14 +1838,16 @@ enum { IP_EXISTS_NO = 0, IP_EXISTS_YES = 1, IP_EXISTS_UNKNOWN = 2 }; * whole for a name a row keeps. Never a node found by name: a File node's * name joins the path's segments with dots, so a.b.proto and a/b.proto share * one (protoc, make and a CFML engine open only the file the path names). A - * CFML template may name any indexed file (`template`). Any other import of a - * name no row keeps is no file to the rule before the listing is asked: a - * CFML file in the run lists every path, and a Make include of such a name - * must not become the rule's answer only then. */ + * CFML template may name any indexed file (`template`). A Make or Protobuf + * candidate of a name outside main's set (ip_path_row_name: not a Dart file or + * a pubspec, which the Dart row lists) is no file to the rule before the + * listing is asked: a CFML file in the run lists every path, the Dart row + * lists its own names, and a Make include of such a name must not become the + * rule's answer only then. */ static int ip_exists(const cbm_include_universe_t *u, const char *rel, bool template) { const char *base = strrchr(rel, '/'); base = base ? base + SKIP_ONE : rel; - if (!template && !cbm_include_path_listed_name(base)) { + if (!template && !ip_path_row_name(base)) { return IP_EXISTS_NO; } if (cbm_ht_get(u->listed, rel)) { @@ -464,6 +1986,309 @@ static cbm_include_path_verdict_t ip_cfml_resolve(const cbm_include_universe_t * return CBM_INCLUDE_PATH_NO_FILE; } +/* ── Dart URIs ───────────────────────────────────────────────────────── */ + +/* A URI path `ref` resolved against the directory `base` (segments of a + * repository path, "" for none) as RFC 3986 does it, dart's order: the paths + * merged, then `.` and `..` removed one segment at a time, an empty segment + * (`//`) counting as one (`sub//../a.dart` is sub/a.dart). `..` above the + * start is dropped when `clamp` (a package library: `package:app/../x` stays + * in the package, *clamped set), else the path leaves (IP_URI_LEAVES). The + * result into out, empty segments left out (the file system reads `a//b` as + * a/b: dart opens bin/sub/a.dart for 'sub//a.dart'). IP_URI_DIR: the path + * ends with `/` (it names a directory: dart fails to read 'u.dart/'). */ +static int ip_uri_join(char *out, size_t sz, const char *base, const char *ref, bool clamp, + bool *clamped) { + const char *seg[IP_SEGS_MAX]; + size_t len[IP_SEGS_MAX]; + int n = 0; + for (const char *s = base; *s;) { + IP_COUNT(); + size_t sl = strcspn(s, "/"); + if (n == IP_SEGS_MAX) { + return IP_URI_LEAVES; + } + seg[n] = s; + len[n++] = sl; + s += sl; + s += *s == '/' ? SKIP_ONE : 0; + } + const char *s = ref; + for (;;) { + IP_COUNT(); + size_t sl = strcspn(s, "/"); + bool last = s[sl] == '\0'; + bool dot = sl == SKIP_ONE && s[0] == '.'; + bool up = sl == PAIR_LEN && s[0] == '.' && s[1] == '.'; + if (up) { + if (n > 0) { + n--; + } else if (clamp) { + *clamped = true; + } else { + return IP_URI_LEAVES; + } + } + if (!dot && !up) { + if (n == IP_SEGS_MAX) { + return IP_URI_LEAVES; + } + seg[n] = s; + len[n++] = sl; + } + if (last) { + break; + } + s += sl + SKIP_ONE; + } + /* s is the last segment: `` (a trailing `/`), `.` or `..` end in a directory */ + bool dir_end = !s[0] || strcmp(s, ".") == 0 || strcmp(s, "..") == 0; + size_t o = 0; + for (int i = 0; i < n; i++) { + if (len[i] == 0) { + continue; + } + if (o + len[i] + PAIR_LEN > sz) { + return IP_URI_LEAVES; + } + if (o) { + out[o++] = '/'; + } + memcpy(out + o, seg[i], len[i]); + o += len[i]; + } + out[o] = '\0'; + return dir_end || o == 0 ? IP_URI_DIR : IP_URI_FILE; +} + +/* The package of a repository file: the one whose pubspec.yaml is in its + * directory or the nearest above. NULL when none is, or *unknown when a + * pubspec too long for the rule may be the nearest. */ +static const ip_pkg_t *ip_pkg_of(const cbm_include_universe_t *u, const char *rel, bool *unknown) { + char dir[IP_PATH_MAX]; + if (!ip_dirname(dir, sizeof(dir), rel)) { + *unknown = true; + return NULL; + } + for (;;) { + IP_COUNT(); + const char *key = dir[0] ? dir : "."; + if (u->long_pubs > 0 && strlen(dir) + sizeof("/pubspec.yaml") > IP_PATH_MAX) { + *unknown = true; + return NULL; + } + const ip_pkg_t *pk = cbm_ht_get(u->pkgs, key); + if (pk) { + return pk; + } + if (!dir[0]) { + return NULL; + } + char *slash = strrchr(dir, '/'); + if (slash) { + *slash = '\0'; + } else { + dir[0] = '\0'; + } + } +} + +/* The resolution class of a package answer (include_path.h; logged at debug + * level as `include_path.dart_package class=`). */ +static const char *const IP_CLASS[] = { + [CBM_INCLUDE_DART_SELF] = "i_self", + [CBM_INCLUDE_DART_PATH] = "ii_path", + [CBM_INCLUDE_DART_TRANSITIVE] = "ii_transitive", + [CBM_INCLUDE_DART_MEMBER] = "iii_member", + [CBM_INCLUDE_DART_PLAIN] = "iv_plain", + [CBM_INCLUDE_DART_EXTERNAL] = "v_external", + [CBM_INCLUDE_DART_UNLISTED] = "vi_unlisted", + [CBM_INCLUDE_DART_UNDECIDED] = "undecided", +}; + +/* `package:/` from the file rel: under the lib/ of the + * package stands for in the importer's resolution. */ +static cbm_include_path_verdict_t ip_dart_package(const cbm_include_universe_t *u, const char *rel, + const char *uri, char *cand, size_t cand_sz, + cbm_include_dart_class_t *cls, int *namesakes) { + *cls = CBM_INCLUDE_DART_UNDECIDED; + *namesakes = 0; + const char *name = uri + IP_PACKAGE_SCHEME_LEN; + const char *slash = strchr(name, '/'); + const char *path = slash ? slash + SKIP_ONE : NULL; + char pname[IP_PATH_MAX]; + size_t nl = slash ? (size_t)(slash - name) : 0; + if (nl == 0 || nl >= sizeof(pname) || !path[0] || strpbrk(path, "\\%?#")) { + return CBM_INCLUDE_PATH_NONE; + } + for (const char *s = path; *s;) { + size_t sl = strcspn(s, "/"); + if ((sl == SKIP_ONE && s[0] == '.') || (sl == PAIR_LEN && s[0] == '.' && s[1] == '.')) { + return CBM_INCLUDE_PATH_NONE; /* not decided by dart */ + } + s += sl; + s += *s == '/' ? SKIP_ONE : 0; + } + memcpy(pname, name, nl); + pname[nl] = '\0'; + bool unknown = false; + const ip_pkg_t *own = ip_pkg_of(u, rel, &unknown); + ip_pkg_t *root = own && !unknown && own->read ? own->root : NULL; + if (!root) { + /* no package, one whose resolution is unknown, or a pubspec the + * reader does not take whole: undecided */ + return CBM_INCLUDE_PATH_NONE; + } + cbm_include_universe_t *mu = (cbm_include_universe_t *)u; /* the name table: under its lock */ + cbm_mutex_lock(&mu->lock); + const ip_res_t *got = ip_res_get(mu, root, pname); + ip_res_t e = got ? *got : (ip_res_t){.kind = IP_RES_UNDECIDED}; + bool unread = !got || root->rs->unread || root->rs->clash || root->rs->lost || !root->rs->whole; + cbm_mutex_unlock(&mu->lock); + if (unread) { + /* a package of the resolution itself not read whole; a name with two + * known sources in the closure: pub refuses the resolution ("version + * solving failed"), dart resolves no package: URI; + * or a package of the closure not read, a source the reader cannot + * place, a workspace member the index does not hold: it may hold a + * second source of the name. A readable closure is the condition for any + * package: answer. */ + return CBM_INCLUDE_PATH_NONE; + } + const ip_pubname_t *pn = cbm_ht_get(u->pub_names, pname); + switch (e.kind) { + case IP_RES_ABSENT: + /* listed by no package of the resolution: dart cannot resolve it, + * or only through a package outside the + * repository; unknown when a package the walk reached was not read */ + *cls = CBM_INCLUDE_DART_UNLISTED; + return e.whole ? CBM_INCLUDE_PATH_NO_FILE : CBM_INCLUDE_PATH_NONE; + case IP_RES_EXTERNAL: + case IP_RES_PLAIN: + /* pub's default host, git, a hosted URL, the SDK. No indexed pubspec + * carries the name: no repository file (an override the index cannot + * see would point at an indexed pubspec of that name, or at no + * indexed file). One or more do, or a pubspec whose name the reader + * did not take may: undecided (a version constraint lands here only + * with two or more namesakes or such a pubspec; with exactly one, + * ip_source takes its directory and the class is a path's). */ + *cls = e.kind == IP_RES_PLAIN ? CBM_INCLUDE_DART_PLAIN : CBM_INCLUDE_DART_EXTERNAL; + *namesakes = pn ? pn->n : 0; + return pn || u->unnamed_pubs > 0 ? CBM_INCLUDE_PATH_NONE : CBM_INCLUDE_PATH_NO_FILE; + case IP_RES_UNDECIDED: + return CBM_INCLUDE_PATH_NONE; + case IP_RES_DIR: + break; + } + *cls = e.pkg == own ? CBM_INCLUDE_DART_SELF + : e.via == IP_VIA_MEMBER ? CBM_INCLUDE_DART_MEMBER + : e.via == IP_VIA_PATH ? CBM_INCLUDE_DART_PATH + : CBM_INCLUDE_DART_TRANSITIVE; + bool clamped = false; + char sub[IP_PATH_MAX]; + int k = ip_uri_join(sub, sizeof(sub), "", path, false, &clamped); + if (k == IP_URI_DIR) { + return CBM_INCLUDE_PATH_NO_FILE; /* 'package:app/u.dart/': dart fails to read it */ + } + int w = k == IP_URI_FILE ? snprintf(cand, cand_sz, "%s/%s", e.pkg->lib, sub) : -1; + return w > 0 && (size_t)w < cand_sz ? CBM_INCLUDE_PATH_FILE : CBM_INCLUDE_PATH_NONE; +} + +/* A relative URI from the file rel. A file under its package's lib/ is the + * library package:/ (as dart analyze reads it), so the URI + * resolves inside lib/ and a `..` above lib/ is dropped (fixtures f2_*: from + * lib/app.dart, '../test/t.dart' is lib/test/t.dart, uri_does_not_exist). + * Any other file resolves on disk, from its directory. `any_pubspec`: the + * candidate also when the package's pubspec is not read whole (the one file + * the URI means, for cbm_include_path_accepts; the rule itself then answers + * NONE for a URI that leaves lib/). */ +static cbm_include_path_verdict_t ip_dart_relative(const cbm_include_universe_t *u, const char *rel, + const char *uri, char *cand, size_t cand_sz, + bool any_pubspec) { + if (uri[0] == '/' || strpbrk(uri, ":\\%?#")) { + return CBM_INCLUDE_PATH_NONE; /* another scheme, or a path the rule cannot read */ + } + bool unknown = false; + const ip_pkg_t *own = ip_pkg_of(u, rel, &unknown); + if (unknown) { + return CBM_INCLUDE_PATH_NONE; + } + size_t ll = own ? strlen(own->lib) : 0; + bool in_lib = own && strncmp(rel, own->lib, ll) == 0 && rel[ll] == '/'; + char dir[IP_PATH_MAX]; + if (!ip_dirname(dir, sizeof(dir), in_lib ? rel + ll + SKIP_ONE : rel)) { + return CBM_INCLUDE_PATH_NONE; + } + bool clamped = false; + char sub[IP_PATH_MAX]; + int k = ip_uri_join(sub, sizeof(sub), dir, uri, in_lib, &clamped); + if (k == IP_URI_LEAVES || (clamped && !any_pubspec && (!own->read || !own->name))) { + /* out of the repository; or out of lib/ in a package whose library + * names are unknown (its pubspec is not read whole) */ + return CBM_INCLUDE_PATH_NONE; + } + if (k == IP_URI_DIR) { + return CBM_INCLUDE_PATH_NO_FILE; /* 'u.dart/': dart fails to read it */ + } + int w = in_lib ? snprintf(cand, cand_sz, "%s/%s", own->lib, sub) + : snprintf(cand, cand_sz, "%s", sub); + return w > 0 && (size_t)w < cand_sz ? CBM_INCLUDE_PATH_FILE : CBM_INCLUDE_PATH_NONE; +} + +/* A Dart URI: the one file it names when that exact path is indexed; provably + * none otherwise. Existence is the listed path itself, never a node found by + * name (lib/a.b.dart and lib/a/b.dart share one File node name: dart rejects + * 'a/b.dart' when only lib/a.b.dart exists, fixtures f1_*). The answer reads + * no other indexed path: a file of another letter case is not the file (dart + * on a case-sensitive file system: uri_does_not_exist), and every indexed + * Dart path the candidate could equal fits the listing. So deleting a Dart + * file changes only the answers that named it. */ +static cbm_include_path_verdict_t ip_dart_resolve(const cbm_include_universe_t *u, const char *rel, + const char *p, char *buf, size_t buf_sz) { + if (strncmp(p, "dart:", IP_DART_SCHEME_LEN) == 0) { + return CBM_INCLUDE_PATH_NO_FILE; /* a library of the SDK */ + } + char cand[IP_PATH_MAX]; + cbm_include_path_verdict_t v; + if (strncmp(p, "package:", IP_PACKAGE_SCHEME_LEN) == 0) { + cbm_include_dart_class_t cls; + int namesakes = 0; + v = ip_dart_package(u, rel, p, cand, sizeof(cand), &cls, &namesakes); + char ns[CBM_SZ_16]; + snprintf(ns, sizeof(ns), "%d", namesakes); + cbm_log_debug("include_path.dart_package", "class", IP_CLASS[cls], "namesakes", ns, "file", + rel, "uri", p); + } else { + v = ip_dart_relative(u, rel, p, cand, sizeof(cand), false); + } + if (v != CBM_INCLUDE_PATH_FILE) { + return v; + } + /* the listed path of a name the listing keeps without a CFML file: a CFML + * file lists every path, which must not change a Dart answer */ + const char *cb = strrchr(cand, '/'); + if (!cbm_ht_get(u->listed, cand) || !cbm_include_path_listed_name(cb ? cb + SKIP_ONE : cand)) { + return CBM_INCLUDE_PATH_NO_FILE; + } + if (strlen(cand) >= buf_sz) { + return CBM_INCLUDE_PATH_NONE; + } + memcpy(buf, cand, strlen(cand) + SKIP_ONE); + return CBM_INCLUDE_PATH_FILE; +} + +cbm_include_dart_class_t cbm_include_path_dart_class(const cbm_include_universe_t *u, + const char *rel, const char *uri) { + cbm_include_dart_class_t cls = CBM_INCLUDE_DART_UNDECIDED; + if (u && !ip_failed(u) && !u->dart_failed && rel && uri && + strncmp(uri, "package:", IP_PACKAGE_SCHEME_LEN) == 0) { + char cand[IP_PATH_MAX]; + int namesakes = 0; + (void)ip_dart_package(u, rel, uri, cand, sizeof(cand), &cls, &namesakes); + } + return cls; +} + cbm_include_path_verdict_t cbm_include_path_resolve(const cbm_include_universe_t *u, const cbm_gbuf_t *graph, const char *project, const char *rel, CBMLanguage lang, @@ -476,9 +2301,17 @@ cbm_include_path_verdict_t cbm_include_path_resolve(const cbm_include_universe_t const char *p = imp->module_path; (void)graph; /* existence is the listed path, never a node found by name */ (void)project; + if (lang == CBM_LANG_CFML && imp->kind != CBM_IMPORT_KIND_TEMPLATE) { + return CBM_INCLUDE_PATH_NOT_A_PATH; /* a CFML import other than a template */ + } + if (!u || ip_failed(u)) { + return CBM_INCLUDE_PATH_NONE; /* no universe, or one an allocation failure left partial */ + } if (lang == CBM_LANG_CFML) { - return imp->kind == CBM_IMPORT_KIND_TEMPLATE ? ip_cfml_resolve(u, row, rel, p, buf, buf_sz) - : CBM_INCLUDE_PATH_NOT_A_PATH; + return ip_cfml_resolve(u, row, rel, p, buf, buf_sz); + } + if (row->dart_uri) { + return u->dart_failed ? CBM_INCLUDE_PATH_NONE : ip_dart_resolve(u, rel, p, buf, buf_sz); } if (row->path_needs_suffix) { bool named = false; @@ -490,7 +2323,7 @@ cbm_include_path_verdict_t cbm_include_path_resolve(const cbm_include_universe_t } } char dir[IP_PATH_MAX]; - if (!u || p[0] == '/' || strpbrk(p, "$`") || (row->virtual_path && !ip_virtual_ok(p)) || + if (p[0] == '/' || strpbrk(p, "$`") || (row->virtual_path && !ip_virtual_ok(p)) || !ip_dirname(dir, sizeof(dir), rel)) { return CBM_INCLUDE_PATH_NONE; /* a path the rule cannot read */ } @@ -529,8 +2362,8 @@ cbm_include_path_verdict_t cbm_include_path_resolve(const cbm_include_universe_t /* The file's Module node (named by its path) when it has one: the node a * module-path import named before; else its File node. Only a node of that - * exact file (a node found by name may be another file's); NULL when the file - * has neither. */ + * exact file: a node found by name may be another file's (lib/a.b.dart and + * lib/a/b.dart share one name). NULL when the file has neither. */ static const cbm_gbuf_node_t *ip_file_target(const cbm_pipeline_ctx_t *ctx, const char *path) { const cbm_gbuf_node_t **hits = NULL; int n = 0; @@ -577,18 +2410,41 @@ static bool ip_ends_with_path(const char *s, const char *tail) { return t > 0 && n >= t && strcmp(s + n - t, tail) == 0 && (n == t || s[n - t - 1] == '/'); } +/* The Dart row: a URI means at most one file, so a proposed target is taken + * only when it is a File or Module node (an import names a file, never a + * symbol in it) of the one file a relative URI means, against the importer's + * directory as the rule reads it (in its package's lib/ for a file under + * lib/): no tail match, no root candidate ('../../x.dart' from lib/a.dart is + * never tool/x.dart). A `package:` URI the rule does not decide + * (its resolution unread or undecided), `dart:` or another scheme: nothing. */ +static bool ip_dart_accepts(const cbm_pipeline_ctx_t *ctx, const char *rel, const char *p, + const cbm_gbuf_node_t *target) { + const char *label = target->label; + if (!ctx || !ctx->include_universe || !label || + (strcmp(label, "File") != 0 && strcmp(label, "Module") != 0) || + strncmp(p, "package:", IP_PACKAGE_SCHEME_LEN) == 0) { + return false; + } + char cand[IP_PATH_MAX]; + return ip_dart_relative(ctx->include_universe, rel, p, cand, sizeof(cand), true) == + CBM_INCLUDE_PATH_FILE && + strcmp(cand, target->file_path) == 0; +} + bool cbm_include_path_accepts(const cbm_pipeline_ctx_t *ctx, const char *rel, CBMLanguage lang, const CBMImport *imp, const cbm_gbuf_node_t *target) { const cbm_include_path_row_t *row = cbm_include_path_row(lang); if (!row || !target || lang == CBM_LANG_CFML) { return true; /* not a path row, nothing proposed, or CFML (see its row) */ } - (void)ctx; const char *fp = target->file_path; const char *p = imp ? imp->module_path : NULL; if (!fp || !p || !p[0] || !rel) { return false; } + if (row->dart_uri) { + return ip_dart_accepts(ctx, rel, p, target); + } /* the named path itself, or a file that ends with it */ if (ip_ends_with_path(fp, p)) { return true; @@ -631,7 +2487,9 @@ int cbm_include_path_inventory_digest(const cbm_file_info_t *files, int count, const char *rel = files[i].rel_path; const char *base = rel ? strrchr(rel, '/') : NULL; base = base ? base + SKIP_ONE : rel; - if (rel && rel[0] && (has_cfml || cbm_include_path_listed_name(base))) { + /* every path when a CFML template may name any file; else the names + * whose indexed set decides an answer (not a Dart file) */ + if (rel && rel[0] && (has_cfml || ip_keyed_name(base))) { sorted[n++] = rel; } } diff --git a/src/pipeline/include_path.h b/src/pipeline/include_path.h index 009576070..08068e843 100644 --- a/src/pipeline/include_path.h +++ b/src/pipeline/include_path.h @@ -21,12 +21,68 @@ * paths from the directory it runs in). A guess decides no IMPORTS edge (main * decides) and resolves no include of the shared layer. * + * Dart reads a URI, not a path, as the Dart SDK 3.14.1 resolves it (each + * case checked with `dart pub get`, `dart analyze` and `dart run`), with one + * exception by the project's decision: a version constraint on the + * repository's one package of that name takes that package, as the working + * setup does, where the SDK on the committed files takes the published copy. + * `package:/` names under the lib/ of + * the package stands for in the importer's resolution: the importer's + * package is the nearest indexed pubspec.yaml at or above it; its resolution + * (a workspace member's: its workspace's) holds the package itself and the + * workspace members, an override of the name (it counts when nothing depends + * on it), then the dependencies and dev_dependencies of those packages and + * the dependencies of every path dependency reached. pub takes one source per + * name for the whole closure: two sources at any depth leave the name + * undecided, two known ones make pub refuse the resolution (every package: + * answer of the root undecided), and an unread or unplaceable closure leaves + * the root's package: answers undecided too (a readable closure is the + * condition for any of them); an override replaces a dependency's source, and + * the dependency_overrides of a pubspec_overrides.yaml beside the pubspec + * replace the pubspec's own (a file without that key leaves them). A path + * dependency names the directory it states. A version constraint on a name + * exactly one indexed pubspec carries is that package (the working setup); + * git, a hosted URL, the SDK, and a version with two namesakes are undecided, + * with none no file. A name no level lists is one dart cannot + * resolve, or one reached only through a package outside the repository (no + * file). Undecided as well: two sources of one name at one level, a path + * dependency the rule cannot follow. `dart:` names a library of the SDK. Any + * other URI is relative to the importing library: a file under its package's + * lib/ is the library package:/..., so the URI stays in lib/ (`..` above + * it is dropped); any other file resolves on disk. A URI path ending in `/` + * names a directory (no file). The pubspecs are read once, when the universe + * is built, from the indexed pubspec.yaml files themselves, by the rule's own + * line reader, a whitelist: at the root a line is blank, a comment or a plain + * key (letters, digits, underscore, then a colon), and any other root line + * makes the pubspec unread; inside the sections it takes, an entry twice, a + * key of an entry twice, a scalar entry with a deeper line or a form it does + * not take makes it unread too. An unread pubspec makes that package's + * resolution undecided. It reads CRLF line ends and a quoted key without an + * escape (dart reads them), skips block scalars whole, and reads `key :` as + * key. A Dart manifest that cannot be read at all makes every Dart answer + * undecided (the Protobuf and Make answers read none). A workspace member + * outside its workspace's directory makes that workspace unread (pub refuses + * it), so a member's workspace is never one of two listings. + * The file a Dart URI names is one exact listed path: a node found by name is + * no proof (lib/a.b.dart and lib/a/b.dart share one File node name), a file + * of another letter case is not it (dart on a case-sensitive file system + * rejects the import), and no other indexed path takes part in the answer, so + * deleting a Dart file changes only the imports that named it (the closure + * repair re-resolves those, through their edges into it). The incremental key + * therefore holds the pubspecs, not the Dart files; an edited pubspec declines + * the closure repair. + * * Lifted from the parked include-scope branch (round 5, include_scope.c * section 2): its bases, exactly-one, tail index and import node; the shell * and Make evaluated paths and run directories stay there. * - * Threads: a universe is built once, from the file list, before any question, - * and is read-only afterwards: a question writes nothing (sealed at creation). + * Threads: a universe is built once, from the file list (and the indexed + * pubspec.yaml files), before any question. A Dart root's name table is made + * on that root's first question, by one walk over its closure, and kept, + * under the universe's lock (the walk marks shared packages and allocates + * from the universe's arena); every later question of the root is one lookup + * under that lock. Nothing else is written after the build. The answers do + * not depend on the order of the questions. */ #include "cbm.h" @@ -43,6 +99,14 @@ typedef struct { CBMLanguage lang; const char *const *suffixes; /* file names the listing keeps: ending in one of these */ const char *const *prefixes; /* ... or starting with one of these */ + /* ... or named exactly one of these: a file whose content decides where + * the row's imports point (Dart: pubspec.yaml, whose name, dependencies + * and workspace place a `package:` URI, and pubspec_overrides.yaml, whose + * dependency_overrides replace the pubspec's) */ + const char *const *root_names; + /* a Dart URI (`package:`, `dart:`, else relative to the importing file) + * instead of the bases and tail below */ + bool dart_uri; /* an import whose path does not end in one of `suffixes` is not a path * the rule reads (Protobuf: a row that names no `.proto` file) */ bool path_needs_suffix; @@ -61,11 +125,23 @@ const cbm_include_path_row_t *cbm_include_path_row(CBMLanguage lang); /* True for a file name the listing keeps (a name some row's import can name). */ bool cbm_include_path_listed_name(const char *name); +/* True for an indexed path whose content decides where a row's imports point + * (a root name: pubspec.yaml, pubspec_overrides.yaml). An edit of such a file + * changes which file an import of an unchanged file names. */ +bool cbm_include_path_root_file(const char *rel); + typedef struct cbm_include_universe cbm_include_universe_t; /* The universe of the run's indexed files (`files`, the discovered list of - * the run on every route): every file whose name a row's import can name. - * Built here, read-only afterwards. NULL on allocation failure. */ + * the run on every route): every file whose name a row's import can name, and + * the package of every indexed pubspec.yaml (read from `files[i].path`). + * NULL on allocation failure; a table insert that fails leaves a universe + * whose every answer is NONE, a Dart manifest that cannot be read one whose + * every Dart answer is NONE. Building costs the files' path segments and the + * pubspecs' lines. A Dart root costs its closure (the packages and entries + * its walk reaches) once, on its first question; each question one lookup. + * Roots that share a subgraph each walk it: r roots over h shared packages + * cost r times h (stated, not capped). */ cbm_include_universe_t *cbm_include_universe_new(const cbm_file_info_t *files, int count); void cbm_include_universe_free(cbm_include_universe_t *u); @@ -78,7 +154,9 @@ typedef enum { CBM_INCLUDE_PATH_FILE, /* names one indexed file (path in the buffer) */ CBM_INCLUDE_PATH_NONE, /* a path whose file the rule cannot tell (several, unknown) */ /* No indexed file can be selected: the path is absent, or the CFML - * mapping rule has no unique match. */ + * mapping rule has no unique match; Dart: the one path the URI names is + * not indexed, or the URI names an SDK library or a package outside the + * repository */ CBM_INCLUDE_PATH_NO_FILE, /* a file picked by an assumption the index cannot check (path in the * buffer): the include root or the directory make runs in. Not FILE: main @@ -95,12 +173,58 @@ cbm_include_path_verdict_t cbm_include_path_resolve(const cbm_include_universe_t const char *rel, CBMLanguage lang, const CBMImport *imp, char *buf, size_t buf_sz); +/* Which package a `package:` URI of the file `rel` names, by the source the + * importer's resolution gives the name (include_path.h, Dart). */ +typedef enum { + CBM_INCLUDE_DART_SELF = 0, /* (i) the importer's own package: exact */ + /* (ii) a path dependency (dev, override): exact; also a version + * constraint on the repository's one package of that name, whose + * directory the resolution takes as the source, as for a path */ + CBM_INCLUDE_DART_PATH, + CBM_INCLUDE_DART_TRANSITIVE, /* (ii) the same, a dependency of a path dependency: exact */ + CBM_INCLUDE_DART_MEMBER, /* (iii) a member of the importer's workspace: exact */ + /* (iv) a version constraint the rule does not answer: undecided with two + * or more namesakes or a pubspec it could not name, no file with none */ + CBM_INCLUDE_DART_PLAIN, + CBM_INCLUDE_DART_EXTERNAL, /* (v) git, a hosted URL, the SDK: as (iv) */ + CBM_INCLUDE_DART_UNLISTED, /* (vi) not in the resolution: no file (undecided when not whole) */ + CBM_INCLUDE_DART_UNDECIDED, /* no package, a form not read, two sources */ +} cbm_include_dart_class_t; + +cbm_include_dart_class_t cbm_include_path_dart_class(const cbm_include_universe_t *u, + const char *rel, const char *uri); + +#if defined(CBM_MEM_TEST_API) && CBM_MEM_TEST_API +/* Test-only, current thread: the nth table insert from now on fails as a + * failed allocation would (1 = the next one); reset disarms and returns + * whether it fired. */ +void cbm_include_path_test_fail_insert(int nth); +bool cbm_include_path_test_reset_insert_failure(void); +/* Test-only, current thread: the nth manifest read from now on fails as an + * unreadable file or a failed allocation would; reset disarms and returns + * whether it fired. */ +void cbm_include_path_test_fail_read(int nth); +bool cbm_include_path_test_reset_read_failure(void); +/* Test-only: the steps this thread's rule has counted (building a universe, + * answering), for growth tests. */ +uint64_t cbm_include_path_test_steps(void); +/* Test-only, current thread: the nth answer array a finished Dart walk makes + * from now on fails as a failed allocation would; reset disarms and returns + * whether it fired. */ +void cbm_include_path_test_fail_answers(int nth); +bool cbm_include_path_test_reset_answers_failure(void); +/* Test-only: the answer-array slots this thread has examined (putting an + * answer, looking one up), for growth tests that must see collisions. */ +uint64_t cbm_include_path_test_probes(void); +#endif + /* The IMPORTS target of an import, for resolve_import_strategies: true when * the path rule decides it, with *out the target node (the file's Module node * when it has one, else its File node) or NULL: no edge (the named file has no - * node, or no indexed file is named; a symbol is never the target of a - * statement that names a file). False: main's strategies propose a target (a - * guess is not a decision), which cbm_include_path_accepts judges. */ + * node, or no indexed file is named; the rule never decides a symbol as the + * target of a statement that names a file). False: main's strategies propose + * a target (a guess is not a decision), which cbm_include_path_accepts + * judges. */ bool cbm_include_path_decides(const cbm_pipeline_ctx_t *ctx, const char *rel, CBMLanguage lang, const CBMImport *imp, const cbm_gbuf_node_t **out); @@ -111,15 +235,20 @@ bool cbm_include_path_decides(const cbm_pipeline_ctx_t *ctx, const char *rel, CB * own candidates (the path from the importer's directory or the root, `.` and * `..` folded). The bytes are compared exactly: a file of another letter case * names the file on a case-insensitive disk only, so it stays no edge. False: - * no edge (the dotted name strategies would reach a/b.mk for `a.b.mk`). True + * no edge (the dotted name strategies would reach a/b.mk for `a.b.mk`). The + * Dart row: only a File or Module node of the one file a relative URI means + * (against the importer's directory as the rule reads it, no tail, no root + * candidate); nothing for a `package:` URI the rule does not decide. True * for any other language, for CFML (a template is always decided; any other * CFML import is no path) and for no target. */ bool cbm_include_path_accepts(const cbm_pipeline_ctx_t *ctx, const char *rel, CBMLanguage lang, const CBMImport *imp, const cbm_gbuf_node_t *target); -/* The semantic-manifest key of the universe: every indexed path a row's - * import can name, sorted, hashed. Reads the list only (no disk). Returns 0, - * or -1 on allocation failure. */ +/* The semantic-manifest key of the universe: every indexed path whose set + * decides answers for other paths (a name the Protobuf and Make rows keep, and + * every pubspec.yaml; not a Dart file; every path when the repository holds a + * CFML file, since a template may name any file), sorted, hashed. Reads the + * list only (no disk). Returns 0, or -1 on allocation failure. */ int cbm_include_path_inventory_digest(const cbm_file_info_t *files, int count, char out[CBM_SHA256_HEX_LEN + 1]); diff --git a/src/pipeline/pipeline_incremental.c b/src/pipeline/pipeline_incremental.c index 276ae0d26..e9e21247e 100644 --- a/src/pipeline/pipeline_incremental.c +++ b/src/pipeline/pipeline_incremental.c @@ -3497,6 +3497,13 @@ static int closure_try_plan(cbm_pipeline_t *p, cbm_store_t *store, const char *p decline = "new_file"; goto done; } + if (cbm_include_path_root_file(fresh[i].rel_path)) { + /* a pubspec.yaml or pubspec_overrides.yaml: what it declares + * decides which file a `package:` import of an unchanged Dart + * file names (include_path.h) */ + decline = "include_root_changed"; + goto done; + } changed_paths[n_changed++] = (char *)fresh[i].rel_path; continue; } diff --git a/tests/test_include_path.c b/tests/test_include_path.c index 13c40d96c..50ead215b 100644 --- a/tests/test_include_path.c +++ b/tests/test_include_path.c @@ -3,6 +3,7 @@ * indexed file a CFML, Protobuf or Make import names. */ #include "../src/foundation/compat.h" +#include "../src/foundation/log.h" #include "test_framework.h" #include "test_helpers.h" #include "../src/pipeline/include_path.h" @@ -391,6 +392,1322 @@ TEST(include_path_cfml_long_paths_preserve_tail_counts) { PASS(); } +/* ── Dart: package, relative and dart: URIs ──────────────────────────────── */ + +/* Writes the files (path, content pairs, NULL-terminated) under `root` and + * makes the universe of them, every one indexed and read from its path; and + * `extra` (NULL for none), indexed with no file to read. */ +static cbm_include_universe_t *ip_dart_universe(const char *root, const char *const *files, + const char *extra) { + enum { IP_DART_MAX = 64 }; + cbm_file_info_t list[IP_DART_MAX + 1]; + static char paths[IP_DART_MAX][512]; + int n = 0; + for (; files[2 * n] && n < IP_DART_MAX; n++) { + snprintf(paths[n], sizeof(paths[n]), "%s/%s", root, files[2 * n]); + if (th_write_file(paths[n], files[2 * n + 1]) != 0) { + return NULL; + } + memset(&list[n], 0, sizeof(list[n])); + list[n].rel_path = (char *)files[2 * n]; + list[n].path = paths[n]; + } + if (extra) { + memset(&list[n], 0, sizeof(list[n])); + list[n++].rel_path = (char *)extra; + } + return cbm_include_universe_new(list, n); +} + +/* The run's File nodes of the files (path, content pairs) in a graph of + * project "ipd", as the pipeline makes them. */ +static cbm_gbuf_t *ip_dart_graph(const char *const *files) { + cbm_gbuf_t *g = cbm_gbuf_new("ipd", "/"); + for (int i = 0; g && files[2 * i]; i++) { + char *qn = cbm_pipeline_fqn_compute("ipd", files[2 * i], "__file__"); + const char *slash = strrchr(files[2 * i], '/'); + (void)cbm_gbuf_upsert_node(g, "File", slash ? slash + 1 : files[2 * i], qn, files[2 * i], + 0, 0, "{}"); + free(qn); + } + return g; +} + +/* The verdict for a Dart import `path` of the file `rel` with the graph's + * File nodes, the file in *out. */ +static cbm_include_path_verdict_t ip_dask(cbm_include_universe_t *u, cbm_gbuf_t *g, + const char *rel, const char *path, char *out, + size_t out_sz) { + CBMImport imp; + memset(&imp, 0, sizeof(imp)); + imp.module_path = path; + out[0] = '\0'; + return cbm_include_path_resolve(u, g, g ? "ipd" : NULL, rel, CBM_LANG_DART, &imp, out, + out_sz); +} + +#define IP_DFILE(rel, uri, want) \ + do { \ + ASSERT_EQ(ip_dask(u, g, (rel), (uri), got, sizeof(got)), CBM_INCLUDE_PATH_FILE); \ + ASSERT_STR_EQ(got, (want)); \ + } while (0) +#define IP_DVERDICT(rel, uri, want) \ + ASSERT_EQ(ip_dask(u, g, (rel), (uri), got, sizeof(got)), (want)) + +#define IP_DCLASS(rel, uri, want) \ + ASSERT_EQ(cbm_include_path_dart_class(u, (rel), (uri)), (want)) + +/* A repository path of more than 1024 bytes ending in `/name`. */ +static const char *ip_long_path(char *buf, size_t sz, const char *name) { + size_t n = 0; + while (n + 5 + strlen(name) + 1 < sz && n < 1100) { + memcpy(buf + n, "deep/", 5); + n += 5; + } + snprintf(buf + n, sz - n, "%s", name); + return buf; +} + +/* The incremental key of a file list (rel paths, NULL-terminated). */ +static void ip_digest_of(const char *const *rels, char out[CBM_SHA256_HEX_LEN + 1]) { + cbm_file_info_t f[16]; + int n = 0; + for (; rels[n] && n < 16; n++) { + memset(&f[n], 0, sizeof(f[n])); + f[n].rel_path = (char *)rels[n]; + } + (void)cbm_include_path_inventory_digest(f, n, out); +} + +/* The URI fixture: every question is asked with the run's File nodes (a + * node found by name proves no file); each verdict is the one the Dart SDK + * 3.14.1 gives (each case run through `dart analyze` and `dart run`). */ +static const char *const IP_URI_FILES[] = { + "pubspec.yaml", "name: app\n", + "lib/app.dart", "", + "lib/src/u.dart", "", + "lib/a/b.dart", "", + "lib/x.y.dart", "", + "lib/deep/app2.dart", "", + "lib/c.dart", "", + "c.dart", "", + "core/c.dart", "", + "test/t.dart", "", + "bin/main.dart", "", + "bin/a.dart", "", + "bin/sub/a.dart", "", + "bin/u.dart", "", + "lib/u.dart", "", + "lib/sub/a.dart", "", + "tool/Gen.dart", "", + NULL}; + +#define IP_URI_SETUP(tag) \ + char *made = th_mktempdir(tag); \ + ASSERT_NOT_NULL(made); \ + char tmp[256]; \ + snprintf(tmp, sizeof(tmp), "%s", made); \ + cbm_include_universe_t *u = ip_dart_universe(tmp, IP_URI_FILES, NULL); \ + ASSERT_NOT_NULL(u); \ + cbm_gbuf_t *g = ip_dart_graph(IP_URI_FILES); \ + ASSERT_NOT_NULL(g); \ + char got[1024]; \ + const char *app = "lib/app.dart"; \ + const char *bin = "bin/main.dart"; \ + (void)app; \ + (void)bin +#define IP_URI_DONE() \ + do { \ + cbm_gbuf_free(g); \ + cbm_include_universe_free(u); \ + th_cleanup(tmp); \ + } while (0) + +/* The URI rule: relative, package and dart: URIs, a file of another letter + * case (not the file), the URIs left undecided; over-long paths; the listing + * and its incremental key. */ +TEST(include_path_dart_uri_rule) { + IP_URI_SETUP("cbm_ip_dart"); + IP_DFILE(app, "src/u.dart", "lib/src/u.dart"); + IP_DFILE(app, "./src/u.dart", "lib/src/u.dart"); + IP_DFILE(app, "package:app/src/u.dart", "lib/src/u.dart"); + /* another letter case; the SDK */ + IP_DVERDICT(bin, "../tool/gen.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT(app, "dart:async", CBM_INCLUDE_PATH_NO_FILE); + /* undecided, never a guess: `..` in a package path (not decided by + * dart), a URI with no path, no name, another scheme, an escape, a path + * out of the repository */ + IP_DVERDICT(app, "package:app/../x.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:app", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:/x.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "https://example.com/x.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(bin, "%61.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(bin, "../../x.dart", CBM_INCLUDE_PATH_NONE); + cbm_gbuf_free(g); + cbm_include_universe_free(u); + + /* a path too long for the rule: a Dart file of it changes no answer, the + * Protobuf tails' included; a pubspec of it changes none of a file whose + * package it cannot be */ + static const char *const fits[] = { + "pubspec.yaml", "name: app\n", + "lib/app.dart", "", + "lib/src/u.dart", "", + "api/a.proto", "syntax = \"proto3\";\n", + "x/common.proto", "syntax = \"proto3\";\n", + NULL}; + char longp[1200]; + char tmp3[512]; + snprintf(tmp3, sizeof(tmp3), "%s/three", tmp); + g = NULL; + u = ip_dart_universe(tmp3, fits, ip_long_path(longp, sizeof(longp), "f.dart")); + ASSERT_NOT_NULL(u); + IP_DFILE(app, "package:app/src/u.dart", "lib/src/u.dart"); + IP_DVERDICT(app, "package:flutter/material.dart", CBM_INCLUDE_PATH_NO_FILE); + ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/a.proto", "common.proto", got, sizeof(got)), + CBM_INCLUDE_PATH_FILE); + ASSERT_STR_EQ(got, "x/common.proto"); + cbm_include_universe_free(u); + u = ip_dart_universe(tmp3, fits, ip_long_path(longp, sizeof(longp), "pubspec.yaml")); + ASSERT_NOT_NULL(u); + IP_DFILE(app, "package:app/src/u.dart", "lib/src/u.dart"); + IP_DFILE(app, "src/u.dart", "lib/src/u.dart"); + cbm_include_universe_free(u); + + /* the listing keeps Dart files and pubspecs; a pubspec is a root file */ + ASSERT_TRUE(cbm_include_path_listed_name("a.dart")); + ASSERT_TRUE(cbm_include_path_listed_name("pubspec.yaml")); + ASSERT_FALSE(cbm_include_path_listed_name("pubspec.lock")); + ASSERT_TRUE(cbm_include_path_root_file("packages/core/pubspec.yaml")); + ASSERT_TRUE(cbm_include_path_root_file("pubspec.yaml")); + ASSERT_TRUE(cbm_include_path_root_file("examples/a/pubspec_overrides.yaml")); + ASSERT_FALSE(cbm_include_path_root_file("lib/pubspec.yaml.dart")); + ASSERT_FALSE(cbm_include_path_root_file("api/a.proto")); + + /* the incremental key holds the pubspecs and the Protobuf files, not the + * Dart files: a Dart file added or deleted leaves it as it is */ + static const char *const k0[] = {"pubspec.yaml", "lib/a.dart", "api/a.proto", NULL}; + static const char *const k1[] = {"pubspec.yaml", "lib/a.dart", "lib/b.dart", "api/a.proto", + NULL}; + static const char *const k2[] = {"pubspec.yaml", "lib/a.dart", "core/pubspec.yaml", + "api/a.proto", NULL}; + static const char *const k3[] = {"pubspec.yaml", "lib/a.dart", NULL}; + static const char *const k4[] = {"pubspec.yaml", "pubspec_overrides.yaml", "lib/a.dart", + "api/a.proto", NULL}; + char d4[CBM_SHA256_HEX_LEN + 1]; + ip_digest_of(k4, d4); + char d0[CBM_SHA256_HEX_LEN + 1]; + char d1[CBM_SHA256_HEX_LEN + 1]; + char d2[CBM_SHA256_HEX_LEN + 1]; + char d3[CBM_SHA256_HEX_LEN + 1]; + ip_digest_of(k0, d0); + ip_digest_of(k1, d1); + ip_digest_of(k2, d2); + ip_digest_of(k3, d3); + ASSERT_STR_EQ(d1, d0); + ASSERT_STR_NEQ(d2, d0); + ASSERT_STR_NEQ(d3, d0); + ASSERT_STR_NEQ(d4, d0); + th_cleanup(tmp); + PASS(); +} + +/* lib/a.b.dart and lib/a/b.dart share one File node name; 'a.b.dart' + * names no file when only lib/a/b.dart exists, 'x/y.dart' none when only + * lib/x.y.dart does, relative and package form (dart: uri_does_not_exist + * both ways). */ +TEST(include_path_dart_exact_path_not_node_name) { + IP_URI_SETUP("cbm_ip_df1"); + /* both directions, both forms */ + IP_DFILE(app, "a/b.dart", "lib/a/b.dart"); + IP_DVERDICT(app, "a.b.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT(bin, "package:app/a.b.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DFILE(app, "x.y.dart", "lib/x.y.dart"); + IP_DVERDICT(app, "x/y.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT(bin, "package:app/x/y.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_URI_DONE(); + PASS(); +} + +/* A file under lib/ is a package library, its relative URIs stay in + * lib/: '../test/t.dart' from lib/app.dart is lib/test/t.dart + * (uri_does_not_exist), '../core/c.dart' lib/core/c.dart, '../../c.dart' + * from lib/deep/ lib/c.dart (fixtures f2_*); a file outside lib/ resolves on + * disk. */ +TEST(include_path_dart_lib_is_package_space) { + IP_URI_SETUP("cbm_ip_df2"); + /* out of lib/ stays in lib/ */ + IP_DVERDICT(app, "../test/t.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT(app, "../core/c.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DFILE(app, "../c.dart", "lib/c.dart"); + IP_DFILE("lib/deep/app2.dart", "../../c.dart", "lib/c.dart"); + IP_DFILE("lib/deep/app2.dart", "../c.dart", "lib/c.dart"); + IP_DFILE(bin, "../lib/c.dart", "lib/c.dart"); + IP_DFILE("test/t.dart", "../c.dart", "c.dart"); + IP_DFILE("test/t.dart", "../core/c.dart", "core/c.dart"); + IP_URI_DONE(); + PASS(); +} + +/* `..` removes an empty segment (`sub//../a.dart` is bin/sub/a.dart); an + * empty segment left names the file without it, in a relative and in a + * package URI. */ +TEST(include_path_dart_dot_segments_in_order) { + IP_URI_SETUP("cbm_ip_df3"); + /* empty segments */ + IP_DFILE(bin, "sub//../a.dart", "bin/sub/a.dart"); + IP_DFILE(bin, "sub//a.dart", "bin/sub/a.dart"); + IP_DFILE(bin, "package:app/sub//a.dart", "lib/sub/a.dart"); + IP_DFILE(bin, "sub/../a.dart", "bin/a.dart"); + IP_URI_DONE(); + PASS(); +} + +/* A URI path ending in `/` names a directory: no file (dart fails to + * read 'u.dart/' and 'package:app/u.dart/', fixtures f4_*). */ +TEST(include_path_dart_directory_uri) { + IP_URI_SETUP("cbm_ip_df4"); + /* a directory */ + IP_DVERDICT(bin, "u.dart/", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT(bin, "package:app/u.dart/", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT(bin, "sub/.", CBM_INCLUDE_PATH_NO_FILE); + IP_URI_DONE(); + PASS(); +} + +/* A package URI is read by the importer's own pubspec, as the Dart SDK 3.14.1 + * resolves it (each case run through `dart pub get` and `dart run`): + * (i) the package itself, listed nowhere: exact; + * (ii) a path dependency, dev_dependency or override: the directory it + * states; a dependency of a path dependency too, its dev_dependency + * not (uri_does_not_exist); + * (iii) a member of the importer's workspace, listed or not; + * (iv) a version constraint: the one indexed pubspec of that name when + * exactly one carries it (the project's decision, the + * working setup; by the committed files pub reads the published copy), + * undecided when two do, no file when none does; + * (v) git, a hosted URL, the SDK: no file, also with an indexed namesake; + * (vi) a name the resolution does not hold: no file (uri_does_not_exist). + * Two pubspecs of one name elsewhere do not touch the importer's own. */ +TEST(include_path_dart_package_classes) { + char *made = th_mktempdir("cbm_ip_dcls"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const char *const files[] = { + "pubspec.yaml", + "name: app\n" + "dependencies:\n" + " core:\n" + " path: packages/core\n" + " mid:\n" + " path: mid\n" + " plain: ^2.0.0\n" + " hosted_only: ^3.0.0\n" + " gitp:\n" + " git: https://example.com/gitp.git\n" + " hostp:\n" + " hosted: https://pub.example.com\n" + " version: ^1.0.0\n" + " flutter:\n" + " sdk: flutter\n" + " ov: ^1.0.0 # overridden below\n" + "dev_dependencies:\n" + " devp:\n" + " path: ./devp/\n" + "dependency_overrides:\n" + " ov:\n" + " path: 'ovdir'\n", + "lib/app.dart", "", + "lib/x.dart", "", + "packages/core/pubspec.yaml", "name: core\n", + "packages/core/lib/core.dart", "", + "mid/pubspec.yaml", + "name: mid\ndependencies:\n trans:\n path: ../trans\n" + "dev_dependencies:\n middev:\n path: ../middev\n", + "mid/lib/mid.dart", "", + "trans/pubspec.yaml", "name: trans\n", + "trans/lib/t.dart", "", + "middev/pubspec.yaml", "name: middev\n", + "middev/lib/m.dart", "", + "devp/pubspec.yaml", "name: devp\n", + "devp/lib/d.dart", "", + "ovdir/pubspec.yaml", "name: ov\n", + "ovdir/lib/o.dart", "", + "plain/pubspec.yaml", "name: plain\n", + "plain/lib/p.dart", "", + "gitp/pubspec.yaml", "name: gitp\n", + "gitp/lib/g.dart", "", + "vendor/dep/pubspec.yaml", "name: dep\n", + "vendor/dep/lib/a.dart", "", + "ws/pubspec.yaml", "name: ws\nworkspace:\n - a\n - b\n - c\n", + "ws/a/pubspec.yaml", "name: a\nresolution: workspace\ndependencies:\n b: any\n", + "ws/a/lib/a.dart", "", + "ws/b/pubspec.yaml", "name: b\nresolution: workspace\n", + "ws/b/lib/b.dart", "", + "ws/c/pubspec.yaml", "name: c\nresolution: workspace\n", + "ws/c/lib/c.dart", "", + "dup1/pubspec.yaml", "name: dup\n", + "dup1/bin/main.dart", "", + "dup1/bin/d.dart", "", + "dup1/lib/d.dart", "", + "dup2/pubspec.yaml", "name: dup\n", + "dup2/lib/d.dart", "", + NULL}; + cbm_include_universe_t *u = ip_dart_universe(tmp, files, NULL); + ASSERT_NOT_NULL(u); + cbm_gbuf_t *g = ip_dart_graph(files); + ASSERT_NOT_NULL(g); + char got[1024]; + const char *app = "lib/app.dart"; + IP_DFILE(app, "package:app/x.dart", "lib/x.dart"); + IP_DCLASS(app, "package:app/x.dart", CBM_INCLUDE_DART_SELF); + IP_DFILE(app, "package:core/core.dart", "packages/core/lib/core.dart"); + IP_DCLASS(app, "package:core/core.dart", CBM_INCLUDE_DART_PATH); + IP_DFILE(app, "package:trans/t.dart", "trans/lib/t.dart"); + IP_DCLASS(app, "package:trans/t.dart", CBM_INCLUDE_DART_TRANSITIVE); + IP_DFILE(app, "package:devp/d.dart", "devp/lib/d.dart"); + IP_DFILE(app, "package:ov/o.dart", "ovdir/lib/o.dart"); + IP_DVERDICT(app, "package:middev/m.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DFILE(app, "package:plain/p.dart", "plain/lib/p.dart"); + IP_DCLASS(app, "package:plain/p.dart", CBM_INCLUDE_DART_PATH); + /* a version constraint no indexed pubspec answers: no repository file */ + IP_DVERDICT(app, "package:hosted_only/h.dart", CBM_INCLUDE_PATH_NO_FILE); + /* git with an indexed pubspec of that name: undecided (an override the + * index cannot see may point at it); without one: no file */ + IP_DVERDICT(app, "package:gitp/g.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:hostp/h.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT(app, "package:flutter/material.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DCLASS(app, "package:flutter/material.dart", CBM_INCLUDE_DART_EXTERNAL); + IP_DVERDICT(app, "package:dep/a.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DCLASS(app, "package:dep/a.dart", CBM_INCLUDE_DART_UNLISTED); + IP_DVERDICT(app, "package:core/gone.dart", CBM_INCLUDE_PATH_NO_FILE); + /* the workspace */ + const char *wa = "ws/a/lib/a.dart"; + IP_DFILE(wa, "package:b/b.dart", "ws/b/lib/b.dart"); + IP_DCLASS(wa, "package:b/b.dart", CBM_INCLUDE_DART_MEMBER); + IP_DFILE(wa, "package:c/c.dart", "ws/c/lib/c.dart"); + IP_DFILE(wa, "package:a/a.dart", "ws/a/lib/a.dart"); + IP_DVERDICT(wa, "package:core/core.dart", CBM_INCLUDE_PATH_NO_FILE); + /* the importer's own package among two of one name */ + IP_DFILE("dup1/bin/main.dart", "package:dup/d.dart", "dup1/lib/d.dart"); + cbm_gbuf_free(g); + cbm_include_universe_free(u); + th_cleanup(tmp); + PASS(); +} + +/* A pubspec_overrides.yaml beside the importer's pubspec: its + * dependency_overrides replace the pubspec's (alone, against the pubspec's + * own overrides, and replacing them whole); one beside a dependency's + * pubspec takes no part in the importer's resolution. */ +TEST(include_path_dart_overrides_file) { + char *made = th_mktempdir("cbm_ip_dovf"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const char *const files[] = { + "pubspec.yaml", + "name: app\ndependencies:\n core: ^1.0.0\n x: ^1.0.0\n mid:\n path: mid\n" + "dependency_overrides:\n core:\n path: a\n x:\n path: x\n", + "pubspec_overrides.yaml", "dependency_overrides:\n core:\n path: b\n", + "lib/app.dart", "", + "a/pubspec.yaml", "name: core\n", + "a/lib/core.dart", "", + "b/pubspec.yaml", "name: core\n", + "b/lib/core.dart", "", + "x/pubspec.yaml", "name: x\n", + "x/lib/x.dart", "", + "mid/pubspec.yaml", "name: mid\ndependencies:\n dep: ^1.0.0\n", + "mid/pubspec_overrides.yaml", "dependency_overrides:\n dep:\n path: ../dep\n", + "mid/lib/mid.dart", "", + "dep/pubspec.yaml", "name: dep\n", + "dep/lib/dep.dart", "", + NULL}; + cbm_include_universe_t *u = ip_dart_universe(tmp, files, NULL); + ASSERT_NOT_NULL(u); + cbm_gbuf_t *g = NULL; + char got[1024]; + const char *app = "lib/app.dart"; + IP_DFILE(app, "package:core/core.dart", "b/lib/core.dart"); + /* the pubspec's own override of x is replaced: x is a version constraint, + * and x/ the one package of that name (the in-repo version rule; dart on + * the committed files reads the published copy) */ + IP_DFILE(app, "package:x/x.dart", "x/lib/x.dart"); + IP_DFILE(app, "package:dep/dep.dart", "dep/lib/dep.dart"); + IP_DCLASS(app, "package:dep/dep.dart", CBM_INCLUDE_DART_TRANSITIVE); + /* mid's own files resolve with mid's overrides */ + IP_DFILE("mid/lib/mid.dart", "package:dep/dep.dart", "dep/lib/dep.dart"); + cbm_include_universe_free(u); + th_cleanup(tmp); + PASS(); +} + +/* The rule's pubspec reader: a templated pubspec elsewhere (`name: + * {{projectName}}`) touches no answer of another package, and its own files' + * package URIs are undecided; a block scalar's indented `name:` line is no + * name; a quoted name with a comment, CRLF lines; forms the reader does not + * take leave a name undecided and the resolution not whole (no name is then + * provably absent); a path dependency with no indexed pubspec, or another + * name there, is undecided; a file with no pubspec above it has no package. */ +TEST(include_path_dart_pubspec_reader) { + char *made = th_mktempdir("cbm_ip_drd"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const char *const files[] = { + "pubspec.yaml", + "description: |\n" + " name: evil\n" + "name: app\n" + "dependencies:\n" + " core:\n" + " path: core\n", + "lib/app.dart", "", + "lib/x.dart", "", + "evil/lib/x.dart", "", + "core/pubspec.yaml", "name: \"core\" # the core\r\nversion: 1.0.0\r\n", + "core/lib/core.dart", "", + "tpl/pubspec.yaml", "name: {{projectName}}\n", + "tpl/lib/t.dart", "", + NULL}; + cbm_include_universe_t *u = ip_dart_universe(tmp, files, NULL); + ASSERT_NOT_NULL(u); + cbm_gbuf_t *g = NULL; + char got[1024]; + const char *app = "lib/app.dart"; + IP_DFILE(app, "package:app/x.dart", "lib/x.dart"); + IP_DVERDICT(app, "package:evil/x.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DFILE(app, "package:core/core.dart", "core/lib/core.dart"); + IP_DVERDICT("tpl/lib/t.dart", "package:core/core.dart", CBM_INCLUDE_PATH_NONE); + cbm_include_universe_free(u); + + /* a form the reader does not take (a flow map) leaves the whole + * resolution undecided, the package's own URIs included; a path + * dependency with no indexed pubspec, or another name there, is + * undecided; a file with no pubspec above it has no package */ + static const char *const odd[] = { + "pubspec.yaml", + "name: app\ndependencies:\n flowp: {path: flowp}\n ext:\n path: ext\n" + " other:\n path: named\n", + "lib/app.dart", "", + "flowp/pubspec.yaml", "name: flowp\n", + "flowp/lib/f.dart", "", + "ext/lib/e.dart", "", + "named/pubspec.yaml", "name: named\n", + "named/lib/n.dart", "", + "vendor/dep/pubspec.yaml", "name: dep\n", + "vendor/dep/lib/a.dart", "", + NULL}; + char tmp2[512]; + snprintf(tmp2, sizeof(tmp2), "%s/two", tmp); + u = ip_dart_universe(tmp2, odd, NULL); + ASSERT_NOT_NULL(u); + g = NULL; + IP_DVERDICT(app, "package:flowp/f.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:ext/e.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:other/n.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:dep/a.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:app/app.dart", CBM_INCLUDE_PATH_NONE); + cbm_include_universe_free(u); + static const char *const odd2[] = { + "pubspec.yaml", "name: app\ndependencies:\n ext:\n path: ext\n other:\n path: named\n", + "lib/app.dart", "", + "ext/lib/e.dart", "", + "named/pubspec.yaml", "name: named\n", + "named/lib/n.dart", "", + "vendor/dep/pubspec.yaml", "name: dep\n", + "vendor/dep/lib/a.dart", "", + NULL}; + char tmp3[512]; + snprintf(tmp3, sizeof(tmp3), "%s/three", tmp); + u = ip_dart_universe(tmp3, odd2, NULL); + ASSERT_NOT_NULL(u); + IP_DVERDICT(app, "package:ext/e.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:other/n.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:dep/a.dart", CBM_INCLUDE_PATH_NONE); + /* a source the reader cannot place (a path with no pubspec, another name + * there: pub refuses both) leaves the whole root undecided, its own + * package's URIs included: a readable closure is the condition) */ + IP_DVERDICT(app, "package:app/app.dart", CBM_INCLUDE_PATH_NONE); + cbm_include_universe_free(u); + static const char *const nopub[] = { + "src/a.dart", "", + "src/b.dart", "", + "pkg/pubspec.yaml", "name: pkg\n", + "pkg/lib/p.dart", "", + NULL}; + char tmp4[512]; + snprintf(tmp4, sizeof(tmp4), "%s/four", tmp); + u = ip_dart_universe(tmp4, nopub, NULL); + ASSERT_NOT_NULL(u); + IP_DVERDICT("src/a.dart", "package:pkg/p.dart", CBM_INCLUDE_PATH_NONE); + IP_DFILE("src/a.dart", "b.dart", "src/b.dart"); + cbm_include_universe_free(u); + th_cleanup(tmp); + PASS(); +} + +/* How many IMPORTS edges go from a node of the file `src` to a node of the + * file `tgt` with the label `label` (repository paths; tgt NULL: any node). */ +static int ip_file_imports_to(const char *db, const char *src, const char *tgt, + const char *label) { + sqlite3 *h = NULL; + if (sqlite3_open_v2(db, &h, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { + sqlite3_close(h); + return -1; + } + sqlite3_stmt *st = NULL; + int n = -1; + if (sqlite3_prepare_v2(h, + "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 = 'IMPORTS' " + "AND s.file_path = ?1 AND (?2 IS NULL OR t.file_path = ?2) " + "AND (?3 IS NULL OR t.label = ?3)", + -1, &st, NULL) == SQLITE_OK) { + sqlite3_bind_text(st, 1, src, -1, SQLITE_TRANSIENT); + if (tgt) { + sqlite3_bind_text(st, 2, tgt, -1, SQLITE_TRANSIENT); + } + if (label) { + sqlite3_bind_text(st, 3, label, -1, SQLITE_TRANSIENT); + } + if (sqlite3_step(st) == SQLITE_ROW) { + n = sqlite3_column_int(st, 0); + } + } + sqlite3_finalize(st); + sqlite3_close(h); + return n; +} + +static int ip_file_imports(const char *db, const char *src, const char *tgt) { + return ip_file_imports_to(db, src, tgt, NULL); +} + +/* The IMPORTS edges of Dart files: each URI that names a file reaches that + * file's Module node (label and file asserted), and nothing else; a URI that + * names no file draws no edge at all. The cases main's strategies get wrong: + * '../../c.dart' from lib/deep/ (main: the root's c.dart), '../core/c.dart' + * from lib/ (main: core/c.dart), 'a/b.dart' when only lib/a.b.dart exists + * (one File node name), and a package of the importer's resolution whose + * name another pubspec shares. */ +TEST(include_path_dart_edges_name_the_package_file) { + char *made = th_mktempdir("cbm_ip_dedges"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char dir[512]; + snprintf(dir, sizeof(dir), "%s/repo", tmp); + ASSERT_EQ(th_write_file(TH_PATH(dir, "pubspec.yaml"), + "name: app\ndependencies:\n core:\n path: packages/core\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "lib/app.dart"), + "import 'package:app/src/util.dart';\n" + "import 'package:core/core.dart';\n" + "import 'package:flutter/material.dart';\n" + "import 'dart:async';\n" + "\nvoid run() { util(); Core(); }\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "lib/src/util.dart"), "void util() {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "lib/deep/up.dart"), + "import '../../c.dart';\n\nvoid up() { c(); }\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "lib/c.dart"), "void c() {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "c.dart"), "void c() {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "lib/out.dart"), + "import '../core/c.dart';\n\nvoid out() { cc(); }\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "core/c.dart"), "void cc() {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "lib/m.dart"), "import 'a/b.dart';\n\nvoid m() {}\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "lib/a.b.dart"), "void ab() {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "packages/core/pubspec.yaml"), "name: core\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "packages/core/lib/core.dart"), "class Core {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "fork/pubspec.yaml"), "name: core\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "fork/lib/core.dart"), "class Core {}\n"), 0); + /* same-named files of the repository: no import above names them */ + ASSERT_EQ(th_write_file(TH_PATH(dir, "tool/material.dart"), "class Material {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "tool/async.dart"), "void waitFor() {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "tool/util.dart"), "void util() {}\n"), 0); + char db[512]; + snprintf(db, sizeof(db), "%s/dart.db", tmp); + cbm_pipeline_t *p = cbm_pipeline_new(dir, db, CBM_MODE_FULL); + ASSERT_NOT_NULL(p); + ASSERT_EQ(cbm_pipeline_run(p), 0); + cbm_pipeline_free(p); + const char *app = "lib/app.dart"; + ASSERT_EQ(ip_file_imports_to(db, app, "lib/src/util.dart", "Module"), 1); + ASSERT_EQ(ip_file_imports_to(db, app, "packages/core/lib/core.dart", "Module"), 1); + ASSERT_EQ(ip_file_imports_to(db, app, NULL, NULL), 2); + ASSERT_EQ(ip_file_imports_to(db, "lib/deep/up.dart", "lib/c.dart", "Module"), 1); + ASSERT_EQ(ip_file_imports_to(db, "lib/deep/up.dart", NULL, NULL), 1); + ASSERT_EQ(ip_file_imports_to(db, "lib/out.dart", NULL, NULL), 0); + ASSERT_EQ(ip_file_imports_to(db, "lib/m.dart", NULL, NULL), 0); + th_cleanup(tmp); + PASS(); +} + +/* The IMPORTS target of a file the rule names is a node of that file: a + * File node found by name is another file's when the names collide (a root + * Makefile's `include a.b.mk` with only a/b.mk indexed: the existence check of + * the Make row takes the colliding node, the target must not). */ +TEST(include_path_file_target_is_that_file) { + char *made = th_mktempdir("cbm_ip_target"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char dir[512]; + snprintf(dir, sizeof(dir), "%s/repo", tmp); + ASSERT_EQ(th_write_file(TH_PATH(dir, "Makefile"), "include a.b.mk\ninclude x/y.mk\n\nall:\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "a/b.mk"), "B = 1\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(dir, "x/y.mk"), "Y = 1\n"), 0); + char db[512]; + snprintf(db, sizeof(db), "%s/make.db", tmp); + cbm_pipeline_t *p = cbm_pipeline_new(dir, db, CBM_MODE_FULL); + ASSERT_NOT_NULL(p); + ASSERT_EQ(cbm_pipeline_run(p), 0); + cbm_pipeline_free(p); + ASSERT_EQ(ip_file_imports(db, "Makefile", "x/y.mk"), 1); + ASSERT_EQ(ip_file_imports(db, "Makefile", "a/b.mk"), 0); + th_cleanup(tmp); + PASS(); +} + +/* The IMPORTS edges of a stored index, one sorted line each. */ +static char *ip_imports_listing(const char *db_path) { + sqlite3 *db = NULL; + if (sqlite3_open_v2(db_path, &db, SQLITE_OPEN_READONLY, NULL) != SQLITE_OK) { + sqlite3_close(db); + return NULL; + } + sqlite3_stmt *st = NULL; + char *buf = calloc(1, 1); + size_t len = 0; + if (buf && sqlite3_prepare_v2(db, + "SELECT s.qualified_name||'|'||t.qualified_name||'|'||t.label||'|'||" + "coalesce(e.properties,'') FROM edges e JOIN nodes s ON " + "s.id=e.source_id JOIN nodes t ON t.id=e.target_id WHERE " + "e.type='IMPORTS' ORDER BY 1", + -1, &st, NULL) == SQLITE_OK) { + while (sqlite3_step(st) == SQLITE_ROW) { + const char *row = (const char *)sqlite3_column_text(st, 0); + size_t n = row ? strlen(row) : 0; + char *grown = realloc(buf, len + n + 2); + if (!grown) { + break; + } + buf = grown; + memcpy(buf + len, row ? row : "", n); + buf[len + n] = '\n'; + len += n + 1; + buf[len] = '\0'; + } + } + sqlite3_finalize(st); + sqlite3_close(db); + return buf; +} + +/* Index `repo` into `db` (incremental when `db` holds its index). */ +static int ip_index(const char *repo, const char *db) { + cbm_pipeline_t *p = cbm_pipeline_new(repo, db, CBM_MODE_FULL); + if (!p) { + return -1; + } + (void)cbm_pipeline_set_project_name(p, "dartinc"); + cbm_pipeline_set_persistence(p, false); + int rc = cbm_pipeline_run(p); + cbm_pipeline_free(p); + return rc; +} + +/* The reason of the last `incremental.closure_decline` line the log wrote + * while the sink was set ("" when none). */ +static char g_ip_decline[128]; + +static void ip_decline_sink(const char *line) { + const char *at = line ? strstr(line, "msg=incremental.closure_decline ") : NULL; + const char *reason = at ? strstr(at, "reason=") : NULL; + if (reason) { + reason += strlen("reason="); + size_t n = strcspn(reason, " \n"); + if (n >= sizeof(g_ip_decline)) { + n = sizeof(g_ip_decline) - 1; + } + memcpy(g_ip_decline, reason, n); + g_ip_decline[n] = '\0'; + } +} + +/* After the edit, the kept index (incremental) holds the IMPORTS edges a + * fresh index of the tree holds; *route: the route the incremental run took, + * `decline`: the reason its log line `incremental.closure_decline` gave ("" when + * the closure planned). */ +static bool ip_incr_equals_full(const char *tmp, const char *repo, int step, + cbm_incremental_route_t *route, char *decline, size_t decline_sz) { + char kept[512]; + char fresh[512]; + snprintf(kept, sizeof(kept), "%s/kept.db", tmp); + snprintf(fresh, sizeof(fresh), "%s/fresh-%d.db", tmp, step); + cbm_pipeline_incremental_test_reset_faults(); + CBMLogLevel saved_level = cbm_log_get_level(); + CBMLogFormat saved_format = cbm_log_get_format(); + cbm_log_set_level(CBM_LOG_INFO); + cbm_log_set_format(CBM_LOG_FORMAT_TEXT); + g_ip_decline[0] = '\0'; + cbm_log_set_sink_ex(ip_decline_sink, CBM_LOG_SINK_TEE); + int rc = ip_index(repo, kept); + cbm_log_set_sink(NULL); + cbm_log_set_level(saved_level); + cbm_log_set_format(saved_format); + snprintf(decline, decline_sz, "%s", g_ip_decline); + if (rc != 0) { + return false; + } + *route = cbm_pipeline_incremental_test_last_route(); + if (ip_index(repo, fresh) != 0) { + return false; + } + char *a = ip_imports_listing(kept); + char *b = ip_imports_listing(fresh); + bool same = a && b && strcmp(a, b) == 0; + if (!same) { + fprintf(stderr, " step %d\n--- incremental ---\n%s--- full ---\n%s", step, a ? a : "", + b ? b : ""); + } + free(a); + free(b); + (void)remove(fresh); + return same; +} + +/* One step: the edit is made, then the kept index is indexed again (the + * incremental route it takes is asserted, with the decline reason its log + * gave, "" for a closure repair) and compared with a fresh index. */ +#define IP_STEP(n, want_route, want_reason) \ + do { \ + ASSERT_TRUE(ip_incr_equals_full(tmp, repo, (n), &route, reason, sizeof(reason))); \ + ASSERT_EQ(route, (want_route)); \ + ASSERT_STR_EQ(reason, (want_reason)); \ + } while (0) + +/* Edits that change which file an import of an UNCHANGED Dart file names + * leave the incremental index equal to a full one. The setup's edges need the + * path rule; each step below binds one rule of the incremental key (the + * variant without that rule fails it): + * - 1, 2: a pubspec added below the importer becomes its package (package:app + * is then unlisted: no file), deleted it gives the package back: the + * listing key holds the pubspecs (semantic_input_changed); + * - 3: the importer's pubspec edited to list ext: package:ext names + * ext/lib/e.dart (include_root_changed); + * - 4: a Dart file deleted (before any is added) stays a closure repair: a + * Dart URI names one exact path and reads no other, so only the imports + * that named the file change, and their files had edges into it (the + * listing key leaves the Dart files out); + * - 5 (new_file, main's rule) and the controls (a Protobuf file deleted + * declines through the listing key; the importer alone edited is a closure + * repair) bind no rule of this change. */ +TEST(include_path_dart_incremental_equals_full) { + char *made = th_mktempdir("cbm_ip_dincr"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char repo[512]; + snprintf(repo, sizeof(repo), "%s/repo", tmp); + ASSERT_EQ(th_write_file(TH_PATH(repo, "pubspec.yaml"), + "name: app\ndependencies:\n core:\n path: packages/core\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "lib/app.dart"), + "import 'package:core/core.dart';\n" + "import 'package:core/later.dart';\n" + "import 'package:ext/e.dart';\n" + "\nvoid run() {}\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "tool/gen/bin/g.dart"), + "import 'package:app/app.dart';\n\nvoid gen() {}\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "packages/core/pubspec.yaml"), "name: core\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "packages/core/lib/core.dart"), "class Core {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "packages/core/lib/later.dart"), "class L {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "ext/pubspec.yaml"), "name: ext\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "ext/lib/e.dart"), "class E {}\n"), 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "proto/a.proto"), + "syntax = \"proto3\";\nimport \"proto/b.proto\";\n"), + 0); + ASSERT_EQ(th_write_file(TH_PATH(repo, "proto/b.proto"), "syntax = \"proto3\";\n"), 0); + char kept[512]; + snprintf(kept, sizeof(kept), "%s/kept.db", tmp); + ASSERT_EQ(ip_index(repo, kept), 0); + const char *app = "lib/app.dart"; + const char *gen = "tool/gen/bin/g.dart"; + ASSERT_EQ(ip_file_imports(kept, app, "packages/core/lib/core.dart"), 1); + ASSERT_EQ(ip_file_imports(kept, app, "ext/lib/e.dart"), 0); + ASSERT_EQ(ip_file_imports(kept, gen, "lib/app.dart"), 1); + + cbm_incremental_route_t route = CBM_INCREMENTAL_ROUTE_NONE; + char reason[128]; + /* 1: a pubspec below the importer: package:app is unlisted there */ + ASSERT_EQ(th_write_file(TH_PATH(repo, "tool/gen/pubspec.yaml"), "name: gen\n"), 0); + IP_STEP(1, CBM_INCREMENTAL_ROUTE_FORCED_FULL, "semantic_input_changed"); + ASSERT_EQ(ip_file_imports(kept, gen, "lib/app.dart"), 0); + /* 2: it goes again */ + ASSERT_EQ(remove(TH_PATH(repo, "tool/gen/pubspec.yaml")), 0); + IP_STEP(2, CBM_INCREMENTAL_ROUTE_FORCED_FULL, "semantic_input_changed"); + ASSERT_EQ(ip_file_imports(kept, gen, "lib/app.dart"), 1); + /* 3: the importer's pubspec lists ext, the file set unchanged */ + ASSERT_EQ(th_write_file(TH_PATH(repo, "pubspec.yaml"), + "name: app\ndependencies:\n core:\n path: packages/core\n" + " ext:\n path: ext\n"), + 0); + IP_STEP(3, CBM_INCREMENTAL_ROUTE_FORCED_FULL, "include_root_changed"); + ASSERT_EQ(ip_file_imports(kept, app, "ext/lib/e.dart"), 1); + /* 4: the lib file package:core/later.dart names deleted, before any Dart + * file is added: a closure repair */ + ASSERT_EQ(remove(TH_PATH(repo, "packages/core/lib/later.dart")), 0); + IP_STEP(4, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, ""); + ASSERT_EQ(ip_file_imports(kept, app, "packages/core/lib/later.dart"), 0); + ASSERT_EQ(ip_file_imports(kept, app, "packages/core/lib/core.dart"), 1); + /* 5: and added again */ + ASSERT_EQ(th_write_file(TH_PATH(repo, "packages/core/lib/later.dart"), "class L {}\n"), 0); + IP_STEP(5, CBM_INCREMENTAL_ROUTE_FORCED_FULL, "new_file"); + ASSERT_EQ(ip_file_imports(kept, app, "packages/core/lib/later.dart"), 1); + /* 6: control: a Protobuf file deleted declines through the listing key */ + ASSERT_EQ(remove(TH_PATH(repo, "proto/b.proto")), 0); + IP_STEP(6, CBM_INCREMENTAL_ROUTE_FORCED_FULL, "semantic_input_changed"); + /* 7: control: the importer alone edited */ + ASSERT_EQ(th_write_file(TH_PATH(repo, "lib/app.dart"), + "import 'package:core/core.dart';\n\nvoid run() {}\n"), + 0); + IP_STEP(7, CBM_INCREMENTAL_ROUTE_CLOSURE_REPAIR, ""); + ASSERT_EQ(ip_file_imports(kept, app, "packages/core/lib/core.dart"), 1); + th_cleanup(tmp); + PASS(); +} +#undef IP_STEP + +/* A table insert that fails while the universe is built (dropped, as a + * failed allocation leaves it: cbm_ht_set reports none) leaves a universe + * whose every answer is NONE, never a lost key read as an absent file or + * package. Every insert of the build in turn. */ +TEST(include_path_failed_insert_answers_none) { + char *made = th_mktempdir("cbm_ip_dfail"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const char *const files[] = { + "pubspec.yaml", "name: app\ndependencies:\n core:\n path: packages/core\n", + "lib/app.dart", "", + "lib/src/u.dart", "", + "packages/core/pubspec.yaml", "name: core\n", + "packages/core/lib/core.dart", "", + "api/a.proto", "syntax = \"proto3\";\n", + "Makefile", "include rules.mk\n", + "rules.mk", "", + NULL}; + char got[1024]; + const char *app = "lib/app.dart"; + cbm_gbuf_t *g = NULL; + int fired = 0; + for (int k = 1; k < 1000; k++) { + cbm_include_path_test_fail_insert(k); + cbm_include_universe_t *u = ip_dart_universe(tmp, files, NULL); + bool hit = cbm_include_path_test_reset_insert_failure(); + ASSERT_NOT_NULL(u); + if (!hit) { + /* past the last insert: the whole universe answers */ + IP_DFILE(app, "package:core/core.dart", "packages/core/lib/core.dart"); + IP_DVERDICT(app, "package:ext/e.dart", CBM_INCLUDE_PATH_NO_FILE); + cbm_include_universe_free(u); + break; + } + fired++; + IP_DVERDICT(app, "package:core/core.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:ext/e.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:app/src/u.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "src/none.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "dart:async", CBM_INCLUDE_PATH_NONE); + ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/b.proto", "a.proto", got, sizeof(got)), + CBM_INCLUDE_PATH_NONE); + cbm_include_universe_free(u); + } + ASSERT_GT(fired, 10); + /* A Dart manifest that cannot be read (opened, or no memory) makes + * every Dart answer NONE, each of the two in turn; the Protobuf and Make + * answers read no manifest and stay decided (before, it failed the whole + * universe) */ + int reads = 0; + for (int k = 1; k < 10; k++) { + cbm_include_path_test_fail_read(k); + cbm_include_universe_t *u = ip_dart_universe(tmp, files, NULL); + bool hit = cbm_include_path_test_reset_read_failure(); + ASSERT_NOT_NULL(u); + if (!hit) { + cbm_include_universe_free(u); + break; + } + reads++; + IP_DVERDICT(app, "package:core/core.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:ext/e.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "src/none.dart", CBM_INCLUDE_PATH_NONE); + ASSERT_EQ(ip_ask(u, CBM_LANG_PROTOBUF, "api/b.proto", "a.proto", got, sizeof(got)), + CBM_INCLUDE_PATH_FILE); + ASSERT_STR_EQ(got, "api/a.proto"); + ASSERT_EQ(ip_ask(u, CBM_LANG_MAKEFILE, "Makefile", "rules.mk", got, sizeof(got)), + CBM_INCLUDE_PATH_FILE); + ASSERT_STR_EQ(got, "rules.mk"); + cbm_include_universe_free(u); + } + ASSERT_EQ(reads, 2); + /* the resolution is made on the first question: an insert of it that + * fails leaves that answer and every later one NONE */ + int asked = 0; + for (int k = 1; k < 100; k++) { + cbm_include_universe_t *u = ip_dart_universe(tmp, files, NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_test_fail_insert(k); + cbm_include_path_verdict_t first = + ip_dask(u, g, app, "package:core/core.dart", got, sizeof(got)); + bool hit = cbm_include_path_test_reset_insert_failure(); + if (!hit) { + ASSERT_EQ(first, CBM_INCLUDE_PATH_FILE); + cbm_include_universe_free(u); + break; + } + asked++; + ASSERT_EQ(first, CBM_INCLUDE_PATH_NONE); + IP_DVERDICT(app, "package:ext/e.dart", CBM_INCLUDE_PATH_NONE); + cbm_include_universe_free(u); + } + ASSERT_GT(asked, 0); + th_cleanup(tmp); + PASS(); +} + +/* The answer-array slots the last counted run examined: a lookup is one step + * however many slots it examines, so a clustering slot choice shows only here. */ +static uint64_t ip_probes_last; +static uint64_t ip_probes_mark; + +/* Starts a counted run on this thread: its steps (returned) and its probes. */ +static uint64_t ip_count_start(void) { + ip_probes_mark = cbm_include_path_test_probes(); + return cbm_include_path_test_steps(); +} + +/* Ends a counted run: its steps; its probes into ip_probes_last. */ +static uint64_t ip_count_since(uint64_t before) { + ip_probes_last = cbm_include_path_test_probes() - ip_probes_mark; + return cbm_include_path_test_steps() - before; +} + +/* Probes are bounded per operation, not by a growth ratio: at most 8 slots + * examined per answer-array put or lookup, on average over a run. The bound + * comes from the expected cost of linear probing with keys spread evenly over + * the slots (Knuth), at the array's load a of at most three quarters: a + * lookup that finds its name examines (1 + 1/(1 - a)) / 2 slots, 2.5 at most, + * and so does a put on average over the fill; a lookup that does not find it + * examines (1 + 1/(1 - a)^2) / 2, 8.5 at most with the empty slot that ends + * it, which the counter does not count (7.5). Names that share one home slot + * examine about as many slots as there are names. A ratio between sizes would + * not hold: capacities are powers of two, + * so the load, and with it the slots examined per operation, steps as the + * names grow. The names are fixed, so the count is a function of the code. */ +#define IP_PROBES_PER_OP 8 + +/* Counted work, building and answering, of n Dart files in n/10 packages, + * each package listing the hub package core: every file asks for core, for + * itself by its package URI and for a file by a relative URI. */ +static bool ip_dart_work(const char *root, int n, uint64_t *steps) { + int pubs = n / 10; + int total = n + pubs + 2; + cbm_file_info_t *files = calloc((size_t)total, sizeof(*files)); + char (*rels)[64] = calloc((size_t)total, sizeof(*rels)); + char (*disk)[512] = calloc((size_t)total, sizeof(*disk)); + bool ok = files && rels && disk; + for (int k = 0; ok && k <= pubs; k++) { + char body[128]; + if (k < pubs) { + snprintf(rels[n + k], 64, "pk%d/pubspec.yaml", k); + snprintf(body, sizeof(body), "name: pk%d\ndependencies:\n core:\n path: ../core\n", + k); + } else { + snprintf(rels[n + k], 64, "core/pubspec.yaml"); + snprintf(body, sizeof(body), "name: core\n"); + } + snprintf(disk[n + k], 512, "%s/%d/%s", root, n, rels[n + k]); + ok = th_write_file(disk[n + k], body) == 0; + files[n + k].rel_path = rels[n + k]; + files[n + k].path = disk[n + k]; + } + snprintf(rels[n + pubs + 1], 64, "core/lib/core.dart"); + files[n + pubs + 1].rel_path = rels[n + pubs + 1]; + for (int i = 0; ok && i < n; i++) { + snprintf(rels[i], 64, "pk%d/lib/d%d/f%d.dart", i % pubs, i % 7, i); + files[i].rel_path = rels[i]; + } + uint64_t before = ip_count_start(); + cbm_include_universe_t *u = ok ? cbm_include_universe_new(files, total) : NULL; + ok = u != NULL; + char got[1024]; + for (int i = 0; ok && i < n; i++) { + char uri[96]; + snprintf(uri, sizeof(uri), "package:pk%d/d%d/f%d.dart", i % pubs, i % 7, i); + ok = ip_ask(u, CBM_LANG_DART, rels[i], uri, got, sizeof(got)) == CBM_INCLUDE_PATH_FILE && + strcmp(got, rels[i]) == 0; + ok = ok && + ip_ask(u, CBM_LANG_DART, rels[i], "package:core/core.dart", got, sizeof(got)) == + CBM_INCLUDE_PATH_FILE && + strcmp(got, "core/lib/core.dart") == 0; + int j = i >= pubs ? i - pubs : i; /* a file of the same package */ + snprintf(uri, sizeof(uri), "../d%d/f%d.dart", j % 7, j); + ok = ok && ip_ask(u, CBM_LANG_DART, rels[i], uri, got, sizeof(got)) == + CBM_INCLUDE_PATH_FILE && + strcmp(got, rels[j]) == 0; + } + *steps = ip_count_since(before); + cbm_include_universe_free(u); + free(files); + free(rels); + free(disk); + return ok; +} + +/* The rule's counted work, building the universe and answering every + * import, at 1x, 4x, 16x files and imports: at most 4.5 times per 4 times (a + * scan of the pubspecs or files per import, or a resolution that grows with + * the packages, grows 16 times). */ +TEST(include_path_dart_universe_grows_linearly) { + char *made = th_mktempdir("cbm_ip_dgrow"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + uint64_t s1, s4, s16; + ASSERT_TRUE(ip_dart_work(tmp, 50, &s1)); + ASSERT_TRUE(ip_dart_work(tmp, 200, &s4)); + ASSERT_TRUE(ip_dart_work(tmp, 800, &s16)); + ASSERT_TRUE(s4 * 2 <= s1 * 9 && s16 * 2 <= s4 * 9); + ASSERT_GT(s16, s4); + th_cleanup(tmp); + PASS(); +} + +/* The reader takes what dart takes, and nothing it cannot read whole: a + * blank before a key's colon names the key (pub reads + * `dependency_overrides :` as the section and `core :` as core); a flow map, a flow map on its own line, an alias, a merge + * key or a tab in the indent make that pubspec's resolution undecided (pub + * takes the first three; the rule does not read them), its own package's URIs included. */ +TEST(include_path_dart_reader_takes_what_dart_takes) { + char *made = th_mktempdir("cbm_ip_dn1"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const struct { + const char *pubspec; + cbm_include_path_verdict_t core; /* package:core/core.dart */ + const char *file; + cbm_include_path_verdict_t self; /* package:app/x.dart */ + } cases[] = { + {"name: app\ndependencies:\n core:\n path: packages/core\ndependency_overrides :\n" + " core:\n path: forks/core\n", + CBM_INCLUDE_PATH_FILE, "forks/core/lib/core.dart", CBM_INCLUDE_PATH_FILE}, + {"name: app\ndependencies:\n core :\n path: packages/core\n", CBM_INCLUDE_PATH_FILE, + "packages/core/lib/core.dart", CBM_INCLUDE_PATH_FILE}, + {"name: app\ndependencies:\n core: {path: packages/core}\n", CBM_INCLUDE_PATH_NONE, "", + CBM_INCLUDE_PATH_NONE}, + {"name: app\ndependencies:\n core:\n {path: packages/core}\n", CBM_INCLUDE_PATH_NONE, "", + CBM_INCLUDE_PATH_NONE}, + {"name: app\ndependencies:\n core: &c\n path: forks/core\ndependency_overrides:\n" + " core: *c\n", + CBM_INCLUDE_PATH_NONE, "", CBM_INCLUDE_PATH_NONE}, + {"name: app\ndependencies:\n <<: *base\n core:\n path: packages/core\n", + CBM_INCLUDE_PATH_NONE, "", CBM_INCLUDE_PATH_NONE}, + {"name: app\ndependencies:\n core:\n\t path: packages/core\n", CBM_INCLUDE_PATH_NONE, "", + CBM_INCLUDE_PATH_NONE}, + {"name: app\nworkspace:\n - pkgs/*\n", CBM_INCLUDE_PATH_NONE, "", CBM_INCLUDE_PATH_NONE}, + }; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + const char *files[] = {"pubspec.yaml", cases[i].pubspec, + "lib/app.dart", "", + "lib/x.dart", "", + "packages/core/pubspec.yaml", "name: core\n", + "packages/core/lib/core.dart", "", + "forks/core/pubspec.yaml", "name: core\n", + "forks/core/lib/core.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/c%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + cbm_gbuf_t *g = NULL; + char got[1024]; + IP_DVERDICT("lib/app.dart", "package:core/core.dart", cases[i].core); + if (cases[i].core == CBM_INCLUDE_PATH_FILE) { + ASSERT_STR_EQ(got, cases[i].file); + } + IP_DVERDICT("lib/app.dart", "package:app/x.dart", cases[i].self); + cbm_include_universe_free(u); + } + th_cleanup(tmp); + PASS(); +} + +/* Overrides and sources, as dart decides them: + * - a pubspec_overrides.yaml without a `dependency_overrides:` key (a comment, + * an empty file) keeps the pubspec's overrides; one with another key is + * refused by pub (undecided); + * - an override enters the resolution when nothing depends on it; + * - git, a hosted URL or the SDK with an indexed pubspec of that name is + * undecided, as a version constraint is; with none, no file. */ +TEST(include_path_dart_overrides_and_sources) { + char *made = th_mktempdir("cbm_ip_dn4"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const struct { + const char *ovfile; + cbm_include_path_verdict_t want; + } ovs[] = { + {"# nothing here\n", CBM_INCLUDE_PATH_FILE}, + {"", CBM_INCLUDE_PATH_FILE}, + {"foo: 1\n", CBM_INCLUDE_PATH_NONE}, + }; + for (size_t i = 0; i < sizeof(ovs) / sizeof(ovs[0]); i++) { + const char *files[] = {"pubspec.yaml", + "name: app\ndependencies:\n core: ^1.0.0\n" + "dependency_overrides:\n core:\n path: core\n", + "pubspec_overrides.yaml", ovs[i].ovfile, + "lib/app.dart", "", + "core/pubspec.yaml", "name: core\n", + "core/lib/core.dart", "", + /* a second package named core: the version entry + * alone is undecided (in-repo rule), so only the + * override the file leaves in place answers */ + "core2/pubspec.yaml", "name: core\n", + "core2/lib/core.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/o%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + cbm_gbuf_t *g = NULL; + char got[1024]; + IP_DVERDICT("lib/app.dart", "package:core/core.dart", ovs[i].want); + cbm_include_universe_free(u); + } + static const char *const unused[] = { + "pubspec.yaml", "name: app\ndependency_overrides:\n core:\n path: core\n", + "lib/app.dart", "", + "core/pubspec.yaml", "name: core\n", + "core/lib/core.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/unused", tmp); + cbm_include_universe_t *u = ip_dart_universe(dir, unused, NULL); + ASSERT_NOT_NULL(u); + cbm_gbuf_t *g = NULL; + char got[1024]; + IP_DFILE("lib/app.dart", "package:core/core.dart", "core/lib/core.dart"); + cbm_include_universe_free(u); + static const char *const sources[] = { + "pubspec.yaml", + "name: app\ndependencies:\n gitp:\n git: https://example.com/gitp.git\n" + " gitq:\n git:\n url: https://example.com/gitq.git\n ref: main\n" + " hostp:\n hosted: https://pub.example.com\n version: ^1.0.0\n" + " flutter:\n sdk: flutter\n", + "lib/app.dart", "", + "gitp/pubspec.yaml", "name: gitp\n", + "gitp/lib/g.dart", "", + "flutter/pubspec.yaml", "name: flutter\n", + "flutter/lib/material.dart", "", + NULL}; + snprintf(dir, sizeof(dir), "%s/sources", tmp); + u = ip_dart_universe(dir, sources, NULL); + ASSERT_NOT_NULL(u); + IP_DVERDICT("lib/app.dart", "package:gitp/g.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT("lib/app.dart", "package:flutter/material.dart", CBM_INCLUDE_PATH_NONE); + IP_DVERDICT("lib/app.dart", "package:gitq/q.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DVERDICT("lib/app.dart", "package:hostp/h.dart", CBM_INCLUDE_PATH_NO_FILE); + IP_DCLASS("lib/app.dart", "package:gitp/g.dart", CBM_INCLUDE_DART_EXTERNAL); + cbm_include_universe_free(u); + th_cleanup(tmp); + PASS(); +} + +/* Counted work, building and answering, of a chain of n packages: package k + * lists package k+1 by path and its one file imports package k+1. */ +static bool ip_chain_work(const char *root, int n, uint64_t *steps) { + cbm_file_info_t *files = calloc((size_t)(2 * n), sizeof(*files)); + char (*rels)[64] = calloc((size_t)(2 * n), sizeof(*rels)); + char (*disk)[512] = calloc((size_t)n, sizeof(*disk)); + bool ok = files && rels && disk; + for (int k = 0; ok && k < n; k++) { + char body[160]; + snprintf(rels[k], 64, "pk%d/pubspec.yaml", k); + if (k + 1 < n) { + snprintf(body, sizeof(body), "name: pk%d\ndependencies:\n pk%d:\n path: ../pk%d\n", k, + k + 1, k + 1); + } else { + snprintf(body, sizeof(body), "name: pk%d\n", k); + } + snprintf(disk[k], 512, "%s/%d/%s", root, n, rels[k]); + ok = th_write_file(disk[k], body) == 0; + files[k].rel_path = rels[k]; + files[k].path = disk[k]; + snprintf(rels[n + k], 64, "pk%d/lib/f.dart", k); + files[n + k].rel_path = rels[n + k]; + } + uint64_t before = ip_count_start(); + cbm_include_universe_t *u = ok ? cbm_include_universe_new(files, 2 * n) : NULL; + ok = u != NULL; + char got[1024]; + for (int k = 0; ok && k + 1 < n; k++) { + char uri[64]; + char want[64]; + snprintf(uri, sizeof(uri), "package:pk%d/f.dart", k + 1); + snprintf(want, sizeof(want), "pk%d/lib/f.dart", k + 1); + ok = ip_ask(u, CBM_LANG_DART, rels[n + k], uri, got, sizeof(got)) == CBM_INCLUDE_PATH_FILE && + strcmp(got, want) == 0; + } + *steps = ip_count_since(before); + cbm_include_universe_free(u); + free(files); + free(rels); + free(disk); + return ok; +} + +/* A stated limit, pinned: a chain of path dependencies where every package + * is a root importing only its neighbour. Each root walks its closure once, + * completely (pub takes one source per name for the whole closure: an answer + * is right only when the walk found no second source deeper), so the chain + * costs the sum of its roots' closures, n^2/2, 16 times the work per 4 times + * the input (the many-roots shape, + * include_path_dart_roots_cost_roots_times_subgraph). Not capped. The counts + * are pinned from above at 1,668 / 25,443 / 401,793 steps for 25 / 100 / 400 + * packages: more work fails here (every root's closure walked when the + * universe is built does); a rule that does less moves the pin and the + * statement. */ +TEST(include_path_dart_chain_square_limit_is_pinned) { + char *made = th_mktempdir("cbm_ip_dchain"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + uint64_t s1, s4, s16; + ASSERT_TRUE(ip_chain_work(tmp, 25, &s1)); + ASSERT_TRUE(ip_chain_work(tmp, 100, &s4)); + ASSERT_TRUE(ip_chain_work(tmp, 400, &s16)); + fprintf(stderr, " chain steps: 25 -> %llu, 100 -> %llu, 400 -> %llu\n", (unsigned long long)s1, + (unsigned long long)s4, (unsigned long long)s16); + /* the square, as stated */ + ASSERT_TRUE(s4 >= s1 * 10 && s4 <= s1 * 18 && s16 >= s4 * 10 && s16 <= s4 * 18); + /* and no more than that */ + ASSERT_TRUE(s1 <= 1668 && s4 <= 25443 && s16 <= 401793); + th_cleanup(tmp); + PASS(); +} + /* ── A path whose dots and slashes are swapped ───────────────────────────── */ /* A File node's name joins a path's segments with dots, so a.b.proto and @@ -983,6 +2300,222 @@ TEST(include_path_cfml_swapped_spelling) { PASS(); } +/* Three pubspecs dart reads and the reader does not (a flow map, a flow + * map on its own line, an alias): their resolution stays undecided, so + * `import 'package:core/core.dart'` from bin/main.dart draws no edge. dart + * 3.14.1 reads packages/core/lib/core.dart (the two flow maps) and + * forks/core/lib/core.dart (the alias). Main's name + * strategies drew an edge to that file's function `core`, by name; + * cbm_include_path_accepts takes no target that is not at the named path. A + * limit of the reader (these forms are not read), pinned on both routes. */ +TEST(include_path_dart_unread_pubspec_draws_no_edge) { + static const char *const cases[][2] = { + {"packages/core", "name: app\ndependencies:\n core: {path: packages/core}\n"}, + {"packages/core", "name: app\ndependencies:\n core:\n {path: packages/core}\n"}, + {"forks/core", "name: app\ndependencies:\n core: &c\n path: forks/core\n" + "dependency_overrides:\n core: *c\n"}, + }; + char *made = th_mktempdir("cbm_ip_dn1e"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char got[128]; + size_t used = 0; + for (int par = 0; par < 2; par++) { + for (int c = 0; c < 3; c++) { + char repo[512]; + char path[700]; + snprintf(repo, sizeof(repo), "%s/%s%d", tmp, par ? "par" : "seq", c); + const char *files[][2] = { + {"pubspec.yaml", cases[c][1]}, + {"bin/main.dart", "import 'package:core/core.dart';\nvoid main() { print(core()); }\n"}, + {"pubspec.yaml", "name: core\n"}, + {"lib/core.dart", "String core() => 'core';\n"}, + }; + for (int i = 0; i < 4; i++) { + if (i < 2) { + snprintf(path, sizeof(path), "%s/%s", repo, files[i][0]); + } else { + snprintf(path, sizeof(path), "%s/%s/%s", repo, cases[c][0], files[i][0]); + } + ASSERT_EQ(th_write_file(path, files[i][1]), 0); + } + for (int i = 0; i < 60; i++) { + snprintf(path, sizeof(path), "%s/fill/f%02d.go", repo, i); + char body[64]; + snprintf(body, sizeof(body), "package fill\n\nfunc F%02d() {}\n", i); + ASSERT_EQ(th_write_file(path, body), 0); + } + char db[600]; + snprintf(db, sizeof(db), "%s/%s%d.db", tmp, par ? "par" : "seq", c); + ip_route_env(par != 0, false); + cbm_pipeline_worker_count_test_reset(); + int rc = ip_run(repo, db); + int workers = cbm_pipeline_worker_count_test_last(); + ip_route_env(par != 0, true); + ASSERT_EQ(rc, 0); + ASSERT_TRUE(par ? workers > 1 : workers == 1); + used += (size_t)snprintf(got + used, sizeof(got) - used, "%s%d", used ? " " : "", + ip_targets(db, "bin/main.dart", NULL, NULL)); + } + } + /* sequential flow map, flow map next line, alias; then parallel */ + ASSERT_STR_EQ(got, "0 0 0 0 0 0"); + th_cleanup(tmp); + PASS(); +} + +/* ── Dart: the reader's whitelist, one source per closure ────────────────── */ + +#define IP_W_HEAD "name: app\nenvironment:\n sdk: ^3.6.0\ndependencies:\n foo:\n path: foo_a\n" +#define IP_W_OVR " foo:\n path: foo_b\n" + +/* Pubspec spellings, each run through `dart pub get` and `dart run` of the + * Dart SDK 3.14.1 (the expectation is the SDK's answer for each): the root + * package depends on foo by path foo_a and overrides it to foo_b with the + * spelling under test. */ +static const struct { + const char *name; + const char *pubspec; + char want; /* 'b': foo_b/lib/x.dart (dart reads it, and the reader exactly); '-': undecided */ +} ip_w_cases[] = { + {"plain", IP_W_HEAD "dependency_overrides:\n" IP_W_OVR, 'b'}, + {"crlf", + "name: app\r\nenvironment:\r\n sdk: ^3.6.0\r\ndependencies:\r\n foo:\r\n path: foo_a\r\n" + "dependency_overrides:\r\n foo:\r\n path: foo_b\r\n", + 'b'}, + {"dquoted", IP_W_HEAD "\"dependency_overrides\":\n" IP_W_OVR, 'b'}, + {"squoted", IP_W_HEAD "'dependency_overrides':\n" IP_W_OVR, 'b'}, + {"qentry", IP_W_HEAD "dependency_overrides:\n \"foo\":\n path: foo_b\n", 'b'}, + {"qsub", IP_W_HEAD "dependency_overrides:\n foo:\n \"path\": foo_b\n", 'b'}, + {"anchor", IP_W_HEAD "&o dependency_overrides:\n" IP_W_OVR, '-'}, + {"tag", IP_W_HEAD "!!str dependency_overrides:\n" IP_W_OVR, '-'}, + {"escape", IP_W_HEAD "\"dependency\\x5Foverrides\":\n" IP_W_OVR, '-'}, + {"uescape", IP_W_HEAD "\"dependency\\u005Foverrides\":\n" IP_W_OVR, '-'}, + {"question", IP_W_HEAD "? dependency_overrides\n:\n" IP_W_OVR, '-'}, + {"merge", IP_W_HEAD "extra: &ov\n dependency_overrides:\n foo:\n path: foo_b\n<<: *ov\n", + '-'}, + {"bom_first", "\xEF\xBB\xBF" "dependency_overrides:\n" IP_W_OVR IP_W_HEAD, '-'}, + {"bom_name", "\xEF\xBB\xBF" IP_W_HEAD "dependency_overrides:\n" IP_W_OVR, '-'}, + {"crlf_anchor", + "name: app\r\nenvironment:\r\n sdk: ^3.6.0\r\ndependencies:\r\n foo:\r\n path: foo_a\r\n" + "&o dependency_overrides:\r\n foo:\r\n path: foo_b\r\n", + '-'}, + {"cr_comment", + "name: app # x\rdependency_overrides:\r foo:\r path: foo_b\nenvironment:\n sdk: ^3.6.0\n" + "dependencies:\n foo:\n path: foo_a\n", + '-'}, + {"lone_cr", + "name: app\renvironment:\r sdk: ^3.6.0\rdependencies:\r foo:\r path: foo_a\r" + "dependency_overrides:\r foo:\r path: foo_b\r", + '-'}, + {"doc_end", IP_W_HEAD "dependency_overrides:\n" IP_W_OVR "...\n", '-'}, + {"hyphen", IP_W_HEAD "dependency_overrides:\n" IP_W_OVR "x-extra: 1\n", 'b'}, + {"rootdup", IP_W_HEAD "dependency_overrides:\n" IP_W_OVR "extra: 1\nextra: 2\n", '-'}, + {"dupentry", IP_W_HEAD " foo:\n path: foo_a\n", '-'}, + {"scalarpath", "name: app\nenvironment:\n sdk: ^3.6.0\ndependencies:\n foo: ^1.0.0\n path: foo_a\n", + '-'}, + {"subdup", "name: app\nenvironment:\n sdk: ^3.6.0\ndependencies:\n foo:\n path: foo_a\n" + " version: ^1.0.0\n version: ^1.0.0\n", + '-'}, +}; + +/* One letter per verdict of package:foo/x.dart from lib/main.dart: 'a' or 'b' + * the file of foo_a or foo_b, '-' undecided, 'x' no file, '?' anything else. */ +static char ip_w_letter(cbm_include_path_verdict_t v, const char *got) { + if (v == CBM_INCLUDE_PATH_FILE) { + return strcmp(got, "foo_a/lib/x.dart") == 0 ? 'a' + : strcmp(got, "foo_b/lib/x.dart") == 0 ? 'b' + : '?'; + } + return v == CBM_INCLUDE_PATH_NONE ? '-' : v == CBM_INCLUDE_PATH_NO_FILE ? 'x' : '?'; +} + +/* The reader is a whitelist (ip_yaml_read). What dart reads and + * the reader reads exactly (plain keys, CRLF, a quoted key without an escape + * at the root, as an entry, as an entry's key) places foo at foo_b. Every + * other spelling dart reads as the override (an anchor, a tag, an escaped key, + * an explicit key, a byte-order mark, a CR alone, a document end, an unknown + * key with a hyphen) or refuses (an entry twice, a scalar entry with a deeper + * line, a key twice: "Duplicate mapping key", "Mapping values are not allowed + * here") leaves the resolution undecided: never foo_a, which the old reader named + * for every skipped override (a wrong edge where main draws none). dart does + * not apply a root merge key (it takes foo_a); undecided here too. */ +TEST(include_path_dart_reader_whitelist) { + char *made = th_mktempdir("cbm_ip_dwl"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char line[640]; + char want[640]; + size_t used = 0; + size_t wused = 0; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (size_t i = 0; i < sizeof(ip_w_cases) / sizeof(ip_w_cases[0]); i++) { + const char *files[] = {"pubspec.yaml", ip_w_cases[i].pubspec, + "foo_a/pubspec.yaml", "name: foo\n", + "foo_a/lib/x.dart", "", + "foo_b/pubspec.yaml", "name: foo\n", + "foo_b/lib/x.dart", "", + "lib/main.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/c%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + char c = ip_w_letter(ip_dask(u, g, "lib/main.dart", "package:foo/x.dart", got, sizeof(got)), got); + cbm_include_universe_free(u); + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%s:%c", used ? " " : "", + ip_w_cases[i].name, c); + wused += (size_t)snprintf(want + wused, sizeof(want) - wused, "%s%s:%c", wused ? " " : "", + ip_w_cases[i].name, ip_w_cases[i].want); + } + ASSERT_STR_EQ(line, want); + th_cleanup(tmp); + PASS(); +} + +/* The resolution key of a workspace member written with a tag + * (`!!str resolution: workspace`; dart: a member, foo from the root's + * override foo_b) leaves the member undecided; the plain key places it. */ +TEST(include_path_dart_reader_whitelist_workspace) { + char *made = th_mktempdir("cbm_ip_dwlw"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const char *const res[] = {"!!str resolution: workspace\n", "resolution: workspace\n"}; + static const cbm_include_path_verdict_t want[] = {CBM_INCLUDE_PATH_NONE, CBM_INCLUDE_PATH_FILE}; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (int i = 0; i < 2; i++) { + char app[256]; + snprintf(app, sizeof(app), "name: app\nenvironment:\n sdk: ^3.6.0\n%sdependencies:\n foo:\n" + " path: ../foo_a\n", res[i]); + const char *files[] = {"pubspec.yaml", + "name: ws\nenvironment:\n sdk: ^3.6.0\nworkspace:\n - app\n" + "dependency_overrides:\n" IP_W_OVR, + "app/pubspec.yaml", app, + "foo_a/pubspec.yaml", "name: foo\n", + "foo_a/lib/x.dart", "", + "foo_b/pubspec.yaml", "name: foo\n", + "foo_b/lib/x.dart", "", + "app/lib/main.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/w%d", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + IP_DVERDICT("app/lib/main.dart", "package:foo/x.dart", want[i]); + if (want[i] == CBM_INCLUDE_PATH_FILE) { + ASSERT_STR_EQ(got, "foo_b/lib/x.dart"); + } + cbm_include_universe_free(u); + } + th_cleanup(tmp); + PASS(); +} + /* The same from a component, in a repository with no .cfm: a tag-dialect * .cfc is tagged CFML by its content (``), so the listing holds * every path there too. app/Widget.cfc's ` 'a';\n", + "foo_b/pubspec.yaml", "name: foo\n", + "foo_b/lib/x.dart", "String x() => 'b';\n", + "lib/main.dart", + "import 'package:foo/x.dart';\nvoid main() { print(x()); }\n", + NULL}; + const char *files_ws[] = { + "pubspec.yaml", + "name: ws\nenvironment:\n sdk: ^3.6.0\nworkspace:\n - app\ndependency_overrides:\n" IP_W_OVR, + "app/pubspec.yaml", + "name: app\nenvironment:\n sdk: ^3.6.0\n!!str resolution: workspace\ndependencies:\n" + " foo:\n path: ../foo_a\n", + "foo_a/pubspec.yaml", "name: foo\n", + "foo_a/lib/x.dart", "String x() => 'a';\n", + "foo_b/pubspec.yaml", "name: foo\n", + "foo_b/lib/x.dart", "String x() => 'b';\n", + "app/lib/main.dart", "import 'package:foo/x.dart';\nvoid main() { print(x()); }\n", + NULL}; + if (restag) { + importer = "app/lib/main.dart"; + } + char repo[512]; + char db[600]; + snprintf(repo, sizeof(repo), "%s/%s%zu", tmp, par ? "par" : "seq", s); + snprintf(db, sizeof(db), "%s/%s%zu.db", tmp, par ? "par" : "seq", s); + int workers = 0; + ASSERT_EQ(ip_index_repo(repo, restag ? files_ws : files_root, db, par != 0, &workers), 0); + ASSERT_TRUE(par ? workers > 1 : workers == 1); + int n = plain ? ip_targets(db, importer, "foo_b/lib/x.dart", "Module") + : ip_targets(db, importer, NULL, NULL); + used += (size_t)snprintf(got + used, sizeof(got) - used, "%s%d", used ? " " : "", n); + } + } + /* anchor escape tag bom_first dupentry scalarpath restag, then plain (one + * Module edge to foo_b): sequential, then parallel */ + ASSERT_STR_EQ(got, "0 0 0 0 0 0 0 1 0 0 0 0 0 0 0 1"); + th_cleanup(tmp); + PASS(); +} + +/* Counted work of the "names" shape: one root package with p path + * dependencies, f files under its lib/ each importing k distinct package + * names no package lists. */ +static bool ip_names_work(const char *root, int p, int f, int k, uint64_t *steps) { + int n = 1 + p + f; + cbm_file_info_t *files = calloc((size_t)n, sizeof(*files)); + char (*rels)[64] = calloc((size_t)n, sizeof(*rels)); + char (*disk)[512] = calloc((size_t)(1 + p), sizeof(*disk)); + size_t cap = (size_t)p * 48 + 64; + char *app = malloc(cap); + bool ok = files && rels && disk && app; + size_t used = ok ? (size_t)snprintf(app, cap, "name: app\ndependencies:\n") : 0; + for (int i = 0; ok && i < p; i++) { + used += (size_t)snprintf(app + used, cap - used, " pk%d:\n path: pk%d\n", i, i); + } + snprintf(rels[0], 64, "pubspec.yaml"); + snprintf(disk[0], 512, "%s/names%d/pubspec.yaml", root, p); + ok = ok && th_write_file(disk[0], app) == 0; + files[0].rel_path = rels[0]; + files[0].path = disk[0]; + for (int i = 0; ok && i < p; i++) { + char body[64]; + snprintf(body, sizeof(body), "name: pk%d\n", i); + snprintf(rels[1 + i], 64, "pk%d/pubspec.yaml", i); + snprintf(disk[1 + i], 512, "%s/names%d/%s", root, p, rels[1 + i]); + ok = th_write_file(disk[1 + i], body) == 0; + files[1 + i].rel_path = rels[1 + i]; + files[1 + i].path = disk[1 + i]; + } + for (int i = 0; ok && i < f; i++) { + snprintf(rels[1 + p + i], 64, "lib/f%d.dart", i); + files[1 + p + i].rel_path = rels[1 + p + i]; + } + uint64_t before = ip_count_start(); + cbm_include_universe_t *u = ok ? cbm_include_universe_new(files, n) : NULL; + ok = u != NULL; + char got[1024]; + for (int i = 0; ok && i < f; i++) { + for (int j = 0; ok && j < k; j++) { + char uri[64]; + snprintf(uri, sizeof(uri), "package:absent%d/x.dart", i * k + j); + ok = ip_ask(u, CBM_LANG_DART, rels[1 + p + i], uri, got, sizeof(got)) == + CBM_INCLUDE_PATH_NO_FILE; + } + } + *steps = ip_count_since(before); + cbm_include_universe_free(u); + free(files); + free(rels); + free(disk); + free(app); + return ok; +} + +/* Counted work of the "chain" shape: the root depends by path on + * pk0, pk on pk, and the root's one file imports every package of the + * chain. */ +static bool ip_chain_all_work(const char *root, int n, uint64_t *steps) { + cbm_file_info_t *files = calloc((size_t)(n + 2), sizeof(*files)); + char (*rels)[64] = calloc((size_t)(n + 2), sizeof(*rels)); + char (*disk)[512] = calloc((size_t)(n + 1), sizeof(*disk)); + bool ok = files && rels && disk; + for (int i = 0; ok && i <= n; i++) { + char body[160]; + if (i == 0) { + snprintf(rels[0], 64, "pubspec.yaml"); + snprintf(body, sizeof(body), "name: app\ndependencies:\n pk0:\n path: pk0\n"); + } else if (i < n) { + snprintf(rels[i], 64, "pk%d/pubspec.yaml", i - 1); + snprintf(body, sizeof(body), "name: pk%d\ndependencies:\n pk%d:\n path: ../pk%d\n", i - 1, + i, i); + } else { + snprintf(rels[i], 64, "pk%d/pubspec.yaml", i - 1); + snprintf(body, sizeof(body), "name: pk%d\n", i - 1); + } + snprintf(disk[i], 512, "%s/chain%d/%s", root, n, rels[i]); + ok = th_write_file(disk[i], body) == 0; + files[i].rel_path = rels[i]; + files[i].path = disk[i]; + } + snprintf(rels[n + 1], 64, "lib/main.dart"); + files[n + 1].rel_path = rels[n + 1]; + uint64_t before = ip_count_start(); + cbm_include_universe_t *u = ok ? cbm_include_universe_new(files, n + 2) : NULL; + ok = u != NULL; + char got[1024]; + for (int i = 0; ok && i < n; i++) { + char uri[64]; + snprintf(uri, sizeof(uri), "package:pk%d/f.dart", i); + ok = ip_ask(u, CBM_LANG_DART, "lib/main.dart", uri, got, sizeof(got)) == + CBM_INCLUDE_PATH_NO_FILE; + } + *steps = ip_count_since(before); + cbm_include_universe_free(u); + free(files); + free(rels); + free(disk); + return ok; +} + +/* One walk per root builds its name table, and every question + * of that root is one lookup. The "names" shape (one root, many + * distinct absent names) and "chain" shape (a root importing every package + * of a long chain), at 1x, 4x, 16x: at most 4.5 times the work per 4 times + * (a walk per name walked the root's closure again: names x closure, and + * the chain n^2/2). */ +TEST(include_path_dart_names_and_chain_grow_linearly) { + char *made = th_mktempdir("cbm_ip_dnames"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + uint64_t n1, n4, n16, c1, c4, c16; + /* each run's probes: puts (the root's names) plus lookups (the questions) */ + uint64_t pr[6]; + ASSERT_TRUE(ip_names_work(tmp, 10, 10, 4, &n1)); + pr[0] = ip_probes_last; + ASSERT_TRUE(ip_names_work(tmp, 40, 40, 4, &n4)); + pr[1] = ip_probes_last; + ASSERT_TRUE(ip_names_work(tmp, 160, 160, 4, &n16)); + pr[2] = ip_probes_last; + ASSERT_TRUE(ip_chain_all_work(tmp, 25, &c1)); + pr[3] = ip_probes_last; + ASSERT_TRUE(ip_chain_all_work(tmp, 100, &c4)); + pr[4] = ip_probes_last; + ASSERT_TRUE(ip_chain_all_work(tmp, 400, &c16)); + pr[5] = ip_probes_last; + static const int ops[6] = {11 + 40, 41 + 160, 161 + 640, 26 + 25, 101 + 100, 401 + 400}; + fprintf(stderr, " names probes: %llu, %llu, %llu; chain: %llu, %llu, %llu\n", + (unsigned long long)pr[0], (unsigned long long)pr[1], (unsigned long long)pr[2], + (unsigned long long)pr[3], (unsigned long long)pr[4], (unsigned long long)pr[5]); + for (int i = 0; i < 6; i++) { + ASSERT_TRUE(pr[i] <= (uint64_t)ops[i] * IP_PROBES_PER_OP); + } + fprintf(stderr, " names steps: 10 -> %llu, 40 -> %llu, 160 -> %llu; chain: 25 -> %llu, 100 -> %llu, " + "400 -> %llu\n", (unsigned long long)n1, (unsigned long long)n4, (unsigned long long)n16, + (unsigned long long)c1, (unsigned long long)c4, (unsigned long long)c16); + ASSERT_TRUE(n4 * 2 <= n1 * 9 && n16 * 2 <= n4 * 9); + ASSERT_TRUE(c4 * 2 <= c1 * 9 && c16 * 2 <= c4 * 9); + th_cleanup(tmp); + PASS(); +} + +/* Counted work of the "roots" shape: r root packages, each + * depending by path on one hub with h path dependencies; each root's one file + * imports one name no package lists. */ +static bool ip_roots_work(const char *root, int r, int h, uint64_t *steps) { + int n = 2 * r + 1 + h; + cbm_file_info_t *files = calloc((size_t)n, sizeof(*files)); + char (*rels)[64] = calloc((size_t)n, sizeof(*rels)); + char (*disk)[512] = calloc((size_t)n, sizeof(*disk)); + size_t cap = (size_t)h * 48 + 64; + char *hub = malloc(cap); + bool ok = files && rels && disk && hub; + size_t used = ok ? (size_t)snprintf(hub, cap, "name: hub\ndependencies:\n") : 0; + for (int i = 0; ok && i < h; i++) { + used += (size_t)snprintf(hub + used, cap - used, " h%d:\n path: ../h%d\n", i, i); + } + int m = 0; + for (int i = 0; ok && i < r; i++, m++) { + char body[96]; + snprintf(body, sizeof(body), "name: r%d\ndependencies:\n hub:\n path: ../hub\n", i); + snprintf(rels[m], 64, "r%d/pubspec.yaml", i); + snprintf(disk[m], 512, "%s/roots%d_%d/%s", root, r, h, rels[m]); + ok = th_write_file(disk[m], body) == 0; + files[m].rel_path = rels[m]; + files[m].path = disk[m]; + } + snprintf(rels[m], 64, "hub/pubspec.yaml"); + snprintf(disk[m], 512, "%s/roots%d_%d/%s", root, r, h, rels[m]); + ok = ok && th_write_file(disk[m], hub) == 0; + files[m].rel_path = rels[m]; + files[m].path = disk[m]; + m++; + for (int i = 0; ok && i < h; i++, m++) { + char body[64]; + snprintf(body, sizeof(body), "name: h%d\n", i); + snprintf(rels[m], 64, "h%d/pubspec.yaml", i); + snprintf(disk[m], 512, "%s/roots%d_%d/%s", root, r, h, rels[m]); + ok = th_write_file(disk[m], body) == 0; + files[m].rel_path = rels[m]; + files[m].path = disk[m]; + } + for (int i = 0; ok && i < r; i++, m++) { + snprintf(rels[m], 64, "r%d/lib/main.dart", i); + files[m].rel_path = rels[m]; + } + uint64_t before = ip_count_start(); + cbm_include_universe_t *u = ok ? cbm_include_universe_new(files, n) : NULL; + ok = u != NULL; + char got[1024]; + for (int i = 0; ok && i < r; i++) { + char rel[64]; + snprintf(rel, sizeof(rel), "r%d/lib/main.dart", i); + ok = ip_ask(u, CBM_LANG_DART, rel, "package:absent/x.dart", got, sizeof(got)) == + CBM_INCLUDE_PATH_NO_FILE; + } + *steps = ip_count_since(before); + cbm_include_universe_free(u); + free(files); + free(rels); + free(disk); + free(hub); + return ok; +} + +/* Stated as it is: r roots over one shared subgraph of h + * packages cost the sum of their closures, r times h (pub itself writes one + * package list per root). Linear in r with h fixed and in h with r fixed; + * 16 times the work when both grow 4 times. Not capped. */ +TEST(include_path_dart_roots_cost_roots_times_subgraph) { + char *made = th_mktempdir("cbm_ip_droots"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + uint64_t w11, w41, w14, w44; + /* each run's probes: per root its closure's names put (its own, the hub, h) + * and one lookup */ + uint64_t pr[4]; + ASSERT_TRUE(ip_roots_work(tmp, 8, 8, &w11)); + pr[0] = ip_probes_last; + ASSERT_TRUE(ip_roots_work(tmp, 32, 8, &w41)); + pr[1] = ip_probes_last; + ASSERT_TRUE(ip_roots_work(tmp, 8, 32, &w14)); + pr[2] = ip_probes_last; + ASSERT_TRUE(ip_roots_work(tmp, 32, 32, &w44)); + pr[3] = ip_probes_last; + static const int ops[4] = {8 * 11, 32 * 11, 8 * 35, 32 * 35}; + fprintf(stderr, " roots probes: %llu, %llu, %llu, %llu\n", (unsigned long long)pr[0], + (unsigned long long)pr[1], (unsigned long long)pr[2], (unsigned long long)pr[3]); + for (int i = 0; i < 4; i++) { + ASSERT_TRUE(pr[i] <= (uint64_t)ops[i] * IP_PROBES_PER_OP); + } + fprintf(stderr, " roots steps: 8x8 -> %llu, 32x8 -> %llu, 8x32 -> %llu, 32x32 -> %llu\n", + (unsigned long long)w11, (unsigned long long)w41, (unsigned long long)w14, + (unsigned long long)w44); + /* linear in each of r and h; their product when both grow (the input 4 + * times, the work at least 10 times) */ + ASSERT_TRUE(w41 * 2 <= w11 * 9 && w14 * 2 <= w11 * 9); + ASSERT_TRUE(w44 >= w11 * 10 && w44 <= w11 * 18); + th_cleanup(tmp); + PASS(); +} + +/* The fallback filter for a Dart URI the rule does not decide: + * the pubspec is not read (`dependencies: &d`), so '../../x.dart' from + * lib/a.dart (a `..` above lib/) is undecided. It means one file, lib/x.dart + * (dart reads lib/ as the package's space, fixtures f2_*): only a File or + * Module node of that file is taken, never a symbol in it, never tool/x.dart + * (the tail of the rest), and nothing for a `package:` URI. */ +TEST(include_path_dart_fallback_takes_the_one_file) { + char *made = th_mktempdir("cbm_ip_dacc"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + const char *files[] = {"pubspec.yaml", "name: app\nenvironment:\n sdk: ^3.0.0\ndependencies: &d\n", + "lib/a.dart", "", + "lib/x.dart", "", + "tool/x.dart", "", + NULL}; + cbm_pipeline_ctx_t ctx; + memset(&ctx, 0, sizeof(ctx)); + ctx.include_universe = ip_dart_universe(tmp, files, NULL); + ASSERT_NOT_NULL(ctx.include_universe); + CBMImport imp; + memset(&imp, 0, sizeof(imp)); + imp.module_path = "../../x.dart"; + cbm_gbuf_node_t n; + memset(&n, 0, sizeof(n)); + char got[64]; + char label[16]; + char path[32]; + static const char *const labels[] = {"Module", "File", "Function", "Module", "Module"}; + static const char *const paths[] = {"lib/x.dart", "lib/x.dart", "lib/x.dart", "tool/x.dart", + "lib/x.dart"}; + size_t used = 0; + n.label = label; + n.file_path = path; + for (int i = 0; i < 5; i++) { + snprintf(label, sizeof(label), "%s", labels[i]); + snprintf(path, sizeof(path), "%s", paths[i]); + imp.module_path = i < 4 ? "../../x.dart" : "package:app/x.dart"; + used += (size_t)snprintf(got + used, sizeof(got) - used, "%s%d", used ? " " : "", + cbm_include_path_accepts(&ctx, "lib/a.dart", CBM_LANG_DART, &imp, &n)); + } + /* Module, File of lib/x.dart; a Function there; tool/x.dart; package: */ + ASSERT_STR_EQ(got, "1 1 0 0 0"); + cbm_include_universe_free(ctx.include_universe); + th_cleanup(tmp); + PASS(); +} + +/* The same on a real index, both routes: only tool/x.dart there, and + * lib/x.dart too. The old filter and main drew lib/a.dart to the + * function x of tool/x.dart and of lib/x.dart; now no edge. */ +TEST(include_path_dart_fallback_draws_no_symbol) { + char *made = th_mktempdir("cbm_ip_dacc2"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char got[64]; + size_t used = 0; + for (int par = 0; par < 2; par++) { + for (int c = 0; c < 2; c++) { + const char *files[] = {"pubspec.yaml", "name: app\nenvironment:\n sdk: ^3.0.0\ndependencies: &d\n", + "lib/a.dart", "import '../../x.dart';\nvoid f() {}\n", + "tool/x.dart", "void x() {}\n", + c ? "lib/x.dart" : NULL, "void x() {}\n", + NULL}; + char repo[512]; + char db[600]; + snprintf(repo, sizeof(repo), "%s/%s%d", tmp, par ? "par" : "seq", c); + snprintf(db, sizeof(db), "%s/%s%d.db", tmp, par ? "par" : "seq", c); + int workers = 0; + ASSERT_EQ(ip_index_repo(repo, files, db, par != 0, &workers), 0); + ASSERT_TRUE(par ? workers > 1 : workers == 1); + used += (size_t)snprintf(got + used, sizeof(got) - used, "%s%d", used ? " " : "", + ip_targets(db, "lib/a.dart", NULL, NULL)); + } + } + /* only tool/x.dart, lib/x.dart too: sequential, then parallel */ + ASSERT_STR_EQ(got, "0 0 0 0"); + th_cleanup(tmp); + PASS(); +} + +/* Two workspaces of one directory depth that both list one member (`- ../m`): + * pub refuses both ("\"workspace\" members must be subdirectories"), and m + * finds no workspace root among its parents, so dart + * resolves nothing from m. The member's answers are undecided, whatever order + * the files arrive in (before: the first listing in file order won). */ +TEST(include_path_dart_two_workspaces_one_member) { + char *made = th_mktempdir("cbm_ip_dws2"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + const char *a[] = {"a/pubspec.yaml", + "name: wa\nenvironment:\n sdk: ^3.6.0\nworkspace:\n - ../m\n" + "dependency_overrides:\n foo:\n path: ../foo_b\n"}; + const char *b[] = {"b/pubspec.yaml", "name: wb\nenvironment:\n sdk: ^3.6.0\nworkspace:\n - ../m\n"}; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (int order = 0; order < 2; order++) { + const char *const *first = order ? b : a; + const char *const *second = order ? a : b; + const char *files[] = {first[0], first[1], + second[0], second[1], + "m/pubspec.yaml", + "name: m\nenvironment:\n sdk: ^3.6.0\nresolution: workspace\n" + "dependencies:\n foo:\n path: ../foo_a\n", + "foo_a/pubspec.yaml", "name: foo\n", + "foo_a/lib/x.dart", "", + "foo_b/pubspec.yaml", "name: foo\n", + "foo_b/lib/x.dart", "", + "m/lib/main.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/o%d", tmp, order); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + IP_DVERDICT("m/lib/main.dart", "package:foo/x.dart", CBM_INCLUDE_PATH_NONE); + cbm_include_universe_free(u); + } + th_cleanup(tmp); + PASS(); +} + +/* One source per name, as `dart pub get` of the Dart SDK 3.14.1 decides it: pub + * takes one source per package name for a root's whole closure. The root + * depends on foo by path a/ and on b; a second foo deeper makes pub refuse the + * resolution, whichever level it is at ("version solving failed", one level + * down or two), as does pub's host deeper. An override settles it (c/), the + * same directory twice is one source, and a workspace member is that name + * whatever an entry says (`foo: ^1.0.0` from the member a is the member c/). + * A walk that stops at the first level listing the name drew foo to a/ in + * the first three (a false edge: dart resolves nothing). */ +TEST(include_path_dart_one_source_per_closure) { + char *made = th_mktempdir("cbm_ip_dsrc"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const char *const app = + "name: app\nenvironment:\n sdk: ^3.6.0\ndependencies:\n foo:\n path: a\n b:\n path: b\n"; + static const struct { + const char *name; + const char *root; + const char *b; + const char *d; + } cases[] = { + {"a", NULL, "name: b\ndependencies:\n foo:\n path: ../c\n", NULL}, + {"b", NULL, "name: b\ndependencies:\n d:\n path: ../d\n", + "name: d\ndependencies:\n foo:\n path: ../c\n"}, + {"d", + "name: app\nenvironment:\n sdk: ^3.6.0\ndependencies:\n foo:\n path: a\n b:\n path: b\n" + "dependency_overrides:\n foo:\n path: c\n", + "name: b\ndependencies:\n foo:\n path: ../c\n", NULL}, + {"same", NULL, "name: b\ndependencies:\n foo:\n path: ../a\n", NULL}, + {"e", NULL, "name: b\ndependencies:\n foo: ^1.0.0\n", NULL}, + }; + char line[128]; + size_t used = 0; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + const char *files[] = {"pubspec.yaml", cases[i].root ? cases[i].root : app, + "b/pubspec.yaml", cases[i].b, + "a/pubspec.yaml", "name: foo\n", + "a/lib/x.dart", "", + "c/pubspec.yaml", "name: foo\n", + "c/lib/x.dart", "", + "b/lib/y.dart", "", + "bin/main.dart", "", + cases[i].d ? "d/pubspec.yaml" : NULL, cases[i].d, + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/q%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_verdict_t v = ip_dask(u, g, "bin/main.dart", "package:foo/x.dart", got, sizeof(got)); + const char *ans = v == CBM_INCLUDE_PATH_NONE ? "-" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "a/lib/x.dart") == 0 ? "a" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "c/lib/x.dart") == 0 ? "c" + : "?"; + /* and b's own library: a refused resolution resolves no name */ + cbm_include_path_verdict_t vb = + ip_dask(u, g, "bin/main.dart", "package:b/y.dart", got, sizeof(got)); + const char *ansb = vb == CBM_INCLUDE_PATH_NONE ? "-" + : vb == CBM_INCLUDE_PATH_FILE && strcmp(got, "b/lib/y.dart") == 0 ? "y" + : "?"; + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%s:%s/%s", used ? " " : "", + cases[i].name, ans, ansb); + cbm_include_universe_free(u); + } + /* the workspace member listed by version */ + const char *ws[] = {"pubspec.yaml", "name: ws\nenvironment:\n sdk: ^3.6.0\nworkspace:\n - a\n - c\n", + "a/pubspec.yaml", "name: app\nresolution: workspace\ndependencies:\n foo: ^1.0.0\n", + "c/pubspec.yaml", "name: foo\nresolution: workspace\n", + "c/lib/x.dart", "", + "a/bin/main.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/ws", tmp); + cbm_include_universe_t *u = ip_dart_universe(dir, ws, NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_verdict_t v = ip_dask(u, g, "a/bin/main.dart", "package:foo/x.dart", got, sizeof(got)); + used += (size_t)snprintf(line + used, sizeof(line) - used, " ws:%s", + v == CBM_INCLUDE_PATH_FILE && strcmp(got, "c/lib/x.dart") == 0 ? "c" : "?"); + cbm_include_universe_free(u); + /* the same with a second package named foo outside the workspace (d/): dart still takes + * the member c/ */ + const char *ws2[] = {"pubspec.yaml", "name: ws\nenvironment:\n sdk: ^3.6.0\nworkspace:\n - a\n - c\n", + "a/pubspec.yaml", "name: app\nresolution: workspace\ndependencies:\n foo: ^1.0.0\n", + "c/pubspec.yaml", "name: foo\nresolution: workspace\n", + "c/lib/x.dart", "", + "d/pubspec.yaml", "name: foo\n", + "d/lib/x.dart", "", + "a/bin/main.dart", "", + NULL}; + snprintf(dir, sizeof(dir), "%s/ws2", tmp); + u = ip_dart_universe(dir, ws2, NULL); + ASSERT_NOT_NULL(u); + v = ip_dask(u, g, "a/bin/main.dart", "package:foo/x.dart", got, sizeof(got)); + used += (size_t)snprintf(line + used, sizeof(line) - used, " ws2:%s", + v == CBM_INCLUDE_PATH_FILE && strcmp(got, "c/lib/x.dart") == 0 ? "c" : "?"); + cbm_include_universe_free(u); + ASSERT_STR_EQ(line, "a:-/- b:-/- d:c/y same:a/y e:-/- ws:c ws2:c"); + th_cleanup(tmp); + PASS(); +} + +/* A readable closure: a FILE answer for a package: URI needs the root's + * whole closure read. An unread pubspec anywhere in it, or a source the reader + * cannot place, leaves the root's package: answers undecided: it may hold a + * second source of the name (d, unread for `&x dependencies:`, lists foo by + * path ../c, and pub refuses the resolution). The same with d depending on + * e only (dart reads foo at a/) is given up with it; its readable twin (the + * plain key) answers a/. */ +TEST(include_path_dart_unread_closure_undecided) { + char *made = th_mktempdir("cbm_ip_dcls"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const struct { + const char *name; + const char *d; + } cases[] = { + {"c", "name: d\n&x dependencies:\n e:\n path: ../e\n"}, + {"twin", "name: d\ndependencies:\n e:\n path: ../e\n"}, + {"cfoo", "name: d\n&x dependencies:\n foo:\n path: ../c\n"}, + }; + char line[96]; + size_t used = 0; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + const char *files[] = {"pubspec.yaml", + "name: app\nenvironment:\n sdk: ^3.6.0\ndependencies:\n foo:\n path: a\n" + " b:\n path: b\n", + "b/pubspec.yaml", "name: b\ndependencies:\n d:\n path: ../d\n", + "d/pubspec.yaml", cases[i].d, + "e/pubspec.yaml", "name: e\n", + "a/pubspec.yaml", "name: foo\n", + "a/lib/x.dart", "", + "c/pubspec.yaml", "name: foo\n", + "c/lib/x.dart", "", + "bin/main.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/c%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_verdict_t v = ip_dask(u, g, "bin/main.dart", "package:foo/x.dart", got, sizeof(got)); + const char *ans = v == CBM_INCLUDE_PATH_NONE ? "-" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "a/lib/x.dart") == 0 ? "a" + : "?"; + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%s:%s", used ? " " : "", + cases[i].name, ans); + cbm_include_universe_free(u); + } + ASSERT_STR_EQ(line, "c:- twin:a cfoo:-"); + th_cleanup(tmp); + PASS(); +} + +/* The in-repo version rule (a project decision): a version dependency (a constraint, + * `any`, none) on a name exactly one package of the repository carries takes + * that package, as the working setup does. By the committed files pub takes + * the published copy: dart offline finds no copy ("could not find package + * foo in cache"), online it reads pub.dev's. Two namesakes: + * undecided; none: no file; git, the SDK, `hosted:` (with or without a URL) + * with a namesake: undecided, as before. It goes through the whole-closure + * rule like any source: the root's path entry to the unique foo and a version + * entry on foo deeper are one source (dart on the committed files refuses + * the resolution, "foo from hosted and app depends on foo from path"; + * the working setup reads a/), and the namesake's own dependencies join the + * closure. A version entry beside a path entry to another directory of that + * name means two namesakes: pub's host against the path, refused. */ +TEST(include_path_dart_version_takes_the_unique_namesake) { + char *made = th_mktempdir("cbm_ip_dver"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const struct { + const char *name; + const char *root; + const char *b; /* b/pubspec.yaml or NULL */ + const char *foo2; /* a second package named foo at c/, or NULL */ + } cases[] = { + {"ver", "name: app\ndependencies:\n foo: ^1.0.0\n", NULL, NULL}, + {"any", "name: app\ndependencies:\n foo: any\n", NULL, NULL}, + {"empty", "name: app\ndependencies:\n foo:\n", NULL, NULL}, + {"two", "name: app\ndependencies:\n foo: ^1.0.0\n", NULL, "name: foo\n"}, + {"git", "name: app\ndependencies:\n foo:\n git: https://example.invalid/foo.git\n", NULL, NULL}, + {"hosted", "name: app\ndependencies:\n foo:\n hosted: https://pub.example.invalid\n", NULL, NULL}, + {"hostedmap", "name: app\ndependencies:\n foo:\n hosted:\n name: foo\n version: ^1.0.0\n", + NULL, NULL}, + {"e2", "name: app\ndependencies:\n foo:\n path: a\n b:\n path: b\n", + "name: b\ndependencies:\n foo: ^1.0.0\n", NULL}, + {"pathother", "name: app\ndependencies:\n foo: ^1.0.0\n b:\n path: b\n", + "name: b\ndependencies:\n foo:\n path: ../c\n", "name: foo\n"}, + {"deep", "name: app\ndependencies:\n foo: ^1.0.0\n", NULL, NULL}, + }; + char line[256]; + size_t used = 0; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + bool deep = strcmp(cases[i].name, "deep") == 0; + const char *files[] = {"pubspec.yaml", cases[i].root, + "a/pubspec.yaml", + deep ? "name: foo\ndependencies:\n bar:\n path: ../bar\n" : "name: foo\n", + "a/lib/x.dart", "", + "bar/pubspec.yaml", "name: bar\n", + "bar/lib/y.dart", "", + "bin/main.dart", "", + cases[i].b ? "b/pubspec.yaml" : "b/lib/none.dart", cases[i].b ? cases[i].b : "", + cases[i].foo2 ? "c/pubspec.yaml" : "c/lib/none.dart", + cases[i].foo2 ? cases[i].foo2 : "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/v%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + const char *uri = deep ? "package:bar/y.dart" : "package:foo/x.dart"; + cbm_include_path_verdict_t v = ip_dask(u, g, "bin/main.dart", uri, got, sizeof(got)); + const char *ans = v == CBM_INCLUDE_PATH_NONE ? "-" + : v == CBM_INCLUDE_PATH_NO_FILE ? "x" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "a/lib/x.dart") == 0 ? "a" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "bar/lib/y.dart") == 0 ? "bar" + : "?"; + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%s:%s", used ? " " : "", + cases[i].name, ans); + cbm_include_universe_free(u); + } + /* and with no package named foo: no file, as before */ + const char *none[] = {"pubspec.yaml", "name: app\ndependencies:\n foo: ^1.0.0\n", "bin/main.dart", "", NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/none", tmp); + cbm_include_universe_t *u = ip_dart_universe(dir, none, NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_verdict_t v = ip_dask(u, g, "bin/main.dart", "package:foo/x.dart", got, sizeof(got)); + used += (size_t)snprintf(line + used, sizeof(line) - used, " none:%s", + v == CBM_INCLUDE_PATH_NO_FILE ? "x" : "?"); + cbm_include_universe_free(u); + ASSERT_STR_EQ(line, "ver:a any:a empty:a two:- git:- hosted:- hostedmap:- e2:a pathother:- deep:bar none:x"); + th_cleanup(tmp); + PASS(); +} + +/* The same rule on a real index, both routes, and incrementally: the root + * lists foo by version; with no package named foo there is no edge; when the + * repository gains foo/ (a pubspec named foo and its lib/x.dart) the import + * draws one edge to its Module node; when it loses it again, none. At every + * step the kept index holds the IMPORTS edges of a fresh index. */ +TEST(include_path_dart_version_namesake_comes_and_goes) { + char *made = th_mktempdir("cbm_ip_dvi"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char got[64]; + size_t used = 0; + for (int par = 0; par < 2; par++) { + const char *files[] = {"pubspec.yaml", "name: app\ndependencies:\n foo: ^1.0.0\n", + "bin/main.dart", "import 'package:foo/x.dart';\nvoid main() { print(x()); }\n", + NULL}; + char repo[512]; + char kept[600]; + snprintf(repo, sizeof(repo), "%s/%s", tmp, par ? "par" : "seq"); + snprintf(kept, sizeof(kept), "%s/%s.db", tmp, par ? "par" : "seq"); + int workers = 0; + ASSERT_EQ(ip_index_repo(repo, files, kept, par != 0, &workers), 0); + ASSERT_TRUE(par ? workers > 1 : workers == 1); + int n0 = ip_targets(kept, "bin/main.dart", NULL, NULL); + char path[700]; + snprintf(path, sizeof(path), "%s/foo/pubspec.yaml", repo); + ASSERT_EQ(th_write_file(path, "name: foo\n"), 0); + snprintf(path, sizeof(path), "%s/foo/lib/x.dart", repo); + ASSERT_EQ(th_write_file(path, "String x() => 'foo';\n"), 0); + cbm_incremental_route_t r1; + ip_route_env(par != 0, false); + bool same1 = ip_kept_equals_fresh(tmp, repo, kept, par * 10 + 1, &r1); + ip_route_env(par != 0, true); + int n1 = ip_targets(kept, "bin/main.dart", "foo/lib/x.dart", "Module"); + ASSERT_EQ(remove(path), 0); + snprintf(path, sizeof(path), "%s/foo/pubspec.yaml", repo); + ASSERT_EQ(remove(path), 0); + cbm_incremental_route_t r2; + ip_route_env(par != 0, false); + bool same2 = ip_kept_equals_fresh(tmp, repo, kept, par * 10 + 2, &r2); + ip_route_env(par != 0, true); + int n2 = ip_targets(kept, "bin/main.dart", NULL, NULL); + ASSERT_TRUE(same1 && same2); + used += (size_t)snprintf(got + used, sizeof(got) - used, "%s%d %d %d", used ? " | " : "", n0, n1, n2); + } + /* none, then the one Module edge, then none: sequential | parallel */ + ASSERT_STR_EQ(got, "0 1 0 | 0 1 0"); + th_cleanup(tmp); + PASS(); +} + +/* A pubspec whose name the reader did not take may carry any name, so while + * one is indexed the version rule takes no package and names no file + * (undecided): c/pubspec.yaml unread before its `name: foo` (an anchored + * root key first: unread), larger than 1 MB with `name: foo` first, at a path + * that does not fit, or with a name value the reader cannot decode (an escape, + * a tag, the value on the next line). The control `after` names foo before + * the unread line: two namesakes, undecided as before. A pubspec with no + * `name:`, a template's `{{projectName}}` (a flow map to YAML) or `foo-bar` + * (no identifier; unread after it) names nothing: the rule takes a/. `alone`: + * no package named foo but an unread pubspec: undecided, where it was no + * file. */ +TEST(include_path_dart_version_counts_unnamed_pubspecs) { + char *made = th_mktempdir("cbm_ip_dun"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + enum { IP_BIG = 1100 * 1024 }; + char *big = malloc(IP_BIG + 64); + ASSERT_NOT_NULL(big); + size_t bn = (size_t)snprintf(big, 64, "name: foo\n"); + while (bn + 8 < IP_BIG) { + memcpy(big + bn, "# pad.\n", 7); + bn += 7; + } + big[bn] = '\0'; + char longp[1200]; + static const struct { + const char *name; + const char *c; /* c/pubspec.yaml, NULL: none */ + bool has_a; /* a/ is the package named foo */ + bool longer; /* a pubspec.yaml at a path that does not fit */ + } cases[] = { + {"unread", "&d description: copy\nname: foo\n", true, false}, + {"big", "", true, false}, + {"long", NULL, true, true}, + {"badname", "name: \"f\\x6fo\"\n", true, false}, + {"tagged", "name: !!str foo\n", true, false}, + {"nextline", "name:\n foo\n", true, false}, + {"after", "name: foo\n&d description: copy\n", true, false}, + {"noname", "description: copy\n", true, false}, + {"template", "name: {{projectName}}\n", true, false}, + {"dashed", "name: foo-bar\n&d description: copy\n", true, false}, + {"alone", "&d description: copy\nname: foo\n", false, false}, + }; + char line[256]; + size_t used = 0; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + const char *c = strcmp(cases[i].name, "big") == 0 ? big : cases[i].c; + const char *files[] = {"pubspec.yaml", "name: app\ndependencies:\n foo: ^1.0.0\n", + "bin/main.dart", "", + cases[i].has_a ? "a/pubspec.yaml" : "a/none.txt", + cases[i].has_a ? "name: foo\n" : "", + "a/lib/x.dart", "", + c ? "c/pubspec.yaml" : "c/lib/none.dart", c ? c : "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/u%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe( + dir, files, cases[i].longer ? ip_long_path(longp, sizeof(longp), "pubspec.yaml") : NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_verdict_t v = ip_dask(u, g, "bin/main.dart", "package:foo/x.dart", got, sizeof(got)); + const char *ans = v == CBM_INCLUDE_PATH_NONE ? "-" + : v == CBM_INCLUDE_PATH_NO_FILE ? "x" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "a/lib/x.dart") == 0 ? "a" + : "?"; + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%s:%s", used ? " " : "", + cases[i].name, ans); + cbm_include_universe_free(u); + } + free(big); + ASSERT_STR_EQ(line, "unread:- big:- long:- badname:- tagged:- nextline:- after:- noname:a template:a " + "dashed:a alone:-"); + th_cleanup(tmp); + PASS(); +} + +/* The same on a real index, both routes, and incrementally: the root lists + * foo by version and a/ is the one package named foo (one Module edge); then + * c/pubspec.yaml appears unread before its `name: foo` (no edge); then it is + * renamed bar and read whole (the edge again). At every step the kept index + * holds the IMPORTS edges of a fresh index. */ +TEST(include_path_dart_version_unnamed_namesake_comes_and_goes) { + char *made = th_mktempdir("cbm_ip_dui"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + char got[64]; + size_t used = 0; + for (int par = 0; par < 2; par++) { + const char *files[] = {"pubspec.yaml", "name: app\ndependencies:\n foo: ^1.0.0\n", + "bin/main.dart", "import 'package:foo/x.dart';\nvoid main() { print(x()); }\n", + "a/pubspec.yaml", "name: foo\n", + "a/lib/x.dart", "String x() => 'a';\n", + NULL}; + char repo[512]; + char kept[600]; + snprintf(repo, sizeof(repo), "%s/%s", tmp, par ? "par" : "seq"); + snprintf(kept, sizeof(kept), "%s/%s.db", tmp, par ? "par" : "seq"); + int workers = 0; + ASSERT_EQ(ip_index_repo(repo, files, kept, par != 0, &workers), 0); + ASSERT_TRUE(par ? workers > 1 : workers == 1); + int n0 = ip_targets(kept, "bin/main.dart", "a/lib/x.dart", "Module"); + char path[700]; + snprintf(path, sizeof(path), "%s/c/pubspec.yaml", repo); + ASSERT_EQ(th_write_file(path, "&d description: copy\nname: foo\n"), 0); + cbm_incremental_route_t r1; + ip_route_env(par != 0, false); + bool same1 = ip_kept_equals_fresh(tmp, repo, kept, par * 10 + 1, &r1); + ip_route_env(par != 0, true); + int n1 = ip_targets(kept, "bin/main.dart", NULL, NULL); + ASSERT_EQ(th_write_file(path, "name: bar\n"), 0); + cbm_incremental_route_t r2; + ip_route_env(par != 0, false); + bool same2 = ip_kept_equals_fresh(tmp, repo, kept, par * 10 + 2, &r2); + ip_route_env(par != 0, true); + int n2 = ip_targets(kept, "bin/main.dart", "a/lib/x.dart", "Module"); + ASSERT_TRUE(same1 && same2); + used += (size_t)snprintf(got + used, sizeof(got) - used, "%s%d %d %d", used ? " | " : "", n0, n1, n2); + } + /* the Module edge, none, the Module edge again: sequential | parallel */ + ASSERT_STR_EQ(got, "1 0 1 | 1 0 1"); + th_cleanup(tmp); + PASS(); +} + +/* A value that opens a quote, `[` or `{` and does not close it on its own + * line makes the pubspec unread, at the root and inside any section: its next + * lines are the value's, not keys (as `dart pub get` of the Dart SDK 3.14.1 + * reads them). A root value + * continued at column 0 would otherwise read `dependency_overrides:` and its + * foo_b as keys; inside `dependencies`, an entry's value continued so; the same + * values continued on indented lines (YAML reads one long value) are unread + * too. Values closed on their line, and a `#` inside quotes, are read. */ +TEST(include_path_dart_reader_open_value_unread) { + char *made = th_mktempdir("cbm_ip_dov"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); +#define IP_OVR "dependency_overrides:\n foo:\n path: foo_b\n" +#define IP_DEPA "dependencies:\n foo:\n path: foo_a\n" +#define IP_HEAD "name: app\nenvironment:\n sdk: ^3.6.0\n" + static const struct { + const char *name; + const char *root; + } cases[] = { + {"dq", IP_HEAD "description: \"one\n" IP_OVR " # two\"\n" IP_DEPA}, + {"sq", IP_HEAD "description: 'one\n" IP_OVR " # two'\n" IP_DEPA}, + {"brack", IP_HEAD "x_note: [one,\n" IP_OVR " # two]\n" IP_DEPA}, + {"brace", IP_HEAD "x_note: {one: 1,\n" IP_OVR " # two: 2}\n" IP_DEPA}, + {"dq_ind", IP_HEAD "description: \"one\n dependency_overrides:\n foo:\n path: foo_b\n two\"\n" IP_DEPA}, + {"sec_dq", IP_HEAD "dependencies:\n foo:\n path: foo_a\n bar: \"one\n" IP_OVR " # two\"\n"}, + {"sec_brace_ind", IP_HEAD "dependencies:\n foo: {\n path: foo_a}\n"}, + {"skipped", IP_HEAD "flutter:\n assets: [one,\n" IP_OVR " # two]\n" IP_DEPA}, + {"closed", IP_HEAD "description: \"one two\"\nx_note: [one, {two: 2}]\n" IP_DEPA}, + {"hash", IP_HEAD "description: \"one # two\"\n" IP_DEPA}, + }; +#undef IP_OVR +#undef IP_DEPA +#undef IP_HEAD + char line[256]; + size_t used = 0; + char got[1024]; + cbm_gbuf_t *g = NULL; + for (size_t i = 0; i < sizeof(cases) / sizeof(cases[0]); i++) { + const char *files[] = {"pubspec.yaml", cases[i].root, + "bin/main.dart", "", + "foo_a/pubspec.yaml", "name: foo\n", + "foo_a/lib/x.dart", "", + "foo_b/pubspec.yaml", "name: foo\n", + "foo_b/lib/x.dart", "", + NULL}; + char dir[512]; + snprintf(dir, sizeof(dir), "%s/o%zu", tmp, i); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_verdict_t v = ip_dask(u, g, "bin/main.dart", "package:foo/x.dart", got, sizeof(got)); + const char *ans = v == CBM_INCLUDE_PATH_NONE ? "-" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "foo_a/lib/x.dart") == 0 ? "a" + : v == CBM_INCLUDE_PATH_FILE && strcmp(got, "foo_b/lib/x.dart") == 0 ? "b" + : "?"; + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%s:%s", used ? " " : "", + cases[i].name, ans); + cbm_include_universe_free(u); + } + ASSERT_STR_EQ(line, "dq:- sq:- brack:- brace:- dq_ind:- sec_dq:- sec_brace_ind:- skipped:- closed:a hash:a"); + th_cleanup(tmp); + PASS(); +} + +/* A CFML file in the run lists every indexed path (a template may name any + * file); a Dart answer reads only the names the listing keeps without one: + * `import 'data.txt'` from bin/main.dart, with bin/data.txt indexed, names no + * file with and without a .cfm in the run, and `import 'util.dart'` names + * bin/util.dart in both. */ +TEST(include_path_dart_answer_ignores_cfml_listing) { + char *made = th_mktempdir("cbm_ip_dcf"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + static const char *const rels[] = {"pubspec.yaml", "bin/main.dart", "bin/data.txt", + "bin/util.dart", "page.cfm"}; + static const char *const texts[] = {"name: app\n", "", "x\n", "", "

x

\n"}; + char paths[5][512]; + cbm_file_info_t files[5]; + for (int i = 0; i < 5; i++) { + snprintf(paths[i], sizeof(paths[i]), "%s/%s", tmp, rels[i]); + ASSERT_EQ(th_write_file(paths[i], texts[i]), 0); + memset(&files[i], 0, sizeof(files[i])); + files[i].rel_path = (char *)rels[i]; + files[i].path = paths[i]; + } + files[4].language = CBM_LANG_CFML; + char line[64]; + size_t used = 0; + char got[1024]; + for (int with = 0; with < 2; with++) { + cbm_include_universe_t *u = cbm_include_universe_new(files, with ? 5 : 4); + ASSERT_NOT_NULL(u); + char a = ip_verdict_letter(ip_dask(u, NULL, "bin/main.dart", "data.txt", got, sizeof(got))); + char b = ip_verdict_letter(ip_dask(u, NULL, "bin/main.dart", "util.dart", got, sizeof(got))); + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%c%c", used ? " " : "", a, b); + cbm_include_universe_free(u); + } + /* data.txt, util.dart: without | with the CFML file */ + ASSERT_STR_EQ(line, "xf xf"); + th_cleanup(tmp); + PASS(); +} + +/* The answer array a finished walk makes cannot be allocated: the universe + * is failed, so every answer is NONE from then on (the package URI that asked, + * a relative one, a Make include), and the walk's state is freed (the + * sanitizers' leak check decides that part). The same questions without the + * failure: foo's file, the relative file, the makefile's include. */ +TEST(include_path_dart_answers_alloc_failure_answers_none) { + char *made = th_mktempdir("cbm_ip_daf"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + const char *files[] = {"pubspec.yaml", "name: app\ndependencies:\n foo:\n path: foo\n", + "foo/pubspec.yaml", "name: foo\n", + "foo/lib/x.dart", "", + "bin/util.dart", "", + "bin/main.dart", "", + "Makefile", "include rules.mk\n", + "rules.mk", "X := 1\n", + NULL}; + char line[64]; + size_t used = 0; + char got[1024]; + for (int fail = 0; fail < 2; fail++) { + char dir[512]; + snprintf(dir, sizeof(dir), "%s/r%d", tmp, fail); + cbm_include_universe_t *u = ip_dart_universe(dir, files, NULL); + ASSERT_NOT_NULL(u); + cbm_include_path_test_fail_answers(fail ? 1 : 0); + char a = ip_verdict_letter(ip_dask(u, NULL, "bin/main.dart", "package:foo/x.dart", got, sizeof(got))); + bool fired = cbm_include_path_test_reset_answers_failure(); + char b = ip_verdict_letter(ip_dask(u, NULL, "bin/main.dart", "util.dart", got, sizeof(got))); + char c = ip_verdict_letter(ip_ask(u, CBM_LANG_MAKEFILE, "Makefile", "rules.mk", got, sizeof(got))); + used += (size_t)snprintf(line + used, sizeof(line) - used, "%s%d%c%c%c", used ? " " : "", + fired ? 1 : 0, a, b, c); + cbm_include_universe_free(u); + } + /* fired, package:foo, util.dart, rules.mk: without | with the failure */ + ASSERT_STR_EQ(line, "0fff 1---"); + th_cleanup(tmp); + PASS(); +} + +/* A character a package name may hold. */ +static bool ip_name_char(uint32_t c) { + return (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_'; +} + +/* FNV-1a over `s`, from the state `h`. */ +static uint32_t ip_fnv_from(uint32_t h, const char *s) { + for (; *s; s++) { + h = (h ^ (uint8_t)*s) * 16777619U; + } + return h; +} + +/* Names that share the low 9 bits of their FNV-1a value, by construction: + * a prefix "p" and two closing characters solved from the prefix's value. + * Each FNV-1a step XORs a byte into the state and multiplies by an odd prime, + * and a product's low bits depend only on its factors' low bits: the low 9 + * bits of the value follow from the low 9 bits of the bytes alone, so the last + * two characters can be chosen to bring them to zero, and everything that + * tells the names apart is left in the high 23 bits. The slot of an answer is + * the low bits of its key (the capacity is a power of two): with FNV-1a alone + * all 300 names share one home slot, and putting and looking up n of them + * examines about n * n slots; the finaliser mixes the high bits into the low + * ones. One root with 300 such dependencies, each asked once: the slots + * examined stay linear in the names. */ +TEST(include_path_dart_answers_spread_colliding_names) { + enum { IP_CN = 300, IP_CN_MASK = 511 }; + static char names[IP_CN][24]; + int found = 0; + for (int i = 0; found < IP_CN; i++) { + char pre[16]; + snprintf(pre, sizeof(pre), "p%d", i); + uint32_t s = ip_fnv_from(2166136261U, pre); + for (uint32_t c1 = 'a'; c1 <= 'z'; c1++) { + /* the low 9 bits after c1; c2 equal to them XORs them to zero */ + uint32_t c2 = ((s ^ c1) * 16777619U) & IP_CN_MASK; + if (ip_name_char(c2)) { + snprintf(names[found++], sizeof(names[0]), "%s%c%c", pre, (char)c1, (char)c2); + break; + } + } + } + for (int i = 0; i < IP_CN; i++) { + ASSERT_EQ(ip_fnv_from(2166136261U, names[i]) & IP_CN_MASK, 0); + } + size_t cap = (size_t)IP_CN * 24 + 64; + char *pub = malloc(cap); + ASSERT_NOT_NULL(pub); + size_t used = (size_t)snprintf(pub, cap, "name: app\ndependencies:\n"); + for (int i = 0; i < IP_CN; i++) { + used += (size_t)snprintf(pub + used, cap - used, " %s: ^1.0.0\n", names[i]); + } + char *made = th_mktempdir("cbm_ip_dcol"); + ASSERT_NOT_NULL(made); + char tmp[256]; + snprintf(tmp, sizeof(tmp), "%s", made); + const char *files[] = {"pubspec.yaml", pub, "lib/main.dart", "", NULL}; + cbm_include_universe_t *u = ip_dart_universe(tmp, files, NULL); + ASSERT_NOT_NULL(u); + char got[1024]; + uint64_t before = cbm_include_path_test_probes(); + cbm_include_path_verdict_t first = CBM_INCLUDE_PATH_NOT_A_PATH; + bool same = true; + for (int i = 0; i < IP_CN; i++) { + char uri[64]; + snprintf(uri, sizeof(uri), "package:%s/a.dart", names[i]); + cbm_include_path_verdict_t v = ip_dask(u, NULL, "lib/main.dart", uri, got, sizeof(got)); + first = i == 0 ? v : first; + same = same && v == first; + } + uint64_t probes = cbm_include_path_test_probes() - before; + cbm_include_universe_free(u); + free(pub); + th_cleanup(tmp); + fprintf(stderr, " answer-array probes, %d names sharing their low bits: %llu\n", IP_CN, + (unsigned long long)probes); + ASSERT_TRUE(same); + /* 301 names put, 300 looked up: at most 4 slots each */ + ASSERT_TRUE(probes <= (uint64_t)(2 * IP_CN + 1) * 4); + PASS(); +} + SUITE(include_path) { RUN_TEST(include_path_fallback_takes_only_the_named_file_sequential); RUN_TEST(include_path_fallback_takes_only_the_named_file_parallel); @@ -1150,4 +3863,40 @@ SUITE(include_path) { RUN_TEST(include_path_cfml_swapped_spelling); RUN_TEST(include_path_cfml_swapped_spelling_component); RUN_TEST(include_path_make_route_ignores_cfml_listing); + RUN_TEST(include_path_make_route_ignores_dart_names); + RUN_TEST(include_path_dart_uri_rule); + RUN_TEST(include_path_dart_exact_path_not_node_name); + RUN_TEST(include_path_dart_lib_is_package_space); + RUN_TEST(include_path_dart_dot_segments_in_order); + RUN_TEST(include_path_dart_directory_uri); + RUN_TEST(include_path_dart_package_classes); + RUN_TEST(include_path_dart_overrides_file); + RUN_TEST(include_path_dart_pubspec_reader); + RUN_TEST(include_path_dart_edges_name_the_package_file); + RUN_TEST(include_path_file_target_is_that_file); + RUN_TEST(include_path_dart_incremental_equals_full); + RUN_TEST(include_path_failed_insert_answers_none); + RUN_TEST(include_path_dart_universe_grows_linearly); + RUN_TEST(include_path_dart_reader_takes_what_dart_takes); + RUN_TEST(include_path_dart_unread_pubspec_draws_no_edge); + RUN_TEST(include_path_dart_overrides_and_sources); + RUN_TEST(include_path_dart_chain_square_limit_is_pinned); + RUN_TEST(include_path_dart_reader_whitelist); + RUN_TEST(include_path_dart_reader_whitelist_workspace); + RUN_TEST(include_path_dart_whitelist_draws_nothing); + RUN_TEST(include_path_dart_names_and_chain_grow_linearly); + RUN_TEST(include_path_dart_roots_cost_roots_times_subgraph); + RUN_TEST(include_path_dart_fallback_takes_the_one_file); + RUN_TEST(include_path_dart_fallback_draws_no_symbol); + RUN_TEST(include_path_dart_two_workspaces_one_member); + RUN_TEST(include_path_dart_one_source_per_closure); + RUN_TEST(include_path_dart_unread_closure_undecided); + RUN_TEST(include_path_dart_version_takes_the_unique_namesake); + RUN_TEST(include_path_dart_version_namesake_comes_and_goes); + RUN_TEST(include_path_dart_version_counts_unnamed_pubspecs); + RUN_TEST(include_path_dart_version_unnamed_namesake_comes_and_goes); + RUN_TEST(include_path_dart_reader_open_value_unread); + RUN_TEST(include_path_dart_answer_ignores_cfml_listing); + RUN_TEST(include_path_dart_answers_alloc_failure_answers_none); + RUN_TEST(include_path_dart_answers_spread_colliding_names); }