MediumRetrievalPython 3
Codebase Symbol Index
Build an incremental code symbol index with file replacement, deletion, case-insensitive prefix search, and stable ranking.
40m3 sample tests6 hidden tests
Implement SymbolIndex, a small in-memory index for code symbols.
Requirements
update_file(path, content)extracts symbols from one file and replaces any old symbols for that path.remove_file(path)removes that file's symbols. If the path isn't indexed, it's a no-op.search(prefix, limit=10)returns matching symbols sorted by:- Exact match first (case-insensitive name equal to prefix),
- Symbol
namecase-insensitively, - File
pathalphabetically, linenumber in ascending order.
- A symbol is a dictionary with
name(str),path(str), andline(1-indexed int). - Extract symbols from lines whose first non-whitespace token is
def,class,function,const,let, orvar(optional leading indentation is allowed). The symbol name is the identifier immediately following the keyword. - Prefix matching is case-insensitive.
- An empty prefix returns
[]. A nonpositive integerlimitalso returns[]. - Declarations in this exercise use ASCII identifiers:
[A-Za-z_][A-Za-z0-9_]*. Keywords are lowercase. This is line-based lexical extraction, so decorators,async def,export const, destructuring, and full language syntax aren't in scope. - Returned dictionaries are snapshots; changing a search result mustn't change the index.
Example
Updating a file indexes its declarations and allows case-insensitive prefix lookup.
python
1index = SymbolIndex()
2index.update_file("src/cache.py", "class Cache:\n pass\ndef clear_cache():\n pass")
3
4assert index.search("Ca")[0] == {"name": "Cache", "path": "src/cache.py", "line": 1}
5
6index.update_file("src/cache.py", "class Store:\n pass")
7assert index.search("cache") == [] # the replaced file must not leave stale symbols
8assert index.search("store")[0]["line"] == 1Constraints
- Keep state in memory.
- Don't use a parser library.
- File updates must remove stale symbols from previous content.
Editor