diff --git a/notes/adding-a-port.md b/notes/adding-a-port.md index 6f9ef83e9..95c1abe50 100644 --- a/notes/adding-a-port.md +++ b/notes/adding-a-port.md @@ -205,6 +205,14 @@ Erlang has no shared site routes or package destinations until the port's delivery checks are complete. The compiler fixture runs in the outer test loop; it requires OTP 29 and Rebar3 on CI and skips locally when that toolchain is absent. +The tmux-usage reader also requires OTP 29. It uses `erl_scan` for literal +decoding and canonical atom names, then attributes written calls by module +and arity, including static imports. Deferred fun bodies do not establish +that their enclosing function sends a command. Macro-generated declaration +heads fail rather than disappear from the scan. Variable-carried commands, +custom sigils and macro-expanded calls need reviewed usage claims. Native +scanner checks belong to the outer loop. + ### Wrapper libraries Kotlin and Scala share Java's repository and release version. F# shares diff --git a/scripts/lib/tmux-usage-audit.mjs b/scripts/lib/tmux-usage-audit.mjs index 79b233f48..417b903a9 100644 --- a/scripts/lib/tmux-usage-audit.mjs +++ b/scripts/lib/tmux-usage-audit.mjs @@ -37,7 +37,7 @@ export const BINDS_ONLY = /^(?:let|var|val|const)\b[^=]*=\s*(?:[\w.]+\()?\s*Comm /** * @typedef {{ symbol: string, command: string, scope: string | null, evidence: string[], reviewed?: boolean, * via?: { port: string, symbol: string, revision: string, evidence: string[], reviewed?: boolean } }} Use - * @typedef {{ read: (path: string) => string | undefined, functions: { file: string, name: string, owner?: string, start: number, end: number, sites: { command: string, line: number, dispatch?: { line: number } | null, why?: string }[], calls: Map, receivers: Map> }[] }} Sources + * @typedef {{ read: (path: string) => string | undefined, functions: (import('./tmux-usage-scan.mjs').ScannedFunction & { file: string })[] }} Sources * * @param {{ * port: string, @@ -131,7 +131,9 @@ export function auditEvidence({ port, revision, uses, claimFor, sourcesAt, spell const next = split(use.evidence[index]) const caller = enclosing(sources, next.file, next.line) if (!callee) problems.push(`${label}: ${use.evidence[index - 1]} is in no function, so ${use.evidence[index]} calls nothing`) - else if (!caller || caller.calls.get(callee.name) !== next.line || !callTargets(caller, callee, named(callee.name))) { + else if (!caller || !(caller.callList + ? caller.callList.some((call) => call.line === next.line && callTargets(caller, callee, named(callee.name), call)) + : caller.calls.get(callee.name) === next.line && callTargets(caller, callee, named(callee.name)))) { problems.push(`${label}: ${use.evidence[index]} is not a call of ${callee.owner ? `${callee.owner}.` : ''}${callee.name}, the function around ${use.evidence[index - 1]}: ${texts[index].trim().slice(0, 90)}`) } } diff --git a/scripts/lib/tmux-usage-derive.mjs b/scripts/lib/tmux-usage-derive.mjs index b9bd9bdd2..b2ef437f4 100644 --- a/scripts/lib/tmux-usage-derive.mjs +++ b/scripts/lib/tmux-usage-derive.mjs @@ -66,6 +66,12 @@ export function shapeFits(call, fn) { */ export function callTargets(caller, callee, named, call) { if (!caller.calls.has(callee.name)) return false + if (call && call.name !== callee.name) return false + // Erlang modules name a static destination even when no other helper shares its name. + if (caller.module !== undefined) { + const calls = call ? [call] : (caller.callList ?? []).filter((candidate) => candidate.name === callee.name) + return calls.some((one) => (one.receiver ?? caller.module) === callee.module) + } if (named.length <= 1) return true const calls = call ? [call] : (caller.callList ?? []).filter((candidate) => candidate.name === callee.name) // Overloads of one type are not always in one file: a Swift extension and a C# partial class add to the type from another. @@ -86,6 +92,8 @@ function resolves(caller, receivers, callee, named) { /** `panes(where:)`, `Server.panes` and `Server#list_panes` all name their last identifier. */ export function bareName(name) { + // Periods and colons inside a quoted Erlang atom belong to its native name. + if (/^(?:\p{Ll}[\p{L}\p{N}_@]*|'(?:\\.|[^'\\])*')\/[0-9]+$/u.test(name)) return name // Kotlin and Scala quote a name that is also a keyword: Buffers.`set`. return name.replace(/\(.*$/s, '').replace(/`/g, '').split(/[.:#\\]+/).filter(Boolean).at(-1) ?? name } @@ -188,7 +196,11 @@ export function deriveUsage({ command, spec, functions, symbols, definitionOptio const own = definitions.get(fn) if (own) return own.map((symbol) => ({ symbol, trail, method: fn })) if (depth >= MAX_HOPS) return [] - return callersOf(fn).flatMap((caller) => reach(caller, [...trail, `${caller.file}:${caller.calls.get(fn.name)}`], depth + 1)) + return callersOf(fn).flatMap((caller) => { + const line = caller.module === undefined ? caller.calls.get(fn.name) + : caller.callList.find((call) => callTargets(caller, fn, byName.get(fn.name) ?? [], call))?.line + return reach(caller, [...trail, `${caller.file}:${line}`], depth + 1) + }) } const entries = new Map() diff --git a/scripts/lib/tmux-usage-dispatch.mjs b/scripts/lib/tmux-usage-dispatch.mjs index ff21521ef..3482c9f0f 100644 --- a/scripts/lib/tmux-usage-dispatch.mjs +++ b/scripts/lib/tmux-usage-dispatch.mjs @@ -32,6 +32,7 @@ export const TRANSPORT = { cxx: { pattern: /::posix_spawnp?\(|::write\(/, files: /(?:posix_child|connection|process)\.cpp$/ }, swift: { pattern: /Subprocess\.run\(|Glibc\.write\(/, files: /Sources\/LibTmux\/(?:Transport|ControlMode|NonblockingLineWriter)\.swift$/ }, elixir: { pattern: /\bsend_port\(/, files: /transport\/oneshot\.ex$/ }, + erlang: { pattern: /open_port\(\{spawn_executable,/, files: /^apps\/libtmux_erlang\/src\/tmux_transport\.erl$/ }, } const CONSTRUCTOR = /^(?:__init__|constructor|init|new|initialize)$/ @@ -85,7 +86,7 @@ function callProblems({ where, hop, current, reached, functions, line }) { /** * @param {{ port: string, rule: { name: string }, item: { at: string, has?: string[], reaches?: { at: string, has?: string[], calls?: string, leads?: string }[] }, - * functions: { file: string, name: string, owner?: string, start: number, end: number, calls: Map }[], + * functions: (import('./tmux-usage-scan.mjs').ScannedFunction & { file: string })[], * readSource: (path: string) => string | undefined }} input * @returns {string[]} */ @@ -97,8 +98,12 @@ export function chainProblems({ port, rule, item, functions, readSource }) { return readSource(file)?.split('\n')[line - 1] } const reachesTransport = (cite) => { - const { file } = split(cite) - return transport && transport.files.test(file) && transport.pattern.test(textAt(cite) ?? '') + const { file, line } = split(cite) + if (!transport || !transport.files.test(file) || !transport.pattern.test(textAt(cite) ?? '')) return false + if (port !== 'erlang') return true + const fn = functionAt(functions, file, line) + return fn?.callList?.some((call) => call.line === line && call.name === 'open_port/2' && call.portMode === 'spawn_executable' + && (call.receiver === 'erlang' || (!call.receiver && !functions.some((local) => local.module === fn.module && local.name === 'open_port/2')))) ?? false } // A definition that starts the process itself, `subprocess.check_call(`, needs no chain. if (reachesTransport(item.at)) return [] @@ -109,7 +114,9 @@ export function chainProblems({ port, rule, item, functions, readSource }) { const problems = [] const head = split(item.at) let current = functionAt(functions, head.file, head.line) - if (!current || current.name !== bareName(rule.name)) return [`${label}: is not a line of a function named ${bareName(rule.name)}`] + const matches = current && (current.module === undefined ? current.name === bareName(rule.name) + : rule.name === current.name || rule.name === `${current.module}:${current.name}`) + if (!matches) return [`${label}: is not a line of a function named ${bareName(rule.name)}`] for (const [index, hop] of chain.entries()) { const at = split(hop.at) const where = `${label}: hop ${hop.at}` @@ -147,7 +154,7 @@ export function chainProblems({ port, rule, item, functions, readSource }) { * * @param {{ port: string, dispatchers: { name: string, why?: string, kind?: string, evidence?: { at: string, has?: string[], reaches?: unknown[] }[], * labels?: { at: number, name: string }[] }[], readSource: (path: string) => string | undefined, - * functions?: { file: string, name: string, owner?: string, start: number, end: number, calls: Map }[] }} input + * functions?: (import('./tmux-usage-scan.mjs').ScannedFunction & { file: string })[] }} input * @returns {string[]} */ export function dispatcherProblems({ port, dispatchers, readSource, functions }) { @@ -162,7 +169,12 @@ export function dispatcherProblems({ port, dispatchers, readSource, functions }) const line = readSource(item.at.slice(0, cut))?.split('\n')[Number(item.at.slice(cut + 1)) - 1] if (line === undefined) { problems.push(`${label}: ${item.at} is not a line of the pinned source`); continue } for (const needle of item.has ?? []) if (!line.includes(needle)) problems.push(`${label}: ${item.at} does not contain ${JSON.stringify(needle)}`) - if ((item.has ?? []).some((needle) => needle.includes(rule.name))) defined = true + if (port === 'erlang') { + const at = split(item.at) + const fn = functions && functionAt(functions, at.file, at.line) + if (fn?.nameLine === at.line && `${fn.module}:${fn.name}` === rule.name) defined = true + } + else if ((item.has ?? []).some((needle) => needle.includes(rule.name))) defined = true if (rule.kind !== 'builder' && functions) problems.push(...chainProblems({ port, rule, item, functions, readSource })) } if (!defined) problems.push(`${label}: no cited line shows ${rule.name} defined`) diff --git a/scripts/lib/tmux-usage-erlang.escript b/scripts/lib/tmux-usage-erlang.escript new file mode 100644 index 000000000..ec9218dc9 --- /dev/null +++ b/scripts/lib/tmux-usage-erlang.escript @@ -0,0 +1,33 @@ +#!/usr/bin/env escript +%%! +S 2:2 +%% OTP owns token boundaries, sigils, string indentation and atom spelling. +main([]) -> + "29" = erlang:system_info(otp_release), + ok = io:setopts(standard_io, [{encoding, unicode}]), + case erl_scan:string(read([]), 1, [text]) of + {ok, Tokens, _} -> io:put_chars(json:encode([token(T) || T <- Tokens])); + {error, {Line, Module, Reason}, _} -> + io:format(standard_error, "line ~tp: ~ts~n", [Line, Module:format_error(Reason)]), + halt(1) + end. + +read(Parts) -> + case io:get_chars(standard_io, "", 65536) of + eof -> lists:append(lists:reverse(Parts)); + {error, Reason} -> error({source_read, Reason}); + Characters -> read([Characters | Parts]) + end. + +token({atom, Anno, Value}) -> + Text = unicode:characters_to_binary(erl_pp:expr({atom, 0, Value}, [{encoding, unicode}])), + #{t => atom, v => atom_to_binary(Value), n => Text, + quoted => binary:first(Text) =:= $', line => erl_anno:line(Anno)}; +token({string, Anno, Value}) -> #{t => str, v => unicode:characters_to_binary(Value), line => erl_anno:line(Anno)}; +token({sigil_prefix, Anno, Value}) -> + #{t => sigil_prefix, v => atom_to_binary(Value), line => erl_anno:line(Anno)}; +token({sigil_suffix, Anno, Value}) -> + #{t => sigil_suffix, v => unicode:characters_to_binary(Value), line => erl_anno:line(Anno)}; +token({integer, Anno, Value}) -> #{t => number, v => integer_to_binary(Value), line => erl_anno:line(Anno)}; +token({Kind, Anno, _}) -> #{t => Kind, v => <<>>, line => erl_anno:line(Anno)}; +token({dot, Anno}) -> #{t => stop, v => <<".">>, line => erl_anno:line(Anno)}; +token({Kind, Anno}) -> #{t => sym, v => atom_to_binary(Kind), line => erl_anno:line(Anno)}. diff --git a/scripts/lib/tmux-usage-erlang.mjs b/scripts/lib/tmux-usage-erlang.mjs new file mode 100644 index 000000000..418878b47 --- /dev/null +++ b/scripts/lib/tmux-usage-erlang.mjs @@ -0,0 +1,206 @@ +/** + * Read written Erlang calls for tmux-usage attribution. OTP scans literals + * and canonical atom spellings; this reader groups forms without expanding + * macros or following variable dataflow. Unsupported declaration heads fail. + */ +import { spawnSync } from 'node:child_process' +import { fileURLToPath } from 'node:url' + +function tokenize(text) { + if (!text.trim()) return [] + if (Buffer.byteLength(text) > 1048576) throw new Error('Erlang source exceeds the 1 MiB scanner limit') + const result = spawnSync('escript', [fileURLToPath(new URL('./tmux-usage-erlang.escript', import.meta.url))], { + input: text, encoding: 'utf8', timeout: 5000, maxBuffer: 16 << 20, + }) + if (result.error || result.status !== 0) throw new Error(`OTP 29 source scan failed: ${result.error?.message ?? result.stderr}`) + const scanned = JSON.parse(result.stdout) + const tokens = [] + let sigil + for (const token of scanned) { + if (token.t === 'sigil_prefix') { sigil = token.v; continue } + if (token.t === 'sigil_suffix') { sigil = undefined; continue } + if (token.t === 'str' && sigil !== undefined && !['', 's', 'S', 'b', 'B'].includes(sigil)) token.t = 'custom_sigil' + if (token.t === 'str' && tokens.at(-1)?.t === 'str' && sigil === undefined) tokens.at(-1).v += token.v + else tokens.push(token) + } + return tokens +} + +/** Bracket and expression-block pairs keep nested commas out of call arity. */ +function groupsOf(tokens) { + const pairs = new Map() + const stack = [] + const closes = { '(': ')', '[': ']', '{': '}', '<<': '>>' } + tokens.forEach((token, index) => { + if (token.t !== 'sym') return + if (closes[token.v]) stack.push({ open: index, close: closes[token.v] }) + else if (token.t === 'sym' && ['case', 'if', 'receive', 'try', 'begin', 'maybe'].includes(token.v)) stack.push({ open: index, close: 'end' }) + else if (token.v === 'fun' && (tokens[index + 1]?.v === '(' || tokens[index + 2]?.v === '(')) stack.push({ open: index, close: 'end' }) + else if (stack.at(-1)?.close === token.v) { const { open } = stack.pop(); pairs.set(open, index) } + }) + return pairs +} + +/** Scope switches use tmux's list-command option grammar; an operand is never another flag. */ +function flagsOf(command, words) { + if (words.includes(null)) return '' + const takesValue = new Set(['list-panes', 'list-windows', 'list-sessions'].includes(command) ? ['F', 'f', 'O', 't'] : []) + const flags = new Set() + for (let at = 0; at < words.length; at++) { + const word = words[at] + if (word === undefined) return '' + if (word === '--' || !/^-[A-Za-z]/.test(word)) break + for (let index = 1; index < word.length; index++) { + const letter = word[index] + if (!/[A-Za-z]/.test(letter)) break + flags.add(letter) + if (takesValue.has(letter)) { if (index === word.length - 1) at++; break } + } + } + return [...flags].sort().join('') +} + +export function scanErlang(text, { commands, known, dispatch, builders = new Set(), labels = new Map() }) { + const tokens = tokenize(text) + const pairs = groupsOf(tokens) + const arity = (open) => { + const close = pairs.get(open) + if (close === undefined) return undefined + if (close === open + 1) return 0 + let count = 1 + for (let at = open + 1; at < close; at++) { + if (pairs.has(at)) at = pairs.get(at) + else if (tokens[at].t === 'sym' && tokens[at].v === ',') count++ + } + return count + } + const callable = (at) => tokens[at]?.t === 'atom' && tokens[at + 1]?.v === '(' && pairs.has(at + 1) + && tokens[at - 1]?.v !== '?' + const callName = (at) => `${tokens[at].n}/${arity(at + 1)}` + // Flatten written argv lists, retaining unknown words so a missing operand + // cannot make a later literal look like an independent scope switch. + const wordsIn = (open, close) => { + const words = [] + for (let at = open + 1; at < close; at++) { + const token = tokens[at] + if (token.t === 'sym' && token.v === ',') continue + if (token.t === 'sym' && ['++', '--', '|', '||', '<-', '<:-'].includes(token.v)) { words.push({ value: null, at }); continue } + if (token.t === 'str') words.push({ value: token.v, at }) + else if (token.v === '[' && pairs.has(at)) words.push(...wordsIn(at, pairs.get(at))) + else if (token.v === '<<' && pairs.get(at) === at + 2 && tokens[at + 1]?.t === 'str') words.push({ value: tokens[at + 1].v, at: at + 1 }) + else { + words.push({ value: undefined, at }) + // A call's module/name and arguments are one computed word. + if (callable(at)) at = pairs.get(at + 1) + else if (tokens[at + 1]?.v === ':' && callable(at + 2)) at = pairs.get(at + 3) + } + if (pairs.has(at)) at = pairs.get(at) + } + return words + } + let module + const imports = new Map() + const functions = [] + let formStart = 0 + for (let end = 0; end < tokens.length; end++) { + if (tokens[end].t !== 'stop') continue + const first = tokens[formStart] + if (first?.v === '-' && tokens[formStart + 1]?.v === 'module' && tokens[formStart + 3]?.t === 'atom') module = tokens[formStart + 3].n + else if (first?.v === '-' && tokens[formStart + 1]?.v === 'import' && tokens[formStart + 3]?.t === 'atom') { + for (let at = formStart + 5; at < end; at++) { + if (tokens[at].t === 'atom' && tokens[at + 1]?.v === '/' && tokens[at + 2]?.t === 'number') imports.set(`${tokens[at].n}/${tokens[at + 2].v}`, tokens[formStart + 3].n) + } + } + else if (callable(formStart)) { + if (module === undefined) throw new Error('Erlang module identity is unresolved; macro-expanded module declarations need a native source adapter') + const fn = { name: callName(formStart), owner: module, module, start: first.line, nameLine: first.line, end: tokens[end].line, + kind: 'function', sites: [], calls: new Map(), receivers: new Map(), callList: [], deferredCalls: [] } + const heads = new Set([formStart]) + for (let at = formStart; at < end; at++) { + if (pairs.has(at)) at = pairs.get(at) + else if (tokens[at].t === 'sym' && tokens[at].v === ';' && callable(at + 1) && callName(at + 1) === fn.name) heads.add(at + 1) + } + const calls = [] + const declaredName = (names, call) => { + const qualified = `${call.receiver ?? module}:${call.name}` + return names.has(qualified) ? qualified : names.has(call.name) ? call.name : undefined + } + const deferred = [...pairs].filter(([open, close]) => tokens[open].v === 'fun' && open > formStart && close < end) + const isDeferred = (at) => deferred.some(([open, close]) => open < at && at < close) + for (let at = formStart; at < end; at++) { + if (!callable(at) || heads.has(at)) continue + const name = callName(at) + const qualified = tokens[at - 1]?.v === ':' + const receiver = qualified ? (tokens[at - 2]?.t === 'atom' ? tokens[at - 2].n : undefined) : imports.get(name) + // A variable module or record field is not a statically resolved call. + if (tokens[at - 1]?.v === '.' || (tokens[at - 1]?.v === ':' && !receiver)) continue + const tuple = at + 2 + const portMode = name === 'open_port/2' && tokens[tuple]?.v === '{' && arity(tuple) === 2 + && tokens[tuple + 1]?.t === 'atom' && tokens[tuple + 2]?.t === 'sym' && tokens[tuple + 2].v === ',' + && tokens[pairs.get(tuple) + 1]?.t === 'sym' && tokens[pairs.get(tuple) + 1].v === ',' ? tokens[tuple + 1].n : undefined + const call = { name, ...(receiver ? { receiver } : {}), ...(portMode ? { portMode } : {}), line: tokens[at].line, calleeLine: tokens[at].line } + if (isDeferred(at)) { fn.deferredCalls.push(call); continue } + fn.calls.set(name, tokens[at].line) + if (receiver) fn.receivers.set(name, new Set([...(fn.receivers.get(name) ?? []), receiver])) + fn.callList.push(call) + calls.push({ ...call, open: at + 1, close: pairs.get(at + 1) }) + } + for (let at = formStart; at < end; at++) { + const token = tokens[at] + if (token.t !== 'str') continue + const [command, next] = token.v.split(/\s+/) + if (!known.has(command) || !commands.has(command) || (next !== undefined && !next.startsWith('-'))) continue + const enclosing = [...pairs].filter(([open, close]) => open < at && at < close).sort((a, b) => (a[1] - a[0]) - (b[1] - b[0])) + const nearest = calls.filter((call) => call.open < at && at < call.close).sort((a, b) => (a.close - a.open) - (b.close - b.open))[0] + const words = nearest ? wordsIn(nearest.open, nearest.close) : [] + const wordIndex = words.findIndex((word) => word.at === at) + const flags = wordIndex < 0 ? '' : flagsOf(command, words.slice(wordIndex + 1).map((word) => word.value)) + const site = { command, line: token.line, flags } + if (dispatch) { + const path = calls.filter((call) => call.open < at && at < call.close).sort((a, b) => (a.close - a.open) - (b.close - b.open)) + const senderIndex = path.findIndex((call) => declaredName(dispatch, call) !== undefined) + const sender = path[senderIndex] + const blocked = path.slice(0, senderIndex).some((call) => declaredName(builders, call) === undefined) + const computed = sender && enclosing.some(([open, close]) => { + if (open < sender.open) return false + if (tokens[open].v === '{') return true + if (tokens[open].v === '<<' && (close !== open + 2 || tokens[open + 1].t !== 'str')) return true + if (tokens[open].t === 'sym' && /^[a-z]/.test(tokens[open].v)) return true + let from = open + 1 + let to = close + for (let index = from; index < close; index++) { + if (pairs.has(index)) index = pairs.get(index) + else if (tokens[index].v === ',') { + if (index < at) from = index + 1 + else { to = index; break } + } + } + for (let index = from; index < to; index++) { + if (pairs.has(index)) index = pairs.get(index) + else if (tokens[index].t === 'sym' && ['=:=', '=/=', '==', '/=', '<', '>', '=<', '>=', 'andalso', 'orelse', 'not', '++', '--'].includes(tokens[index].v)) return true + } + return false + }) + const diagnostic = path.some((call) => { + const labelName = declaredName(labels, call) + if (labelName === undefined) return false + let argument = 0 + for (let index = call.open + 1; index < at; index++) { + if (pairs.has(index)) index = pairs.get(index) + else if (tokens[index].t === 'sym' && tokens[index].v === ',') argument++ + } + return labels.get(labelName).has(argument) + }) + if (sender && !blocked && !computed && !diagnostic && !isDeferred(at)) site.dispatch = { line: sender.line, name: declaredName(dispatch, sender) } + else { site.dispatch = null; site.why = isDeferred(at) ? 'it is inside a deferred fun body' : 'it reaches no declared dispatcher call' } + } + fn.sites.push(site) + } + functions.push(fn) + } + else if (first?.v !== '-') throw new Error('Erlang function head is unresolved; macro-generated functions need a native source adapter') + formStart = end + 1 + } + if (formStart < tokens.length) throw new Error('unterminated Erlang form') + return { functions, types: module ? [{ name: module, start: 1, end: text.split('\n').length }] : [], orphans: [] } +} diff --git a/scripts/lib/tmux-usage-scan.mjs b/scripts/lib/tmux-usage-scan.mjs index 6288c77b3..e27e84cb6 100644 --- a/scripts/lib/tmux-usage-scan.mjs +++ b/scripts/lib/tmux-usage-scan.mjs @@ -8,26 +8,28 @@ */ import { parserFor } from '../../packages/api-model/src/parser.ts' import { receiverOf, scanElixir, scanFSharp, scanJulia } from './tmux-usage-lexical.mjs' +import { scanErlang } from './tmux-usage-erlang.mjs' -/** Port to the grammar that reads its source. PowerShell cmdlets are C#; Julia, F# and Elixir are read by their text. */ +/** Port to its source reader. PowerShell cmdlets are C#; Julia, F#, Elixir and Erlang use lexical readers. */ export const GRAMMARS = { py: 'python', ts: 'typescript', rs: 'rust', go: 'go', java: 'java', kotlin: 'kotlin', scala: 'scala', - csharp: 'csharp', powershell: 'csharp', cxx: 'cpp', swift: 'swift', ruby: 'ruby', lua: 'lua', julia: 'julia', fsharp: 'fsharp', elixir: 'elixir', + csharp: 'csharp', powershell: 'csharp', cxx: 'cpp', swift: 'swift', ruby: 'ruby', lua: 'lua', julia: 'julia', fsharp: 'fsharp', elixir: 'elixir', erlang: 'erlang', } /** Source extensions per grammar, minus declaration-only files. */ export const EXTENSIONS = { python: /\.py$/, typescript: /(? EXTENSIONS[grammar].test(path) && !NOT_LIBRARY.test(path) + && !(grammar === 'erlang' && /(?:^|\/)property(?:\/|$)/.test(path)) const FUNCTIONS = { python: ['function_definition'], @@ -602,9 +604,10 @@ export async function scanSource({ grammar, text, commands, known, dispatch, bui } if (grammar === 'julia') return scanJulia(text, { commands, known, dispatch }) if (grammar === 'elixir') return scanElixir(text, { commands, known, dispatch }) + if (grammar === 'erlang') return scanErlang(text, { commands, known, dispatch, builders, labels }) if (grammar === 'fsharp') return scanFSharp(text) // A grammar that no reader above or below handles would reach the loader as a file that does not exist. - if (!(grammar in FUNCTIONS)) throw new Error(`no reader for the grammar ${JSON.stringify(grammar)}: scanSource reads ${[...Object.keys(FUNCTIONS), 'julia', 'fsharp', 'elixir'].join(', ')}`) + if (!(grammar in FUNCTIONS)) throw new Error(`no reader for the grammar ${JSON.stringify(grammar)}: scanSource reads ${[...Object.keys(FUNCTIONS), 'julia', 'fsharp', 'elixir', 'erlang'].join(', ')}`) const parser = await parserFor(grammar) // The Swift grammar predates typed throws; blanking the type keeps every line and column. const tree = parser.parse(grammar === 'swift' ? withoutNewSwift(text) : grammar === 'csharp' ? withoutPrimaryConstructors(text) : text) @@ -837,6 +840,6 @@ export async function scanSource({ grammar, text, commands, known, dispatch, bui } /** - * @typedef {{ name: string, owner?: string, start: number, nameLine: number, end: number, kind: string, sites: Site[], calls: Map, receivers: Map>, callDepths?: Map, namespace?: string }} ScannedFunction + * @typedef {{ name: string, owner?: string, module?: string, start: number, nameLine: number, end: number, kind: string, sites: Site[], calls: Map, receivers: Map>, callList?: { name: string, receiver?: string, line: number, calleeLine?: number, portMode?: string }[], callDepths?: Map, namespace?: string }} ScannedFunction * @typedef {{ command: string, line: number, flags: string, dispatch?: { line: number, name: string } | null, why?: string, builds?: boolean, depth?: number }} Site */ diff --git a/site/test/tmux-usage-erlang.outer.test.ts b/site/test/tmux-usage-erlang.outer.test.ts new file mode 100644 index 000000000..e6d0de70f --- /dev/null +++ b/site/test/tmux-usage-erlang.outer.test.ts @@ -0,0 +1,284 @@ +import { describe, expect, it } from 'vitest' +import { GRAMMARS, isLibrarySource, scanSource } from '../../scripts/lib/tmux-usage-scan.mjs' +import { callTargets, definitionsOf, deriveUsage } from '../../scripts/lib/tmux-usage-derive.mjs' +import { dispatcherProblems } from '../../scripts/lib/tmux-usage-dispatch.mjs' +import { auditEvidence } from '../../scripts/lib/tmux-usage-audit.mjs' + +// Outer: runs the selected OTP 29 scanner in bounded subprocesses. + +const known = new Set(['list-panes', 'list-windows', 'kill-pane']) +const scan = (text: string) => scanSource({ + grammar: 'erlang', text, commands: known, known, dispatch: new Set(['run/3']), +}) + +describe('Erlang tmux command source', () => { + it('registers library source without tests or generated build copies', () => { + expect(GRAMMARS.erlang).toBe('erlang') + expect(isLibrarySource('apps/core/src/panes.erl', 'erlang')).toBe(true) + for (const path of ['_build/default/lib/core/src/panes.erl', 'src/panes_tests.erl', 'src/panes_SUITE.erl', 'test/panes.erl', 'property/prop_panes.erl']) { + expect(isLibrarySource(path, 'erlang')).toBe(false) + } + }) + + it('keeps native arity and clauses while skipping docs, attributes and comments', async () => { + const { functions, types, orphans } = await scan([ + '-module(tmux_demo).', + '-moduledoc """', + 'fake() -> run(s, <<"kill-pane">>, []).', + '""".', + '-export([panes/1, panes/2]).', + '-record #row{command = <<"kill-pane">>}.', + '-spec panes(term()) -> term().', + 'panes(Server) -> panes(Server, []).', + 'panes(Server, []) ->', + ' % run(Server, <<"kill-pane">>, []).', + ' run(Server, <<"list-panes">>, [<<"-a">>]);', + 'panes(Server, Options) -> run(Server, <<"list-panes">>, Options).', + ].join('\n')) + expect(types).toEqual([{ name: 'tmux_demo', start: 1, end: 12 }]) + expect(orphans).toEqual([]) + expect(functions.map((fn) => [fn.owner, fn.name, fn.start, fn.nameLine, fn.end])).toEqual([ + ['tmux_demo', 'panes/1', 8, 8, 8], ['tmux_demo', 'panes/2', 9, 9, 12], + ]) + expect(functions[1].sites).toEqual([ + { command: 'list-panes', line: 11, flags: 'a', dispatch: { line: 11, name: 'run/3' } }, + { command: 'list-panes', line: 12, flags: '', dispatch: { line: 12, name: 'run/3' } }, + ]) + expect(functions[0].callList).toContainEqual({ name: 'panes/2', line: 8, calleeLine: 8 }) + const symbols = [{ id: 'panes', name: 'panes/2', parentName: 'tmux_demo', file: 'demo.erl', line: 9 }] + expect([...definitionsOf(functions.map((fn) => ({ ...fn, file: 'demo.erl' })), symbols).values()]).toEqual([symbols]) + }) + + it('counts nested argument syntax and resolves local and remote calls by module', async () => { + const { functions } = await scan([ + "-module('demo.mod').", + "read(S) -> tmux_target:run(S, <<\"list-panes\">>, [<<\"-t\">>, <<\"%1\">>]),", + " helper(fun(A, B) -> #{id => {A, B}} end, <<1, 2>>, #tmux_model:pane{id = <<\"%1\">>}).", + "helper(F, B, P) -> {F, B, P}.", + ].join('\n')) + expect(functions.map((fn) => fn.name)).toEqual(['read/1', 'helper/3']) + expect(functions[0].callList).toEqual([ + { name: 'run/3', receiver: 'tmux_target', line: 2, calleeLine: 2 }, + { name: 'helper/3', line: 3, calleeLine: 3 }, + ]) + expect(functions[0].sites[0].flags).toBe('t') + expect(callTargets(functions[0], functions[1], [functions[1], { ...functions[1], owner: 'other' }])).toBe(true) + }) + + it('does not turn a comparison, case label or command builder into a send', async () => { + const { functions } = await scan([ + '-module(demo).', + 'read(S, C) when C =:= <<"list-panes">> ->', + ' case C of <<"list-windows">> -> raw(<<"list-panes">>, [<<"-a">>]);', + ' _ -> run(S, <<"list-panes">>, [<<"-t">>, C]) end.', + ].join('\n')) + const sites = functions[0].sites + expect(sites.map((site) => site.dispatch)).toEqual([null, null, null, { line: 4, name: 'run/3' }]) + expect(sites.at(-1)?.flags).toBe('t') + }) + + it('keeps strings, quoted atoms and character escapes out of syntax', async () => { + const { functions } = await scan([ + "-module(demo).", + "'quoted.name'(S) ->", + " Chars = [$%, $., $;, $\\\", $\\x{2E}],", + " Text = ~\"run(S, \\\"kill-pane\\\", [])\",", + " run(S, <<\"list-\" \"panes\">>, [<<\"-a\">>]),", + " {Chars, Text}.", + ].join('\n')) + expect(functions.map((fn) => [fn.name, fn.end])).toEqual([["'quoted.name'/1", 6]]) + expect(functions[0].sites).toEqual([ + { command: 'list-panes', line: 5, flags: 'a', dispatch: { line: 5, name: 'run/3' } }, + ]) + }) + + it('does not lend flags between calls or send nested predicates and callbacks', async () => { + const { functions } = await scan([ + '-module(demo).', + 'read(S, C) -> case C of', + ' a -> run(S, <<"list-panes">>, [<<"-a">>]);', + ' b -> run(S, <<"list-panes">>, [<<"-t">>]);', + ' c -> run(S, choose(<<"list-panes">>), []);', + ' d -> run(S, fun() -> <<"list-panes">> end, []);', + ' e -> run(S, C =:= <<"list-panes">>, []) end.', + ].join('\n')) + expect(functions[0].sites.map((site) => [site.flags, site.dispatch !== null])).toEqual([ + ['a', true], ['t', true], ['', false], ['', false], ['', false], + ]) + }) + + it('honors declared builders and diagnostic argument labels', async () => { + const { functions } = await scanSource({ + grammar: 'erlang', known, commands: known, dispatch: new Set(['run/3']), + builders: new Set(['raw/2']), labels: new Map([['run/3', new Set([2])]]), + text: '-module(demo).\nread(S) -> run(S, raw(<<"list-panes">>, [<<"-a">>]), <<"list-windows">>).', + }) + expect(functions[0].sites.map((site) => [site.command, site.dispatch !== null])).toEqual([ + ['list-panes', true], ['list-windows', false], + ]) + }) + + it('does not attribute another module\'s call to a sole same-named helper', async () => { + const local = await scan('-module(demo).\nread() -> other:helper().\nhelper() -> ok.') + expect(callTargets(local.functions[0], local.functions[1], [local.functions[1]])).toBe(false) + const remote = await scan('-module(other).\nhelper() -> ok.') + expect(callTargets(local.functions[0], remote.functions[0], [remote.functions[0]])).toBe(true) + }) + + it('excludes deferred fun bodies and refuses unresolved declaration identities', async () => { + const deferred = await scan('-module(demo).\ncallback(S) -> fun() -> run(S, <<"kill-pane">>, []) end.') + expect(deferred.functions[0].sites[0].dispatch).toBe(null) + expect(deferred.functions[0].callList).toEqual([]) + await expect(scan('-define(MOD,demo).\n-module(?MOD).\nread()->other:helper().\nhelper()->ok.')).rejects.toThrow('module identity is unresolved') + await expect(scan('-module(demo).\n-define(NAME, read).\n?NAME(S)->run(S, <<"kill-pane">>, []).')).rejects.toThrow('function head is unresolved') + }) + + it('uses native sigils, triple strings and canonical atom spellings', async () => { + const { functions } = await scan([ + '-module(demo).', + '-doc ~s"""', + '"', + 'fake(S)->run(S, <<"kill-pane">>, []).', + '"', + '""".', + "'quoted.name'(S) -> run(S, ~\"list-\\x70anes\", []).", + 'café(S) -> run(S, <<"""', + 'list-panes', + '""">>, []).', + ].join('\n')) + expect(functions.map((fn) => fn.name)).toEqual(["'quoted.name'/1", 'café/1']) + expect(functions.flatMap((fn) => fn.sites).map((site) => site.command)).toEqual(['list-panes', 'list-panes']) + const symbols = [{ id: 'quoted', name: "'quoted.name'/1", file: 'demo.erl', line: 7 }] + expect([...definitionsOf(functions.map((fn) => ({ ...fn, file: 'demo.erl' })), symbols).values()]).toEqual([symbols]) + }) + + it('resolves static import attributes and consumes flag operands', async () => { + const local = await scan('-module(demo).\n-import(other,[helper/0]).\nread()->helper().') + const remote = await scan('-module(other).\nhelper()->ok.') + expect(callTargets(local.functions[0], remote.functions[0], [remote.functions[0]])).toBe(true) + const { functions } = await scan([ + '-module(demo).', + 'read(S) -> run(S, <<"list-panes">>, [<<"-F">>, <<"-a">>]),', + ' run(S, <<"list-panes">>, [choose(<<"-a">>)]),', + ' run(S, <<"list-panes">>, [<<"-t">>, target(), <<"-a">>]),', + ' run(S, <<"list-panes">>, [<<"--">>, <<"-a">>]).', + ].join('\n')) + expect(functions[0].sites.map((site) => site.flags)).toEqual(['F', '', 'at', '']) + }) + + it('does not credit computed command values or uncertain argv structure', async () => { + const { functions } = await scan([ + '-module(demo).', + 'read(S, X) -> run(S, <<"list-panes", X/binary>>, []),', + ' run(S, #{command => <<"list-panes">>}, []),', + ' run(S, {<<"list-panes">>, X}, []),', + ' run(S, <<"list-panes">>, [<<"-F">>] ++ [<<"-a">>]),', + ' run(S, <<"list-panes">>, [<<"-F">> | [<<"-a">>]]),', + ' run(S, <<"list-panes">>, [<<"-t">>, X | X]).', + ].join('\n')) + expect(functions[0].sites.slice(0, 3).map((site) => site.dispatch)).toEqual([null, null, null]) + expect(functions[0].sites.slice(3).map((site) => site.flags)).toEqual(['', '', '']) + await expect(scan('-module(demo).\nread(S)->run(S, <<"list-panes">>, [])')).rejects.toThrow('unterminated Erlang form') + }) + + it('keeps punctuation atoms out of call arity', async () => { + const { functions } = await scan("-module(demo).\nread()->helper(',').\nhelper(X)->X.") + expect(functions[0].callList).toEqual([{ name: 'helper/1', line: 2, calleeLine: 2 }]) + }) + + it('cites the resolved local call rather than a later remote namesake', async () => { + const text = [ + '-module(demo).', + 'read(S) ->', + ' helper(S),', + ' other:helper(S).', + 'helper(S) -> run(S, <<"kill-pane">>, []).', + ].join('\n') + const { functions } = await scan(text) + const located = functions.map((fn) => ({ ...fn, file: 'demo.erl' })) + const derived = deriveUsage({ command: 'kill-pane', + functions: located, + symbols: [{ id: 'read', name: 'read/1', file: 'demo.erl', line: 2 }], + }) + expect(derived.entries[0].evidence).toEqual(['demo.erl:5', 'demo.erl:3']) + const audit = (evidence: string[]) => auditEvidence({ + port: 'erlang', revision: 'fixture', + uses: [{ ...derived.entries[0], evidence }], claimFor: () => undefined, + sourcesAt: () => ({ read: () => text, functions: located }), + spellings: (command: string) => [command], + }) + expect(audit(derived.entries[0].evidence)).toEqual([]) + expect(audit(['demo.erl:5', 'demo.erl:4']).join('\n')).toMatch(/not a call/) + }) + + it('binds a declared dispatcher to its native module and arity', async () => { + const { functions } = await scanSource({ grammar: 'erlang', commands: known, known, + dispatch: new Set(['tmux_target:run/3']), + text: [ + '-module(demo).', + 'good(S)->tmux_target:run(S, <<"list-panes">>, []).', + 'other(S)->not_tmux:run(S, <<"list-panes">>, []).', + 'local(S)->run(S, <<"list-panes">>, []).', + 'run(S, Name, Args)->{S,Name,Args}.', + ].join('\n'), + }) + expect(functions.slice(0, 3).map((fn) => fn.sites[0].dispatch)).toEqual([ + { line: 2, name: 'tmux_target:run/3' }, null, null, + ]) + }) + + it('does not confuse differently named calls in the same static module', async () => { + const { functions } = await scan('-module(demo).\nread(S)->other:unrelated(S), other:helper(S).') + const target = (await scan('-module(other).\nhelper(S)->S.')).functions[0] + expect(callTargets(functions[0], target, [target], functions[0].callList![0])).toBe(false) + expect(callTargets(functions[0], target, [target], functions[0].callList![1])).toBe(true) + }) + + it('keeps a literal command when a different argument computes its options', async () => { + const { functions } = await scan('-module(demo).\nread(S, Args)->run(S, <<"kill-pane">>, Args ++ [<<"-t">>, <<"%1">>]).') + expect(functions[0].sites[0].dispatch).toEqual({ line: 2, name: 'run/3' }) + }) + + it('proves qualified dispatcher definitions from native heads rather than text mentions', async () => { + const text = '-module(transport).\nraw(Name, Args) ->\n {Name, Args}.\n' + const { functions } = await scan(text) + const input = { + port: 'erlang', readSource: () => text, + functions: functions.map((fn) => ({ ...fn, file: 'transport.erl' })), + } + const rule = { name: 'transport:raw/2', kind: 'builder', why: 'Builds a command value.' } + const check = (name: string, line: number, has: string[]) => dispatcherProblems({ + ...input, dispatchers: [{ ...rule, name, evidence: [{ at: `transport.erl:${line}`, has }] }], + }) + expect(check(rule.name, 2, ['raw(Name, Args)'])).toEqual([]) + expect(check('other:raw/2', 2, ['raw(Name, Args)']).join('\n')).toMatch(/no cited line shows/) + expect(check(rule.name, 3, ['{Name, Args}']).join('\n')).toMatch(/no cited line shows/) + expect(dispatcherProblems({ ...input, functions: undefined, dispatchers: [{ + ...rule, evidence: [{ at: 'transport.erl:2', has: [] }], + }] }).join('\n')).toMatch(/no cited line shows/) + }) + + it('requires an executable native port call rather than transport-looking text', async () => { + for (const [body, accepts] of [ + ['open_port({spawn_executable, Name}, Args)', true], + ['erlang:open_port({spawn_executable, Name}, Args)', true], + ['{Name, Args, <<"open_port({spawn_executable,">>}', false], + ['fun()->open_port({spawn_executable, Name}, Args) end', false], + ['other:open_port({spawn_executable, Name}, Args)', false], + ['{open_port({spawn, Name}, Args), <<"open_port({spawn_executable,">>}', false], + ['{erlang:open_port({spawn_executable =:= spawn, Name}, Args), <<"open_port({spawn_executable,">>}', false], + ['open_port({spawn_executable, Name}, Args).\n-compile({no_auto_import,[open_port/2]}).\nopen_port(_,_) -> ok', false], + ] as const) { + const text = `-module(tmux_transport).\nraw(Name, Args) -> ${body}.\n` + const { functions } = await scan(text) + const file = 'apps/libtmux_erlang/src/tmux_transport.erl' + const problems = dispatcherProblems({ + port: 'erlang', readSource: () => text, + functions: functions.map((fn) => ({ ...fn, file })), + dispatchers: [{ name: 'tmux_transport:raw/2', why: 'Starts the native process.', + evidence: [{ at: `${file}:2`, has: ['raw(Name, Args)'] }] }], + }) + expect(problems.length === 0, body).toBe(accepts) + } + }) +})