cobra

cobra

Has anyone tried exploring Metaprogramming before. I think it’s a really powerful technique. I was looking for someone who has implemented it on any feature he or she was building. This would help me further know where I can apply it. Thanks @chrismccord …this code is from your book , Metaprogramming Elixir :blush:

defmodule Translator do
  defmacro __using__(_options) do
    quote do
      Module.register_attribute(__MODULE__, :locales,
        accumulate: true,
        persist: false
      )

      import unquote(__MODULE__), only: [locale: 2]
      @before_compile unquote(__MODULE__)
    end
  end

  defmacro __before_compile__(env) do
    compile(Module.get_attribute(env.module, :locales))
  end

  defmacro locale(name, mappings) do
    quote bind_quoted: [name: name, mappings: mappings] do
      @locales {name, mappings}
    end
  end

  def compile(translations) do
    translations_ast =
      for {locale, mappings} <- translations do
        deftranslations(locale, "", mappings)
      end

    quote do
      def t(locale, path, bindings \\ [])
      unquote(translations_ast)
      def t(_locale, _path, _bindings), do: {:error, :no_translation}
    end
  end

  defp deftranslations(locale, current_path, mappings) do
    # deftranslations("en", "", mappings)
    # TBD: Return an AST of the t/3 function defs for the given locale

    # * example of a mapping
    # * flash: [hello: "Hello %{first} %{last}!", bye: "Bye, %{name}!"],
    # * users: [title: "Users"]

    for {key, val} <- mappings do
      # e.g path = append_path("", flash) -> "flash"
      path = append_path(current_path, key)
      # append_path("flash", hello) -> "flash.hello"

      if Keyword.keyword?(val) do
        # deftranslations("en", "flash", [hello: "hello", bye: "bye"])
        deftranslations(locale, path, val)
      else
        quote do
          # t("en", "flash.hello", bindings)
          def t(unquote(locale), unquote(path), bindings) do
            unquote(interpolate(val))
          end
        end
      end
    end
  end

  defp interpolate(string) do
    # TBD interpolate bindings within string
    string
  end

  defp append_path("", next), do: to_string(next)
  defp append_path(current, next), do: "#{current}.#{next}"
end

First 10 of 24 Posts Switch mode

Aetherus

Aetherus

I built an Ecto-ish query builder (not the whole ORM library) for PostgreSQL using metaprogramming. TBH, it’s full of sh*tty code. The good thing is that it’s well-tested.

Why do I need yet another Ecto-ish query builder? Because my team was building something like an OLAP platform. The tables are created by the end users, not by the developers, so there’s no compile-time schemas, and everything needs to go run-time. Use of atoms for naming things is also strictly forbidden because it can cause memory leak.

Then why use metaprogramming? Because I love Ecto’s syntax.

mudasobwa

mudasobwa

Creator of Cure
  • GenServer is a nice example of how to build a process code around a behaviour, hiding all the barebone actor model behind a client’s callbacks
  • my implementation of stream/1 comprehension is completely written in Elixir AST
  • Telemetría uses metaprogramming to modify existing code injecting :telemetry calls based on user-defined module attributes
  • Finitomata is the same technique of exporting callbacks as GenServer, for distributed FSM
CharlesIrvine

CharlesIrvine

I used Elixir meta programming to create a DSL for defining executable business processes. See Mozart and Opera.

BartOtten

BartOtten

  1. For a private project I wrote a macro to write boilerplate for me, deriving a lot from schema’s. I did abandon the project long ago but now I am looking at Ash; as it is my dream come true.

  2. An experiment to have call stack based authorization, by decorating function calls. How to get name of 'calling' module and/or function?.

  3. PLR Uses metaprogramming to do all kinds of black magic by rewriting Phoenix routes and creating alternative helpers.

  4. PLR’s successor is Routex which also uses macro’s but aims at being less black magic.

