diff options
| author | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-16 16:35:24 +0000 |
|---|---|---|
| committer | Pjotr Prins <pjotr.public01@thebird.nl> | 2026-11-16 16:35:24 +0000 |
| commit | d5e90011f764ba27251936d4fa628e1100145773 (patch) | |
| tree | 0f671a2b19bb24af91201776746b8e6d511eb95b /git.odin | |
| parent | dc4c16203674191c4821b2f7b53e01febb7a11a6 (diff) | |
| download | ai-memory-d5e90011f764ba27251936d4fa628e1100145773.tar.gz | |
symbols: C and C++ declarations from ctags, diffed between blobs
C and C++ were the one language family where the store could only say "a hunk
landed inside this function". A diff line cannot be read for declarations
there: inside a body `foo(bar);` calls something, inside a class body the same
bytes declare a constructor, and pangemma indents both the same way (of 248538
changed lines in its history, 14991 are indented `name(` lines, and the most
frequent are calls). So the file is handed to universal-ctags and the tags of a
commit's blob are diffed against its parent's: present only in the new blob is
an add, only in the old one is a remove, and a name whose tag survives both is
left to hunk context, which is the honest answer for "the change was inside
this".
The cost is bounded by a cache keyed by git object id (new table `blobs`): a
blob's tags can never change, so each file version is parsed once per store.
On the pangemma history (688 commits, 1163 distinct C/C++ blobs) the first full
pass takes 26 s and touches go from 1404 context-only rows to 6888 add, 5125
remove, 1505 context; the second pass takes 11 s and runs no ctags at all.
ctags is optional at run time. Without it the store behaves exactly as before
and `sync` says so once. The Guix package bakes its absolute path into
$AI_MEMORY_CTAGS through wrap-program, and the check phase now builds a
two-commit git repository with one C++ file to prove it end to end: the
function added in the second commit is `add`, the one whose body changed is
`context`.
Details found by running it on a real history, all in this commit:
- lambdas are tagged by default under names ctags derives from a hash of the
file (`__anon426fc91f0102`), so every touched file reported seven functions
added and seven removed per commit; `--extras=-{anonymous}` turns them off.
- `--kinds-C++=+p` is needed or prototypes are invisible and a declaration in a
header would never be seen.
- include guards (`#define CALC_H`, `#define __CALC_H__`) are filtered: they are
bookkeeping, while other macros are kept as `const`.
- merge_decl keyed a commit's declarations by bare identifier, so two files
declaring the same name in one commit collided and one lost its attribution.
It is keyed by (file, name) now -- a bug that applied to Odin and Rust too.
Diffstat (limited to 'git.odin')
| -rw-r--r-- | git.odin | 397 |
1 files changed, 391 insertions, 6 deletions
diff --git a/git.odin b/git.odin index 27a64cb..f8e0c02 100644 --- a/git.odin +++ b/git.odin @@ -100,10 +100,12 @@ git_log :: proc(limit: int) -> ([]Git_Commit, bool) { return commits[:], true } -// git_touched reports the symbols commit HASH touched, from two sources: -// declarations that appear or disappear on +/- lines, and the enclosing item -// named in each hunk header (git's userdiff patterns, so no parsing needed). -git_touched :: proc(hash: string) -> ([]Decl, bool) { +// git_touched reports the symbols commit HASH touched, from three sources: +// declarations that appear or disappear on +/- lines (Odin, Rust), declarations +// diffed between file blobs by ctags (C, C++), and the enclosing item named in +// each hunk header (git's userdiff patterns, so no parsing needed). DB is the +// store whose blob cache the ctags pass reads and fills; nil disables it. +git_touched :: proc(hash: string, db: ^Db = nil) -> ([]Decl, bool) { raw, ok := git([]string{"show", "--unified=0", "--no-color", "--no-renames", "--format=", "--no-ext-diff", hash}) if !ok { @@ -144,6 +146,18 @@ git_touched :: proc(hash: string) -> ([]Decl, bool) { } } + if db != nil { + // C-family declarations are not readable off a line, so they come from + // the file blobs -- see c_family_decls. + cdecls, cok := c_family_decls(db, hash) + if !cok { + return nil, false + } + for d in cdecls { + merge_decl(&found, d) + } + } + decls := make([dynamic]Decl, 0, len(found)) for _, d in found { append(&decls, d) @@ -151,6 +165,372 @@ git_touched :: proc(hash: string) -> ([]Decl, bool) { return decls[:], true } +// ---- C and C++ declarations, from universal-ctags --------------------------- +// +// A C-family declaration cannot be read off a diff line: inside a function body +// `foo(bar);' calls something, inside a class body the same bytes declare a +// constructor, and both are indented the same way. So the file itself is handed +// to ctags -- a real parser -- and the *sets* of declarations in the parent blob +// and the new blob are compared; what is only in the new one was added, what is +// only in the old one was removed. A name whose tag survives both is left to +// hunk context, which is the honest answer for "the change was inside this". +// +// The cost is bounded by caching: a blob's tags are stored under its git object +// id, and a blob never changes, so each file version is parsed once per store +// however many commits mention it. Re-syncing an imported history runs no ctags +// at all. + +// ctags_path returns the ctags to run: $AI_MEMORY_CTAGS (the Guix package bakes +// in an absolute path, so this does not depend on PATH), else `ctags'. +ctags_path :: proc() -> string { + if env := os.get_env("AI_MEMORY_CTAGS", context.temp_allocator); len(env) > 0 { + return env + } + return "ctags" +} + +// CTAGS_MISSING keeps the warning to one line: ctags is optional, and a missing +// binary must not turn every sync into a wall of text. +CTAGS_MISSING: bool + +// Blob_Change is one file in `git show --raw': the path, and the object ids +// before and after. An all-zero id means the file did not exist on that side. +Blob_Change :: struct { + path: string, + old: string, + new: string, +} + +// raw_changes lists the file-level changes of HASH. +raw_changes :: proc(hash: string) -> ([]Blob_Change, bool) { + raw, ok := git([]string{"show", "--raw", "--no-renames", "--no-abbrev", + "--no-color", "--format=", hash}) + if !ok { + return nil, false + } + changes := make([dynamic]Blob_Change, 0, 8) + for line in split_byte(raw, '\n') { + // ":100644 100644 <old> <new> M\tpath" + if len(line) == 0 || line[0] != ':' { + continue + } + fields := split_byte(line, ' ') + if len(fields) < 5 { + continue + } + tab := strings.index_byte(fields[4], '\t') + if tab < 0 { + continue + } + append(&changes, Blob_Change{ + path = fields[4][tab + 1:], + old = fields[2], + new = fields[3], + }) + } + return changes[:], true +} + +// sha_absent reports whether an object id names nothing, i.e. the file was added +// (old side) or deleted (new side). +sha_absent :: proc(sha: string) -> bool { + if len(sha) == 0 { + return true + } + for c in sha { + if c != '0' { + return false + } + } + return true +} + +// Blob_Source is one blob to parse, with the suffix EXT so ctags can tell a C +// file from a C++ one. +Blob_Source :: struct { + blob: string, + ext: string, +} + +// c_family_decls reports the C-family declarations HASH added and removed. +// +// A commit that touches no C-family file costs one `git show --raw' and returns +// nothing. ctags itself is only run for blobs the cache does not have, and if +// ctags cannot be run at all the store keeps working the way it did before this +// pass existed: hunk context, no add/remove for C and C++. +c_family_decls :: proc(db: ^Db, hash: string) -> (decls: []Decl, ok: bool) { + changes, ok_changes := raw_changes(hash) + if !ok_changes { + return nil, false + } + + // Which blobs this commit needs, and the suffix to parse each under. One + // blob can appear twice (a file changed in two commits); the map keeps one. + needed := make(map[string]string) + defer delete(needed) + n := 0 + for change in changes { + if lang_of(change.path) != .C_Family { + continue + } + n += 1 + ext := c_family_ext(change.path) + if !sha_absent(change.old) { + needed[change.old] = ext + } + if !sha_absent(change.new) { + needed[change.new] = ext + } + } + if n == 0 { + return nil, true + } + if len(needed) == 0 { + return nil, true + } + + // The store's cache first; whatever is left is parsed in one ctags run. + tags := make(map[string]string) + defer delete(tags) + sources := make([dynamic]Blob_Source, 0, len(needed)) + for blob, ext in needed { + if cached, has := cached_blob_tags(db, blob); has { + tags[blob] = cached + } else { + append(&sources, Blob_Source{blob = blob, ext = ext}) + } + } + if len(sources) > 0 { + fresh, ok_parse := parse_blob_tags(sources[:]) + if !ok_parse { + // Caches stay valid; the commit simply gets no declaration-level + // attribution for its C-family files. Not an error: imports must + // not stop because a helper is missing. + return nil, true + } + for blob, t in fresh { + tags[blob] = t + store_blob_tags(db, blob, t) + } + } + + out := make([dynamic]Decl, 0, 8) + for change in changes { + if lang_of(change.path) != .C_Family { + continue + } + old_tags := tags[change.old] or_else "" + new_tags := tags[change.new] or_else "" + old_set := make(map[string]bool) + defer delete(old_set) + for line in split_byte(old_tags, '\n') { + if len(line) > 0 { + old_set[line] = true + } + } + new_set := make(map[string]bool) + defer delete(new_set) + for line in split_byte(new_tags, '\n') { + if len(line) > 0 { + new_set[line] = true + } + } + for line in split_byte(new_tags, '\n') { + if len(line) == 0 || old_set[line] { + continue + } + if d, is_decl := decl_of_tag(line, change.path); is_decl { + d.added = true + append(&out, d) + } + } + for line in split_byte(old_tags, '\n') { + if len(line) == 0 || new_set[line] { + continue + } + if d, is_decl := decl_of_tag(line, change.path); is_decl { + d.removed = true + append(&out, d) + } + } + } + return out[:], true +} + +// decl_of_tag turns a cached tag line, "<ctags kind><TAB><name>", into a Decl. +decl_of_tag :: proc(tag, file: string) -> (d: Decl, ok: bool) { + tab := strings.index_byte(tag, '\t') + if tab < 0 { + return {}, false + } + tag_kind := tag[:tab] + kind, is_decl := c_family_kind(tag_kind) + if !is_decl { + return {}, false + } + name := tag[tab + 1:] + if len(name) == 0 { + return {}, false + } + // `#define CALC_H' and `#define __CALC_H__' guard a header; they are + // bookkeeping, not something a reader asks why about. + if tag_kind == "macro" && is_include_guard(name) { + return {}, false + } + return Decl{name = name, kind = kind, file = file}, true +} + +// is_include_guard reports whether NAME looks like a header guard. +is_include_guard :: proc(name: string) -> bool { + if strings.has_prefix(name, "__") { + return true + } + return strings.has_suffix(name, "_H") || strings.has_suffix(name, "_H__") || + strings.has_suffix(name, "_HPP") || strings.has_suffix(name, "_HH") || + strings.has_suffix(name, "_INCLUDED") +} + +// c_family_ext returns the suffix of PATH, which is what ctags keys the language +// on; the temporary file keeps it. +c_family_ext :: proc(path: string) -> string { + for ext in C_EXTENSIONS { + if strings.has_suffix(path, ext) { + return ext + } + } + return "" +} + +// cached_blob_tags reads the tags of BLOB from the store, if they were parsed +// before. +cached_blob_tags :: proc(db: ^Db, blob: string) -> (tags: string, ok: bool) { + s, sok := stmt(db, "select tags from blobs where blob = ?1") + if !sok { + return "", false + } + defer stmt_close(&s) + stmt_bind_text(&s, 1, blob) + if stmt_step(&s) != .Row { + return "", false + } + return stmt_col_text(&s, 0), true +} + +// store_blob_tags adds a parsed blob to the cache. `on conflict do nothing': +// a blob's tags are a function of its content, so an existing row is already +// right, and re-writing it would only churn the file. +store_blob_tags :: proc(db: ^Db, blob, tags: string) -> bool { + s, ok := stmt(db, `insert into blobs (blob, tags) values (?1, ?2) + on conflict (blob) do nothing`) + if !ok { + return false + } + defer stmt_close(&s) + stmt_bind_text(&s, 1, blob) + stmt_bind_text(&s, 2, tags) + return stmt_step(&s) == .Done +} + +// parse_blob_tags parses each source blob with one ctags run and returns, per +// blob, its tags as "<ctags kind><TAB><name>" lines. The raw ctags kind is kept +// in the cache and mapped to the store's vocabulary when the tag is used, so a +// changed mapping does not need the blobs re-parsed. +// +// The blobs have to be real files: ctags reads the language from the name. They +// are written into one temporary directory and removed again. +parse_blob_tags :: proc(sources: []Blob_Source) -> (tags: map[string]string, ok: bool) { + tmp_root, tmp_err := os.temp_directory(context.temp_allocator) + if tmp_err != nil { + fmt.eprintfln("ai-memory: no temporary directory: %v", tmp_err) + return nil, false + } + dir := fmt.tprintf("%s/ai-memory-tags-%d", tmp_root, os.get_pid()) + if err := os.make_directory_all(dir); err != nil { + fmt.eprintfln("ai-memory: cannot create %s: %v", dir, err) + return nil, false + } + defer os.remove_all(dir) + + paths := make([dynamic]string, 0, len(sources)) + by_path := make(map[string]string) + defer delete(by_path) + for src, i in sources { + content, cat_ok := git([]string{"cat-file", "blob", src.blob}) + if !cat_ok { + continue + } + path := fmt.tprintf("%s/%d%s", dir, i, src.ext) + if err := os.write_entire_file_from_bytes(path, transmute([]u8)content); err != nil { + fmt.eprintfln("ai-memory: cannot write %s: %v", path, err) + continue + } + append(&paths, path) + by_path[path] = src.blob + } + if len(paths) == 0 { + return make(map[string]string), true + } + + args := make([dynamic]string, 0, len(paths) + 8, context.temp_allocator) + append(&args, "--sort=no", "--fields=+K", "-o", "-") + // Lambdas are tagged by default, under names ctags derives from a hash of + // the file (`__anon426fc91f0102'): they change whenever the line moves, so + // every commit would report a handful of functions added and removed. They + // are not declarations a reader asks about; the enclosing function is what + // hunk context already gives. + append(&args, "--extras=-{anonymous}") + // Prototypes are off by default, and without them a declaration in a header + // is invisible: only definitions in .cpp files would ever be `added'. + append(&args, "--kinds-C=+p", "--kinds-C++=+p") + append(&args, ..paths[:]) + + out, run_ok := run_capture(ctags_path(), args[:]) + if !run_ok { + if !CTAGS_MISSING { + CTAGS_MISSING = true + fmt.eprintln("ai-memory: ctags is not runnable, so C and C++ declarations " + + "keep hunk context only (set $AI_MEMORY_CTAGS)") + } + return nil, false + } + + tags = make(map[string]string) + for line in split_byte(out, '\n') { + if len(line) == 0 || line[0] == '!' { + continue + } + // "name<TAB>path<TAB>/^pattern$/;"<TAB>kind[<TAB>extra fields]" + fields := split_byte(line, '\t') + if len(fields) < 4 { + continue + } + name := fields[0] + blob := by_path[fields[1]] or_else "" + if len(blob) == 0 || len(name) == 0 { + continue + } + tag := fmt.tprintf("%s\t%s", fields[3], name) + tags[blob] = strings.concatenate({tags[blob] or_else "", tag, "\n"}, context.temp_allocator) + } + return tags, true +} + +// run_capture runs EXE with ARGS and returns its stdout. Unlike `git', a failure +// here is not fatal: ctags is an optional helper. +run_capture :: proc(exe: string, args: []string) -> (out: string, ok: bool) { + cmd := make([dynamic]string, 0, len(args) + 1, context.temp_allocator) + append(&cmd, exe) + append(&cmd, ..args) + state, stdout, _, err := os.process_exec({command = cmd[:]}, context.temp_allocator) + if err != nil { + return "", false + } + if state.exit_code != 0 { + return "", false + } + return string(stdout), true +} + // is_change_line reports an added or removed line, excluding file headers. is_change_line :: proc(line: string) -> bool { if len(line) < 2 { @@ -165,12 +545,17 @@ is_change_line :: proc(line: string) -> bool { // merge_decl adds D to M, keeping the strongest evidence seen for the symbol. merge_decl :: proc(m: ^map[string]Decl, decl: Decl) { d := decl - if old, exists := m[d.name]; exists { + // Keyed by file *and* name, not by name: `main.open_store' and `db.open' + // in one commit are two symbols, and merging them threw one away and + // gave the survivor the other file's attribution. The separator cannot + // occur in a path or an identifier. + key := fmt.tprintf("%s\x1f%s", d.file, d.name) + if old, exists := m[key]; exists { d.added = d.added || old.added d.removed = d.removed || old.removed d.in_context = d.in_context || old.in_context } - m[d.name] = d + m[key] = d } // hunk_context returns the text after the closing "@@" of a hunk header. |
