Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 8 additions & 0 deletions notes/adding-a-port.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions scripts/lib/tmux-usage-audit.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, number>, receivers: Map<string, Set<string>> }[] }} Sources
* @typedef {{ read: (path: string) => string | undefined, functions: (import('./tmux-usage-scan.mjs').ScannedFunction & { file: string })[] }} Sources
*
* @param {{
* port: string,
Expand Down Expand Up @@ -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)}`)
}
}
Expand Down
14 changes: 13 additions & 1 deletion scripts/lib/tmux-usage-derive.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand All @@ -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
}
Expand Down Expand Up @@ -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()
Expand Down
24 changes: 18 additions & 6 deletions scripts/lib/tmux-usage-dispatch.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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)$/
Expand Down Expand Up @@ -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<string, number> }[],
* functions: (import('./tmux-usage-scan.mjs').ScannedFunction & { file: string })[],
* readSource: (path: string) => string | undefined }} input
* @returns {string[]}
*/
Expand All @@ -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 []
Expand All @@ -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}`
Expand Down Expand Up @@ -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<string, number> }[] }} input
* functions?: (import('./tmux-usage-scan.mjs').ScannedFunction & { file: string })[] }} input
* @returns {string[]}
*/
export function dispatcherProblems({ port, dispatchers, readSource, functions }) {
Expand All @@ -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`)
Expand Down
33 changes: 33 additions & 0 deletions scripts/lib/tmux-usage-erlang.escript
Original file line number Diff line number Diff line change
@@ -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)}.
Loading
Loading