diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4fa4227cf..f510b393c 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -103,7 +103,50 @@ jobs: # Exact versions only: a loose match would resolve a moving release. version-type: strict install-hex: true - rebar3-version: '3.28.0' + + - name: Cache pinned Rebar3 + uses: actions/cache@55cc8345863c7cc4c66a329aec7e433d2d1c52a9 # v6.1.0 + with: + path: ${{ runner.temp }}/libtmux-docs-tools/rebar3/rebar3 + key: rebar3-${{ runner.os }}-${{ runner.arch }}-3.28.0-5a28b1cca082d3b023ec0f5df9d9f9d52557036c6f2a21c1ffa11b93a984dd42 + + - name: Install pinned Rebar3 + shell: bash + env: + GH_TOKEN: ${{ github.token }} + run: | + rebar_dir="$RUNNER_TEMP/libtmux-docs-tools/rebar3" + rebar_file="$rebar_dir/rebar3" + rebar_sha=5a28b1cca082d3b023ec0f5df9d9f9d52557036c6f2a21c1ffa11b93a984dd42 + rebar_download='' + rebar_install_dir='' + rebar_ready=false + cleanup_rebar() { + if [[ -n "$rebar_download" ]]; then + rm -f -- "$rebar_download" + fi + if [[ "$rebar_ready" != true && -n "$rebar_install_dir" ]]; then + rm -rf -- "$rebar_install_dir" + fi + } + trap cleanup_rebar EXIT + mkdir -p "$rebar_dir" + if [[ ! -f "$rebar_file" ]] || ! printf '%s %s\n' "$rebar_sha" "$rebar_file" | sha256sum --check --status; then + rebar_download=$(mktemp "$rebar_dir/.rebar3.XXXXXXXX") + gh api -H 'Accept: application/octet-stream' \ + repos/erlang/rebar3/releases/assets/664140441 > "$rebar_download" + printf '%s %s\n' "$rebar_sha" "$rebar_download" | sha256sum --check --strict + mv "$rebar_download" "$rebar_file" + fi + rebar_install_dir=$(mktemp -d "$RUNNER_TEMP/libtmux-docs-rebar3.XXXXXXXX") + install -m 755 "$rebar_file" "$rebar_install_dir/rebar3" + printf '%s %s\n' "$rebar_sha" "$rebar_install_dir/rebar3" | sha256sum --check --strict + rebar_version=$(REBAR_GLOBAL_CONFIG_DIR="$RUNNER_TEMP/rebar3-empty-config" \ + REBAR_CONFIG="$RUNNER_TEMP/rebar3-empty.config" "$rebar_install_dir/rebar3" version) + printf '%s\n' "$rebar_version" + [[ "$rebar_version" == 'rebar 3.28.0 '* ]] + printf '%s\n' "$rebar_install_dir" >> "$GITHUB_PATH" + rebar_ready=true - name: Stage integrated source guides env: diff --git a/notes/adding-a-port.md b/notes/adding-a-port.md index 5eb73bfe1..6f9ef83e9 100644 --- a/notes/adding-a-port.md +++ b/notes/adding-a-port.md @@ -155,8 +155,8 @@ In the new worktree, on `docs-site`: ### Erlang compiler artifact -The Erlang exporter builds a clean source checkout with its selected Rebar3, -then reads EEP-48 Markdown and abstract code from the compiled application. +The Erlang exporter builds a clean source checkout with its selected Rebar3 +in a temporary build directory, then reads EEP-48 Markdown and abstract code. Use the source project's OTP 29 and Rebar3 toolchain on `PATH`. With the Erlang source checkout beside this docs worktree, export its core API: @@ -167,18 +167,40 @@ $ escript packages/api-model/scripts/export-erlang.escript \ ../libtmux-erlang/_build/docs/api.json ``` -The artifact records the source commit, tracked input hashes, OTP version and -exporter source digest. +The version-3 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. +The exporter parses formatted declarations to identify type and native-record +references, including their arities and UTF-16 ranges. It checks that formatting +preserves the syntax tree. OTP destinations require a compiler-known builtin or +an entry in that module's documentation; unknown types remain unresolved. +The exporter observes compiler file calls inside the temporary Rebar VM and +uses an identity parse transform to capture the actual compiler options before +OTP's deterministic build removes preprocessing context. OTP's preprocessor recovers +full paths in that same VM, preserving its library paths, environment and +working directory. The resulting forms must match the compiled +forms. This rejects external public headers even when their basenames and +declarations match tracked headers. Private OTP headers may supply implementation +records, but every documented declaration must resolve to a regular tracked +source file. Tracked source symlinks are rejected; temporary Rebar build links +back to those regular files are permitted. +An unreproducible preprocessing context fails the export. Explicit `-file` +source remapping is unsupported. Temporary compiler +context and build output are removed on completion or an export error. + `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. +API signatures and their Markdown copies retain Erlang syntax and use the +compiler's reference ranges for links. The site checks the 60-column display +limit after native formatting. The `libtmux_erlang_workspace` application maps +to the workspace product; the core application maps to core. 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. diff --git a/packages/api-model/scripts/export-erlang.escript b/packages/api-model/scripts/export-erlang.escript index 4716b5859..0df7ac8b6 100755 --- a/packages/api-model/scripts/export-erlang.escript +++ b/packages/api-model/scripts/export-erlang.escript @@ -1,12 +1,14 @@ #!/usr/bin/env escript -mode(compile). -include_lib("kernel/include/eep48.hrl"). +-export([capture_compiler/0, parse_transform/2]). %% Build in the source checkout's toolchain; read compiler chunks, never source regexes. main([Root0, AppName, Output0]) -> Output = filename:absname(Output0), try ExporterDigest = exporter_digest(), + Exporter = filename:absname(escript:script_name()), "29" = erlang:system_info(otp_release), Root = filename:absname(Root0), ok = file:set_cwd(Root), @@ -14,14 +16,15 @@ main([Root0, AppName, Output0]) -> clean(), Files = inputs(), Repository = repository(trim(run("git", ["remote", "get-url", "origin"]))), - _ = run("rebar3", ["compile"]), - Ebin = filename:join(["_build", "default", "lib", AppName, "ebin"]), - AppFile = filename:join(Ebin, AppName ++ ".app"), - {ok, [{application, App, Properties}]} = file:consult(AppFile), - true = atom_to_list(App) =:= AppName, - Modules = lists:sort(proplists:get_value(modules, Properties)), - Public = [M || Name <- Modules, - M <- [module(Name, Ebin, Files)], M =/= hidden], + {Properties, Public} = with_compilation(Exporter, fun(Build, Context) -> + Ebin = filename:join([Build, "default", "lib", AppName, "ebin"]), + AppFile = filename:join(Ebin, AppName ++ ".app"), + {ok, [{application, App, Props}]} = file:consult(AppFile), + true = atom_to_list(App) =:= AppName, + Modules = lists:sort(proplists:get_value(modules, Props)), + {Props, [M || Name <- Modules, + M <- [module(Name, Ebin, Files, Modules, Context)], M =/= hidden]} + end), require(Public =/= [], "application documents no public modules"), clean(), require(Files =:= inputs(), "source inputs changed while compiling"), @@ -29,7 +32,7 @@ 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 => 2, + exporter => #{name => <<"Erlang EEP-48 and abstract code">>, version => 3, otp => otp_version(), columns => 60, source_sha256 => ExporterDigest}, package => #{name => bin(AppName), version => bin(proplists:get_value(vsn, Properties))}, @@ -46,7 +49,7 @@ main(_) -> io:format(standard_error, "usage: export-erlang.escript SOURCE_ROOT APP OUTPUT.json~n", []), halt(1). -module(Name, Ebin, Files) -> +module(Name, Ebin, Files, ProjectModules, Context) -> Beam = filename:join(Ebin, atom_to_list(Name) ++ ".beam"), case beam_lib:chunks(Beam, [abstract_code, "Docs"]) of {ok, {Name, [{abstract_code, {raw_abstract_v1, Forms}}, {"Docs", DocsBin}]}} -> @@ -55,18 +58,20 @@ module(Name, Ebin, Files) -> module_doc = hidden} -> hidden; #docs_v1{beam_language = erlang, format = <<"text/markdown">>, module_doc = Doc, metadata = Meta, docs = Entries} -> - File = source_file(atom_to_list(Name) ++ ".erl", Files), - Located = located_forms(Forms, Files), + {File, Located} = source_forms(Name, Forms, Files, Context), Exports = lists:append([Fs || {attribute, _, export, Fs} <- Forms]), Types = lists:append([Ts || {attribute, _, export_type, Ts} <- Forms]), Records = lists:append([Rs || {attribute, _, export_record, Rs} <- Forms]), - Members = [member(E, Located, Types) || E <- lists:sort(Entries), + Scope = #{owner => Name, modules => ProjectModules, files => Files, + otp_types => otp_types(Forms, ProjectModules)}, + Members = [member(E, Located, Types, Scope) || E <- lists:sort(Entries), public(E, Exports)], #{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), display_name => atom_text(R), declaration => pretty(F), - source => location(RecordFile, Anno)} || + references => form_references(pretty(F), Scope), + source => location(source_file(RecordFile, Files), Anno)} || {RecordFile, F = {attribute, Anno, native_record, {R, _}}} <- Located, lists:member(R, Records)]}; _ -> fail([bin(Name), <<": unsupported compiler documentation format">>]) @@ -81,7 +86,7 @@ public({{Kind, Name, Arity}, _, _, Doc, _}, Exports) -> callback -> true end. -member({{Kind, Name, Arity}, _, Signatures, Doc, Meta}, Located, Types) -> +member({{Kind, Name, Arity}, _, Signatures, Doc, Meta}, Located, Types, Scope) -> Declarations = [{File, F} || {File, F} <- Located, declaration(F, Kind, Name, Arity)], require(Declarations =/= [], [bin(Name), <<": missing compiler declaration">>]), Visibility = case [K || {_, {attribute, _, K, _}} <- Declarations] of @@ -91,47 +96,187 @@ member({{Kind, Name, Arity}, _, Signatures, Doc, Meta}, Located, Types) -> end, #{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), + specs => callable_specs(Kind, Name, Arity, Located, Declarations, Scope), 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]}. + source => member_location(Kind, Name, Arity, Located, Declarations, maps:get(files, Scope)), + declarations => [declaration_text(F) || {_, F} <- Declarations], + declaration_references => [declaration_references(F, Scope) || {_, F} <- Declarations]}. -callable_specs(type, _, _, _, _) -> []; -callable_specs(Kind, Name, Arity, Located, Declarations) -> +callable_specs(type, _, _, _, _, _) -> []; +callable_specs(Kind, Name, Arity, Located, Declarations, Scope) -> 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) + [spec_clause(Clause, Patterns, Attribute, Anno, Name, Arity, Scope) || {_, {attribute, Anno, AttributeName, {{Name1, Arity1}, Clauses}}} <- Declarations, AttributeName =:= Attribute, Name1 =:= Name, Arity1 =:= Arity, Clause <- Clauses]. -spec_clause(Clause, Patterns, Attribute, Anno, Name, Arity) -> +spec_clause(Clause, Patterns, Attribute, Anno, Name, Arity, Scope) -> 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) + Text = pretty({attribute, Anno, Attribute, {{Name, Arity}, [Clause]}}), + ReturnText = type_text(Return), + #{parameters => [parameter(Type, Pattern, Index, Scope) || {Type, Pattern, Index} <- lists:zip3(Parameters, Patterns, lists:seq(1, Arity))], - returns => type_text(Return), - text => pretty({attribute, Anno, Attribute, {{Name, Arity}, [Clause]}})}. + returns => ReturnText, returns_references => type_references(ReturnText, Scope), + text => Text, references => form_references(Text, Scope)}. -parameter({ann_type, _, [{var, _, Name}, Type]}, _, _) -> - #{name => bin(Name), type => type_text(Type)}; -parameter(Type, Pattern, Index) -> +parameter({ann_type, _, [{var, _, Name}, Type]}, _, _, Scope) -> + typed_parameter(bin(Name), Type, Scope); +parameter(Type, Pattern, Index, Scope) -> 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)}. + typed_parameter(Name, Type, Scope). + +typed_parameter(Name, Type, Scope) -> + Text = type_text(Type), + #{name => Name, type => Text, references => type_references(Text, Scope)}. + +declaration_references({attribute, _, opaque, _}, _) -> []; +declaration_references({function, _, _, _, _}, _) -> []; +declaration_references(Form, Scope) -> form_references(pretty(Form), Scope). + +type_references(Text, Scope) -> + Prefix = <<"-type reference() :: ">>, + Offset = utf16_length(Prefix), + [R#{start := maps:get(start, R) - Offset, 'end' := maps:get('end', R) - Offset} + || R <- form_references(<>, Scope)]. + +%% Rescan the compiler's own spelling. Parser annotations distinguish types +%% from declaration names, variables and literal lookalikes without a lexer +%% maintained in another language. Browser offsets count UTF-16 code units. +form_references(Text, Scope) -> + Characters = unicode:characters_to_list(Text), + {ok, Tokens, _} = erl_scan:string(Characters, {1, 1}, [text]), + {ok, Form} = erl_parse:parse_form(Tokens), + Positions = positions(Characters, 1, 1, 0, #{}), + References = references(Form, Scope, Positions), + lists:sort(fun(A, B) -> maps:get(start, A) < maps:get(start, B) end, References). + +references({user_type, Anno, Name, Arguments}, Scope, Positions) -> + [reference(Anno, Anno, maps:get(owner, Scope), Name, length(Arguments), Scope, Positions) + | references(Arguments, Scope, Positions)]; +references({remote_type, _, [{atom, First, Module}, {atom, Last, Name}, Arguments]}, Scope, Positions) -> + [reference(First, Last, Module, Name, length(Arguments), Scope, Positions) + | references(Arguments, Scope, Positions)]; +references({type, First, record, [{tuple, _, [{atom, _, Module}, {atom, Last, Name}]} | Fields]}, Scope, Positions) -> + [record_reference(First, Last, Module, Name, Positions) | references(Fields, Scope, Positions)]; +references({type, First, record, [{atom, Last, Name} | Fields]}, Scope, Positions) -> + [record_reference(First, Last, maps:get(owner, Scope), Name, Positions) + | references(Fields, Scope, Positions)]; +references({type, Anno, Name, Arguments}, Scope, Positions) -> + Arity = case Arguments of any -> 0; _ when is_list(Arguments) -> length(Arguments) end, + Explicit = erl_anno:text(Anno) =:= unicode:characters_to_list(atom_text(Name)), + Head = case Explicit andalso erl_internal:is_type(Name, Arity) of + true -> [reference(Anno, Anno, erlang, Name, Arity, Scope, Positions)]; + false -> [] + end, + Head ++ references(Arguments, Scope, Positions); +references(Tuple, Scope, Positions) when is_tuple(Tuple) -> + references(tuple_to_list(Tuple), Scope, Positions); +references(List, Scope, Positions) when is_list(List) -> + lists:append([references(Item, Scope, Positions) || Item <- List]); +references(_, _, _) -> []. + +reference(First, Last, Module, Name, Arity, Scope, Positions) -> + Target = <<"t:", (atom_text(Module))/binary, ":", (atom_text(Name))/binary, + "/", (integer_to_binary(Arity))/binary>>, + Range = reference_range(First, Last, Target, Positions), + case lists:member(Module, maps:get(modules, Scope)) of + true -> Range; + false -> + case documented_otp_type(Module, Name, Arity, Scope) of + none -> Range; + Application -> + Href = iolist_to_binary([<<"https://www.erlang.org/doc/apps/">>, + Application, <<"/">>, uri_string:quote(bin(Module)), <<".html#t:">>, + uri_string:quote(atom_text(Name)), <<"/">>, integer_to_binary(Arity)]), + Range#{external => #{href => Href, project => <<"Erlang/OTP">>}} + end + end. + +otp_types(Forms, ProjectModules) -> + Modules = lists:usort(remote_modules(Forms)), + maps:from_list([{Module, {otp_application(Module), documented_types(Module)}} + || Module <- Modules, not lists:member(Module, ProjectModules), + otp_application(Module) =/= none]). + +documented_types(Module) -> + case code:get_doc(Module) of + {ok, #docs_v1{module_doc = Doc, docs = Entries}} when Doc =/= hidden -> + sets:from_list([{Name, Arity} || {{type, Name, Arity}, _, _, TypeDoc, _} <- Entries, + TypeDoc =/= hidden]); + _ -> sets:new() + end. + +documented_otp_type(erlang, Name, Arity, Scope) -> + case erl_internal:is_type(Name, Arity) of + true -> <<"erts">>; + false -> lookup_otp_type(erlang, Name, Arity, Scope) + end; +documented_otp_type(Module, Name, Arity, Scope) -> lookup_otp_type(Module, Name, Arity, Scope). + +lookup_otp_type(Module, Name, Arity, Scope) -> + case maps:find(Module, maps:get(otp_types, Scope)) of + {ok, {Application, Types}} -> + case sets:is_element({Name, Arity}, Types) of true -> Application; false -> none end; + error -> none + end. + +remote_modules({remote_type, _, [{atom, _, Module}, _, Arguments]}) -> + [Module | remote_modules(Arguments)]; +remote_modules(Tuple) when is_tuple(Tuple) -> remote_modules(tuple_to_list(Tuple)); +remote_modules(List) when is_list(List) -> lists:append([remote_modules(Item) || Item <- List]); +remote_modules(_) -> []. + +record_reference(First, Last, Module, Name, Positions) -> + Target = <<"#", (atom_text(Module))/binary, ":", (atom_text(Name))/binary, "{}">>, + reference_range(First, Last, Target, Positions). + +reference_range(First, Last, Target, Positions) -> + #{start => maps:get(erl_anno:location(First), Positions), + 'end' => maps:get(erl_anno:location(Last), Positions) + utf16_length(erl_anno:text(Last)), + target => Target}. + +otp_application(erlang) -> <<"erts">>; +otp_application(Module) -> + case code:which(Module) of + Beam when is_list(Beam) -> + Library = filename:split(code:lib_dir()), + Parts = filename:split(Beam), + case lists:prefix(Library, Parts) of + true -> + [Application, "ebin", _] = lists:nthtail(length(Library), Parts), + [Name | _] = string:split(Application, "-"), + bin(Name); + false -> none + end; + _ -> none + end. + +positions([], Line, Column, Offset, Acc) -> Acc#{{Line, Column} => Offset}; +positions([Character | Rest], Line, Column, Offset, Acc) -> + Next = Acc#{{Line, Column} => Offset}, + Units = case Character > 16#ffff of true -> 2; false -> 1 end, + case Character of + $\n -> positions(Rest, Line + 1, 1, Offset + Units, Next); + _ -> positions(Rest, Line, Column + 1, Offset + Units, Next) + end. + +utf16_length(Text) -> byte_size(unicode:characters_to_binary(Text, unicode, {utf16, big})) div 2. type_text(Type) -> [_, Body] = binary:split(pretty({attribute, 0, type, {doc_type, Type, []}}), <<"::">>), @@ -143,19 +288,19 @@ exporter_digest() -> {ok, Source} = file:read_file(escript:script_name()), binary:encode_hex(crypto:hash(sha256, Source), lowercase). -member_location(function, Name, Arity, Located, _) -> +member_location(function, Name, Arity, Located, _, Files) -> [{File, {function, Anno, Name, Arity, _}}] = [{F, Form} || {F, Form = {function, _, N, A, _}} <- Located, N =:= Name, A =:= Arity], - location(File, Anno); -member_location(_, _, _, _, [{File, {attribute, Anno, _, _}} | _]) -> - location(File, Anno). + location(source_file(File, Files), Anno); +member_location(_, _, _, _, [{File, {attribute, Anno, _, _}} | _], Files) -> + location(source_file(File, Files), Anno). %% EEP-48 line annotations omit filenames; -file forms retain include boundaries. -located_forms(Forms, Files) -> +located_forms(Forms) -> {Located, _} = lists:mapfoldl(fun (Form = {attribute, _, file, {Path, _}}, _) -> - File = source_file(Path, Files), + File = bin(Path), {{File, Form}, File}; (Form, File) -> {{File, Form}, File} end, undefined, Forms), @@ -174,7 +319,88 @@ declaration_text({attribute, _, opaque, {Name, _, Args}}) -> erl_pp:expr({atom, 0, Name}, [{encoding, unicode}]), $(, Parameters, <<").">>]); declaration_text(Form) -> pretty(Form). -pretty(Form) -> trim(unicode:characters_to_binary(erl_pp:form(Form, [{linewidth, 60}]))). +pretty(Form) -> + State = #{next => 0, names => #{}, atoms => sets:from_list(form_atoms(Form))}, + {Printable, #{names := Names}} = qualified_records(Form, State), + Text = format_form(Printable, Names, 60), + {ok, Tokens, _} = erl_scan:string(unicode:characters_to_list(Text), {1, 1}, [text]), + {ok, Parsed} = erl_parse:parse_form(Tokens), + require(normalized_form(Form) =:= normalized_form(Parsed), + [<<"native declaration formatter changed its syntax tree: ">>, Text]), + Text. + +%% erl_pp can append punctuation beyond linewidth. Reduce its hint when the +%% rendered declaration exceeds the cap; indivisible tokens remain visible +%% to the site's final display-width check instead of being truncated. +format_form(Form, Names, Width) -> + Printed = trim(unicode:characters_to_binary(erl_pp:form(Form, [{linewidth, Width}]))), + Text = restore_record_names(Printed, Names), + Longest = lists:max([length(unicode:characters_to_list(Line)) + || Line <- binary:split(Text, <<"\n">>, [global])]), + case Longest =< 60 orelse Width =:= 1 of + true -> Text; + false -> format_form(Form, Names, max(1, Width - (Longest - 60))) + end. + +normalized_form({attribute, Anno, Kind, Body}) when Kind =:= native_record; Kind =:= nominal -> + %% map_anno does not traverse these new attribute bodies. Their annotation + %% layout matches record/type; retain the actual kind after traversal. + Traversal = case Kind of native_record -> record; nominal -> type end, + {attribute, Zero, Traversal, CleanBody} = + erl_parse:map_anno(fun(_) -> 0 end, {attribute, Anno, Traversal, Body}), + {attribute, Zero, Kind, CleanBody}; +normalized_form(Form) -> erl_parse:map_anno(fun(_) -> 0 end, Form). + +%% OTP29 erl_pp handles local record types but loses a qualified record name. +%% Format those names through private, wider atom tokens, then restore only +%% their scanner tokens. Literal lookalikes cannot be rewritten. The parser +%% round trip above checks the public declaration before it leaves this VM. +qualified_records({type, Anno, record, + [{tuple, _, [{atom, _, Module}, {atom, Last, Name}]} | Fields]}, State0) -> + {Marker, State1} = record_marker(Module, Name, State0), + {Mapped, State} = qualified_records(Fields, State1), + {{type, Anno, record, [{atom, Last, Marker} | Mapped]}, State}; +qualified_records(Tuple, State0) when is_tuple(Tuple) -> + {List, State} = qualified_records(tuple_to_list(Tuple), State0), + {list_to_tuple(List), State}; +qualified_records(List, State) when is_list(List) -> + lists:mapfoldl(fun qualified_records/2, State, List); +qualified_records(Other, State) -> {Other, State}. + +record_marker(Module, Name, #{next := Next, names := Names, atoms := Used} = State) -> + Characters = "__libtmux_record_" ++ integer_to_list(Next) ++ "_" ++ + atom_to_list(Module) ++ ":" ++ atom_to_list(Name), + require(length(Characters) =< 255, "qualified record name exceeds formatter budget"), + Marker = list_to_atom(Characters), + case sets:is_element(Marker, Used) of + true -> record_marker(Module, Name, State#{next := Next + 1}); + false -> + Label = <<(atom_text(Module))/binary, ":", (atom_text(Name))/binary>>, + {Marker, State#{next := Next + 1, names := Names#{Marker => Label}}} + end. + +restore_record_names(Text, Names) when map_size(Names) =:= 0 -> Text; +restore_record_names(Text, Names) -> + Characters = unicode:characters_to_list(Text), + {ok, Tokens, _} = erl_scan:string(Characters, {1, 1}, [text]), + Positions = positions(Characters, 1, 1, 0, #{}), + Ranges = [{maps:get(erl_anno:location(Anno), Positions), + utf16_length(erl_anno:text(Anno)), maps:get(Name, Names)} + || {atom, Anno, Name} <- Tokens, maps:is_key(Name, Names)], + Encoded = unicode:characters_to_binary(Text, unicode, {utf16, big}), + Restored = lists:foldl(fun({Start, Length, Label}, Bytes) -> + PrefixBytes = Start * 2, + NameBytes = Length * 2, + <> = Bytes, + Replacement = unicode:characters_to_binary(Label, unicode, {utf16, big}), + <> + end, Encoded, lists:reverse(lists:sort(Ranges))), + unicode:characters_to_binary(Restored, {utf16, big}, utf8). + +form_atoms(Atom) when is_atom(Atom) -> [Atom]; +form_atoms(Tuple) when is_tuple(Tuple) -> form_atoms(tuple_to_list(Tuple)); +form_atoms(List) when is_list(List) -> lists:append([form_atoms(Item) || Item <- List]); +form_atoms(_) -> []. documentation(none) -> null; documentation(Doc) when is_map(Doc) -> @@ -192,21 +418,172 @@ metadata(Key, Meta) -> location(File, Anno) -> #{file => File, line => erl_anno:line(Anno)}. +%% Deterministic BEAMs omit paths and preprocessing options. Capture the +%% actual compiler context with an identity transform in a fresh build; +%% no project configuration or existing build directory is rewritten. +with_compilation(Exporter, Function) -> + Temporary = filename:join(case os:getenv("TMPDIR") of false -> "/tmp"; P -> P end, + "libtmux-erlang-export-" ++ integer_to_list(erlang:system_time(nanosecond))), + ok = file:make_dir(Temporary), + try + {ok, Sections} = escript:extract(Exporter, [compile_source]), + {source, Beam} = lists:keyfind(source, 1, Sections), + {ok, {Transform, _}} = beam_lib:chunks(Beam, []), + ok = file:write_file(filename:join(Temporary, atom_to_list(Transform) ++ ".beam"), Beam), + Build = filename:join(Temporary, "build"), + Flags = case os:getenv("ERL_AFLAGS") of false -> ""; Existing -> Existing end, + Options = [{parse_transform, Transform} | compile:env_compiler_options()], + Environment = [{"REBAR_BASE_DIR", Build}, + {"LIBTMUX_ERLANG_EXPORT_CONTEXT", Temporary}, + {"ERL_AFLAGS", Flags ++ " -pa " ++ lists:flatten(io_lib:format("~tp", [Temporary])) ++ + " -s " ++ atom_to_list(Transform) ++ " capture_compiler"}, + {"ERL_COMPILER_OPTIONS", lists:flatten(io_lib:format("~tp", [Options]))}], + _ = run("rebar3", ["compile"], Environment), + Function(Build, Temporary) + after + ok = file:del_dir_r(Temporary) + end. + +parse_transform(Forms, Options) -> + [Name] = [M || {attribute, _, module, M} <- Forms], + %% Trace signals may lag ordinary sends from a reused compiler worker. + %% Deliver its current file call before requesting the recorded entry. + Delivered = erlang:trace_delivered(self()), + receive {trace_delivered, _, Delivered} -> ok + after 1000 -> error(compiler_trace_not_delivered) + end, + Ref = make_ref(), + whereis(?MODULE) ! {source, self(), Ref}, + Source = receive {Ref, File} -> File + after 1000 -> error(compiler_source_entry_not_observed) + end, + true = filename:pathtype(Source) =:= absolute, + Preprocessing = preprocessing_context(Source, Options), + Output = context_file(os:getenv("LIBTMUX_ERLANG_EXPORT_CONTEXT"), Name), + ok = file:write_file(Output, term_to_binary({Source, Forms, Preprocessing})), + Forms. + +%% include_lib, environment expansion and relative includes belong to the +%% compiler VM. Recover paths there instead of replaying its ambient state +%% in the exporter. Keep failures as data; only documented modules need proof. +preprocessing_context(Source, Options) -> + try + Includes = [".", filename:dirname(Source) | [I || {i, I} <- Options]], + Macros = [{N, V} || {d, N, V} <- Options] ++ [{N, true} || {d, N} <- Options], + {ok, {Features, Reserved}} = erl_features:init_parse_state(Options, fun erl_scan:f_reserved_word/1), + EppOptions = [{includes, Includes}, {macros, Macros}, + {features, Features}, {reserved_word_fun, Reserved}, {location, {1, 1}}], + {ok, Original} = epp:parse_file(Source, + [{deterministic, lists:member(deterministic, Options)} | EppOptions]), + {ok, Located} = epp:parse_file(Source, [{deterministic, false} | EppOptions]), + Absolute = [case Form of + {attribute, Anno, file, {Path, Line}} -> + {attribute, Anno, file, {filename:absname(Path), Line}}; + _ -> Form + end || Form <- Located], + {ok, Original, Absolute} + catch + Class:Reason -> {error, {Class, Reason}} + end. + +%% Observe the compiler's actual file argument, not a basename reconstructed +%% from BEAM metadata. Tracing is confined to the temporary Rebar VM. +capture_compiler() -> + {module, compile} = code:ensure_loaded(compile), + Tracer = spawn(fun() -> compiler_entries(#{}, #{}) end), + true = register(?MODULE, Tracer), + erlang:trace_pattern({compile, file, 2}, true, [local]), + erlang:trace_pattern({compile, noenv_file, 2}, true, [local]), + erlang:trace(all, true, [call, set_on_spawn, {tracer, Tracer}]), + ok. + +compiler_entries(Sources, Pending) -> + receive + {trace, Pid, call, {compile, _, [Source, _]}} -> + case maps:take(Pid, Pending) of + {{From, Ref}, Rest} -> + From ! {Ref, Source}, compiler_entries(Sources#{Pid => Source}, Rest); + error -> compiler_entries(Sources#{Pid => Source}, Pending) + end; + {source, From, Ref} -> + case maps:find(From, Sources) of + {ok, Source} -> From ! {Ref, Source}, compiler_entries(Sources, Pending); + error -> compiler_entries(Sources, Pending#{From => {From, Ref}}) + end + end. + +context_file(Directory, Name) -> + Digest = binary:encode_hex(crypto:hash(sha256, atom_to_binary(Name)), lowercase), + filename:join(Directory, <>). + +source_forms(Name, Compiled, Files, Context) -> + Base = <<(atom_to_binary(Name))/binary, ".erl">>, + {Actual, Captured, Preprocessing} = binary_to_term(read(context_file(Context, Name))), + Source = source_file(Actual, Files), + require(source_tree(Captured) =:= source_tree(Compiled), + [Base, <<": compiler transform context differs from compiled forms">>]), + {Deterministic, Located} = case Preprocessing of + {ok, D, L} -> {D, L}; + _ -> fail([Base, <<": preprocessing context is unavailable">>]) + end, + require(not lists:any(fun + ({attribute, Anno, file, _}) -> erl_anno:generated(Anno); + (_) -> false + end, Located), [Base, <<": explicit source remapping cannot be verified">>]), + Expected = source_tree(Compiled), + require(source_tree(Deterministic) =:= Expected andalso source_tree(Located) =:= Expected, + [Base, <<": preprocessing context cannot reproduce compiled forms">>]), + {source_file(Source, Files), located_forms(Located)}. + +%% OTP consumes doc attributes before saving abstract code. File attributes +%% are the locations being recovered; every other form must still agree. +source_tree(Forms) -> + [normalized_form(F) || F <- Forms, source_form(F)]. + +source_form({attribute, _, Kind, _}) -> not lists:member(Kind, [file, doc, moduledoc]); +source_form(_) -> true. + source_file(Path, Files) -> Base = filename:basename(bin(Path)), - case [P || #{path := P} <- Files, filename:basename(P) =:= Base] of + Resolved = source_path(Path), + case [P || #{path := P} <- Files, Resolved =/= unsafe, + filename:basename(P) =:= Base, source_path(P) =:= Resolved] of [File] -> File; _ -> fail([Base, <<": source path is missing or ambiguous">>]) end. +%% Rebar's isolated build links src/include back to the source checkout. +%% Follow each link before processing '..', with a bounded symlink count. +source_path(Path) -> source_path(filename:split(filename:absname(bin(Path))), [], 40). + +source_path([], Parts, _) -> filename:join(Parts); +source_path([<<".">> | Rest], Parts, Left) -> source_path(Rest, Parts, Left); +source_path([<<"..">> | Rest], Parts, Left) when length(Parts) > 1 -> + source_path(Rest, lists:droplast(Parts), Left); +source_path([<<"..">> | Rest], Parts, Left) -> source_path(Rest, Parts, Left); +source_path([Part | Rest], Parts, Left) -> + Candidate = filename:join(Parts ++ [Part]), + case file:read_link_all(Candidate) of + {ok, Link} when Left > 0 -> + Prefix = case filename:pathtype(Link) of absolute -> []; relative -> Parts end, + source_path(filename:split(bin(Link)) ++ Rest, Prefix, Left - 1); + {error, einval} -> source_path(Rest, Parts ++ [Part], Left); + _ -> unsafe + end. + inputs() -> Names = binary:split(run("git", ["ls-files", "-z"]), <<0>>, [global]), - [#{path => Name, sha256 => binary:encode_hex(crypto:hash(sha256, read(Name)), lowercase)} + [#{path => Name, sha256 => binary:encode_hex(crypto:hash(sha256, input_bytes(Name)), lowercase)} || Name <- lists:sort(Names), Name =/= <<>>, input(Name)]. input(Name) -> lists:member(filename:extension(Name), [<<".erl">>, <<".hrl">>, <<".src">>]) orelse lists:member(filename:basename(Name), - [<<"rebar.config">>, <<"rebar.lock">>, <<".tool-versions">>]). + [<<"rebar.config">>, <<"rebar.config.script">>, <<"rebar.lock">>, <<".tool-versions">>]). + +input_bytes(Name) -> + require(file:read_link_all(Name) =:= {error, einval}, + [filename:basename(Name), <<": source input must be a regular file">>]), + read(Name). read(Name) -> {ok, Content} = file:read_file(Name), Content. clean() -> require(trim(run("git", ["status", "--porcelain", "--untracked-files=all"])) =:= <<>>, @@ -224,11 +601,14 @@ otp_version() -> trim(read(File)). run(Executable, Arguments) -> + run(Executable, Arguments, []). + +run(Executable, Arguments, Environment) -> case os:find_executable(Executable) of false -> fail([bin(Executable), <<" is required on PATH">>]); Path -> Port = open_port({spawn_executable, Path}, [binary, exit_status, use_stdio, - stderr_to_stdout, {args, Arguments}]), + stderr_to_stdout, {args, Arguments}, {env, Environment}]), collect(Port, [], Executable) end. diff --git a/packages/api-model/src/languages/erlang.ts b/packages/api-model/src/languages/erlang.ts index b6f65cb51..ad9a1bd78 100644 --- a/packages/api-model/src/languages/erlang.ts +++ b/packages/api-model/src/languages/erlang.ts @@ -1,8 +1,14 @@ import { parseMarkdownDocFull } from '../doc/markdown.ts' -import type { ApiModel, ApiSymbol, DocBlock, Modifier, Signature } from '../model.ts' +import type { ApiModel, ApiSymbol, DocBlock, Modifier, Signature, TypeReference } from '../model.ts' interface Source { file: string; line: number } -interface Spec { parameters: { name: string; type: string }[]; returns: string; text: string } +interface Spec { + parameters: { name: string; type: string; references: TypeReference[] }[] + returns: string + returns_references: TypeReference[] + text: string + references: TypeReference[] +} interface Member { name: string display_name: string @@ -15,6 +21,7 @@ interface Member { exported: boolean signatures: string[] declarations: string[] + declaration_references: TypeReference[][] specs: Spec[] source: Source } @@ -24,7 +31,7 @@ interface Module { doc: string | null source: Source members: Member[] - records: { name: string; display_name: string; declaration: string; source: Source }[] + records: { name: string; display_name: string; declaration: string; references: TypeReference[]; source: Source }[] } interface Artifact { schema: number @@ -37,7 +44,7 @@ interface Artifact { function assertArtifact(input: unknown, expectedRevision?: string): Artifact { const artifact = input as Artifact - if (artifact?.schema !== 1 || artifact.port !== 'erlang' || artifact.exporter?.version !== 2 || + if (artifact?.schema !== 1 || artifact.port !== 'erlang' || artifact.exporter?.version !== 3 || 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 ?? '') || @@ -82,6 +89,12 @@ function assertArtifact(input: unknown, expectedRevision?: string): Artifact { if (member.visibility === 'opaque' && member.declarations.some(opaqueBody)) { throw new Error('Erlang artifact exposes an opaque type body') } + if (!Array.isArray(member.declaration_references) || + member.declaration_references.length !== member.declarations.length || + member.visibility === 'opaque' && member.declaration_references.some((refs) => refs.length)) { + throw new Error('Erlang artifact lost declaration references or exposes an opaque body') + } + member.declarations.forEach((text, index) => assertReferences(text, member.declaration_references[index])) 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 || @@ -93,16 +106,51 @@ function assertArtifact(input: unknown, expectedRevision?: string): Artifact { typeof spec.text !== 'string' || !spec.text.trim()))) { throw new Error('Erlang artifact lost its native callable signature') } + for (const spec of member.specs) { + assertReferences(spec.text, spec.references) + assertReferences(spec.returns, spec.returns_references) + for (const parameter of spec.parameters) assertReferences(parameter.type, parameter.references) + } } 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) + assertReferences(record.declaration, record.references) } } return artifact } +function assertReferences(text: string, references: TypeReference[] | undefined): void { + if (!Array.isArray(references)) throw new Error('Erlang artifact lost its compiler references') + let offset = 0 + const boundary = (at: number) => !(at > 0 && at < text.length && + /[\uD800-\uDBFF]/.test(text[at - 1]!) && /[\uDC00-\uDFFF]/.test(text[at]!)) + for (const reference of references) { + if (!reference || !Number.isInteger(reference.start) || !Number.isInteger(reference.end) || + reference.start < offset || reference.end <= reference.start || reference.end > text.length || + !boundary(reference.start) || !boundary(reference.end) || + typeof reference.target !== 'string' || !/^(?:t:.+\/\d+|#.+\{\})$/.test(reference.target)) { + throw new Error('Erlang artifact has invalid compiler reference ranges') + } + if (reference.external) { + let url: URL + try { url = new URL(reference.external.href) } + catch { throw new Error('Erlang artifact has an invalid OTP reference destination') } + const target = /^t:([a-z][A-Za-z0-9_]*):(.+)\/(\d+)$/.exec(reference.target) + if (!target || reference.external.project !== 'Erlang/OTP' || + url.origin !== 'https://www.erlang.org' || url.username || url.password || url.search || + !/^\/doc\/apps\/[a-z][a-z0-9_]*\/[a-z][A-Za-z0-9_]*\.html$/.test(url.pathname) || + !url.pathname.endsWith(`/${target[1]}.html`) || + decodeURIComponent(url.hash.slice(1)) !== `t:${target[2]}/${target[3]}`) { + throw new Error('Erlang artifact has an invalid OTP reference destination') + } + } + offset = reference.end + } +} + /** A body delimiter inside a compiler-quoted atom is part of its name. */ function opaqueBody(text: string): boolean { let quoted = false @@ -133,7 +181,8 @@ export function extractErlang(input: unknown, expectedRevision?: string): ApiMod ...location, repo: artifact.source.repository, revision: artifact.source.revision, extractedRevision: artifact.source.revision, }) - const common = { package: artifact.package.name, product: 'core' as const } + const common = { package: artifact.package.name, + product: artifact.package.name === 'libtmux_erlang_workspace' ? 'workspace' as const : 'core' as const } const symbols: ApiSymbol[] = [] for (const module of artifact.modules) { const owner = module.display_name @@ -149,11 +198,14 @@ export function extractErlang(input: unknown, expectedRevision?: string): ApiMod ...(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, - })) + ? member.declarations.map((raw, index) => ({ raw, params: [], references: member.declaration_references[index] })) + : member.specs.map((spec) => { + const prefix = member.kind === 'callback' ? '' : `${member.signatures[0]}\n` + return { raw: prefix + spec.text, + references: spec.references.map((ref) => ({ ...ref, start: ref.start + prefix.length, end: ref.end + prefix.length })), + params: spec.parameters.map((param) => ({ name: param.name, type: param.type, typeReferences: param.references })), + returns: spec.returns, returnsReferences: spec.returns_references } + }) 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, @@ -165,7 +217,7 @@ export function extractErlang(input: unknown, expectedRevision?: string): ApiMod 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, + signatures: [{ raw: record.declaration, params: [], references: record.references }], ...common, apiScope: 'exported', source: source(record.source) }) } } diff --git a/packages/api-model/src/link.ts b/packages/api-model/src/link.ts index de0a8a197..9d2df46a9 100644 --- a/packages/api-model/src/link.ts +++ b/packages/api-model/src/link.ts @@ -1350,16 +1350,31 @@ export class SymbolIndex { return [{ text: ident, ...(builtin ? { link: { href: builtin, external: true } } : {}) }] } - /** - * Split a type annotation into linked and literal spans. - * - * A tokenizer, not a regex substitution: `list[Window]` must link `Window` - * and leave the brackets alone, `t.Literal["-"]` must not link the string, - * and `dict[str, Pane]` has two linkable names and a separator. Splitting on - * identifier boundaries and passing everything else through verbatim is what - * makes those all work without a grammar for type syntax. - */ + /** Consume exact compiler ranges; literal gaps never introduce a guessed type. */ + private erlangTypeSpans(annotation: string, context?: ApiSymbol, signature?: Signature): TypeSpan[] { + const candidates = (signature ? [signature] : context?.signatures ?? []).flatMap((entry) => [ + { text: entry.raw, references: entry.references }, + { text: entry.returns, references: entry.returnsReferences }, + ...entry.params.map((param) => ({ text: param.type, references: param.typeReferences })), + ]) + const match = candidates.find((entry) => entry.text === annotation && entry.references !== undefined) + if (!match) return [{ text: annotation }] + const out: TypeSpan[] = [] + let offset = 0 + for (const reference of match.references!) { + if (reference.start > offset) out.push({ text: annotation.slice(offset, reference.start), nonReference: true }) + const link = this.resolveErlang(reference.target, 'any', context) ?? + (reference.external ? { ...reference.external, external: true } : undefined) + out.push({ text: annotation.slice(reference.start, reference.end), ...(link ? { link } : {}) }) + offset = reference.end + } + if (offset < annotation.length) out.push({ text: annotation.slice(offset), nonReference: true }) + return out + } + + /** Link annotation names while preserving punctuation, variables and literal text. */ linkType(annotation: string, context?: ApiSymbol, signature?: Signature): TypeSpan[] { + if (this.lang === 'erlang') return this.erlangTypeSpans(annotation, context, signature) if (neverLinks(annotation)) return [{ text: annotation }] const out: TypeSpan[] = [] const rustPayload = this.lang === 'rs' && (context?.variant || (context?.parent && this.byDeclared.get(context.parent)?.variant)) diff --git a/packages/api-model/src/model.ts b/packages/api-model/src/model.ts index e9241d377..f2b48d484 100644 --- a/packages/api-model/src/model.ts +++ b/packages/api-model/src/model.ts @@ -80,11 +80,22 @@ export type Modifier = | 'unsafe' | 'annotation' +/** A compiler-resolved name in exact annotation text; offsets use UTF-16 code units. */ +export interface TypeReference { + start: number + end: number + /** Native symbol identity, including its namespace and arity where applicable. */ + target: string + /** A provider-validated canonical language-library destination. */ + external?: { href: string; project: string } +} + /** One parameter, as written. */ export interface Param { name: string /** Type annotation verbatim from the source, unresolved. */ type?: string + typeReferences?: TypeReference[] /** Default value verbatim, when one is written. */ default?: string /** The caller may omit the parameter without supplying a default. */ @@ -169,12 +180,15 @@ export interface Signature { extension?: string /** Native signature text when its grammar carries more than the shared fields. */ raw?: string + /** References into `raw`, supplied by the native compiler rather than inferred from spelling. */ + references?: TypeReference[] /** Native impl or trait header that owns this callable, without its body. */ enclosingDeclaration?: string /** Lexical bindings from that impl or trait, separate from callable generics. */ enclosingTypeParamNames?: string[] params: Param[] returns?: string + returnsReferences?: TypeReference[] returnsDoc?: string /** Type parameters / generics, as written: `T`, `T: Clone`, ``. */ typeParams?: string[] diff --git a/packages/api-model/src/prose-fields.ts b/packages/api-model/src/prose-fields.ts index 988a36a2e..b5958b166 100644 --- a/packages/api-model/src/prose-fields.ts +++ b/packages/api-model/src/prose-fields.ts @@ -61,6 +61,9 @@ export const STRUCTURAL_FIELDS: string[] = [ '.signatures[].receiver.*', '.signatures[].raises[].type', '.signatures[].params[].name', '.signatures[].params[].type', '.signatures[].params[].default', '.signatures[].params[].variadic', '.signatures[].params[].since', '.signatures[].params[].deprecated', + '.signatures[].references[].target', '.signatures[].references[].external.*', + '.signatures[].returnsReferences[].target', '.signatures[].returnsReferences[].external.*', + '.signatures[].params[].typeReferences[].target', '.signatures[].params[].typeReferences[].external.*', // A command's facts and a parameter's binding are written into prose by `commandFacts` and `parameterBindingText`. '.command.confirmImpact', '.command.defaultParameterSet', '.command.kind', '.command.outputTypes[]', '.command.inputTypes[].type', '.command.inputTypes[].description', '.command.relatedLinks[].*', diff --git a/packages/api-model/test/erlang.test.ts b/packages/api-model/test/erlang.test.ts index 82e5328cb..2e6877276 100644 --- a/packages/api-model/test/erlang.test.ts +++ b/packages/api-model/test/erlang.test.ts @@ -16,8 +16,13 @@ describe('Erlang compiler artifact adapter', () => { 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')) + for (const file of fixture.source.files) { + expect(file.sha256).toBe(createHash('sha256') + .update(readFileSync(new URL(`./fixtures/erlang-project/${file.path}`, 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([ + expect(symbol('probe:double/1').signatures.map((signature) => + signature.params.map(({ name, type }) => ({ name, type })))).toEqual([ [{ name: 'Number', type: 'integer()' }], [{ name: 'Number', type: 'float()' }], ]) expect(symbol('probe:double/1').modifiers).toContain('overload') @@ -70,4 +75,64 @@ describe('Erlang compiler artifact adapter', () => { 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/) }) + + it('links compiler type ranges by native arity and namespace without rewriting text', () => { + const result = model() + const index = new SymbolIndex(result.symbols, (symbol) => `/reference/${encodeURIComponent(symbol.id)}`, 'erlang') + const read = result.symbols.find((symbol) => symbol.id === 'probe:read/1')! + const handle = result.symbols.find((symbol) => symbol.id === 'probe:handle/0')! + expect(index.linkType(read.signatures[0]!.params[0]!.type!, read) + .filter((span) => span.link).map((span) => span.link?.symbol?.id)).toEqual(['t:probe:handle/0']) + const handleSpans = index.linkType(handle.signatures[0]!.raw!, handle, handle.signatures[0]) + expect(handleSpans.filter((span) => span.link).map((span) => span.link?.symbol?.id)).toEqual(['t:probe:handle/0']) + const links = result.symbols.find((symbol) => symbol.id === 'probe:links/1')! + const signature = links.signatures[0]! + const spans = index.linkType(signature.raw!, links, signature) + expect(spans.map((span) => span.text).join('')).toBe(signature.raw) + expect(spans.filter((span) => span.link?.symbol).map((span) => span.link!.symbol!.id)).toEqual([ + 't:probe:container/3', 't:probe:box/0', '#probe:row{}', + 't:probe:box/0', "t:probe:'馃Л'/0", "t:probe:'a::b'/0", 't:probe:box/1', + ]) + expect(spans.find((span) => span.link?.href.includes('/kernel/file.html'))?.text).toBe('file:filename_all') + expect(spans.find((span) => span.link?.symbol?.id === "t:probe:'馃Л'/0")?.text).toBe("'馃Л'") + expect(spans.find((span) => span.link?.symbol?.id === '#probe:row{}')?.text).toBe('#probe:row') + expect(spans.filter((span) => span.link).some((span) => span.text.includes('literal'))).toBe(false) + expect(spans.filter((span) => span.link).some((span) => span.text.includes('__libtmux_record'))).toBe(false) + const unresolved = result.symbols.find((symbol) => symbol.id === 't:probe:unresolved/0')! + expect(index.linkType(unresolved.signatures[0]!.raw!, unresolved) + .find((span) => span.text === 'file:no_such_type')?.link).toBeUndefined() + }) + + it('retains the workspace application product boundary', () => { + const workspace = structuredClone(fixture) + workspace.package.name = 'libtmux_erlang_workspace' + expect(extractErlang(workspace).symbols.every((symbol) => symbol.product === 'workspace' && + symbol.package === 'libtmux_erlang_workspace')).toBe(true) + expect(model().symbols.every((symbol) => symbol.product === 'core')).toBe(true) + }) + + it('rejects malformed, overlapping, surrogate-splitting and unsafe external reference ranges', () => { + const changed = (mutate: (input: typeof fixture) => void) => { + const input = structuredClone(fixture) + mutate(input) + return () => extractErlang(input) + } + const read = (input: typeof fixture) => input.modules[0].members.find((member: { name: string }) => member.name === 'read') + expect(changed((input) => { delete read(input).specs[0].parameters[0].references })).toThrow(/references/) + expect(changed((input) => { read(input).specs[0].references[1].start = 0 })).toThrow(/ranges/) + expect(changed((input) => { read(input).specs[0].parameters[0].references[0].end = 999 })).toThrow(/ranges/) + expect(changed((input) => { + const spec = input.modules[0].members.find((member: { name: string }) => member.name === 'links').specs[0] + const at = spec.parameters[0].type.indexOf('馃Л') + expect(at).toBeGreaterThan(0) + spec.parameters[0].references = [{ start: at + 1, end: at + 2, target: "t:probe:'馃Л'/0" }] + })).toThrow(/ranges/) + expect(changed((input) => { + read(input).specs[0].parameters[0].references[0].external = { href: 'javascript:alert(1)', project: 'Erlang/OTP' } + })).toThrow(/destination/) + expect(changed((input) => { + input.modules[0].members.find((member: { name: string; kind: string }) => member.name === 'handle' && member.kind === 'type') + .declaration_references[0] = [{ start: 8, end: 14, target: 't:probe:private/0' }] + })).toThrow(/opaque/) + }) }) diff --git a/packages/api-model/test/export-erlang.outer.test.ts b/packages/api-model/test/export-erlang.outer.test.ts index f70fe6c6e..65dd58df9 100644 --- a/packages/api-model/test/export-erlang.outer.test.ts +++ b/packages/api-model/test/export-erlang.outer.test.ts @@ -1,6 +1,6 @@ import { execFileSync, spawnSync } from 'node:child_process' import { createHash } from 'node:crypto' -import { cpSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs' +import { cpSync, mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs' import { tmpdir } from 'node:os' import { join, relative } from 'node:path' import { describe, expect, it } from 'vitest' @@ -27,8 +27,8 @@ function checkout() { return { directory, git, revision: git('rev-parse', 'HEAD') } } -const exportFrom = (directory: string, output = join(directory, '_build/api.json')) => - spawnSync('escript', [script, directory, 'probe', output], { encoding: 'utf8', env }) +const exportFrom = (directory: string, output = join(directory, '_build/api.json'), environment = env) => + spawnSync('escript', [script, directory, 'probe', output], { encoding: 'utf8', env: environment }) // These cases compile a real OTP project; they belong outside the medium loop. describe.skipIf(!available)('Erlang compiler export', { timeout: 30_000 }, () => { @@ -45,14 +45,42 @@ describe.skipIf(!available)('Erlang compiler export', { timeout: 30_000 }, () => expect(module.name).toBe('probe') expect(module.doc).toContain('`m:probe` and `read/1`') const member = (kind: string, name: string) => module.members.find((m: { kind: string; name: string }) => m.kind === kind && m.name === name) + const parameter = member('function', 'read').specs[0].parameters[0] + expect(parameter.references).toEqual([ + { start: 0, end: 6, target: 't:probe:handle/0' }, + ]) + expect(member('type', 'handle').declaration_references).toEqual([[]]) expect(member('function', 'hidden')).toBeUndefined() + expect(member('function', 'wide').specs[0].text.split('\n') + .every((line: string) => Array.from(line).length <= 60)).toBe(true) 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.objectContaining({ parameters: [expect.objectContaining({ name: 'Number', type: 'integer()' })], returns: 'integer()' }), + expect.objectContaining({ parameters: [expect.objectContaining({ name: 'Number', type: 'float()' })], returns: 'float()' }), + ]) + const linked = member('function', 'links').specs[0] + const parameterTargets = linked.parameters[0].references.map((ref: { target: string }) => ref.target) + expect(parameterTargets).toEqual([ + 't:probe:container/3', 't:probe:box/0', '#probe:row{}', + 't:probe:box/0', "t:probe:'馃Л'/0", + ]) + const returned = linked.returns_references + expect(returned.map((ref: { target: string }) => ref.target)).toEqual([ + "t:probe:'a::b'/0", 't:probe:box/1', 't:erlang:term/0', 't:file:filename_all/0', ]) + expect(returned.at(-1).external).toEqual({ + href: 'https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0', + project: 'Erlang/OTP', + }) + expect(member('type', 'unresolved').declaration_references[0]).toEqual([ + expect.objectContaining({ target: 't:file:no_such_type/0' }), + ]) + expect(member('type', 'unresolved').declaration_references[0][0].external).toBeUndefined() + for (const ref of returned) { + expect(linked.returns.slice(ref.start, ref.end)).not.toContain('literal') + } 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') @@ -89,4 +117,134 @@ describe.skipIf(!available)('Erlang compiler export', { timeout: 30_000 }, () => expect(spawnSync('test', ['-e', join(directory, '_build/api.json')]).status).toBe(1) } finally { rmSync(directory, { recursive: true, force: true }) } }) + + it('rejects an external public header even when its basename matches a tracked header', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-header-')) + try { + const header = join(outside, 'public_types.hrl') + writeFileSync(header, '-type outsourced() :: binary().\n') + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-module(probe).', + `-module(probe).\n-export_type([outsourced/0]).\n-include("${header}").`)) + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Include external type') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('public_types.hrl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('captures compiler macros when identical headers have different source provenance', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-macro-')) + try { + const header = join(outside, 'public_types.hrl') + cpSync(join(directory, 'include/public_types.hrl'), header) + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-include("public_types.hrl").', + `-ifdef(USE_EXTERNAL).\n-include("${header}").\n-else.\n-include("public_types.hrl").\n-endif.`)) + const config = join(directory, 'rebar.config') + writeFileSync(config, readFileSync(config, 'utf8').replace('deterministic,', + "deterministic, {d, 'USE_EXTERNAL'},")) + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Select identical external header') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('public_types.hrl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('rejects an external header that remaps itself to a tracked source', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-remap-')) + try { + const header = join(outside, 'public_types.hrl') + writeFileSync(header, '-file("include/public_types.hrl", 1).\n-type outsourced() :: binary().\n') + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-module(probe).', + `-module(probe).\n-export_type([outsourced/0]).\n-include("${header}").`)) + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qam', 'Remap external header') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('explicit source remapping cannot be verified') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('rejects a tracked source symlink instead of citing its target bytes', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-link-')) + try { + const header = join(outside, 'public_types.hrl') + const tracked = join(directory, 'include/public_types.hrl') + cpSync(tracked, header) + rmSync(tracked) + symlinkSync(header, tracked) + git('add', '.') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'Link external source') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('source input must be a regular file') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('binds the primary source to the compiler entry rather than a same-named tracked file', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-entry-')) + try { + const external = join(outside, 'probe.erl') + cpSync(join(directory, 'src/probe.erl'), external) + mkdirSync(join(directory, 'unused')) + git('mv', 'src/probe.erl', 'unused/probe.erl') + symlinkSync(external, join(directory, 'src/probe.erl')) + const ignore = join(directory, '.gitignore') + writeFileSync(ignore, `${readFileSync(ignore, 'utf8')}\nsrc/probe.erl\n`) + git('add', '.') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'Compile ignored external source') + const result = exportFrom(directory) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('probe.erl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) + + it('resolves include_lib in the compiler VM instead of the exporter library path', () => { + const { directory, git } = checkout() + const outside = mkdtempSync(join(tmpdir(), 'export-erlang-library-')) + try { + const tracked = join(directory, 'vendor/aliaslib') + const external = join(outside, 'aliaslib') + for (const library of [tracked, external]) { + mkdirSync(join(library, 'include'), { recursive: true }) + mkdirSync(join(library, 'ebin')) + writeFileSync(join(library, 'include/public_types.hrl'), '-type outsourced() :: binary().\n') + writeFileSync(join(library, 'ebin/aliaslib.app'), '{application, aliaslib, [{vsn, "0.1.0"}, {modules, []}]}.\n') + } + writeFileSync(join(directory, 'rebar.config.script'), + `true = code:add_patha(${JSON.stringify(join(external, 'ebin'))}), CONFIG.\n`) + const source = join(directory, 'src/probe.erl') + writeFileSync(source, readFileSync(source, 'utf8').replace('-module(probe).', + '-module(probe).\n-export_type([outsourced/0]).\n-include_lib("aliaslib/include/public_types.hrl").')) + git('add', '.') + git('-c', 'user.name=Fixture', '-c', 'user.email=fixture@example.invalid', 'commit', '-qm', 'Select compiler library path') + const result = exportFrom(directory, undefined, { ...env, ERL_LIBS: join(directory, 'vendor') }) + expect(result.status).not.toBe(0) + expect(result.stderr).toContain('public_types.hrl: source path is missing or ambiguous') + } finally { + rmSync(directory, { recursive: true, force: true }) + rmSync(outside, { recursive: true, force: true }) + } + }) }) diff --git a/packages/api-model/test/fixtures/erlang-native.json b/packages/api-model/test/fixtures/erlang-native.json index 20728342d..d2f185485 100644 --- a/packages/api-model/test/fixtures/erlang-native.json +++ b/packages/api-model/test/fixtures/erlang-native.json @@ -1 +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"}} +{"port":"erlang","modules":[{"name":"probe","records":[{"name":"row","source":{"line":18,"file":"src/probe.erl"},"display_name":"row","declaration":"-record #row{id :: id()}.","references":[{"start":19,"end":21,"target":"t:probe:id/0"}]}],"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()}.","references":[{"start":18,"end":21,"target":"t:probe:row/0"},{"start":33,"end":39,"target":"t:probe:handle/0"}],"parameters":[{"name":"Argument1","type":"row()","references":[{"start":0,"end":3,"target":"t:probe:row/0"}]}],"returns":"{ok, handle()}","returns_references":[{"start":5,"end":11,"target":"t:probe:handle/0"}]}],"source":{"line":40,"file":"src/probe.erl"},"display_name":"prepare","kind":"callback","signatures":["prepare/1"],"since":null,"visibility":"public","declarations":["-callback prepare(row()) -> {ok, handle()}."],"declaration_references":[[{"start":18,"end":21,"target":"t:probe:row/0"},{"start":33,"end":39,"target":"t:probe:handle/0"}]]},{"arity":1,"name":"double","deprecated":"Use a calculator.","doc":"Double an integer or float.","exported":true,"specs":[{"text":"-spec double(integer()) -> integer().","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":13,"end":20,"target":"t:erlang:integer/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":27,"end":34,"target":"t:erlang:integer/0"}],"parameters":[{"name":"Number","type":"integer()","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":0,"end":7,"target":"t:erlang:integer/0"}]}],"returns":"integer()","returns_references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":0,"end":7,"target":"t:erlang:integer/0"}]},{"text":"-spec double(float()) -> float().","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":13,"end":18,"target":"t:erlang:float/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":25,"end":30,"target":"t:erlang:float/0"}],"parameters":[{"name":"Number","type":"float()","references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":0,"end":5,"target":"t:erlang:float/0"}]}],"returns":"float()","returns_references":[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":0,"end":5,"target":"t:erlang:float/0"}]}],"source":{"line":45,"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()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":13,"end":20,"target":"t:erlang:integer/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":27,"end":34,"target":"t:erlang:integer/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":51,"end":56,"target":"t:erlang:float/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:float/0","project":"Erlang/OTP"},"start":63,"end":68,"target":"t:erlang:float/0"}]]},{"arity":0,"name":"handle","deprecated":null,"doc":"Construct a handle; the type and function share a name.","exported":true,"specs":[{"text":"-spec handle() -> handle().","references":[{"start":18,"end":24,"target":"t:probe:handle/0"}],"parameters":[],"returns":"handle()","returns_references":[{"start":0,"end":6,"target":"t:probe:handle/0"}]}],"source":{"line":53,"file":"src/probe.erl"},"display_name":"handle","kind":"function","signatures":["handle()"],"since":null,"visibility":"public","declarations":["-spec handle() -> handle()."],"declaration_references":[[{"start":18,"end":24,"target":"t:probe:handle/0"}]]},{"arity":1,"name":"links","deprecated":null,"doc":"Compiler references distinguish arities, native records and literal names.","exported":true,"specs":[{"text":"-spec links(probe:container(fun((box(),\n #probe:row{}) ->\n box()),\n #{key := 'a,b'},\n '馃Л'())) ->\n {'literal:box()', '馃Л',\n '__libtmux_record_0_probe:row',\n <<_:8>>,\n 'a::b'(),\n box(term()),\n file:filename_all()}.","references":[{"start":12,"end":27,"target":"t:probe:container/3"},{"start":33,"end":36,"target":"t:probe:box/0"},{"start":73,"end":83,"target":"#probe:row{}"},{"start":126,"end":129,"target":"t:probe:box/0"},{"start":207,"end":211,"target":"t:probe:'馃Л'/0"},{"start":347,"end":353,"target":"t:probe:'a::b'/0"},{"start":373,"end":376,"target":"t:probe:box/1"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":377,"end":381,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0","project":"Erlang/OTP"},"start":402,"end":419,"target":"t:file:filename_all/0"}],"parameters":[{"name":"_Input","type":"probe:container(fun((box(),\n #probe:row{}) ->\n box()),\n #{key := 'a,b'},\n '馃Л'())","references":[{"start":0,"end":15,"target":"t:probe:container/3"},{"start":21,"end":24,"target":"t:probe:box/0"},{"start":59,"end":69,"target":"#probe:row{}"},{"start":110,"end":113,"target":"t:probe:box/0"},{"start":187,"end":191,"target":"t:probe:'馃Л'/0"}]}],"returns":"{'literal:box()', '馃Л',\n '__libtmux_record_0_probe:row',\n <<_:8>>,\n 'a::b'(),\n box(term()),\n file:filename_all()}","returns_references":[{"start":98,"end":104,"target":"t:probe:'a::b'/0"},{"start":119,"end":122,"target":"t:probe:box/1"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":123,"end":127,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0","project":"Erlang/OTP"},"start":143,"end":160,"target":"t:file:filename_all/0"}]}],"source":{"line":60,"file":"src/probe.erl"},"display_name":"links","kind":"function","signatures":["links(Input)"],"since":null,"visibility":"public","declarations":["-spec links(probe:container(fun((box(),\n #probe:row{}) ->\n box()),\n #{key := 'a,b'},\n '馃Л'())) ->\n {'literal:box()', '馃Л',\n '__libtmux_record_0_probe:row',\n <<_:8>>,\n 'a::b'(),\n box(term()),\n file:filename_all()}."],"declaration_references":[[{"start":12,"end":27,"target":"t:probe:container/3"},{"start":33,"end":36,"target":"t:probe:box/0"},{"start":73,"end":83,"target":"#probe:row{}"},{"start":126,"end":129,"target":"t:probe:box/0"},{"start":207,"end":211,"target":"t:probe:'馃Л'/0"},{"start":347,"end":353,"target":"t:probe:'a::b'/0"},{"start":373,"end":376,"target":"t:probe:box/1"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":377,"end":381,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0","project":"Erlang/OTP"},"start":402,"end":419,"target":"t:file:filename_all/0"}]]},{"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()}.","references":[{"start":11,"end":17,"target":"t:probe:handle/0"},{"start":29,"end":42,"target":"t:probe:internal_mode/0"}],"parameters":[{"name":"_Handle","type":"handle()","references":[{"start":0,"end":6,"target":"t:probe:handle/0"}]}],"returns":"{ok, internal_mode()}","returns_references":[{"start":5,"end":18,"target":"t:probe:internal_mode/0"}]}],"source":{"line":49,"file":"src/probe.erl"},"display_name":"read","kind":"function","signatures":["read(Handle)"],"since":null,"visibility":"public","declarations":["-spec read(handle()) -> {ok, internal_mode()}."],"declaration_references":[[{"start":11,"end":17,"target":"t:probe:handle/0"},{"start":29,"end":42,"target":"t:probe:internal_mode/0"}]]},{"arity":2,"name":"wide","deprecated":null,"doc":"Keep native typespec punctuation within the API column limit.","exported":true,"specs":[{"text":"-spec wide(probe:container(term(), term(), term()),\n box()) ->\n box().","references":[{"start":11,"end":26,"target":"t:probe:container/3"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":27,"end":31,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":35,"end":39,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":43,"end":47,"target":"t:erlang:term/0"},{"start":63,"end":66,"target":"t:probe:box/0"},{"start":87,"end":90,"target":"t:probe:box/0"}],"parameters":[{"name":"_Input","type":"probe:container(term(), term(), term())","references":[{"start":0,"end":15,"target":"t:probe:container/3"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":16,"end":20,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":24,"end":28,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":32,"end":36,"target":"t:erlang:term/0"}]},{"name":"Value","type":"box()","references":[{"start":0,"end":3,"target":"t:probe:box/0"}]}],"returns":"box()","returns_references":[{"start":0,"end":3,"target":"t:probe:box/0"}]}],"source":{"line":64,"file":"src/probe.erl"},"display_name":"wide","kind":"function","signatures":["wide(Input, Value)"],"since":null,"visibility":"public","declarations":["-spec wide(probe:container(term(), term(), term()),\n box()) ->\n box()."],"declaration_references":[[{"start":11,"end":26,"target":"t:probe:container/3"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":27,"end":31,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":35,"end":39,"target":"t:erlang:term/0"},{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:term/0","project":"Erlang/OTP"},"start":43,"end":47,"target":"t:erlang:term/0"},{"start":63,"end":66,"target":"t:probe:box/0"},{"start":87,"end":90,"target":"t:probe:box/0"}]]},{"arity":0,"name":"a::b","deprecated":null,"doc":"A quoted opaque type whose name includes a delimiter.","exported":true,"specs":[],"source":{"line":28,"file":"src/probe.erl"},"display_name":"'a::b'","kind":"type","signatures":["'a::b'()"],"since":null,"visibility":"opaque","declarations":["-opaque 'a::b'()."],"declaration_references":[[]]},{"arity":0,"name":"box","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":33,"file":"src/probe.erl"},"display_name":"box","kind":"type","signatures":["box()"],"since":null,"visibility":"public","declarations":["-type box() :: atom()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:atom/0","project":"Erlang/OTP"},"start":15,"end":19,"target":"t:erlang:atom/0"}]]},{"arity":1,"name":"box","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":34,"file":"src/probe.erl"},"display_name":"box","kind":"type","signatures":["box(T)"],"since":null,"visibility":"public","declarations":["-type box(T) :: [T]."],"declaration_references":[[]]},{"arity":3,"name":"container","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":35,"file":"src/probe.erl"},"display_name":"container","kind":"type","signatures":["container(A, B, C)"],"since":null,"visibility":"public","declarations":["-type container(A, B, C) :: {A, B, C}."],"declaration_references":[[]]},{"arity":0,"name":"handle","deprecated":null,"doc":"An opaque handle; its representation stays private.","exported":true,"specs":[],"source":{"line":22,"file":"src/probe.erl"},"display_name":"handle","kind":"type","signatures":["handle()"],"since":null,"visibility":"opaque","declarations":["-opaque handle()."],"declaration_references":[[]]},{"arity":0,"name":"id","deprecated":null,"doc":"A nominal identifier.","exported":true,"specs":[],"source":{"line":20,"file":"src/probe.erl"},"display_name":"id","kind":"type","signatures":["id()"],"since":null,"visibility":"nominal","declarations":["-nominal id() :: binary()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:binary/0","project":"Erlang/OTP"},"start":17,"end":23,"target":"t:erlang:binary/0"}]]},{"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()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:non_neg_integer/0","project":"Erlang/OTP"},"start":23,"end":38,"target":"t:erlang:non_neg_integer/0"}]]},{"arity":0,"name":"internal_mode","deprecated":null,"doc":"A supporting output mode.","exported":false,"specs":[],"source":{"line":30,"file":"src/probe.erl"},"display_name":"internal_mode","kind":"type","signatures":["internal_mode()"],"since":null,"visibility":"public","declarations":["-type internal_mode() :: ready | stopped."],"declaration_references":[[]]},{"arity":1,"name":"odd-name","deprecated":null,"doc":"A handle with a quoted type name.","exported":true,"specs":[],"source":{"line":24,"file":"src/probe.erl"},"display_name":"'odd-name'","kind":"type","signatures":["'odd-name'(T)"],"since":null,"visibility":"opaque","declarations":["-opaque 'odd-name'(T)."],"declaration_references":[[]]},{"arity":0,"name":"row","deprecated":null,"doc":"One public row.","exported":true,"specs":[],"source":{"line":32,"file":"src/probe.erl"},"display_name":"row","kind":"type","signatures":["row()"],"since":null,"visibility":"public","declarations":["-type row() :: #row{}."],"declaration_references":[[{"start":15,"end":19,"target":"#probe:row{}"}]]},{"arity":0,"name":"unresolved","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":37,"file":"src/probe.erl"},"display_name":"unresolved","kind":"type","signatures":["unresolved()"],"since":null,"visibility":"public","declarations":["-type unresolved() :: file:no_such_type()."],"declaration_references":[[{"start":22,"end":39,"target":"t:file:no_such_type/0"}]]},{"arity":1,"name":"位-handle","deprecated":null,"doc":"A handle with a Unicode name.","exported":true,"specs":[],"source":{"line":26,"file":"src/probe.erl"},"display_name":"'位-handle'","kind":"type","signatures":["'\\x{3BB}-handle'(T)"],"since":null,"visibility":"opaque","declarations":["-opaque '位-handle'(T)."],"declaration_references":[[]]},{"arity":0,"name":"馃Л","deprecated":null,"doc":null,"exported":true,"specs":[],"source":{"line":36,"file":"src/probe.erl"},"display_name":"'馃Л'","kind":"type","signatures":["'\\x{1F9ED}'()"],"since":null,"visibility":"public","declarations":["-type '馃Л'() :: integer()."],"declaration_references":[[{"external":{"href":"https://www.erlang.org/doc/apps/erts/erlang.html#t:integer/0","project":"Erlang/OTP"},"start":16,"end":23,"target":"t:erlang:integer/0"}]]}]}],"source":{"repository":"libtmux/probe","revision":"b808994828b801b465408b02e0b35a8893c4e1a5","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":"c4c95aa75344f69eeee799ffff9873990ed22cae86d3620e6bfaf37914fc45c4"}]},"schema":1,"exporter":{"name":"Erlang EEP-48 and abstract code","version":3,"otp":"29.1.2","columns":60,"source_sha256":"2fc491ad480e74fded943bf072d5bfd452116a9dfc6dc7062860727fe487f1ab"},"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 3a6479f4f..ecb266a03 100644 --- a/packages/api-model/test/fixtures/erlang-project/src/probe.erl +++ b/packages/api-model/test/fixtures/erlang-project/src/probe.erl @@ -7,9 +7,12 @@ Captured values with `m:probe` and `read/1` references. 4 ``` """. --export([double/1, hidden/0, read/1, handle/0]). +-export([double/1, hidden/0, read/1, handle/0, links/1, wide/2]). -export_type([handle/0, id/0, row/0, included_id/0, 'odd-name'/1, '位-handle'/1, 'a::b'/0]). +-export_type([box/0, box/1, container/3, '馃Л'/0]). +-export_type([unresolved/0]). -include("public_types.hrl"). +-include_lib("kernel/include/file.hrl"). -export_record([row]). -record #row{id :: id()}. @@ -27,6 +30,11 @@ Captured values with `m:probe` and `read/1` references. -type internal_mode() :: ready | stopped. -doc "One public row.". -type row() :: #row{}. +-type box() :: atom(). +-type box(T) :: [T]. +-type container(A, B, C) :: {A, B, C}. +-type '馃Л'() :: integer(). +-type unresolved() :: file:no_such_type(). -doc "Prepare one row.". -callback prepare(row()) -> {ok, handle()}. @@ -44,5 +52,16 @@ read(_Handle) -> {ok, ready}. -spec handle() -> handle(). handle() -> #{private_token => make_ref()}. +-doc "Compiler references distinguish arities, native records and literal names.". +-spec links(probe:container(fun((box(), #probe:row{}) -> box()), + #{key := 'a,b'}, '馃Л'())) -> + {'literal:box()', '馃Л', '__libtmux_record_0_probe:row', + <<_:8>>, 'a::b'(), box(term()), file:filename_all()}. +links(_Input) -> error(not_called). + +-doc "Keep native typespec punctuation within the API column limit.". +-spec wide(probe:container(term(), term(), term()), box()) -> box(). +wide(_Input, Value) -> Value. + -doc false. hidden() -> secret. diff --git a/site/src/lib/api-sections.ts b/site/src/lib/api-sections.ts index 982fd64ee..c997afc04 100644 --- a/site/src/lib/api-sections.ts +++ b/site/src/lib/api-sections.ts @@ -2,7 +2,7 @@ import { createHash } from 'node:crypto' import { commandFacts, memberTier, moduleOf, parameterBindingFacts, parameterBindingText, qualifiedNameOf, typeParametersOf, type ApiModelBase, type ApiSymbol, type MemberSignals, type Param, type Signature, type SymbolIndex } from '@libtmux/api-model' import { apiGlossaryHref } from './api-glossary' import { relatedLabels } from './api-labels' -import { csharpParameters, supportsCSharpSignatures, supportsElixirSignatures, supportsGoSignatures, supportsJavaSignatures, supportsLuaSignatures, supportsRubySignatures, supportsRustSignatures, supportsTypeScriptSignatures, swiftBaseName } from './code-layout' +import { csharpParameters, supportsCSharpSignatures, supportsElixirSignatures, supportsErlangSignatures, supportsGoSignatures, supportsJavaSignatures, supportsLuaSignatures, supportsRubySignatures, supportsRustSignatures, supportsTypeScriptSignatures, swiftBaseName } from './code-layout' export interface ApiSection { id: string @@ -228,7 +228,7 @@ export function aliasDeclaration(symbol: ApiSymbol, language?: string): { name: /** Keep native declaration syntax consistent in HTML and copied Markdown. */ export function usesNativeSignatures(symbol: ApiSymbol, port?: string): boolean { - return (port === 'rs' && Boolean(symbol.variant)) || supportsRustSignatures(symbol, port) || supportsTypeScriptSignatures(symbol, port) || supportsGoSignatures(symbol, port) || supportsJavaSignatures(symbol, port) || supportsCSharpSignatures(symbol, port) || supportsRubySignatures(symbol, port) || supportsLuaSignatures(symbol, port) || supportsElixirSignatures(symbol, port) || ['kotlin', 'scala', 'fsharp', 'c', 'powershell', 'julia'].includes(port ?? '') || + return (port === 'rs' && Boolean(symbol.variant)) || supportsRustSignatures(symbol, port) || supportsTypeScriptSignatures(symbol, port) || supportsGoSignatures(symbol, port) || supportsJavaSignatures(symbol, port) || supportsCSharpSignatures(symbol, port) || supportsRubySignatures(symbol, port) || supportsLuaSignatures(symbol, port) || supportsElixirSignatures(symbol, port) || supportsErlangSignatures(symbol, port) || ['kotlin', 'scala', 'fsharp', 'c', 'powershell', 'julia'].includes(port ?? '') || (port === 'cxx' && symbol.signatures.length > 0 && symbol.signatures.every((signature) => Boolean(signature.raw))) } diff --git a/site/src/lib/code-layout.ts b/site/src/lib/code-layout.ts index 7abe54eb8..ae19f6227 100644 --- a/site/src/lib/code-layout.ts +++ b/site/src/lib/code-layout.ts @@ -258,6 +258,12 @@ export function supportsElixirSignatures(symbol: ApiSymbol, language?: string): symbol.signatures.length > 0 && symbol.signatures.every((signature) => Boolean(signature.raw?.trim())) } +/** Erlang declarations already carry compiler formatting and resolved reference ranges. */ +export function supportsErlangSignatures(symbol: ApiSymbol, language?: string): boolean { + return language === 'erlang' && ['function', 'typealias', 'struct'].includes(symbol.kind) && + symbol.signatures.length > 0 && symbol.signatures.every((signature) => Boolean(signature.raw?.trim())) +} + export function supportsLuaSignatures(symbol: ApiSymbol, language?: string): boolean { return language === 'lua' && ['method', 'function'].includes(symbol.kind) && symbol.signatures.length > 0 && symbol.signatures.every((signature) => Boolean(signature.raw?.trim())) @@ -292,6 +298,13 @@ export function supportsCSignatures(symbol: ApiSymbol, language?: string): boole /** Prepare one layout per overload for both HTML and the Markdown twin. */ export async function apiSignatureLayouts(symbol: ApiSymbol, language?: string): Promise> { + if (supportsErlangSignatures(symbol, language)) { + return new Map(await Promise.all(symbol.signatures.map(async (signature) => { + const text = signature.raw! + return [signature, { text, limit: CODE_COLUMNS.api, + failures: await codeWidthFailures(text, 'api') }] as const + }))) + } if (language === 'rs' && ['method', 'function'].includes(symbol.kind) && symbol.signatures.length && !supportsRustSignatures(symbol, language)) { throw new Error(`Unavailable native Rust callable header: ${symbol.id}`) } diff --git a/site/test/native-signature.test.ts b/site/test/native-signature.test.ts index cc6cdc15a..9bf37d5e3 100644 --- a/site/test/native-signature.test.ts +++ b/site/test/native-signature.test.ts @@ -7,7 +7,7 @@ import { runInNewContext } from 'node:vm' import { describe, expect, it } from 'vitest' import { experimental_AstroContainer } from 'astro/container' import { Window, type Element, type HTMLElement } from 'happy-dom' -import { parameterId, parentInventory, SymbolIndex, type ApiModel, type ApiSymbol, type Signature } from '@libtmux/api-model' +import { extractErlang, parameterId, parentInventory, SymbolIndex, type ApiModel, type ApiSymbol, type Signature } from '@libtmux/api-model' import { apiEntryFields, nativeSignatureText, usesNativeSignatures } from '../src/lib/api-sections' import { API_MODEL_PORTS } from '../src/lib/ports' import { extractSourceWithSpec } from '../../packages/api-model/src/languages/spec' @@ -58,6 +58,45 @@ function displayedSignature(element: Element): string { return copy.textContent ?? '' } +it('renders Erlang compiler references with exact native declarations and Markdown', async () => { + const artifact = JSON.parse(readFileSync(new URL('../../packages/api-model/test/fixtures/erlang-native.json', import.meta.url), 'utf8')) + const model = extractErlang(artifact) + const href = (symbol: ApiSymbol) => `/reference/${encodeURIComponent(symbol.id)}/` + const index = new SymbolIndex(model.symbols, href, 'erlang') + const component = await (componentPromise ??= signatureComponent()) + const container = await experimental_AstroContainer.create() + const win = new Window() + try { + for (const id of ['probe:read/1', 'probe:links/1', '#probe:row{}', 't:probe:handle/0', 'c:probe:prepare/1']) { + const symbol = model.symbols.find((entry) => entry.id === id)! + const sig = symbol.signatures[0]! + expect(usesNativeSignatures(symbol, 'erlang')).toBe(true) + const signatureLayouts = await apiSignatureLayouts(symbol, 'erlang') + expect(signatureLayouts.get(sig)?.failures).toEqual([]) + win.document.body.innerHTML = await container.renderToString(component, { props: { + symbol, sig, port: 'erlang', language: 'erlang', index, signatureLayouts, + nativeSignatureText: () => signatureLayouts.get(sig)!.text, + } }) + const element = win.document.querySelector('.api-native-signature')! + expect(displayedSignature(element)).toBe(sig.raw) + expect(element.getAttribute('data-code-width-status')).toBe('fits') + const links = [...element.querySelectorAll('a.api-type-link')].map((link) => link.getAttribute('href')) + if (id === 'probe:read/1') { + expect(links).toContain(href(model.symbols.find((entry) => entry.id === 't:probe:handle/0')!)) + expect(links).not.toContain(href(model.symbols.find((entry) => entry.id === 'probe:handle/0')!)) + } + if (id === 'probe:links/1') { + for (const target of ['#probe:row{}', 't:probe:box/0', 't:probe:box/1']) { + expect(links).toContain(href(model.symbols.find((entry) => entry.id === target)!)) + } + expect(links).toContain('https://www.erlang.org/doc/apps/kernel/file.html#t:filename_all/0') + } + const markdown = await symbolMarkdownWithLayout({ model, symbol, index }) + expect(fromMarkdown(markdown).children.find((node) => node.type === 'code')).toMatchObject({ value: sig.raw }) + } + } finally { await win.happyDOM.abort() } +}) + const cases = [ ['ts', 'server.Server.setHook'], ['ts', 'selection.Selection.filter'],