Abstract
Retrieval-Augmented Generation (RAG) has become essential for large-scale code generation, grounding predictions in external code corpora to improve factuality. However, a critical yet underexplored aspect of RAG pipelines is chunking—the process of dividing documents into retrievable units. Existing line-based chunking heuristics often break semantic structures, splitting functions or merging unrelated code, which can degrade generation quality. We propose chunking via Abstract Syntax Trees (CAST), a structure-aware method that recursively breaks large AST nodes into smaller chunks and merges sibling nodes while respecting size limits. This approach generates self-contained, semantically coherent units across programming languages and tasks, improving performance on diverse code generation tasks, e.g., boosting Recall@5 by 4.3 points on RepoEval retrieval and Pass@1 by 2.67 points on SWE-bench generation. Our work highlights the importance of structure-aware chunking for scaling retrieval-enhanced code intelligence.
The Problem with Naive Chunking
Retrieval-Augmented Generation (RAG) has become a standard way to help Large Language Models (LLMs) write code by providing them with relevant snippets from a massive external codebase. However, before you can retrieve code, you have to "chunk" it—breaking long files into smaller pieces that fit into a model's context window.
Most current systems use "naive" chunking: they simply split a file every $X$ lines or characters. This is syntax-agnostic. Imagine a retriever handing an LLM the bottom half of a complex function without the signature or the variable definitions at the top. The model loses the "big picture," leading to "hallucinations" or broken code. As shown in Figure 1, syntax-agnostic chunks can break code structure, leading to incorrect generation, whereas syntax-aware chunks preserve the necessary context.
The CAST Approach
The authors introduce CAST, a structure-aware chunking method that leverages Abstract Syntax Trees (ASTs). An AST is a tree representation of the abstract syntactic structure of source code. Unlike fixed-size chunking, which ignores the logical boundaries of code, CAST respects the hierarchical nature of the source (Figure 2).
The CAST algorithm uses a recursive split-then-merge approach:
- AST Parsing: It uses the
tree-sitterlibrary to parse source code into a hierarchical tree of nodes (e.g., function definitions, class bodies, loops). - Top-Down Splitting: It traverses the tree. If a node (like a whole class) is too large for the character budget, it recursively breaks it down into its children (individual methods).
- Greedy Merging: To prevent "fragmentation"—where chunks become too small to be useful—CAST greedily merges adjacent sibling nodes into a single chunk until the size limit is reached.
- Density Metric: Unlike previous work that counts lines, CAST measures size by non-whitespace characters. This ensures chunks are "text-dense" and comparable across different coding styles and languages.
Experimental Evaluation and Results
The authors evaluated CAST across three diverse benchmarks: RepoEval (code completion), CrossCodeEval (multi-file reasoning), and SWE-bench Lite (real-world software engineering tasks).
CAST consistently outperformed fixed-size chunking across all models and retrievers tested:
- Retrieval Performance: On RepoEval, CAST improved Recall@5 by 4.3 points and Precision by up to 3.3 points.
- Generation Quality: Using StarCoder2-7B, CAST achieved an average 5.5 point gain on RepoEval. On the difficult SWE-bench, it boosted Pass@1 by 2.67 points.
- Cross-Language Robustness: On CrossCodeEval, CAST showed a 4.3 point gain, proving its effectiveness in multi-file, multi-language environments (Python, Java, C#, and TypeScript). The benefits held true whether using general-purpose retrievers (like BGE) or specialized code retrievers (like CodeSage).
Discussion and Future Directions
A key insight from this work is that syntactic integrity is paramount. A slightly smaller, syntactically complete chunk is far more valuable to an LLM than a larger, "broken" chunk. By keeping functions and classes whole, the model retains the necessary context to understand variable scopes and return types. Furthermore, the paper finds that Precision (relevance of top-k chunks) correlates more strongly with generation quality than Recall.
However, limitations remain. The current implementation focuses on pure source code, not yet treating docstrings or READMEs as distinct structural elements. Future work could explore "multi-level" information retrieval to bridge the gap between leaf-node functions and their parent class context, or incorporate dynamic analysis to account for runtime execution dynamics.
Summary updated