Rickesh's picture
Upload folder using huggingface_hub
829dbce verified
Raw
History Blame Contribute Delete
13.1 kB
// Code graph: scan a repo, find symbols and file-to-file edges, then segment
// along that structure instead of along character offsets.
//
// Deliberately lexical, not a parser. A real parse (tree-sitter, clang) is a
// dependency and a build burden, and the segmentation only needs to know where
// a symbol starts and which files reference which. Heuristics that are right
// most of the time produce better segments than exact offsets would, because
// the consumer is a language model reading the text anyway.
#include "ctxstream.hpp"
#include <algorithm>
#include <cctype>
#include <filesystem>
#include <fstream>
#include <map>
#include <regex>
#include <set>
#include <sstream>
namespace fs = std::filesystem;
namespace ctxstream {
static std::string lang_of(const std::string& ext) {
static const std::map<std::string, std::string> m = {
{".c", "c"}, {".h", "c"}, {".cpp", "cpp"}, {".cc", "cpp"},
{".hpp", "cpp"}, {".hh", "cpp"}, {".cxx", "cpp"},
{".py", "python"}, {".pyi", "python"},
{".js", "js"}, {".mjs", "js"}, {".ts", "ts"}, {".tsx", "ts"},
{".go", "go"}, {".rs", "rust"}, {".java", "java"},
{".rb", "ruby"}, {".sh", "shell"}, {".bash", "shell"},
{".cs", "csharp"}, {".kt", "kotlin"}, {".swift", "swift"},
{".php", "php"}, {".lua", "lua"}, {".m", "objc"},
};
const auto it = m.find(ext);
return it == m.end() ? std::string() : it->second;
}
static bool looks_binary(const std::string& head) {
for (unsigned char c : head) {
if (c == 0) return true;
}
return false;
}
static std::string read_file(const fs::path& p, std::size_t cap, bool* too_big) {
std::error_code ec;
const auto sz = fs::file_size(p, ec);
if (!ec && sz > cap) { *too_big = true; return {}; }
std::ifstream in(p, std::ios::binary);
if (!in) return {};
std::ostringstream ss;
ss << in.rdbuf();
return ss.str();
}
// One pattern per language family. Captures the symbol name in group 1.
static const std::vector<std::pair<std::regex, NodeKind>>& defs_for(
const std::string& lang) {
static const std::vector<std::pair<std::regex, NodeKind>> c_like = {
{std::regex(R"(^\s*(?:class)\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Class},
{std::regex(R"(^\s*(?:struct)\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Struct},
// return-type name(...) at line start, not a call or control keyword
{std::regex(R"(^[A-Za-z_][A-Za-z0-9_:<>,\s\*&]*\s[\*&]?([A-Za-z_][A-Za-z0-9_]*)\s*\([^;]*\)\s*(?:const)?\s*\{)"),
NodeKind::Function},
};
static const std::vector<std::pair<std::regex, NodeKind>> python = {
{std::regex(R"(^\s*class\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Class},
{std::regex(R"(^\s*(?:async\s+)?def\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
};
static const std::vector<std::pair<std::regex, NodeKind>> js_like = {
{std::regex(R"(^\s*(?:export\s+)?class\s+([A-Za-z_$][A-Za-z0-9_$]*))"), NodeKind::Class},
{std::regex(R"(^\s*(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][A-Za-z0-9_$]*))"), NodeKind::Function},
{std::regex(R"(^\s*(?:export\s+)?const\s+([A-Za-z_$][A-Za-z0-9_$]*)\s*=\s*(?:async\s*)?\()"), NodeKind::Function},
};
static const std::vector<std::pair<std::regex, NodeKind>> go_like = {
{std::regex(R"(^\s*func\s+(?:\([^)]*\)\s*)?([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
{std::regex(R"(^\s*type\s+([A-Za-z_][A-Za-z0-9_]*)\s+struct)"), NodeKind::Struct},
};
static const std::vector<std::pair<std::regex, NodeKind>> rust_like = {
{std::regex(R"(^\s*(?:pub\s+)?fn\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Function},
{std::regex(R"(^\s*(?:pub\s+)?struct\s+([A-Za-z_][A-Za-z0-9_]*))"), NodeKind::Struct},
};
static const std::vector<std::pair<std::regex, NodeKind>> none;
if (lang == "c" || lang == "cpp" || lang == "java" || lang == "csharp") return c_like;
if (lang == "python") return python;
if (lang == "js" || lang == "ts") return js_like;
if (lang == "go") return go_like;
if (lang == "rust") return rust_like;
return none;
}
// #include "x.h" / import x / from x import / require('x')
static std::vector<std::string> imports_of(const std::string& text,
const std::string& lang) {
static const std::regex inc_c(R"(^\s*#\s*include\s*[\"<]([^\">]+)[\">])");
static const std::regex imp_py(R"(^\s*(?:from\s+([A-Za-z0-9_.]+)\s+import|import\s+([A-Za-z0-9_.]+)))");
static const std::regex imp_js(R"((?:from\s*[\"']([^\"']+)[\"']|require\(\s*[\"']([^\"']+)[\"']\s*\)))");
std::vector<std::string> out;
std::istringstream in(text);
std::string line;
while (std::getline(in, line)) {
std::smatch m;
if ((lang == "c" || lang == "cpp") && std::regex_search(line, m, inc_c)) {
out.push_back(m[1].str());
} else if (lang == "python" && std::regex_search(line, m, imp_py)) {
out.push_back(m[1].matched ? m[1].str() : m[2].str());
} else if ((lang == "js" || lang == "ts") && std::regex_search(line, m, imp_js)) {
out.push_back(m[1].matched ? m[1].str() : m[2].str());
}
}
return out;
}
CodeGraph scan_repo(const std::string& root, const ScanOptions& opt) {
CodeGraph g;
g.root = root;
const std::set<std::string> excluded(opt.exclude_dirs.begin(),
opt.exclude_dirs.end());
// path (as written in imports) -> file id, for edge resolution
std::map<std::string, int> by_stem;
std::vector<std::string> texts;
std::error_code ec;
auto it = fs::recursive_directory_iterator(
root,
opt.follow_symlinks ? fs::directory_options::follow_directory_symlink
: fs::directory_options::skip_permission_denied,
ec);
if (ec) return g;
for (fs::recursive_directory_iterator end; it != end; it.increment(ec)) {
if (ec) { ec.clear(); continue; }
const fs::path p = it->path();
if (it->is_directory(ec)) {
if (excluded.count(p.filename().string())) it.disable_recursion_pending();
continue;
}
if (!it->is_regular_file(ec)) continue;
const std::string lang = lang_of(p.extension().string());
if (lang.empty()) continue;
bool too_big = false;
const std::string text = read_file(p, opt.max_file_bytes, &too_big);
const std::string rel = fs::relative(p, root, ec).string();
if (too_big) { g.skipped.emplace_back(rel, "over max_file_bytes"); continue; }
if (text.empty()) { g.skipped.emplace_back(rel, "empty or unreadable"); continue; }
if (looks_binary(text.substr(0, 512))) {
g.skipped.emplace_back(rel, "binary");
continue;
}
FileNode f;
f.id = static_cast<int>(g.files.size());
f.path = rel;
f.language = lang;
f.bytes = text.size();
g.files.push_back(f);
texts.push_back(text);
by_stem[p.filename().string()] = f.id;
by_stem[p.stem().string()] = f.id;
}
// Symbols
for (std::size_t fi = 0; fi < g.files.size(); ++fi) {
const auto& pats = defs_for(g.files[fi].language);
if (pats.empty()) continue;
const std::string& text = texts[fi];
std::size_t off = 0;
int line_no = 0;
std::istringstream in(text);
std::string line;
while (std::getline(in, line)) {
++line_no;
for (const auto& [re, kind] : pats) {
std::smatch m;
if (std::regex_search(line, m, re)) {
SymbolNode s;
s.id = static_cast<int>(g.symbols.size());
s.kind = kind;
s.name = m[1].str();
s.file = static_cast<int>(fi);
s.line = line_no;
s.offset = off;
g.symbols.push_back(s);
g.files[fi].symbols++;
break;
}
}
off += line.size() + 1;
}
}
// Edges from imports/includes, resolved by filename or stem.
std::set<std::pair<int, int>> seen;
for (std::size_t fi = 0; fi < g.files.size(); ++fi) {
for (const std::string& imp : imports_of(texts[fi], g.files[fi].language)) {
fs::path ip(imp);
for (const std::string& key : {ip.filename().string(), ip.stem().string()}) {
const auto hit = by_stem.find(key);
if (hit == by_stem.end() || hit->second == static_cast<int>(fi)) continue;
if (!seen.insert({static_cast<int>(fi), hit->second}).second) break;
g.edges.push_back({static_cast<int>(fi), hit->second, EdgeKind::Includes});
break;
}
}
}
return g;
}
std::string graph_summary(const CodeGraph& g) {
std::map<std::string, int> per_lang;
std::size_t bytes = 0;
for (const auto& f : g.files) { per_lang[f.language]++; bytes += f.bytes; }
std::ostringstream o;
o << "files=" << g.files.size() << " symbols=" << g.symbols.size()
<< " edges=" << g.edges.size() << " bytes=" << bytes
<< " skipped=" << g.skipped.size() << " langs=";
bool first = true;
for (const auto& [l, n] : per_lang) {
o << (first ? "" : ",") << l << ":" << n;
first = false;
}
return o.str();
}
// Dependency-first ordering: a file appears after the files it includes, so a
// segment carrying a caller has a decent chance of following its callee. Cycles
// are broken arbitrarily rather than dropped -- coverage matters more than order.
static std::vector<int> topo_order(const CodeGraph& g) {
const int n = static_cast<int>(g.files.size());
std::vector<std::vector<int>> out(n);
std::vector<int> indeg(n, 0);
for (const auto& e : g.edges) {
if (e.from == e.to) continue;
out[e.to].push_back(e.from); // dependency -> dependent
indeg[e.from]++;
}
std::vector<int> ready, order;
for (int i = 0; i < n; ++i) {
if (indeg[i] == 0) ready.push_back(i);
}
std::vector<bool> done(n, false);
while (!ready.empty()) {
const int v = ready.back();
ready.pop_back();
if (done[v]) continue;
done[v] = true;
order.push_back(v);
for (int w : out[v]) {
if (--indeg[w] == 0) ready.push_back(w);
}
}
for (int i = 0; i < n; ++i) {
if (!done[i]) order.push_back(i); // cycle members
}
return order;
}
std::vector<Segment> plan_codebase(const CodeGraph& g, const ManifestOptions& opt,
std::string* packed_text) {
packed_text->clear();
std::vector<Segment> segs;
if (g.files.empty()) return segs;
// Pack files in dependency order into one buffer with explicit headers, so
// the model always knows which file a fragment came from, then cut segments
// on file boundaries.
struct Placed { std::size_t start, end; };
std::vector<Placed> placed;
placed.reserve(g.files.size());
for (int fi : topo_order(g)) {
const FileNode& f = g.files[fi];
std::error_code ec;
std::ifstream in(fs::path(g.root) / f.path, std::ios::binary);
std::ostringstream ss;
ss << in.rdbuf();
const std::size_t start = packed_text->size();
*packed_text += "\n===== FILE " + f.path + " (" + f.language + ") =====\n";
*packed_text += ss.str();
placed.push_back({start, packed_text->size()});
}
// Greedy: accumulate whole files until the next one would overflow.
int index = 0;
std::size_t seg_start = 0;
for (std::size_t i = 0; i < placed.size(); ++i) {
const std::size_t seg_end = placed[i].end;
const bool last = (i + 1 == placed.size());
const std::size_t next_end = last ? seg_end : placed[i + 1].end;
if (last || next_end - seg_start > opt.segment_chars) {
Segment s;
s.index = index++;
s.offset = seg_start;
s.length = seg_end - seg_start;
s.overlap_prefix = 0;
segs.push_back(s);
seg_start = seg_end;
}
}
// A single file larger than a segment still has to be split; fall back to
// line-boundary cutting inside it rather than dropping it.
std::vector<Segment> final_segs;
for (const Segment& s : segs) {
if (s.length <= opt.segment_chars) { final_segs.push_back(s); continue; }
const std::string sub = packed_text->substr(s.offset, s.length);
for (Segment inner : plan(sub, opt)) {
inner.offset += s.offset;
final_segs.push_back(inner);
}
}
for (std::size_t i = 0; i < final_segs.size(); ++i) {
final_segs[i].index = static_cast<int>(i);
}
return final_segs;
}
} // namespace ctxstream