garrison

garrison

Why do macro sigils accept a bitstring literal instead of a string literal?

The first time I tried to create a custom (macro) sigil, I assumed the first argument would be a string as I knew string literals represented themselves in the AST. Of course, a quick look into the Elixir source reveals this is not the case; sigils accept a strange tuple as their first argument. I simply copied this without knowing what was actually going on.

Today, I was trying to write a sigil to hijack Phoenix’s HEEx as part of a silly hack that will no doubt warrant its own post in the near future. As a result of that, I spent some time trying to figure out how sigils actually work.

My Elixir metaprogramming knowledge is unfortunately not the best, but as I understand it, this tuple:

{:<<>>, [], ["hello world"]}

is the AST representation of a bitstring literal.

So when we write a custom sigil:

defmacro sigil_H({:<<>>, _meta, [expr]}, []) do
  # whatever
end

That custom sigil accepts a bitstring literal.

The first thing that threw me off here was that, as I understand it, these AST tuples are structured as {operator, metadata, arguments}. So the argument for this bitstring is, well, a string. However, I see from the docs that this is in fact valid syntax for a bitstring:

iex> quote do: <<"hello world">>
{:<<>>, [], ["hello world"]}

Go figure.

Further experimentation reveals that sigil calls are parsed into this:

iex> quote do: ~S"hello world"
{
  :sigil_S,
  [delimiter: "\"", context: Elixir, imports: [{2, Kernel}]],
  [{:<<>>, [], ["hello world"]}, []]
}

Again, my understanding is that calls are represented in the AST as {name, metadata, arguments}, so in this case sigil_S is indeed being called with two arguments: a bitstring literal, and an empty list. Which is exactly what the macros pattern match on, so everything checks out.

Which means that a sigil call is effectively parsed into (the AST representation of) this code:

sigil_S(<<"hello world">>, [])

So my question is this: why do sigils accept the AST representation of a bitstring, which contains a string, instead of just accepting a string? As far as I can tell, this is not mentioned in the documentation. In fact, I can’t seem to find any mention of it on the internet at all, hence my post.

My guess is the answer has something to do with the metadata list included in the bitstring’s AST tuple, which is indeed used by HEEx to get indentation information, and which is absent from the AST representation of a string literal.

Marked As Solved

josevalim

josevalim

Creator of Elixir

Correct. Strings are bitstrings internally and the sigil macro also receives them in the bitstring syntax for consistency/simplicity, otherwise you would have to match on both.

It also has the upside of including a meta, which may carry additional information.

Also Liked

Eiji

Eiji

In Elixir the String is an UTF-8 encoded binary

A UTF-8 encoded binary.

The types String.t() and binary() are equivalent to analysis tools. Although, for those reading the documentation, String.t() implies it is a UTF-8 encoded binary.
Source: t:String.t/0

Example code for String and it’s binary representation:

# less sugar
iex> <<"test"::binary>> == <<"test">>
true

# more sugar
iex> <<"test"::binary>> == "test"
true

# UTF-8 encoding
iex> for <<char::utf8 <- "test">>, do: <<char::utf8>>
["t", "e", "s", "t"]

Instead of looking at kernel special forms you should read the Syntax reference, see: Lists, tuples and binaries section.

Where Next?

Popular in Questions Top

logicmason
Hi there, I'm working through my first release with elixir/phoenix. I've built a release with distillery and found that it crashes when I...
New
SoCreat
i’m a new one to elixir which editor can i use vs code? or atom? Thanks! :smiley:
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
script
If I have a string “1000 cfu/ml” . I want to remove the characters and / and space . So the string is like this "1000" What is the ...
New
ashish173
I am using Ecto timestamps with postgres, I can see the timestamps() use the :naive_dateime but for my use case I wanted to store the ti...
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
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
chewm
Hi guys, nice to meet you to the whole forum, I’m new here, I’m trying to configure visual studio code for elixir, right now the intellis...
New
wernerlaude
In AR this is so simple @articles = current_user.articles How to do in Ecto? def index(conn, _params) do current_user = conn.assig...
New
idi527
I’ve been re-reading swift book again and noticed that multiline strings there don’t have a trailing line break, unlike in elixir iex(2)...
New

Other popular topics Top

JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
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
minhajuddin
I have seen a lot of code which picks the first element from a list using Enum.at(0) instead of List.first. Is there a reason why people ...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
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
fireproofsocks
Forgive me if this is obvious, but how does one delete a database record WITHOUT selecting it first? https://hexdocs.pm/ecto/Ecto.Repo.h...
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
beno
I will often find my self writing things similar to: case some_value do nil -&gt; something() "" -&gt; something() _ -&gt; someth...
New
Qqwy
Original source of discussion: This topic on the Pragmatic Programmers' Functional Web Development with Elixir, OTP, and Phoenix forum. ...
New
AstonJ
by Lance Halvorsen Elixir and Phoenix are generating tremendous excitement as an unbeatable platform for building modern web application...
460 27162 124
New

We're in Beta

About us Mission Statement