Somewhere between 3 and 4 I read the Metaprogramming book from Chris McCord and some nice blog posts from @sasajuric.

Have fun with macro’s; escape into functions as soon as you possibly can and do not start writing macro’s that write macro’s :wink:

dimitarvp

dimitarvp

You mean to say that its library for generating DSLs is doing what yours did (and maybe better)? Because if not, yours can be valuable to open-source.

cobra

cobra OP

writing macros that write macros seems like a perilous idea :joy: :skull:

dimitarvp

dimitarvp

LISP-ers have been doing it for decades. They have meta-meta-meta-programming. :003:

krasenyp

krasenyp

Don’t get me started on the metacircular evaluator and the meta object protocol!

zachdaniel

zachdaniel

Creator of Ash

We really need to document this better, but all of our DSLs (which support all kinds of useful things, are type validated, have an ElixirLS extension for customized autocomplete, can accept complex values like anonymous functions, etc.) are all built using spark: Spark — spark v2.7.2

Spark takes a declarative structure, and generates a DSL from that structure.

For a very simple example:

defmodule MyApp.Dsl.Extension do
  @dsl %Spark.Dsl.Section{
    name: :dsl,
    schema: [
      foo: [
        type: :integer, 
        doc: "The amount of coolness to add", 
        default: 100
      ]
    ]
  }

  use Spark.Dsl.Extension, sections: [@dsl]
end

defmodule MyApp.Dsl do
    use Spark.Dsl, default_extensions: [extensions: [MyApp.Dsl.Extension]]
end

defmodule MyApp.Dsl.Info do
  use Spark.InfoGenerator, extension: MyApp.Dsl.Extension, sections: [:dsl]

end

Then you can use it like so:

defmodule Something do
  use MyApp.Dsl

  dsl do
    foo 10
  end
end

# and introspect it

MyApp.Dsl.Info.dsl_foo(Something) 
# => {:ok, 10}

That example is just the tip of the iceberg. It looks like “macro magic” but in reality it’s a thin veneer over a data structure that gives you elixir-specific niceties and handles the complexity that comes with building these kinds of things.

So you can write a DSL without having to write a single macro, we write the macros for you :laughing: Macros writing macros, there are cases where it makes sense :person_shrugging:

11
Post #9
D4no0

D4no0

My only concern about Spark is that it lacks documentation, are you planning on writing documentation for that project or it is more of a internal project that powers Ash?

Where Next? Top

Trending in Discussions Top

AstonJ
As the title says, please share what you’ve been up to with Elixir. Whether that’s been learning it, looking into it, making stuff with i...
2977 91898 914
New
AstonJ
The obligatory hello world thread! Who are you and where are you from? :stuck_out_tongue:
4616 55835 594
New
byu
@chrismccord : I just saw the Extract AGENTS.md from Phoenix.new into phx.new generator commit to the phoenix project. My initial shotgu...
New
arcanemachine
I was working on an Ecto migration and I needed a timestamp. So, for the nth time, I looked up the different data types for timestamps, a...
New
alexslade
Fly’s CEO posted this recently - Turn And Face The Strange · The Fly Blog It says that Fly is going all-in on sprites, which is a worry ...
New
Herve37
We’re evaluating API mocking tools for OpenAPI-based projects and would love to hear what other teams are using. We’re particularly inte...
New
matt-savvy
Is there a word for the ~> symbol used in Version strings? Do you also just call it a Squiggle Arrow™ ?!
New

Other Trending Topics Top

JesseHerrick
Hey, I’m Jesse and I’m the main contributor behind Dexter, a full-featured, lightning-fast Elixir LSP optimized for large codebases. It s...
New
jimsynz
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge &amp; Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
ausimian
Emily is an Elixir library that runs Nx computations on Apple’s MLX. Install it as the default Nx backend and Nx, defn, Axon, Nx.Serving,...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New

We're in Beta

About us Mission Statement