DidactMacros

DidactMacros

Regarding evaluation of arguments to ExUnit.Assertions.assert/2

This pertains to when a call is made to the function ExUnit.Assertions.assert/2 from within ExUnit.Assertions.translate_operator/6 (matched against the equality_check: false argument-set), and the first argument sent to it is unquote(call).

The call made to this function is from within a quote do: block, and the first argument sent is unquote(call), with the second being a keyword list.

In the ExUnit.Assertions.assert/2 function there is an unless expression that is to execute its code in the event that unquote(call), matched to the variable value, evaluates to false.

How can value ever be false?

When does unquote(call) have a chance to be evaluated?

Code for reference:-

assert/1

  defmacro assert(assertion) do
    if translated = translate_assertion(:assert, assertion, __CALLER__) do
      translated
    else
      {args, value} = extract_args(assertion, __CALLER__)

      quote generated: true do
        if value = unquote(value) do
          value
        else
          raise ExUnit.AssertionError,
            args: unquote(args),
            expr: unquote(escape_quoted(:assert, [], assertion)),
            message: "Expected truthy, got #{inspect(value)}"
        end
      end
    end
  end

translate_assertion

  defp translate_assertion(:assert, {operator, meta, [_, _]} = expr, caller)
       when operator in @operator do
    if match?([{_, Kernel}], Macro.Env.lookup_import(caller, {operator, 2})) do
      left = Macro.var(:left, __MODULE__)
      right = Macro.var(:right, __MODULE__)
      call = {operator, meta, [left, right]}
      equality_check? = operator in [:<, :>, :!==, :!=]
      message = "Assertion with #{operator} failed"
      translate_operator(:assert, expr, call, message, equality_check?, caller)
    end
  end

translate_operator

  defp translate_operator(kind, {op, meta, [left, right]} = expr, call, message, false, _caller) do
    expr = escape_quoted(kind, meta, expr)
    context = if op in [:===, :!==], do: :===, else: :==

    quote do
      left = unquote(left)
      right = unquote(right)

      ExUnit.Assertions.assert(unquote(call),
        left: left,
        right: right,
        expr: unquote(expr),
        message: unquote(message),
        context: unquote(context)
      )
    end
  end

assert/2

  def assert(value, opts) when is_list(opts) do
    unless value, do: raise(ExUnit.AssertionError, opts)
    true
  end

Marked As Solved

DidactMacros

DidactMacros

The quote dounquote is located in a def do: block which is quoted, so the unquote is in a nested quote which means that is quoted rather than executed.

  defp translate_operator(kind, {op, meta, [left, right]} = expr, call, message, false, _caller) do
    expr = escape_quoted(kind, meta, expr)
    context = if op in [:===, :!==], do: :===, else: :==

    quote do
      left = unquote(left)
      right = unquote(right)

      ExUnit.Assertions.assert(unquote(call),
        left: left,
        right: right,
        expr: unquote(expr),
        message: unquote(message),
        context: unquote(context)
      )
    end
  end

Results in…

    quote do
      left = unquote(left)
      right = unquote(right)

      ExUnit.Assertions.assert(unquote(call),
        left: left,
        right: right,
        expr: unquote(expr),
        message: unquote(message),
        context: unquote(context)
      )
    end

…getting sent back to the macro that started the chain of function calls.

The macro will then subject the AST to a macro.escape-like processing that identifies :unquote operators in the AST and does not escape the args (children), leaving them in their current form with :unquote stripped or generating a valid AST to describe them. This occurs because the returned AST from translate_operator is the last reachable expression in the macro, and so it must be validated as a formal AST.

The macro will then insert this valid AST fragment into the over all AST at the location were it (the macro, defmacro assert(assertion)) was called.

I initial thought that evaluation was taking place at unquote and at escape, however this was corrected:

If anyone has an question about this I’d be happy to go into further detail.

If I got anything wrong please let me know.

Also Liked

al2o3cr

al2o3cr

Code like:

assert 3 * 14 == 6 * 7

will expand to:

      left = 3 * 14
      right = 6 * 7

      ExUnit.Assertions.assert(left == right,
        left: left,
        right: right,
        expr: #<ast omitted>,
        message: "Assertion with operator == failed",
        context: #<__CALLER__ omitted>
      )
al2o3cr

al2o3cr

Functions like unq would need to be called from inside a defmacro to get the AST they generate turned into executable code.

Where Next?

Popular in Questions Top

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
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
sacepums
Hey guys. I'm new to elixir and im really stocked about it. But I ran into a bit of problem - I need to convert a date sting, for examp...
New
myronmarston
The Elixir Typespec docs show the following syntax for keyword lists in typespecs: # ... | [key: type] # keyword lis...
New
Phillipp
Hey, I have a NanoPi-M3 and try to install Elixir on their Ubuntu image. I followed the Raspberry Pi installation instructions from the ...
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
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
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
Mooodi
Given a string, how can I get access to its character by index? Enum.at("my_string", 2) doesn't work. Or rather, not char, but a substr...
New
jc00ke
Expanding on this topic: https://forum.elixirforum.net/t/map-typespec-question/19217 Let’s say I have a map with required and optional k...
New

Other popular topics Top

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
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
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
_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
lk-geimfari
What is most correct way to open, read and parse JSON file with poison? For example if we have example.json file in root of some projec...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
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
WestKeys
Currently suffering from paralysis by [HTTP client] analysis. This is rather unusual in Elixirland as there tends to be consensus on the ...
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