1# Syntax reference
2
3Elixir syntax was designed to have a straightforward conversion to an abstract syntax tree (AST). This means the Elixir syntax is mostly uniform with a handful of "syntax sugar" constructs to reduce the noise in common Elixir idioms.
4
5This document covers all of Elixir syntax constructs as a reference and then discuss their exact AST representation.
6
7## Reserved words
8
9These are the reserved words in the Elixir language. They are detailed throughout this guide but summed up here for convenience:
10
11  * `true`, `false`, `nil` - used as atoms
12  * `when`, `and`, `or`, `not`, `in` - used as operators
13  * `fn` - used for anonymous function definitions
14  * `do`, `end`, `catch`, `rescue`, `after`, `else` - used in do/end blocks
15
16## Data types
17
18### Numbers
19
20Integers (`1234`) and floats (`123.4`) in Elixir are represented as a sequence of digits that may be separated by underscore for readability purposes, such as `1_000_000`. Integers never contain a dot (`.`) in their representation. Floats contain a dot and at least one other digit after the dot. Floats also support the scientific notation, such as `123.4e10` or `123.4E10`.
21
22### Atoms
23
24Unquoted atoms start with a colon (`:`) which must be immediately followed by a Unicode letter or an underscore. The atom may continue using a sequence of Unicode letters, numbers, underscores, and `@`. Atoms may end in `!` or `?`. See [Unicode syntax](unicode-syntax.md) for a formal specification. Valid unquoted atoms are: `:ok`, `:ISO8601`, and `:integer?`.
25
26If the colon is immediately followed by a pair of double- or single-quotes surrounding the atom name, the atom is considered quoted. In contrast with an unquoted atom, this one can be made of any Unicode character (not only letters), such as `:'�� Elixir'`, `:"++olá++"`, and `:"123"`.
27
28Quoted and unquoted atoms with the same name are considered equivalent, so `:atom`, `:"atom"`, and `:'atom'` represent the same atom. The only catch is that the compiler will warn when quotes are used in atoms that do not need to be quoted.
29
30All operators in Elixir are also valid atoms. Valid examples are `:foo`, `:FOO`, `:foo_42`, `:foo@bar`, and `:++`. Invalid examples are `:@foo` (`@` is not allowed at start), `:123` (numbers are not allowed at start), and `:(*)` (not a valid operator).
31
32`true`, `false`, and `nil` are reserved words that are represented by the atoms `:true`, `:false` and `:nil` respectively.
33
34### Strings
35
36Single-line strings in Elixir are written between double-quotes, such as `"foo"`. Any double-quote inside the string must be escaped with `\ `. Strings support Unicode characters and are stored as UTF-8 encoded binaries.
37
38Multi-line strings in Elixir are written with three double-quotes, and can have unescaped quotes within them. The resulting string will end with a newline. The indentation of the last `"""` is used to strip indentation from the inner string. For example:
39
40```
41iex> test = """
42...>     this
43...>     is
44...>     a
45...>     test
46...> """
47"    this\n    is\n    a\n    test\n"
48iex> test = """
49...>     This
50...>     Is
51...>     A
52...>     Test
53...>     """
54"This\nIs\nA\nTest\n"
55```
56
57Strings are always represented as themselves in the AST.
58
59### Charlists
60
61Charlists in Elixir are written in single-quotes, such as `'foo'`. Any single-quote inside the string must be escaped with `\ `. Charlists are made of non-negative integers, where each integer represents a Unicode code point.
62
63Multi-line charlists are written with three single-quotes (`'''`), the same way multi-line strings are.
64
65Charlists are always represented as themselves in the AST.
66
67For more in-depth information, please read the "Charlists" section in the `List` module.
68
69### Lists, tuples and binaries
70
71Data structures such as lists, tuples, and binaries are marked respectively by the delimiters `[...]`, `{...}`, and `<<...>>`. Each element is separated by comma. A trailing comma is also allowed, such as in `[1, 2, 3,]`.
72
73### Maps and keyword lists
74
75Maps use the `%{...}` notation and each key-value is given by pairs marked with `=>`, such as `%{"hello" => 1, 2 => "world"}`.
76
77Both keyword lists (list of two-element tuples where the first element is atom) and maps with atom keys support a keyword notation where the colon character `:` is moved to the end of the atom. `%{hello: "world"}` is equivalent to `%{:hello => "world"}` and `[foo: :bar]` is equivalent to `[{:foo, :bar}]`. This notation is a syntax sugar that emits the same AST representation. It will be explained in later sections.
78
79### Structs
80
81Structs built on the map syntax by passing the struct name between `%` and `{`. For example, `%User{...}`.
82
83## Expressions
84
85### Variables
86
87Variables in Elixir must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The variable may continue using a sequence of Unicode letters, numbers, and underscores. Variables may end in `?` or `!`. See [Unicode syntax](unicode-syntax.md) for a formal specification.
88
89[Elixir's naming conventions](naming-conventions.md) recommend variables to be in `snake_case` format.
90
91### Non-qualified calls (local calls)
92
93Non-qualified calls, such as `add(1, 2)`, must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The call may continue using a sequence of Unicode letters, numbers, and underscore. Calls may end in `?` or `!`. See [Unicode syntax](unicode-syntax.md) for a formal specification.
94
95Parentheses for non-qualified calls are optional, except for zero-arity calls, which would then be ambiguous with variables. If parentheses are used, they must immediately follow the function name *without spaces*. For example, `add (1, 2)` is a syntax error, since `(1, 2)` is treated as an invalid block which is attempted to be given as a single argument to `add`.
96
97[Elixir's naming conventions](naming-conventions.md) recommend calls to be in `snake_case` format.
98
99### Operators
100
101As many programming languages, Elixir also support operators as non-qualified calls with their precedence and associativity rules. Constructs such as `=`, `when`, `&` and `@` are simply treated as operators. See [the Operators page](operators.md) for a full reference.
102
103### Qualified calls (remote calls)
104
105Qualified calls, such as `Math.add(1, 2)`, must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The call may continue using a sequence of Unicode letters, numbers, and underscores. Calls may end in `?` or `!`. See [Unicode syntax](unicode-syntax.md) for a formal specification.
106
107[Elixir's naming conventions](naming-conventions.md) recommend calls to be in `snake_case` format.
108
109For qualified calls, Elixir also allows the function name to be written between double- or single-quotes, allowing calls such as `Math."++add++"(1, 2)`. Operators can be used as qualified calls without a need for quote, such as `Kernel.+(1, 2)`.
110
111Parentheses for qualified calls are optional. If parentheses are used, they must immediately follow the function name *without spaces*.
112
113### Aliases
114
115Aliases are constructs that expand to atoms at compile-time. The alias `String` expands to the atom `:"Elixir.String"`. Aliases must start with an ASCII uppercase character which may be followed by any ASCII letter, number, or underscore. Non-ASCII characters are not supported in aliases.
116
117[Elixir's naming conventions](naming-conventions.md) recommend aliases to be in `CamelCase` format.
118
119### Blocks
120
121Blocks are multiple Elixir expressions separated by newlines or semi-colons. A new block may be created at any moment by using parentheses.
122
123### Left to right arrow
124
125The left to right arrow (`->`) is used to establish a relationship between left and right, commonly referred as clauses. The left side may have zero, one, or more arguments; the right side is zero, one, or more expressions separated by new line. The `->` may appear one or more times between one of the following terminators: `do`/`end`, `fn`/`end` or `(`/`)`. When `->` is used, only other clauses are allowed between those terminators. Mixing clauses and regular expressions is invalid syntax.
126
127It is seen on `case` and `cond` constructs between `do`/`end`:
128
129```elixir
130case 1 do
131  2 -> 3
132  4 -> 5
133end
134
135cond do
136  true -> false
137end
138```
139
140Seen in typespecs between `(`/`)`:
141
142```elixir
143(integer(), boolean() -> integer())
144```
145
146It is also used between `fn/end` for building anonymous functions:
147
148```elixir
149fn
150  x, y -> x + y
151end
152```
153
154### Sigils
155
156Sigils start with `~` and are followed by a letter and one of the following pairs:
157
158  * `(` and `)`
159  * `{` and `}`
160  * `[` and `]`
161  * `<` and `>`
162  * `"` and `"`
163  * `'` and `'`
164  * `|` and `|`
165  * `/` and `/`
166
167After closing the pair, zero or more ASCII letters can be given as a modifier. Sigils are expressed as non-qualified calls prefixed with `sigil_` where the first argument is the sigil contents as a string and the second argument is a list of integers as modifiers:
168
169If the sigil letter is in uppercase, no interpolation is allowed in the sigil, otherwise its contents may be dynamic. Compare the results of the sigils below for more information:
170
171```elixir
172~s/f#{"o"}o/
173~S/f#{"o"}o/
174```
175
176Sigils are useful to encode text with their own escaping rules, such as regular expressions, datetimes, and others.
177
178## The Elixir AST
179
180Elixir syntax was designed to have a straightforward conversion to an abstract syntax tree (AST). Elixir's AST is a regular Elixir data structure composed of the following elements:
181
182  * atoms - such as `:foo`
183  * integers - such as `42`
184  * floats - such as `13.1`
185  * strings - such as `"hello"`
186  * lists - such as `[1, 2, 3]`
187  * tuples with two elements - such as `{"hello", :world}`
188  * tuples with three elements, representing calls or variables, as explained next
189
190The building block of Elixir's AST is a call, such as:
191
192```elixir
193sum(1, 2, 3)
194```
195
196which is represented as a tuple with three elements:
197
198```elixir
199{:sum, meta, [1, 2, 3]}
200```
201
202the first element is an atom (or another tuple), the second element is a list of two-element tuples with metadata (such as line numbers) and the third is a list of arguments.
203
204We can retrieve the AST for any Elixir expression by calling `quote`:
205
206```elixir
207quote do
208  sum()
209end
210#=> {:sum, [], []}
211```
212
213Variables are also represented using a tuple with three elements and a combination of lists and atoms, for example:
214
215```elixir
216quote do
217  sum
218end
219#=> {:sum, [], Elixir}
220```
221
222You can see that variables are also represented with a tuple, except the third element is an atom expressing the variable context.
223
224Over the course of this section, we will explore many Elixir syntax constructs alongside their AST representations.
225
226### Operators
227
228Operators are treated as non-qualified calls:
229
230```elixir
231quote do
232  1 + 2
233end
234#=> {:+, [], [1, 2]}
235```
236
237Note that `.` is also an operator. Remote calls use the dot in the AST with two arguments, where the second argument is always an atom:
238
239```elixir
240quote do
241  foo.bar(1, 2, 3)
242end
243#=> {{:., [], [{:foo, [], Elixir}, :bar]}, [], [1, 2, 3]}
244```
245
246Calling anonymous functions uses the dot in the AST with a single argument, mirroring the fact the function name is "missing" from right side of the dot:
247
248```elixir
249quote do
250  foo.(1, 2, 3)
251end
252#=> {{:., [], [{:foo, [], Elixir}]}, [], [1, 2, 3]}
253```
254
255### Aliases
256
257Aliases are represented by an `__aliases__` call with each segment separated by dot as an argument:
258
259```elixir
260quote do
261  Foo.Bar.Baz
262end
263#=> {:__aliases__, [], [:Foo, :Bar, :Baz]}
264
265quote do
266  __MODULE__.Bar.Baz
267end
268#=> {:__aliases__, [], [{:__MODULE__, [], Elixir}, :Bar, :Baz]}
269```
270
271All arguments, except the first, are guaranteed to be atoms.
272
273### Data structures
274
275Remember lists are literals, so they are represented as themselves in the AST:
276
277```elixir
278quote do
279  [1, 2, 3]
280end
281#=> [1, 2, 3]
282```
283
284Tuples have their own representation, except for two-element tuples, which are represented as themselves:
285
286```elixir
287quote do
288  {1, 2}
289end
290#=> {1, 2}
291
292quote do
293  {1, 2, 3}
294end
295#=> {:{}, [], [1, 2, 3]}
296```
297
298Binaries have a representation similar to tuples, except they are tagged with `:<<>>` instead of `:{}`:
299
300```elixir
301quote do
302  <<1, 2, 3>>
303end
304#=> {:<<>>, [], [1, 2, 3]}
305```
306
307The same applies to maps where each pair is treated as a list of tuples with two elements:
308
309```elixir
310quote do
311  %{1 => 2, 3 => 4}
312end
313#=> {:%{}, [], [{1, 2}, {3, 4}]}
314```
315
316### Blocks
317
318Blocks are represented as a `__block__` call with each line as a separate argument:
319
320```elixir
321quote do
322  1
323  2
324  3
325end
326#=> {:__block__, [], [1, 2, 3]}
327
328quote do 1; 2; 3; end
329#=> {:__block__, [], [1, 2, 3]}
330```
331
332### Left to right arrow
333
334The left to right arrow (`->`) is represented similar to operators except that they are always part of a list, its left side represents a list of arguments and the right side is an expression.
335
336For example, in `case` and `cond`:
337
338```elixir
339quote do
340  case 1 do
341    2 -> 3
342    4 -> 5
343  end
344end
345#=> {:case, [], [1, [do: [{:->, [], [[2], 3]}, {:->, [], [[4], 5]}]]]}
346
347quote do
348  cond do
349    true -> false
350  end
351end
352#=> {:cond, [], [[do: [{:->, [], [[true], false]}]]]}
353```
354
355Between `(`/`)`:
356
357```elixir
358quote do
359  (1, 2 -> 3
360   4, 5 -> 6)
361end
362#=> [{:->, [], [[1, 2], 3]}, {:->, [], [[4, 5], 6]}]
363```
364
365Between `fn/end`:
366
367```elixir
368quote do
369  fn
370    1, 2 -> 3
371    4, 5 -> 6
372  end
373end
374#=> {:fn, [], [{:->, [], [[1, 2], 3]}, {:->, [], [[4, 5], 6]}]}
375```
376
377## Syntactic sugar
378
379All of the constructs above are part of Elixir's syntax and have their own representation as part of the Elixir AST. This section will discuss the remaining constructs that "desugar" to one of the constructs explored above. In other words, the constructs below can be represented in more than one way in your Elixir code and retain AST equivalence.
380
381### Integers in other bases and Unicode code points
382
383Elixir allows integers to contain `_` to separate digits and provides conveniences to represent integers in other bases:
384
385```elixir
3861_000_000
387#=> 1000000
388
3890xABCD
390#=> 43981 (Hexadecimal base)
391
3920o01234567
393#=> 342391 (Octal base)
394
3950b10101010
396#=> 170 (Binary base)
397
398399#=> 233 (Unicode code point)
400```
401
402Those constructs exist only at the syntax level. All of the examples above are represented as their underlying integers in the AST.
403
404### Access syntax
405
406The access syntax is represented as a call to `Access.get/2`:
407
408```elixir
409quote do
410  opts[arg]
411end
412#=> {{:., [], [Access, :get]}, [], [{:opts, [], Elixir}, {:arg, [], Elixir}]}
413```
414
415### Optional parentheses
416
417Elixir provides optional parentheses for non-qualified and qualified calls.
418
419```elixir
420quote do
421  sum 1, 2, 3
422end
423#=> {:sum, [], [1, 2, 3]}
424```
425
426The above is treated the same as `sum(1, 2, 3)` by the parser.
427
428The same applies to qualified calls such as `Foo.bar(1, 2, 3)`, which is equivalent to `Foo.bar 1, 2, 3`. There are, however, some situations where parentheses are required:
429
430  * when calling anonymous functions, such as `f.(1, 2)`;
431
432  * for non-qualified calls with no arguments, such as `sum()`. Removing the parentheses for `sum` causes it to be represented as the variable `sum`;
433
434  * for dynamic qualified calls with no arguments. `data.key` means accessing a field named `key` in the map given by `data`. `mod.fun()`, with parens, means calling a function named `fun` in the module `mod`;
435
436In practice, developers prefer to add parentheses to most of their calls. They are skipped mainly in Elixir's control-flow constructs, such as `defmodule`, `if`, `case`, etc, and in certain DSLs.
437
438### Keywords
439
440Keywords in Elixir are a list of tuples of two elements where the first element is an atom. Using the base constructs, they would be represented as:
441
442```elixir
443[{:foo, 1}, {:bar, 2}]
444```
445
446However Elixir introduces a syntax sugar where the keywords above may be written as follows:
447
448```elixir
449[foo: 1, bar: 2]
450```
451
452Atoms with foreign characters, such as whitespace, must be wrapped in quotes. This rule applies to keywords as well:
453
454```elixir
455[{:"foo bar", 1}, {:"bar baz", 2}] == ["foo bar": 1, "bar baz": 2]
456```
457
458Remember that, because lists and two-element tuples are quoted literals, by definition keywords are also literals (in fact, the only reason tuples with two elements are quoted literals is to support keywords as literals).
459
460### Keywords as last arguments
461
462Elixir also supports a syntax where if the last argument of a call is a keyword list then the square brackets can be skipped. This means that the following:
463
464```elixir
465if(condition, do: this, else: that)
466```
467
468is the same as
469
470```elixir
471if(condition, [do: this, else: that])
472```
473
474which in turn is the same as
475
476```elixir
477if(condition, [{:do, this}, {:else, that}])
478```
479
480### `do`/`end` blocks
481
482The last syntax convenience are `do`/`end` blocks. `do`/`end` blocks are equivalent to keywords as the last argument of a function call where the block contents are wrapped in parentheses. For example:
483
484```elixir
485if true do
486  this
487else
488  that
489end
490```
491
492is the same as:
493
494```elixir
495if(true, do: (this), else: (that))
496```
497
498which we have explored in the previous section.
499
500Parentheses are important to support multiple expressions. This:
501
502```elixir
503if true do
504  this
505  that
506end
507```
508
509is the same as:
510
511```elixir
512if(true, do: (
513  this
514  that
515))
516```
517
518Inside `do`/`end` blocks you may introduce other keywords, such as `else` used in the `if` above. The supported keywords between `do`/`end` are static and are:
519
520  * `after`
521  * `catch`
522  * `else`
523  * `rescue`
524
525You can see them being used in constructs such as `receive`, `try`, and others.
526
527## Summary
528
529This document provides a reference to Elixir syntax, exploring its constructs and their AST equivalents.
530
531We have also discussed a handful of syntax conveniences provided by Elixir. Those conveniences are what allow us to write
532
533```elixir
534defmodule Math do
535  def add(a, b) do
536    a + b
537  end
538end
539```
540
541instead of
542
543```elixir
544defmodule(Math, [
545  {:do, def(add(a, b), [{:do, a + b}])}
546])
547```
548
549The mapping between code and data (the underlying AST) is what allows Elixir to implement `defmodule`, `def`, `if`, and others in Elixir itself. Elixir makes the constructs available for building the language accessible to developers who want to extend the language to new domains.
550