From d5c01521448539e2b0b8909171a35e9ccbbfc827 Mon Sep 17 00:00:00 2001 From: Tony Narlock Date: Sat, 7 Nov 2026 21:53:41 -0600 Subject: [PATCH] feat(api-model[erlang]) Add native API symbols why: Erlang reference pages need compiler-derived declarations and native identities before they can join the shared API catalog. what: - Export structured typespec clauses, quoted names and exporter identity - Map native declarations with checked provenance and opaque boundaries - Resolve module, arity, type and callback documentation references - Exercise compiler fixtures, validation failures and native name collisions --- notes/adding-a-port.md | 12 +- .../api-model/scripts/export-erlang.escript | 58 +++++- packages/api-model/src/doc/roles.ts | 2 + packages/api-model/src/index.ts | 1 + packages/api-model/src/inventory.ts | 1 + packages/api-model/src/languages/erlang.ts | 177 ++++++++++++++++++ packages/api-model/src/link.ts | 20 ++ packages/api-model/src/model.ts | 2 +- packages/api-model/test/erlang.test.ts | 73 ++++++++ .../test/export-erlang.outer.test.ts | 13 +- .../test/fixtures/erlang-native.json | 1 + .../fixtures/erlang-project/src/probe.erl | 10 +- 12 files changed, 356 insertions(+), 14 deletions(-) create mode 100644 packages/api-model/src/languages/erlang.ts create mode 100644 packages/api-model/test/erlang.test.ts create mode 100644 packages/api-model/test/fixtures/erlang-native.json diff --git a/notes/adding-a-port.md b/notes/adding-a-port.md index b7bccf1be..5eb73bfe1 100644 --- a/notes/adding-a-port.md +++ b/notes/adding-a-port.md @@ -167,16 +167,20 @@ $ escript packages/api-model/scripts/export-erlang.escript \ ../libtmux-erlang/_build/docs/api.json ``` -The artifact records the source commit, tracked input hashes and OTP version. +The artifact records the source commit, tracked input hashes, OTP version and +exporter source digest. It retains native module, function, type and callback documentation, typespecs, nominal types, supporting non-exported types and exported native records. Source locations follow included headers. Opaque declarations expose their name and parameters. Hidden modules and members stay out. Dirty sources, missing compiler chunks and ambiguous source paths fail the export. -This artifact is preparation for an Erlang model adapter. Erlang has no shared -site routes or package destinations until that adapter and the port's delivery -checks are complete. The compiler fixture runs in the outer test loop; it +`extractErlang` maps the artifact to the shared API model. The compiler supplies +callable parameters, return types, overload clauses and quoted atom spellings. +The model retains native arities, supporting types and distinct type/callback +identities. Native `m:`, `t:` and `c:` references resolve within their module. +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. ### Wrapper libraries diff --git a/packages/api-model/scripts/export-erlang.escript b/packages/api-model/scripts/export-erlang.escript index 8dfbcf2b4..4716b5859 100755 --- a/packages/api-model/scripts/export-erlang.escript +++ b/packages/api-model/scripts/export-erlang.escript @@ -6,6 +6,7 @@ main([Root0, AppName, Output0]) -> Output = filename:absname(Output0), try + ExporterDigest = exporter_digest(), "29" = erlang:system_info(otp_release), Root = filename:absname(Root0), ok = file:set_cwd(Root), @@ -28,8 +29,9 @@ main([Root0, AppName, Output0]) -> "source revision changed while compiling"), Artifact = #{schema => 1, port => <<"erlang">>, source => #{repository => Repository, revision => Revision, files => Files}, - exporter => #{name => <<"Erlang EEP-48 and abstract code">>, version => 1, - otp => otp_version(), columns => 60}, + exporter => #{name => <<"Erlang EEP-48 and abstract code">>, version => 2, + otp => otp_version(), columns => 60, + source_sha256 => ExporterDigest}, package => #{name => bin(AppName), version => bin(proplists:get_value(vsn, Properties))}, modules => Public}, ok = filelib:ensure_dir(Output), @@ -60,10 +62,10 @@ module(Name, Ebin, Files) -> Records = lists:append([Rs || {attribute, _, export_record, Rs} <- Forms]), Members = [member(E, Located, Types) || E <- lists:sort(Entries), public(E, Exports)], - #{name => bin(Name), doc => documentation(Doc), + #{name => bin(Name), display_name => atom_text(Name), doc => documentation(Doc), source => location(File, maps:get(source_anno, Meta, 1)), members => Members, - records => [#{name => bin(R), declaration => pretty(F), + records => [#{name => bin(R), display_name => atom_text(R), declaration => pretty(F), source => location(RecordFile, Anno)} || {RecordFile, F = {attribute, Anno, native_record, {R, _}}} <- Located, lists:member(R, Records)]}; @@ -87,14 +89,60 @@ member({{Kind, Name, Arity}, _, Signatures, Doc, Meta}, Located, Types) -> [nominal] -> nominal; _ -> public end, - #{kind => Kind, name => bin(Name), arity => Arity, + #{kind => Kind, name => bin(Name), display_name => atom_text(Name), arity => Arity, signatures => Signatures, doc => documentation(Doc), + specs => callable_specs(Kind, Name, Arity, Located, Declarations), since => metadata(since, Meta), deprecated => metadata(deprecated, Meta), visibility => Visibility, exported => Kind =/= type orelse lists:member({Name, Arity}, Types), source => member_location(Kind, Name, Arity, Located, Declarations), declarations => [declaration_text(F) || {_, F} <- Declarations]}. +callable_specs(type, _, _, _, _) -> []; +callable_specs(Kind, Name, Arity, Located, Declarations) -> + Patterns = case [Args || {_, {function, _, N, A, [{clause, _, Args, _, _} | _]}} <- Located, + N =:= Name, A =:= Arity] of + [Args] -> Args; + [] -> lists:duplicate(Arity, none) + end, + Attribute = case Kind of function -> spec; callback -> callback end, + [spec_clause(Clause, Patterns, Attribute, Anno, Name, Arity) + || {_, {attribute, Anno, AttributeName, {{Name1, Arity1}, Clauses}}} <- Declarations, + AttributeName =:= Attribute, Name1 =:= Name, Arity1 =:= Arity, Clause <- Clauses]. + +spec_clause(Clause, Patterns, Attribute, Anno, Name, Arity) -> + Fun = case Clause of + {type, _, bounded_fun, [Function, _]} -> Function; + _ -> Clause + end, + {type, _, 'fun', [{type, _, product, Parameters}, Return]} = Fun, + require(length(Parameters) =:= Arity, "compiler typespec arity mismatch"), + #{parameters => [parameter(Type, Pattern, Index) + || {Type, Pattern, Index} <- lists:zip3(Parameters, Patterns, lists:seq(1, Arity))], + returns => type_text(Return), + text => pretty({attribute, Anno, Attribute, {{Name, Arity}, [Clause]}})}. + +parameter({ann_type, _, [{var, _, Name}, Type]}, _, _) -> + #{name => bin(Name), type => type_text(Type)}; +parameter(Type, Pattern, Index) -> + Name = case Pattern of + {var, _, Variable} when Variable =/= '_' -> bin(Variable); + {match, _, {var, _, Variable}, _} when Variable =/= '_' -> bin(Variable); + {match, _, _, {var, _, Variable}} when Variable =/= '_' -> bin(Variable); + _ -> <<"Argument", (integer_to_binary(Index))/binary>> + end, + #{name => Name, type => type_text(Type)}. + +type_text(Type) -> + [_, Body] = binary:split(pretty({attribute, 0, type, {doc_type, Type, []}}), <<"::">>), + trim(binary:part(Body, 0, byte_size(Body) - 1)). + +atom_text(Name) -> unicode:characters_to_binary(erl_pp:expr({atom, 0, Name}, [{encoding, unicode}])). + +exporter_digest() -> + {ok, Source} = file:read_file(escript:script_name()), + binary:encode_hex(crypto:hash(sha256, Source), lowercase). + member_location(function, Name, Arity, Located, _) -> [{File, {function, Anno, Name, Arity, _}}] = [{F, Form} || {F, Form = {function, _, N, A, _}} <- Located, diff --git a/packages/api-model/src/doc/roles.ts b/packages/api-model/src/doc/roles.ts index 791867b29..2eb713edf 100644 --- a/packages/api-model/src/doc/roles.ts +++ b/packages/api-model/src/doc/roles.ts @@ -295,6 +295,7 @@ const SYNTAX: Record> = { julia: new Set(['markdown-link', 'documenter']), // ExDoc links a Markdown destination written as code: [the server](`LibTmux.Server`). elixir: new Set(['markdown-link', 'exdoc']), + erlang: new Set(['markdown-link', 'exdoc']), powershell: new Set(['markdown-link']), } @@ -604,6 +605,7 @@ function tokenizeRun(text: string, lang?: string): DocSpan[] { : syntax.has('docc') && code.ticks === 2 ? { kind: 'ref', role: 'any', target: doccTarget(code.text), label: code.text } : { kind: 'code', text: code.text } + if (lang === 'erlang' && span.kind === 'ref') span.label = span.label.replace(/^[mtc]:/, '') hits.push({ start: code.start, end: code.end, span }) } } diff --git a/packages/api-model/src/index.ts b/packages/api-model/src/index.ts index f85d23d4f..1098a0234 100644 --- a/packages/api-model/src/index.ts +++ b/packages/api-model/src/index.ts @@ -8,6 +8,7 @@ export { extractLua } from './languages/lua.ts' export { extractPowerShell } from './languages/powershell.ts' export { extractJulia } from './languages/julia.ts' export { ELIXIR_DECLARATION_COLUMNS, extractElixir } from './languages/elixir.ts' +export { extractErlang } from './languages/erlang.ts' export { extractFSharp, extractFSharpArtifact } from './languages/fsharp.ts' export { extractProject } from './project.ts' export { resolvePublicIds } from './reexports.ts' diff --git a/packages/api-model/src/inventory.ts b/packages/api-model/src/inventory.ts index 7c6867981..103a418e1 100644 --- a/packages/api-model/src/inventory.ts +++ b/packages/api-model/src/inventory.ts @@ -38,6 +38,7 @@ const DOMAIN: Record = { powershell: 'std', julia: 'std', elixir: 'std', + erlang: 'std', cxx: 'cpp', ts: 'js', rs: 'std', diff --git a/packages/api-model/src/languages/erlang.ts b/packages/api-model/src/languages/erlang.ts new file mode 100644 index 000000000..b6f65cb51 --- /dev/null +++ b/packages/api-model/src/languages/erlang.ts @@ -0,0 +1,177 @@ +import { parseMarkdownDocFull } from '../doc/markdown.ts' +import type { ApiModel, ApiSymbol, DocBlock, Modifier, Signature } from '../model.ts' + +interface Source { file: string; line: number } +interface Spec { parameters: { name: string; type: string }[]; returns: string; text: string } +interface Member { + name: string + display_name: string + kind: 'function' | 'callback' | 'type' + arity: number + doc: string | null + since: string | null + deprecated: string | null + visibility: 'public' | 'opaque' | 'nominal' + exported: boolean + signatures: string[] + declarations: string[] + specs: Spec[] + source: Source +} +interface Module { + name: string + display_name: string + doc: string | null + source: Source + members: Member[] + records: { name: string; display_name: string; declaration: string; source: Source }[] +} +interface Artifact { + schema: number + port: string + source: { repository: string; revision: string; files: { path: string; sha256: string }[] } + exporter: { name: string; version: number; columns: number; otp: string; source_sha256: string } + package: { name: string; version: string } + modules: Module[] +} + +function assertArtifact(input: unknown, expectedRevision?: string): Artifact { + const artifact = input as Artifact + if (artifact?.schema !== 1 || artifact.port !== 'erlang' || artifact.exporter?.version !== 2 || + artifact.exporter.columns !== 60 || !/^[a-f0-9]{64}$/.test(artifact.exporter.source_sha256 ?? '') || + !Array.isArray(artifact.modules) || !artifact.modules.length || + !/^[a-f0-9]{40}$/.test(artifact.source?.revision ?? '') || + !Array.isArray(artifact.source?.files) || !artifact.source.files.length || + !artifact.source.repository || !artifact.package?.name || !artifact.package.version) { + throw new Error('Erlang compiler artifact has an unsupported schema or source identity') + } + if (expectedRevision && artifact.source.revision !== expectedRevision) { + throw new Error('Erlang artifact source revision differs from the selected checkout') + } + const files = new Set(artifact.source.files.map((file) => { + if (!file.path || file.path.startsWith('/') || file.path.split('/').includes('..') || + !/^[a-f0-9]{64}$/.test(file.sha256)) throw new Error('Erlang artifact has invalid source inputs') + return file.path + })) + if (files.size !== artifact.source.files.length) throw new Error('Erlang artifact repeats a source input') + const location = (source: Source) => { + if (!source || !files.has(source.file) || !Number.isInteger(source.line) || source.line < 1) { + throw new Error('Erlang artifact lost a declaration source') + } + } + const seen = new Set() + const unique = (id: string) => { + if (seen.has(id)) throw new Error(`Erlang artifact repeats ${id}`) + seen.add(id) + } + for (const module of artifact.modules) { + if (!module.display_name || !Array.isArray(module.members) || !Array.isArray(module.records)) { + throw new Error('Erlang artifact lost a module declaration') + } + unique(module.display_name) + location(module.source) + for (const member of module.members) { + if (!['function', 'callback', 'type'].includes(member.kind) || !member.display_name || + !Number.isInteger(member.arity) || member.arity < 0 || member.arity > 255 || + !member.declarations?.length || !Array.isArray(member.specs) || + typeof member.exported !== 'boolean' || !['public', 'opaque', 'nominal'].includes(member.visibility)) { + throw new Error('Erlang artifact lost a member declaration') + } + unique(memberId(module, member)) + location(member.source) + if (member.visibility === 'opaque' && member.declarations.some(opaqueBody)) { + throw new Error('Erlang artifact exposes an opaque type body') + } + if (member.kind !== 'type' && (!Array.isArray(member.signatures) || + !member.signatures.length || member.signatures.some((head) => typeof head !== 'string' || !head.trim()) || + !member.specs.length || member.specs.some((spec) => !spec || + !Array.isArray(spec.parameters) || spec.parameters.length !== member.arity || + spec.parameters.some((parameter) => !parameter || + typeof parameter.name !== 'string' || !parameter.name.trim() || + typeof parameter.type !== 'string' || !parameter.type.trim()) || + typeof spec.returns !== 'string' || !spec.returns.trim() || + typeof spec.text !== 'string' || !spec.text.trim()))) { + throw new Error('Erlang artifact lost its native callable signature') + } + } + for (const record of module.records) { + if (!record.display_name || !record.declaration) throw new Error('Erlang artifact lost a native record declaration') + unique(recordId(module, record.display_name)) + location(record.source) + } + } + return artifact +} + +/** A body delimiter inside a compiler-quoted atom is part of its name. */ +function opaqueBody(text: string): boolean { + let quoted = false + for (let at = 0; at < text.length; at++) { + const character = text[at] + if (quoted && character === '\\') { at++; continue } + if (character === "'") { quoted = !quoted; continue } + if (!quoted && character === ':' && text[at + 1] === ':') return true + } + return quoted +} + +const memberId = (module: Module, member: Member): string => + `${member.kind === 'type' ? 't:' : member.kind === 'callback' ? 'c:' : ''}${module.display_name}:${member.display_name}/${member.arity}` +const recordId = (module: Module, name: string): string => `#${module.display_name}:${name}{}` + +function documentation(text: string | null, since?: string | null, deprecated?: string | null): DocBlock | undefined { + const doc = text?.trim() ? parseMarkdownDocFull(text, 'erlang').doc : undefined + return doc || since || deprecated + ? { ...(doc ?? { summary: '' }), ...(since ? { since } : {}), ...(deprecated ? { deprecated } : {}) } + : undefined +} + +/** Map compiler declarations without guessing types or parsing Erlang source in JavaScript. */ +export function extractErlang(input: unknown, expectedRevision?: string): ApiModel { + const artifact = assertArtifact(input, expectedRevision) + const source = (location: Source): ApiSymbol['source'] => ({ + ...location, repo: artifact.source.repository, revision: artifact.source.revision, + extractedRevision: artifact.source.revision, + }) + const common = { package: artifact.package.name, product: 'core' as const } + const symbols: ApiSymbol[] = [] + for (const module of artifact.modules) { + const owner = module.display_name + symbols.push({ id: owner, publicId: owner, qualifiedName: owner, name: owner, + kind: 'module', modifiers: [], signatures: [], apiScope: 'exported', + ...common, doc: documentation(module.doc), source: source(module.source) }) + for (const member of module.members) { + const type = member.kind === 'type' + const modifiers: Modifier[] = [ + ...(member.visibility === 'opaque' ? ['opaque' as const] : []), + ...(member.kind === 'callback' ? ['abstract' as const] : []), + ...(member.deprecated ? ['deprecated' as const] : []), + ...(member.specs.length > 1 ? ['overload' as const] : []), + ] + const signatures: Signature[] = type + ? member.declarations.map((raw) => ({ raw, params: [] })) + : member.specs.map((spec) => ({ + raw: member.kind === 'callback' ? spec.text : `${member.signatures[0]}\n${spec.text}`, + params: spec.parameters, returns: spec.returns, + })) + const id = memberId(module, member) + symbols.push({ id, publicId: id, qualifiedName: `${owner}:${member.display_name}/${member.arity}`, + name: `${member.display_name}/${member.arity}`, namespace: owner, parent: owner, + kind: type ? 'typealias' : 'function', modifiers, signatures, + ...common, apiScope: member.exported ? 'exported' : 'supporting', + doc: documentation(member.doc, member.since, member.deprecated), source: source(member.source) }) + } + for (const record of module.records) { + const id = recordId(module, record.display_name) + symbols.push({ id, publicId: id, qualifiedName: id, name: `#${record.display_name}{}`, + namespace: owner, parent: owner, kind: 'struct', modifiers: [], + signatures: [{ raw: record.declaration, params: [] }], ...common, + apiScope: 'exported', source: source(record.source) }) + } + } + return { port: 'erlang', repo: artifact.source.repository, revision: artifact.source.revision, + extractor: `@libtmux/api-model@0.0.1 (${artifact.exporter.name} v${artifact.exporter.version})`, + nativeProvenance: { files: artifact.source.files, exporter: artifact.exporter }, + sources: [{ ...common, version: artifact.package.version, repo: artifact.source.repository, + revision: artifact.source.revision, extractedRevision: artifact.source.revision }], symbols } +} diff --git a/packages/api-model/src/link.ts b/packages/api-model/src/link.ts index e8e8553be..de0a8a197 100644 --- a/packages/api-model/src/link.ts +++ b/packages/api-model/src/link.ts @@ -716,6 +716,7 @@ export class SymbolIndex { } private resolveSymbol(target: string, role: string, context?: ApiSymbol): LinkTarget | undefined { + if (this.lang === 'erlang') return this.resolveErlang(target, role, context) const relative = target.startsWith('.') const goType = this.lang === 'go' && role === 'class' if (this.lang === 'ruby') { @@ -948,6 +949,25 @@ export class SymbolIndex { return undefined } + /** Resolve compiler-qualified Erlang identities within the native namespace. */ + private resolveErlang(target: string, role: string, context?: ApiSymbol): LinkTarget | undefined { + const prefix = /^(?:([mtc]):)?/.exec(target)![1] + const body = prefix ? target.slice(2) : target + const wanted = prefix === 'm' ? body : target + const kinds = ROLE_KINDS[role] ?? [] + const matches = (symbol: ApiSymbol | undefined) => symbol && + (!kinds.length || kinds.includes(symbol.kind)) && + (prefix === 'm' ? symbol.kind === 'module' : prefix === 't' ? symbol.kind === 'typealias' + : prefix === 'c' ? symbol.modifiers.includes('abstract') : !symbol.id.startsWith('t:') && !symbol.id.startsWith('c:')) + let hit = this.byDeclared.get(wanted) + if (!matches(hit) && prefix !== 'm') { + let owner = context + while (owner?.parent) owner = this.byDeclared.get(owner.parent) + if (owner?.kind === 'module') hit = this.byDeclared.get(`${prefix ? `${prefix}:` : ''}${owner.id}:${body}`) + } + return matches(hit) ? { href: this.hrefFor(hit!), external: false, symbol: hit } : undefined + } + /** The module a declaration belongs to: itself, or its parent. */ private elixirOwner(context?: ApiSymbol): ApiSymbol | undefined { return context?.parent ? this.byDeclared.get(context.parent) : context diff --git a/packages/api-model/src/model.ts b/packages/api-model/src/model.ts index 7ebbdd9c4..e9241d377 100644 --- a/packages/api-model/src/model.ts +++ b/packages/api-model/src/model.ts @@ -14,7 +14,7 @@ */ /** Language libraries, by the slug the site uses. */ -export type PortSlug = 'py' | 'ruby' | 'lua' | 'ts' | 'rs' | 'go' | 'java' | 'csharp' | 'cxx' | 'swift' | 'kotlin' | 'scala' | 'fsharp' | 'powershell' | 'julia' | 'elixir' +export type PortSlug = 'py' | 'ruby' | 'lua' | 'ts' | 'rs' | 'go' | 'java' | 'csharp' | 'cxx' | 'swift' | 'kotlin' | 'scala' | 'fsharp' | 'powershell' | 'julia' | 'elixir' | 'erlang' export type ApiProduct = 'core' | 'workspace' | 'mcp' diff --git a/packages/api-model/test/erlang.test.ts b/packages/api-model/test/erlang.test.ts new file mode 100644 index 000000000..82e5328cb --- /dev/null +++ b/packages/api-model/test/erlang.test.ts @@ -0,0 +1,73 @@ +import { readFileSync } from 'node:fs' +import { createHash } from 'node:crypto' +import { describe, expect, it } from 'vitest' +import { extractErlang } from '../src/languages/erlang.ts' +import { SymbolIndex } from '../src/link.ts' +import { tokenizeDoc } from '../src/doc/roles.ts' + +const fixture = JSON.parse(readFileSync(new URL('./fixtures/erlang-native.json', import.meta.url), 'utf8')) +const model = () => extractErlang(fixture, fixture.source.revision) + +describe('Erlang compiler artifact adapter', () => { + it('retains source identity, native arities and compiler declarations', () => { + const result = model() + const symbol = (id: string) => result.symbols.find((entry) => entry.id === id)! + expect(result).toMatchObject({ port: 'erlang', revision: fixture.source.revision, repo: 'libtmux/probe' }) + expect(result.nativeProvenance?.files).toEqual(fixture.source.files) + expect(fixture.exporter.source_sha256).toBe(createHash('sha256') + .update(readFileSync(new URL('../scripts/export-erlang.escript', import.meta.url))).digest('hex')) + expect(symbol('probe:double/1')).toMatchObject({ name: 'double/1', parent: 'probe', kind: 'function' }) + expect(symbol('probe:double/1').signatures.map((signature) => signature.params)).toEqual([ + [{ name: 'Number', type: 'integer()' }], [{ name: 'Number', type: 'float()' }], + ]) + expect(symbol('probe:double/1').modifiers).toContain('overload') + expect(symbol('t:probe:handle/0').signatures[0]?.raw).toBe('-opaque handle().') + expect(symbol('t:probe:handle/0').type).toBeUndefined() + expect(symbol('t:probe:internal_mode/0').apiScope).toBe('supporting') + expect(symbol('t:probe:id/0').signatures[0]?.raw).toContain('-nominal id()') + expect(symbol('t:probe:included_id/0').source?.file).toBe('include/public_types.hrl') + expect(symbol("t:probe:'λ-handle'/1").name).toBe("'λ-handle'/1") + expect(symbol("t:probe:'a::b'/0").signatures[0]?.raw).toBe("-opaque 'a::b'().") + expect(symbol('#probe:row{}')).toMatchObject({ kind: 'struct', parent: 'probe' }) + expect(symbol('c:probe:prepare/1').signatures[0]?.raw).toContain('-callback prepare(') + expect(symbol('probe').doc?.examples?.[0]?.code).toContain('1> probe:double(2).') + }) + + it('resolves native module, function, type and callback references in their module', () => { + const result = model() + const index = new SymbolIndex(result.symbols, (symbol) => `/reference/${encodeURIComponent(symbol.id)}`, 'erlang') + const context = result.symbols.find((symbol) => symbol.id === 'probe:read/1')! + const refs = tokenizeDoc('`m:probe` `read/1` `t:handle/0` `c:prepare/1`', 'erlang') + expect(refs.filter((span) => span.kind === 'ref').map((span) => span.label)).toEqual(['probe', 'read/1', 'handle/0', 'prepare/1']) + for (const [target, id] of [['m:probe', 'probe'], ['read/1', 'probe:read/1'], ['t:handle/0', 't:probe:handle/0'], ['c:prepare/1', 'c:probe:prepare/1']]) { + expect(index.resolve(target!, 'any', context)?.symbol?.id).toBe(id) + } + expect(index.resolve('handle/0', 'any', context)?.symbol?.id).toBe('probe:handle/0') + expect(tokenizeDoc('[the module](`m:probe`)', 'erlang')).toEqual([ + { kind: 'ref', role: 'any', target: 'm:probe', label: 'the module' }, + ]) + expect(index.resolve('missing:read/1', 'any', context)).toBeUndefined() + expect(index.resolve('t:read/1', 'any', context)).toBeUndefined() + expect(index.resolve('probe:read/1', 'class', context)).toBeUndefined() + }) + + it('rejects unsupported, mismatched, duplicate or source-less artifacts', () => { + expect(() => extractErlang(fixture, '0'.repeat(40))).toThrow(/revision/) + expect(() => extractErlang({ ...fixture, schema: 2 })).toThrow(/schema/) + const duplicate = structuredClone(fixture) + duplicate.modules[0].members.push(duplicate.modules[0].members[0]) + expect(() => extractErlang(duplicate)).toThrow(/repeats/) + const missing = structuredClone(fixture) + missing.modules[0].members[0].source.file = '../outside.erl' + expect(() => extractErlang(missing)).toThrow(/source/) + const opaque = structuredClone(fixture) + opaque.modules[0].members.find((member: { visibility: string }) => member.visibility === 'opaque').declarations[0] += ' :: private_body' + expect(() => extractErlang(opaque)).toThrow(/opaque type body/) + const head = structuredClone(fixture) + head.modules[0].members.find((member: { kind: string }) => member.kind === 'function').signatures = [] + expect(() => extractErlang(head)).toThrow(/signature/) + const parameter = structuredClone(fixture) + delete parameter.modules[0].members.find((member: { kind: string; arity: number }) => member.kind === 'function' && member.arity > 0).specs[0].parameters[0].type + expect(() => extractErlang(parameter)).toThrow(/signature/) + }) +}) diff --git a/packages/api-model/test/export-erlang.outer.test.ts b/packages/api-model/test/export-erlang.outer.test.ts index 2d6af730d..f70fe6c6e 100644 --- a/packages/api-model/test/export-erlang.outer.test.ts +++ b/packages/api-model/test/export-erlang.outer.test.ts @@ -1,7 +1,8 @@ import { execFileSync, spawnSync } from 'node:child_process' +import { createHash } from 'node:crypto' import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' -import { join } from 'node:path' +import { join, relative } from 'node:path' import { describe, expect, it } from 'vitest' const script = new URL('../scripts/export-erlang.escript', import.meta.url).pathname @@ -39,6 +40,7 @@ describe.skipIf(!available)('Erlang compiler export', { timeout: 30_000 }, () => const artifact = JSON.parse(readFileSync(join(directory, '_build/api.json'), 'utf8')) expect(artifact).toMatchObject({ schema: 1, port: 'erlang', source: { repository: 'libtmux/probe', revision }, package: { name: 'probe', version: '0.1.0' } }) expect(artifact.source.files.map((file: { path: string }) => file.path)).toContain('src/probe.erl') + expect(artifact.exporter.source_sha256).toBe(createHash('sha256').update(readFileSync(script)).digest('hex')) const module = artifact.modules[0] expect(module.name).toBe('probe') expect(module.doc).toContain('`m:probe` and `read/1`') @@ -47,6 +49,11 @@ describe.skipIf(!available)('Erlang compiler export', { timeout: 30_000 }, () => expect(member('function', 'double')).toMatchObject({ arity: 1, since: '0.1.0', deprecated: 'Use a calculator.', source: { file: 'src/probe.erl' } }) expect(member('function', 'double').declarations.join('')).toContain('float()') expect(member('function', 'double').declarations.join('')).toContain('integer()') + expect(member('function', 'double').specs).toEqual([ + expect.objectContaining({ parameters: [{ name: 'Number', type: 'integer()' }], returns: 'integer()' }), + expect.objectContaining({ parameters: [{ name: 'Number', type: 'float()' }], returns: 'float()' }), + ]) + expect(member('type', 'λ-handle').display_name).toBe("'λ-handle'") expect(member('type', 'handle')).toMatchObject({ visibility: 'opaque', declarations: ['-opaque handle().'] }) expect(JSON.stringify(artifact)).not.toContain('private_token') expect(member('type', 'id').declarations.join('')).toContain('-nominal id()') @@ -59,7 +66,9 @@ describe.skipIf(!available)('Erlang compiler export', { timeout: 30_000 }, () => expect(module.records[0].declaration).toContain('-record #row{') expect(module.members.every((m: { source: { line: number } }) => m.source.line > 0)).toBe(true) const first = readFileSync(join(directory, '_build/api.json'), 'utf8') - const repeat = exportFrom(directory) + const repository = new URL('../../../', import.meta.url).pathname + const repeat = spawnSync('escript', [relative(repository, script), relative(repository, directory), 'probe', join(directory, '_build/api.json')], + { cwd: repository, encoding: 'utf8', env }) expect(repeat.status, repeat.stderr).toBe(0) expect(readFileSync(join(directory, '_build/api.json'), 'utf8')).toBe(first) } finally { rmSync(directory, { recursive: true, force: true }) } diff --git a/packages/api-model/test/fixtures/erlang-native.json b/packages/api-model/test/fixtures/erlang-native.json new file mode 100644 index 000000000..20728342d --- /dev/null +++ b/packages/api-model/test/fixtures/erlang-native.json @@ -0,0 +1 @@ +{"port":"erlang","modules":[{"name":"probe","records":[{"name":"row","source":{"line":15,"file":"src/probe.erl"},"display_name":"row","declaration":"-record #row{id :: id()}."}],"doc":"Captured values with `m:probe` and `read/1` references.\n\n```erlang\n1> probe:double(2).\n4\n```","source":{"line":1,"file":"src/probe.erl"},"display_name":"probe","members":[{"arity":1,"name":"prepare","deprecated":null,"doc":"Prepare one row.","exported":true,"specs":[{"text":"-callback prepare(row()) -> {ok, handle()}.","parameters":[{"name":"Argument1","type":"row()"}],"returns":"{ok, handle()}"}],"source":{"line":32,"file":"src/probe.erl"},"display_name":"prepare","kind":"callback","signatures":["prepare/1"],"since":null,"visibility":"public","declarations":["-callback prepare(row()) -> {ok, handle()}."]},{"arity":1,"name":"double","deprecated":"Use a calculator.","doc":"Double an integer or float.","exported":true,"specs":[{"text":"-spec double(integer()) -> integer().","parameters":[{"name":"Number","type":"integer()"}],"returns":"integer()"},{"text":"-spec double(float()) -> float().","parameters":[{"name":"Number","type":"float()"}],"returns":"float()"}],"source":{"line":37,"file":"src/probe.erl"},"display_name":"double","kind":"function","signatures":["double(Number)"],"since":"0.1.0","visibility":"public","declarations":["-spec double(integer()) -> integer();\n (float()) -> float()."]},{"arity":0,"name":"handle","deprecated":null,"doc":"Construct a handle; the type and function share a name.","exported":true,"specs":[{"text":"-spec handle() -> handle().","parameters":[],"returns":"handle()"}],"source":{"line":45,"file":"src/probe.erl"},"display_name":"handle","kind":"function","signatures":["handle()"],"since":null,"visibility":"public","declarations":["-spec handle() -> handle()."]},{"arity":1,"name":"read","deprecated":null,"doc":"Read one `t:handle/0`; see `c:prepare/1`.","exported":true,"specs":[{"text":"-spec read(handle()) -> {ok, internal_mode()}.","parameters":[{"name":"_Handle","type":"handle()"}],"returns":"{ok, internal_mode()}"}],"source":{"line":41,"file":"src/probe.erl"},"display_name":"read","kind":"function","signatures":["read(Handle)"],"since":null,"visibility":"public","declarations":["-spec read(handle()) -> {ok, internal_mode()}."]},{"arity":0,"name":"a::b","deprecated":null,"doc":"A quoted opaque type whose name includes a delimiter.","exported":true,"specs":[],"source":{"line":25,"file":"src/probe.erl"},"display_name":"'a::b'","kind":"type","signatures":["'a::b'()"],"since":null,"visibility":"opaque","declarations":["-opaque 'a::b'()."]},{"arity":0,"name":"handle","deprecated":null,"doc":"An opaque handle; its representation stays private.","exported":true,"specs":[],"source":{"line":19,"file":"src/probe.erl"},"display_name":"handle","kind":"type","signatures":["handle()"],"since":null,"visibility":"opaque","declarations":["-opaque handle()."]},{"arity":0,"name":"id","deprecated":null,"doc":"A nominal identifier.","exported":true,"specs":[],"source":{"line":17,"file":"src/probe.erl"},"display_name":"id","kind":"type","signatures":["id()"],"since":null,"visibility":"nominal","declarations":["-nominal id() :: binary()."]},{"arity":0,"name":"included_id","deprecated":null,"doc":"An included public type.","exported":true,"specs":[],"source":{"line":2,"file":"include/public_types.hrl"},"display_name":"included_id","kind":"type","signatures":["included_id()"],"since":null,"visibility":"public","declarations":["-type included_id() :: non_neg_integer()."]},{"arity":0,"name":"internal_mode","deprecated":null,"doc":"A supporting output mode.","exported":false,"specs":[],"source":{"line":27,"file":"src/probe.erl"},"display_name":"internal_mode","kind":"type","signatures":["internal_mode()"],"since":null,"visibility":"public","declarations":["-type internal_mode() :: ready | stopped."]},{"arity":1,"name":"odd-name","deprecated":null,"doc":"A handle with a quoted type name.","exported":true,"specs":[],"source":{"line":21,"file":"src/probe.erl"},"display_name":"'odd-name'","kind":"type","signatures":["'odd-name'(T)"],"since":null,"visibility":"opaque","declarations":["-opaque 'odd-name'(T)."]},{"arity":0,"name":"row","deprecated":null,"doc":"One public row.","exported":true,"specs":[],"source":{"line":29,"file":"src/probe.erl"},"display_name":"row","kind":"type","signatures":["row()"],"since":null,"visibility":"public","declarations":["-type row() :: #row{}."]},{"arity":1,"name":"λ-handle","deprecated":null,"doc":"A handle with a Unicode name.","exported":true,"specs":[],"source":{"line":23,"file":"src/probe.erl"},"display_name":"'λ-handle'","kind":"type","signatures":["'\\x{3BB}-handle'(T)"],"since":null,"visibility":"opaque","declarations":["-opaque 'λ-handle'(T)."]}]}],"source":{"repository":"libtmux/probe","revision":"6e9cd33bd3e8d3965c49ae911c8a09466d0eae53","files":[{"path":"include/public_types.hrl","sha256":"9bd63bbce8119cc4fed46a42aa8640d9350b01267a34ae4878b139fdcb8cfb01"},{"path":"rebar.config","sha256":"f94e6aa5c003ce3151b59b58106aa791612a98de65a14407bc5da2e174cdca4a"},{"path":"src/probe.app.src","sha256":"582fd682d87092b0497ca977f633d7061f0afb2185a8b4bed2e00745356a19ce"},{"path":"src/probe.erl","sha256":"a03324380538cc5520faa29d8423633f92b0302171a23ad094d2a83cff04756d"}]},"schema":1,"exporter":{"name":"Erlang EEP-48 and abstract code","version":2,"otp":"29.1.2","columns":60,"source_sha256":"989546ac2b748b23f7fbbe928e4bb6a65ea29aad95638cb22e1af3d9f087f156"},"package":{"name":"probe","version":"0.1.0"}} diff --git a/packages/api-model/test/fixtures/erlang-project/src/probe.erl b/packages/api-model/test/fixtures/erlang-project/src/probe.erl index 4300162d6..3a6479f4f 100644 --- a/packages/api-model/test/fixtures/erlang-project/src/probe.erl +++ b/packages/api-model/test/fixtures/erlang-project/src/probe.erl @@ -7,8 +7,8 @@ Captured values with `m:probe` and `read/1` references. 4 ``` """. --export([double/1, hidden/0, read/1]). --export_type([handle/0, id/0, row/0, included_id/0, 'odd-name'/1, 'λ-handle'/1]). +-export([double/1, hidden/0, read/1, handle/0]). +-export_type([handle/0, id/0, row/0, included_id/0, 'odd-name'/1, 'λ-handle'/1, 'a::b'/0]). -include("public_types.hrl"). -export_record([row]). @@ -21,6 +21,8 @@ Captured values with `m:probe` and `read/1` references. -opaque 'odd-name'(T) :: {private_token, T}. -doc "A handle with a Unicode name.". -opaque 'λ-handle'(T) :: {private_token, T}. +-doc "A quoted opaque type whose name includes a delimiter.". +-opaque 'a::b'() :: private_token. -doc "A supporting output mode.". -type internal_mode() :: ready | stopped. -doc "One public row.". @@ -38,5 +40,9 @@ double(Number) -> Number * 2. -spec read(handle()) -> {ok, internal_mode()}. read(_Handle) -> {ok, ready}. +-doc "Construct a handle; the type and function share a name.". +-spec handle() -> handle(). +handle() -> #{private_token => make_ref()}. + -doc false. hidden() -> secret.