yolo007wizard

yolo007wizard OP

Here is v1 prototype to get a json spec from module docs. I also learned about running iex> c("MathOps.ex", ".") to compile the file.

defmodule MathOps do
  @moduledoc """
  This module provides math operations
  """
  @after_compile {__MODULE__, :_build_json_def}
  def _build_json_def(_env, bytecode) do
    {:docs_v1, _, _, _, module_doc, _, docs} = Code.fetch_docs(__MODULE__)
    {:ok, specs} = Code.Typespec.fetch_specs(bytecode)
    defs =
      for {{_, doc_name, _}, _, [sig], doc, _} <- docs,
        {{spec_name, _}, [{:type, _, :fun, [{:type, _, :product, args}, {_, _, result, _}]}]} <- specs,
        doc != :hidden,
        doc_name == spec_name do
          params =
            for arg <- args,
            {:type, _, type, _} = arg do
              %{"type" => Atom.to_string(type)}
            end
          %{"name"=> Atom.to_string(doc_name), "doc"=> doc, "signature"=> sig, "params"=> params, "return"=> result}
      end
    document = %{"module"=> Atom.to_string(__MODULE__), "doc"=> module_doc["en"], "defs"=> defs}
    IO.inspect(document)
  end

  @doc """
  This function adds
  """
  @spec add(integer, integer) :: map()
  def add(a, b) do
    %{"result" => Integer.to_string(a + b)}
  end

end

Looks kinda bad in my opinion but it works :stuck_out_tongue: . On compile it spits out clean looking map. Couple minor things yet and then json dump to file.

%{
  "module" => "Elixir.MathOps",
  "doc" => "This module provides math operations\n",
  "defs" => [
    %{
      "doc" => %{"en" => "This function adds\n"},
      "name" => "add",
      "params" => [%{"type" => "integer"}, %{"type" => "integer"}],
      "return" => "map",
      "signature" => "add(a, b)"
    }
  ]
}

Thinking later on this could be a mix compile task but haven’t learned about it yet.

0
Post #11
— All posts loaded —