zoedsoupe

zoedsoupe

Generate typespec and defstruct from runtime values?

I’m not very used to macros/compile time manipulation, but I will explain what I want to achieve and would like to know if it’s possible by any way.

I’m building a CLI framework for Elixir, with high inspirations on clap lib for rust. There you can do something like:

use clap::{Parser, Subcommand};

#[derive(Parser)]
#[command(author, version, about, long_about = None)]
#[command(propagate_version = true)]
struct Cli {
    #[command(subcommand)]
    command: Commands,
}

#[derive(Subcommand)]
enum Commands {
    /// Adds files to myapp
    Add { name: Option<String> },
}

fn main() {
    let cli = Cli::parse();

    // You can check for the existence of subcommands, and if found use their
    // matches just as you would the top level cmd
    match &cli.command {
        Commands::Add { name } => {
            println!("'myapp add' was used, name is: {name:?}")
        }
    }
}

In other words, define a CLI struct and then parse the data structure with available/parsed input. So in the Elixir world I made some macros like: defcommand/2, defcommand/3 and defoption/2, that can be used as:

defmodule CLI do
 use Nexus

  defcommand :foo,
    required: true,
    type: :string,
    doc: "Command that receives a string as argument and prints it."

  defcommand :fizzbuzz, type: {:enum, ~w(fizz buzz)a}, doc: "Fizz bUZZ", required: true

  defcommand :foo_bar, type: :null, doc: "Teste" do
    defoption :some, short: :s
    defcommand :baz, default: "hello", doc: "Hello"
    defcommand :bar, default: "hello", doc: "Hello"
  end
end

So, basically, given that macros/definitions of commands I would like construct a %CLI{} struct, or better: a %__MODULE__{} struct with fields :foo, :fizzbuzz and submodules for subcommands like :foo_bar that would be a sub-struct with :baz, :bar fields and also typespecs for that, for example for the CLI module:

defmodule CLI do
  defmodule CLI.FooBar do
    @type t :: %__MODULE__{baz: String.t, bar: String.t}
    defstruct baz: “hello”, bar: “hello”
  end

  @type t :: %__MODULE__{foo: String.t, fizzbuzz: :fizz | :buzz, foo_bar: CLI.FooBar.t}
  defstruct foo: nil, fizzbuzz: nil, foo_bar: %FooBar{}
end

However, commands and flags will only be available after compilation of their respective macros, so, how would be possible to achieve I want?

The complete source code for my library (is already usable) can be found in GitHub - zoedsoupe/nexus: CLI framework for Elixir, with magic!

EDIT 1: I think I could define a global macro called defcli, and then receive commands and flags definitions inside it, but I don’t think it matches my usage requirements :confused:.

defmodule CLI do
  use Nexus
  
  defcli do
    defoption :help, short: :h
    defcommand :foo, default: “bar”, type: :string
  end
end

That way I can build the typespec and struct with those definitions, but it would break the library contract for now, would be a super major change in the public API, so I would like another possible approach, if there is?

Marked As Solved

al2o3cr

al2o3cr

One approach that can help make macros more powerful to use and easier to write: avoid parsing the contents of do blocks if you can.

An example in Ecto.Schema:

block is the block passed to the schema macro, which sets up a “prelude” and “postlude” and then expands the block as regular AST. This side-steps the need for code like Nexus.build_subcommands and lets users do things like:

schema do
  %w(foo bar baz wat)a
  |> Enum.each(fn name ->
    field name, :string
  end)
end

Calls to field accumulate data in module attributes, then the postlude built by schema uses them to construct __schema__ and so forth.


Another spot in that file worth reviewing for inspiration - the code in embeds_one and embeds_many that handles declaring a (nested) schema inline using a nested module:


One more technique to consider: use __before_compile__ to generate code “at the end” of the module.

  • use Nexus would set up a @before_compile
  • then each call to defcommand would accumulate details in module attributes
  • then the before_compile could generate the @type and defstruct lines using all the accumulated commands

Where Next?

Popular in Questions Top

JDanielMartinez
Hi! May someone helps me, please! I have two apps into an umbrella project: the first one is Database, which manages queries, and the se...
New
joaquinalcerro
Hi there, I am working with Ecto-Postgresql and I need to call all of the records from a specific table but the table has 40,000 record...
New
aalberti333
As the title describes, I’m trying to run Enum.map() over a list of key/value pairs, where the value is a map. My data looks like this: ...
New
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
stefanchrobot
What’s the safe way to decode a JSON string into a struct? I want to avoid calling String.to_atom. Jason.decode can give me a map with st...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
johnnyicon
Hi all, I've just started learning Elixir and Phoenix Framework, so please pardon my n00bness at this stage. I'm trying to use Postg...
New
kostonstyle
Hi all I want to have a unix time, from the current time plus 1 hour. DateTime.now + 1 hour How to get it in elixir? Thanks
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
977 41022 311
New
yawaramin
In the Dialyzer docs ( http://erlang.org/doc/man/dialyzer.html#requesting-or-suppressing-warnings-in-source-files ), there is a way to tu...
New
albydarned
Hello all! I am typing this post from my new MacBook Pro with the M1 chip. I’m loving it so far, and will probably use it as my daily dr...
New
New
vac
Hi, I'm quite new in Elixir and I'm trying to format a string to a PEM format. I have the certificate value like MIIDBTCCAe2...... and ...
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
aadeshere1
I have a another noob question about loop. Since elixir is immutable, while loop is not directly possible. total = 10 while total != 0 ...
New
shahryarjb
Hello, I have map which I want to convert it to string like this: the map: %{last_name: "tavakkoli", name: "shahryar"} the string I ne...
New
aesmail
Hello guys, I have finally made it. I created an admin interface for a framework. It’s been on my todo list for years and with the curre...
New
Nvim
Elixir appears to be a superior language to Python. I don’t see any advantage of Python over Elixir. Are there any?
New

We're in Beta

About us Mission Statement