mudasobwa

mudasobwa

Creator of Cure

How do I get `@spec` of the external module

I need to get specs for the function which may be located in the external module, like Process or :math.

Dialyzer source code does roughly this:

{:ok, core} = Process |> :code.which() |> :dialyzer_utils.get_core_from_beam([])
{:ok, rec_dict} = :dialyzer_utils.get_record_and_type_info(core)
:dialyzer_utils.get_spec_info(Process, core, rec_dict)

and it kinda works. Is there any better documented and/or less hacky way to get the spec? Is there any reason specs are not there in beam chunks? Should not Code.fetch_docs/2 (or maybe another not yet existing Code.fetch_specs/2) retrieve specs? What am I missing?

Marked As Solved

LostKobrakai

LostKobrakai

Code.fetch_docs is about fetching the “Docs” chunk of a beam file (as proposed initially here: Eep 0048 - Erlang/OTP), which specifically includes only documentation text. There is no chunk for types though. E.g. ex_doc seems to parse them from the abstract code provided in the debug_info (“Dbgi”) chunk. Dialyzer also fetches the what seems like core erlang code from the debug_info chunk. I’m wondering if there’s also some history around where and how that data is fetched (seems like there is). So the answer might be that there’s multiple ways to skin the cat and nobody bothered normalizing one of them within the elixir core codebase.

Also Liked

mudasobwa

mudasobwa

Creator of Cure

For the record, I used this code to fetch the spec as a string.

  @spec fetch_spec(module(), atom(), arity()) :: {:ok, String.t()} | {:error, any()}
  def fetch_spec(mod, fun, arity) do
    with {:ok, core} <- mod |> :code.which() |> :dialyzer_utils.get_core_from_beam(),
         {:ok, rec_dict} <- :dialyzer_utils.get_record_and_type_info(core),
         {:ok, spec_info, %{}} <- :dialyzer_utils.get_spec_info(mod, core, rec_dict),
         {:ok, {{_file, _line}, {_tmp_contract, [_fun], type}, []}} <-
           fetch_spec_info(spec_info, {mod, fun, arity}),
         do: {:ok, type_to_string(fun, type)}
  end

  defp fetch_spec_info(spec_info, {mod, fun, arity}) do
    with :error <- Map.fetch(spec_info, {mod, fun, arity}), do: {:error, :no_mfa_info}
  end

  defp type_to_quoted(fun, type) do
    for {{:type, _, _, _} = type, _} <- type do
      Code.Typespec.spec_to_quoted(fun, type)
    end
  end

  defp type_to_string(fun, type) do
    fun
    |> type_to_quoted(type)
    |> Enum.map_join(" ", &Macro.to_string/1)
  end

The first naïve attempt was to use :erl_types.t_form_to_string/1 from :dialyzer and it worked to some extent, returning somewhat alongside

~c"fun((['Elixir.Task.Supervisor':option()]) -> 'Elixir.Task.Supervisor':on_start())"

I struggled to find an elixir helper to parse this into an elixir format and reached for Code.Typespec.spec_to_quoted/2 which kinda worked but not without glitches.

The type it returned for Process.send_after/4 did not recornize the when option: {:abs, boolean()} guard and gave me when option: var which resulted in compile error. I will probably file a bug to the core.

Another glitch I found is function spec syntax. While (binary() -> boolean()) is translated to the expected erlang ~c"fun((binary()) -> boolean())", the any-arity notation lacks parentheses around the fun as ~c"fun(...) -> integer()". That I am not sure whether it’s expected or not.

Anyway.

mudasobwa

mudasobwa

Creator of Cure

Same as @doc is, btw.

Specs are there in generated documentation for a reason.

LostKobrakai

LostKobrakai

Seems like ex_doc also reaches into the private API of Code.Typespec. Sounds like there could be an effort made to lift functionality into proper public APIs.

mudasobwa

mudasobwa

Creator of Cure

I am positive that specs should be optionally added to “Docs” chunks.

Now when Erlang uses ex_doc to generate docs, at least two different toolings reach for two different private APIs to retrieve what is de facto a part of docs.

Or, alternatively, the new “Spec” chunk should be added to unify the representation of specs in the chunks.

Where Next?

Popular in Questions Top

senggen
Erlang/OTP 25 [erts-13.2.2] [source] [64-bit] [smp:8:8] [ds:8:8:10] [async-threads:1] 15:22:35.803 [error] gen_event {lager_file_backend...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
Tee
can someone please explain to me how Enum.reduce works with maps
New
makeitrein
Hey all, just started picking up Elixir last week and am writing a scraper as a learning project. Baby step #1 is extracting the number ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New
gonzofish
I’m currently trying to understand how to join three tables using Ecto. All the examples I’ve seen use 2, so maybe I’m just missing somet...
New
stefanluptak
Hello everybody, usually, I use a 29" ultra-wide monitor for VSCode which can easily accomodate explorer (files panel) + file with code ...
New
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
Exadra37
Sometimes I want to check if the input into a function is not a blank string. My first approach: defmodule Example do def do_stuff(s...
New

Other popular topics Top

lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chrismccord
Phoenix 1.4.0 released Phoenix 1.4 is out! This release ships with exciting new features, most notably with HTTP2 support, improved deve...
688 30048 115
New
sergio
In Ruby, I can go: User.find_by(email: "foobar@email.com").update(email: "hello@email.com") How can I do something similar in Elixir? ...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call th...
New
romenigld
I am trying to run a deploy with docker and I successfully runned with this command: docker build -t romenigld/blog-prod . but when I t...
New
quazar
How to set Jason to encode all fields in ecto schema, I don’t care about security and implementing only is taking long list of attributes...
New
chrismccord
As promised, the first release candidate of Phoenix 1.3.0 is out! This release focuses on code generators with improved project structure...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
fayddelight
I tried installing elixir 1.11.2 erlang 23.3.4 via asdf in my zsh shell. Enabled the versions locally and globally. When I list them ...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New

We're in Beta

About us Mission Statement