saleyn

saleyn

How to create a type attribute in a macro?

How can I create a macro that defines a type using atom that represents the type name? In the macro __type__ below, for the visibility argument :private, I’d like the macro to emit:
@typep t() :: { ... }

def visibility(:public),  do: :type
def visibility(:private), do: :typep
def visibility(:opaque),  do: :opaque

defmacro __type__(types, visibility) do
  attr = visibility(visibility)
  quote bind_quoted: [attr: attr, types: types] do
    Module.put_attribute(__MODULE__, unquote(attr), t() :: {unquote_splicing(types)}
  end
end

Compilation fails with:

== Compilation error in file test/type_test.exs ==
** (CompileError) test/type_test.exs:49: misplaced operator ::/2

The :: operator is typically used in bitstrings to specify types and sizes of segments:

    <<size::32-integer, letter::utf8, rest::binary>>

It is also used in typespecs, such as @type and @spec, to describe inputs and outputs
    ... expanding macro: Mod.__type__/2

Most Liked

josevalim

josevalim

Creator of Elixir

You want to emit the actual type notation, something like this:

@unquote(attr)(t() :: {unquote_splicing(types)})
ityonemo

ityonemo

You can’t mix bind_quoted with unquoutes.

Eiji

Eiji

Here you go:

defmodule Example do
  defmacro sample(ast, visibility) do
    # sample visibility handling
    attr =
      case visibility do
        :public -> :type
        :private -> :typep
      end

    # this optional line allows you to use sigils:
    # Example.sample(~w[a b c]a, :private)
    list = Macro.expand(ast, __CALLER__)

    # if unuoqte needs to be used which is the case here
    # then quote cannot have bind_quoted option set
    # as this option sets unquote option to false
    # making unquote/1 calls not work
    quote do
      # @ is a macro which means we need to use unquote here
      # to pass a raw data instead of ast not recognized by said macro
      @unquote(attr)(t() :: {unquote_splicing(list)})
    end
  end
end

Helpful resources:

  1. @/1 macro
  2. quote/2 special form

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
mcarvalho
What is the difference between System.get_env and Application.get_env? For example, what are best practices to use one versus another.
New
jononomo
I am trying to figure out how Mix knows whether the environment is test, dev, or prod – where is this set? Thanks.
New
shahryarjb
Hello, I get Persian date from my client and convert it to normal calendar like this: def jalali_string_to_miladi_english_number(persi...
New
jay1
Why is it that the mnesia database isn’t the most preferred database for use in Elixir/Phoenix?
New
baxterw3b
Hi guys, i’m new in the Elixir world, and i have to say, that i love it! i’m having some problem to understand anonymous functions with ...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
vonH
When I run the Plug and I recompile I wind up having to use Ctrl C to quit iex and start again. Witht the help of rlwrap I can use the cu...
New
Brian
What is the proper way to load a module from a file in to IEX? In the python world, doing something like this pretty standard: from ....
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" =&gt; #BSON.ObjectId&lt;58eb1a7a9ad169198c3dXXXX&gt;, "email" =&gt; ...
New

Other popular topics Top

danschultzer
None of the current solutions worked well for me, so I went ahead and built a user management system from scratch. This project took far...
548 29377 241
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
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
msaraiva
Surface is an experimental library built on top of Phoenix LiveView and its new LiveComponent API that aims to provide a more declarative...
564 43622 214
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
marick
I had some trouble figuring out how to make many-to-many associations work. Once I got it working, I wrote a blog post. Because I’m a nov...
New
sergio
Kind of like when jquery came out, it was super necessary. Existing drag and drop libraries have a bunch of baggage to support old browse...
New

We're in Beta

About us Mission Statement