- MCP
- code on this site's /mcp
- CLI
- none: the JSON below is the answer
- JSON
- /christopher/abso-core/files/worker/project/names.ts?format=json
229 linesFirst import 91% · engine 7% · codex-capacity-chair 3%Last change codex-capacity-chair in version 175, 3 versions changed it
1// Reading names out of lines of code, for branch mode's questions ("does this
2// commit need the one that introduced a name it uses?"). Cheap, deterministic
3// and not tied to one language: it never parses, it only leaves out what is
4// surely not a use of someone's name.
5//
6// - String literals and comments are left out (//, /* */, # and -- with a
7// space after them, Python's triple quotes, and lines inside a block comment
8// that start with *). Code inside a template literal's ${...} stays.
9// - Keywords, built-ins and common library names of the usual languages are
10// not names anyone introduced.
11// - Prose files (Markdown, plain text, READMEs) have no code.
12// - A name the commit declares itself (const x, def x, x = ..., x := ...) is
13// its own, not a use of another commit's.
15/** Identifiers counted as names: three or more characters. */
16const IDENT = /[A-Za-z_$][A-Za-z0-9_$]*/g;
17const MIN_LENGTH = 3;
19/**
20 * Keywords and built-ins of common languages (JavaScript/TypeScript, Python,
21 * Go, Rust, Java, C and C#, shell, SQL), and the standard library names agents
22 * use everywhere. Compared in lower case.
23 */
24const COMMON = new Set(
25 [
26 // JavaScript and TypeScript
27 "abstract any arguments as async await bigint boolean break case catch class const constructor continue debugger declare default delete do else enum export extends false finally for from function get global if implements import in infer instanceof interface is keyof let module namespace never new null number object of override package private protected public readonly require return satisfies set static string super switch symbol this throw true try type typeof undefined unique unknown var void while with yield",
28 "array buffer console date document error evalerror function globalthis infinity intl json map math nan promise proxy rangeerror referenceerror reflect regexp syntaxerror typeerror urierror weakmap weakset window process aggregateerror arraybuffer uint8array",
29 "clearinterval cleartimeout decodeuricomponent encodeuricomponent fetch isfinite isnan parsefloat parseint queuemicrotask setinterval settimeout structuredclone",
30 "awaited exclude extract iterable iterator nonnullable omit parameters partial pick readonlyarray record required returntype",
31 // Methods and properties of the standard library
32 "add apply assign bind call ceil clear concat entries every filter find findindex findlast flat flatmap floor foreach freeze has hasownproperty includes indexof isarray join keys lastindexof length log max min now padend padstart parse pop prototype push random reduce reject replace replaceall resolve reverse round shift size slice some sort splice split startswith endswith stringify substring then tofixed tolowercase tostring touppercase trim trimend trimstart unshift valueof values warn info debug abs sqrt pow sign trunc next done value",
33 // Tests
34 "after afterall aftereach assert before beforeall beforeeach deepequal deepstrictequal describe equal expect notequal ok rejects strictequal test throws tobe toequal",
35 // Python
36 "and def del elif except false lambda none nonlocal not or pass raise self cls print len range list dict tuple int float str bool bytes isinstance issubclass property staticmethod classmethod enumerate zip sorted reversed open exception valueerror keyerror indexerror attributeerror runtimeerror notimplementederror stopiteration __init__ __name__ __main__",
37 // Go and Rust
38 "func chan defer fallthrough goto nil make append cap copy panic recover rune int64 int32 float64 float32 uint uint8 uint32 uint64 usize isize fn mut pub use mod impl trait match loop where crate some ok err vec option result box unsafe dyn ref move",
39 // Java, C, C#
40 "void long short char double byte final synchronized volatile transient native throws struct union typedef sizeof unsigned signed auto register extern include define ifdef ifndef endif pragma using virtual template typename operator friend inline explicit nullptr std vector printf malloc free main",
41 // Shell and SQL
42 "echo then fi esac local source exit read unset select where insert update create table values into join left right inner outer group order having limit offset distinct union all primary key foreign references index view begin commit rollback",
43 ]
44 .join(" ")
45 .split(/\s+/),
46);
48/** Whether a name is a keyword, built-in or common library name. */
49export function isCommonName(name: string): boolean {
50 return COMMON.has(name.toLowerCase());
51}
53const PROSE_EXTENSIONS = new Set(["md", "markdown", "mdown", "txt", "text", "rst", "adoc", "asciidoc", "org"]);
54const PROSE_NAMES = new Set([
55 "readme",
56 "license",
57 "licence",
58 "changelog",
59 "changes",
60 "notice",
61 "authors",
62 "contributing",
63 "copying",
64]);
66/** Files of prose, whose words are not code: Markdown, plain text, READMEs and the like. */
67/** Data files: no code defines or uses a name in them, however big they are (abso issue 158). */
68const DATA_EXTENSIONS = new Set(["json", "jsonc", "json5", "jsonl", "ndjson", "geojson", "csv", "tsv", "lock", "svg"]);
70/**
71 * Whether the definition rule passes over a file: prose, or data. Scanning a
72 * 23,000-line JSON fixture for definitions it can't hold cost a big publish
73 * hundreds of milliseconds, and its keys could pass for uses of code names.
74 */
75export function holdsNoCode(path: string): boolean {
76 if (isProse(path)) return true;
77 const base = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
78 const dot = base.lastIndexOf(".");
79 return dot > 0 && DATA_EXTENSIONS.has(base.slice(dot + 1));
80}
82export function isProse(path: string): boolean {
83 const base = path.slice(path.lastIndexOf("/") + 1).toLowerCase();
84 const dot = base.lastIndexOf(".");
85 const ext = dot > 0 ? base.slice(dot + 1) : "";
86 const stem = dot > 0 ? base.slice(0, dot) : base;
87 return PROSE_EXTENSIONS.has(ext) || PROSE_NAMES.has(stem);
88}
90interface ScanState {
91 /** Open template literals and the code inside their ${...}, innermost last. */
92 readonly stack: ({ kind: "code"; depth: number } | { kind: "template" })[];
93 /** Inside a block comment. */
94 block: boolean;
95 /** Inside a Python triple-quoted string: its quote. */
96 triple: string | undefined;
97}
99function spaceBefore(line: string, i: number): boolean {
100 return i === 0 || line[i - 1] === " " || line[i - 1] === "\t";
101}
103function spaceAfter(line: string, i: number): boolean {
104 return i >= line.length || line[i] === " " || line[i] === "\t";
105}
107/** One line's code, given what the lines before it left open. */
108function scanLine(line: string, st: ScanState): string {
109 if (!st.block && st.triple === undefined && st.stack.length === 1) {
110 // A line inside a block comment that started above these lines.
111 const t = line.trimStart();
112 if (t.startsWith("*")) return "";
113 }
114 let out = "";
115 let i = 0;
116 const n = line.length;
117 while (i < n) {
118 if (st.block) {
119 const end = line.indexOf("*/", i);
120 if (end < 0) return out;
121 st.block = false;
122 i = end + 2;
123 out += " ";
124 continue;
125 }
126 if (st.triple !== undefined) {
127 const end = line.indexOf(st.triple, i);
128 if (end < 0) return out;
129 i = end + 3;
130 st.triple = undefined;
131 out += " ";
132 continue;
133 }
134 const top = st.stack[st.stack.length - 1]!;
135 const c = line[i]!;
136 if (top.kind === "template") {
137 if (c === "\\") i += 2;
138 else if (c === "`") {
139 st.stack.pop();
140 i++;
141 out += " ";
142 } else if (c === "$" && line[i + 1] === "{") {
143 st.stack.push({ kind: "code", depth: 0 });
144 i += 2;
145 out += " ";
146 } else i++;
147 continue;
148 }
149 if (c === "/" && line[i + 1] === "/") return out;
150 if (c === "/" && line[i + 1] === "*") {
151 st.block = true;
152 i += 2;
153 continue;
154 }
155 if (c === "#" && spaceBefore(line, i) && spaceAfter(line, i + 1)) return out;
156 if (c === "-" && line[i + 1] === "-" && spaceBefore(line, i) && spaceAfter(line, i + 2)) return out;
157 if (c === '"' || c === "'") {
158 if (line.startsWith(c.repeat(3), i)) {
159 st.triple = c.repeat(3);
160 i += 3;
161 continue;
162 }
163 let j = i + 1;
164 while (j < n && line[j] !== c) j += line[j] === "\\" ? 2 : 1;
165 // An unclosed quote (an apostrophe, a Rust lifetime) is just a character.
166 i = j < n ? j + 1 : i + 1;
167 out += " ";
168 continue;
169 }
170 if (c === "`") {
171 st.stack.push({ kind: "template" });
172 i++;
173 out += " ";
174 continue;
175 }
176 if (c === "{") top.depth++;
177 else if (c === "}") {
178 if (top.depth === 0 && st.stack.length > 1) {
179 st.stack.pop();
180 i++;
181 out += " ";
182 continue;
183 }
184 top.depth = Math.max(0, top.depth - 1);
185 }
186 out += c;
187 i++;
188 }
189 return out;
190}
192/**
193 * The code of consecutive lines (one inserted run, or a file): each line
194 * without its string literals and comments. A string or comment opened on
195 * one line continues on the next.
196 */
197export function codeOfLines(lines: Iterable<string>): string[] {
198 return [...eachCodeLine(lines)];
199}
201export function* eachCodeLine(lines: Iterable<string>): IterableIterator<string> {
202 const st: ScanState = { stack: [{ kind: "code", depth: 0 }], block: false, triple: undefined };
203 for (const line of lines) yield scanLine(line, st);
204}
206/** Names in some code (from codeOfLines): identifiers of three or more characters that aren't common names. */
207export function namesIn(code: string): string[] {
208 return (code.match(IDENT) ?? []).filter((w) => w.length >= MIN_LENGTH && !isCommonName(w));
209}
211const DECLARATION =
212 /\b(?:const|let|var|function\*?|class|def|fn|func|type|interface|enum|struct|trait|val|my|local)\s+(?:mut\s+)?([A-Za-z_$][A-Za-z0-9_$]*)/g;
213const ASSIGNMENT = /^\s*([A-Za-z_$][A-Za-z0-9_$]*)\s*(?::[^=]*)?(?::=|=(?![=>]))/;
214const FOR_IN = /\bfor\s+([A-Za-z_$][A-Za-z0-9_$]*)\s+in\b/g;
216/**
217 * Names some code declares: after a declaring keyword (const x, def x, class
218 * X, fn x, ...), assigned at the start of a line (x = ..., x: T = ...,
219 * x := ...), or a Python loop variable. Destructuring and parameters are left
220 * alone: there the name may well be someone else's.
221 */
222export function declaredIn(code: string): string[] {
223 const out: string[] = [];
224 for (const m of code.matchAll(DECLARATION)) out.push(m[1]!);
225 for (const m of code.matchAll(FOR_IN)) out.push(m[1]!);
226 const a = ASSIGNMENT.exec(code);
227 if (a) out.push(a[1]!);
228 return out;
229}