1defmodule Kernel.SpecialForms do 2 @moduledoc """ 3 Special forms are the basic building blocks of Elixir, and therefore 4 cannot be overridden by the developer. 5 6 The `Kernel.SpecialForms` module consists solely of macros that can be 7 invoked anywhere in Elixir code without the use of the 8 `Kernel.SpecialForms.` prefix. This is possible because they all have 9 been automatically imported, in the same fashion as the functions and 10 macros from the `Kernel` module. 11 12 These building blocks are defined in this module. Some of these special forms are lexical (such as 13 `alias/2` and `case/2`). The macros `{}/1` and `<<>>/1` are also special 14 forms used to define tuple and binary data structures respectively. 15 16 This module also documents macros that return information about Elixir's 17 compilation environment, such as (`__ENV__/0`, `__MODULE__/0`, `__DIR__/0`, 18 `__STACKTRACE__/0`, and `__CALLER__/0`). 19 20 Additionally, it documents two special forms, `__block__/1` and 21 `__aliases__/1`, which are not intended to be called directly by the 22 developer but they appear in quoted contents since they are essential 23 in Elixir's constructs. 24 """ 25 26 defmacrop error!(args) do 27 quote do 28 _ = unquote(args) 29 30 message = 31 "Elixir's special forms are expanded by the compiler and must not be invoked directly" 32 33 :erlang.error(RuntimeError.exception(message)) 34 end 35 end 36 37 @doc """ 38 Creates a tuple. 39 40 More information about the tuple data type and about functions to manipulate 41 tuples can be found in the `Tuple` module; some functions for working with 42 tuples are also available in `Kernel` (such as `Kernel.elem/2` or 43 `Kernel.tuple_size/1`). 44 45 ## AST representation 46 47 Only two-element tuples are considered literals in Elixir and return themselves 48 when quoted. Therefore, all other tuples are represented in the AST as calls to 49 the `:{}` special form. 50 51 iex> quote do 52 ...> {1, 2} 53 ...> end 54 {1, 2} 55 56 iex> quote do 57 ...> {1, 2, 3} 58 ...> end 59 {:{}, [], [1, 2, 3]} 60 61 """ 62 defmacro unquote(:{})(args), do: error!([args]) 63 64 @doc """ 65 Creates a map. 66 67 See the `Map` module for more information about maps, their syntax, and ways to 68 access and manipulate them. 69 70 ## AST representation 71 72 Regardless of whether `=>` or the keyword syntax is used, key-value pairs in 73 maps are always represented internally as a list of two-element tuples for 74 simplicity: 75 76 iex> quote do 77 ...> %{"a" => :b, c: :d} 78 ...> end 79 {:%{}, [], [{"a", :b}, {:c, :d}]} 80 81 """ 82 defmacro unquote(:%{})(args), do: error!([args]) 83 84 @doc """ 85 Matches on or builds a struct. 86 87 A struct is a tagged map that allows developers to provide 88 default values for keys, tags to be used in polymorphic 89 dispatches and compile time assertions. 90 91 Structs are usually defined with the `Kernel.defstruct/1` macro: 92 93 defmodule User do 94 defstruct name: "john", age: 27 95 end 96 97 Now a struct can be created as follows: 98 99 %User{} 100 101 Underneath a struct is just a map with a `:__struct__` key 102 pointing to the `User` module: 103 104 %User{} == %{__struct__: User, name: "john", age: 27} 105 106 The struct fields can be given when building the struct: 107 108 %User{age: 31} 109 #=> %{__struct__: User, name: "john", age: 31} 110 111 Or also on pattern matching to extract values out: 112 113 %User{age: age} = user 114 115 An update operation specific for structs is also available: 116 117 %User{user | age: 28} 118 119 The advantage of structs is that they validate that the given 120 keys are part of the defined struct. The example below will fail 121 because there is no key `:full_name` in the `User` struct: 122 123 %User{full_name: "john doe"} 124 125 The syntax above will guarantee the given keys are valid at 126 compilation time and it will guarantee at runtime the given 127 argument is a struct, failing with `BadStructError` otherwise. 128 129 Although structs are maps, by default structs do not implement 130 any of the protocols implemented for maps. Check 131 `Kernel.defprotocol/2` for more information on how structs 132 can be used with protocols for polymorphic dispatch. Also 133 see `Kernel.struct/2` and `Kernel.struct!/2` for examples on 134 how to create and update structs dynamically. 135 136 ## Pattern matching on struct names 137 138 Besides allowing pattern matching on struct fields, such as: 139 140 %User{age: age} = user 141 142 Structs also allow pattern matching on the struct name: 143 144 %struct_name{} = user 145 struct_name #=> User 146 147 You can also assign the struct name to `_` when you want to 148 check if something is a struct but you are not interested in 149 its name: 150 151 %_{} = user 152 153 """ 154 defmacro unquote(:%)(struct, map), do: error!([struct, map]) 155 156 @doc """ 157 Defines a new bitstring. 158 159 ## Examples 160 161 iex> <<1, 2, 3>> 162 <<1, 2, 3>> 163 164 ## Types 165 166 A bitstring is made of many segments and each segment has a 167 type. There are 9 types used in bitstrings: 168 169 - `integer` 170 - `float` 171 - `bits` (alias for `bitstring`) 172 - `bitstring` 173 - `binary` 174 - `bytes` (alias for `binary`) 175 - `utf8` 176 - `utf16` 177 - `utf32` 178 179 When no type is specified, the default is `integer`: 180 181 iex> <<1, 2, 3>> 182 <<1, 2, 3>> 183 184 Elixir also accepts by default the segment to be a literal 185 string or a literal charlist, which are by default expanded to integers: 186 187 iex> <<0, "foo">> 188 <<0, 102, 111, 111>> 189 190 Binaries need to be explicitly tagged as `binary`: 191 192 iex> rest = "oo" 193 iex> <<102, rest::binary>> 194 "foo" 195 196 The `utf8`, `utf16`, and `utf32` types are for Unicode code points. They 197 can also be applied to literal strings and charlists: 198 199 iex> <<"foo"::utf16>> 200 <<0, 102, 0, 111, 0, 111>> 201 iex> <<"foo"::utf32>> 202 <<0, 0, 0, 102, 0, 0, 0, 111, 0, 0, 0, 111>> 203 204 Otherwise we get an `ArgumentError` when constructing the binary: 205 206 rest = "oo" 207 <<102, rest>> 208 ** (ArgumentError) argument error 209 210 ## Options 211 212 Many options can be given by using `-` as separator. Order is 213 arbitrary, so the following are all equivalent: 214 215 <<102::integer-native, rest::binary>> 216 <<102::native-integer, rest::binary>> 217 <<102::unsigned-big-integer, rest::binary>> 218 <<102::unsigned-big-integer-size(8), rest::binary>> 219 <<102::unsigned-big-integer-8, rest::binary>> 220 <<102::8-integer-big-unsigned, rest::binary>> 221 <<102, rest::binary>> 222 223 ### Unit and Size 224 225 The length of the match is equal to the `unit` (a number of bits) times the 226 `size` (the number of repeated segments of length `unit`). 227 228 Type | Default Unit 229 --------- | ------------ 230 `integer` | 1 bit 231 `float` | 1 bit 232 `binary` | 8 bits 233 234 Sizes for types are a bit more nuanced. The default size for integers is 8. 235 236 For floats, it is 64. For floats, `size * unit` must result in 16, 32, or 64, 237 corresponding to [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point) 238 binary16, binary32, and binary64, respectively. 239 240 For binaries, the default is the size of the binary. Only the last binary in a 241 match can use the default size. All others must have their size specified 242 explicitly, even if the match is unambiguous. For example: 243 244 iex> <<name::binary-size(5), " the ", species::binary>> = <<"Frank the Walrus">> 245 "Frank the Walrus" 246 iex> {name, species} 247 {"Frank", "Walrus"} 248 249 The size can be a variable: 250 251 iex> name_size = 5 252 iex> <<name::binary-size(name_size), " the ", species::binary>> = <<"Frank the Walrus">> 253 iex> {name, species} 254 {"Frank", "Walrus"} 255 256 And the variable can be defined in the match itself (prior to its use): 257 258 iex> <<name_size::size(8), name::binary-size(name_size), " the ", species::binary>> = <<5, "Frank the Walrus">> 259 iex> {name, species} 260 {"Frank", "Walrus"} 261 262 However, the size cannot be defined in the match outside the binary/bitstring match: 263 264 {name_size, <<name::binary-size(name_size), _rest::binary>>} = {5, <<"Frank the Walrus">>} 265 ** (CompileError): undefined variable "name_size" in bitstring segment 266 267 Failing to specify the size for the non-last causes compilation to fail: 268 269 <<name::binary, " the ", species::binary>> = <<"Frank the Walrus">> 270 ** (CompileError): a binary field without size is only allowed at the end of a binary pattern 271 272 #### Shortcut Syntax 273 274 Size and unit can also be specified using a syntax shortcut 275 when passing integer values: 276 277 iex> x = 1 278 iex> <<x::8>> == <<x::size(8)>> 279 true 280 iex> <<x::8*4>> == <<x::size(8)-unit(4)>> 281 true 282 283 This syntax reflects the fact the effective size is given by 284 multiplying the size by the unit. 285 286 ### Modifiers 287 288 Some types have associated modifiers to clear up ambiguity in byte 289 representation. 290 291 Modifier | Relevant Type(s) 292 -------------------- | ---------------- 293 `signed` | `integer` 294 `unsigned` (default) | `integer` 295 `little` | `integer`, `float`, `utf16`, `utf32` 296 `big` (default) | `integer`, `float`, `utf16`, `utf32` 297 `native` | `integer`, `utf16`, `utf32` 298 299 ### Sign 300 301 Integers can be `signed` or `unsigned`, defaulting to `unsigned`. 302 303 iex> <<int::integer>> = <<-100>> 304 <<156>> 305 iex> int 306 156 307 iex> <<int::integer-signed>> = <<-100>> 308 <<156>> 309 iex> int 310 -100 311 312 `signed` and `unsigned` are only used for matching binaries (see below) and 313 are only used for integers. 314 315 iex> <<-100::signed, _rest::binary>> = <<-100, "foo">> 316 <<156, 102, 111, 111>> 317 318 ### Endianness 319 320 Elixir has three options for endianness: `big`, `little`, and `native`. 321 The default is `big`: 322 323 iex> <<number::little-integer-size(16)>> = <<0, 1>> 324 <<0, 1>> 325 iex> number 326 256 327 iex> <<number::big-integer-size(16)>> = <<0, 1>> 328 <<0, 1>> 329 iex> number 330 1 331 332 `native` is determined by the VM at startup and will depend on the 333 host operating system. 334 335 ## Binary/Bitstring Matching 336 337 Binary matching is a powerful feature in Elixir that is useful for extracting 338 information from binaries as well as pattern matching. 339 340 Binary matching can be used by itself to extract information from binaries: 341 342 iex> <<"Hello, ", place::binary>> = "Hello, World" 343 "Hello, World" 344 iex> place 345 "World" 346 347 Or as a part of function definitions to pattern match: 348 349 defmodule ImageTyper do 350 @png_signature <<137::size(8), 80::size(8), 78::size(8), 71::size(8), 351 13::size(8), 10::size(8), 26::size(8), 10::size(8)>> 352 @jpg_signature <<255::size(8), 216::size(8)>> 353 354 def type(<<@png_signature, _rest::binary>>), do: :png 355 def type(<<@jpg_signature, _rest::binary>>), do: :jpg 356 def type(_), do: :unknown 357 end 358 359 ### Performance & Optimizations 360 361 The Erlang compiler can provide a number of optimizations on binary creation 362 and matching. To see optimization output, set the `bin_opt_info` compiler 363 option: 364 365 ERL_COMPILER_OPTIONS=bin_opt_info mix compile 366 367 To learn more about specific optimizations and performance considerations, 368 check out the 369 ["Constructing and matching binaries" chapter of the Erlang's Efficiency Guide](https://erlang.org/doc/efficiency_guide/binaryhandling.html). 370 """ 371 defmacro unquote(:<<>>)(args), do: error!([args]) 372 373 @doc """ 374 Dot operator. Defines a remote call, a call to an anonymous function, or an alias. 375 376 The dot (`.`) in Elixir can be used for remote calls: 377 378 iex> String.downcase("FOO") 379 "foo" 380 381 In this example above, we have used `.` to invoke `downcase` in the 382 `String` module, passing `"FOO"` as argument. 383 384 The dot may be used to invoke anonymous functions too: 385 386 iex> (fn n -> n end).(7) 387 7 388 389 in which case there is a function on the left hand side. 390 391 We can also use the dot for creating aliases: 392 393 iex> Hello.World 394 Hello.World 395 396 This time, we have joined two aliases, defining the final alias 397 `Hello.World`. 398 399 ## Syntax 400 401 The right side of `.` may be a word starting with an uppercase letter, which represents 402 an alias, a word starting with lowercase or underscore, any valid language 403 operator or any name wrapped in single- or double-quotes. Those are all valid 404 examples: 405 406 iex> Kernel.Sample 407 Kernel.Sample 408 409 iex> Kernel.length([1, 2, 3]) 410 3 411 412 iex> Kernel.+(1, 2) 413 3 414 415 iex> Kernel."+"(1, 2) 416 3 417 418 Wrapping the function name in single- or double-quotes is always a 419 remote call. Therefore `Kernel."Foo"` will attempt to call the function "Foo" 420 and not return the alias `Kernel.Foo`. This is done by design as module names 421 are more strict than function names. 422 423 When the dot is used to invoke an anonymous function there is only one 424 operand, but it is still written using a postfix notation: 425 426 iex> negate = fn n -> -n end 427 iex> negate.(7) 428 -7 429 430 ## Quoted expression 431 432 When `.` is used, the quoted expression may take two distinct 433 forms. When the right side starts with a lowercase letter (or 434 underscore): 435 436 iex> quote do 437 ...> String.downcase("FOO") 438 ...> end 439 {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], ["FOO"]} 440 441 Note that we have an inner tuple, containing the atom `:.` representing 442 the dot as first element: 443 444 {:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]} 445 446 This tuple follows the general quoted expression structure in Elixir, 447 with the name as first argument, some keyword list as metadata as second, 448 and the list of arguments as third. In this case, the arguments are the 449 alias `String` and the atom `:downcase`. The second argument in a remote call 450 is **always** an atom. 451 452 In the case of calls to anonymous functions, the inner tuple with the dot 453 special form has only one argument, reflecting the fact that the operator is 454 unary: 455 456 iex> quote do 457 ...> negate.(0) 458 ...> end 459 {{:., [], [{:negate, [], __MODULE__}]}, [], [0]} 460 461 When the right side is an alias (i.e. starts with uppercase), we get instead: 462 463 iex> quote do 464 ...> Hello.World 465 ...> end 466 {:__aliases__, [alias: false], [:Hello, :World]} 467 468 We go into more details about aliases in the `__aliases__/1` special form 469 documentation. 470 471 ## Unquoting 472 473 We can also use unquote to generate a remote call in a quoted expression: 474 475 iex> x = :downcase 476 iex> quote do 477 ...> String.unquote(x)("FOO") 478 ...> end 479 {{:., [], [{:__aliases__, [alias: false], [:String]}, :downcase]}, [], ["FOO"]} 480 481 Similar to `Kernel."FUNCTION_NAME"`, `unquote(x)` will always generate a remote call, 482 independent of the value of `x`. To generate an alias via the quoted expression, 483 one needs to rely on `Module.concat/2`: 484 485 iex> x = Sample 486 iex> quote do 487 ...> Module.concat(String, unquote(x)) 488 ...> end 489 {{:., [], [{:__aliases__, [alias: false], [:Module]}, :concat]}, [], 490 [{:__aliases__, [alias: false], [:String]}, Sample]} 491 492 """ 493 defmacro unquote(:.)(left, right), do: error!([left, right]) 494 495 @doc """ 496 `alias/2` is used to set up aliases, often useful with modules' names. 497 498 ## Examples 499 500 `alias/2` can be used to set up an alias for any module: 501 502 defmodule Math do 503 alias MyKeyword, as: Keyword 504 end 505 506 In the example above, we have set up `MyKeyword` to be aliased 507 as `Keyword`. So now, any reference to `Keyword` will be 508 automatically replaced by `MyKeyword`. 509 510 In case one wants to access the original `Keyword`, it can be done 511 by accessing `Elixir`: 512 513 Keyword.values #=> uses MyKeyword.values 514 Elixir.Keyword.values #=> uses Keyword.values 515 516 Note that calling `alias` without the `:as` option automatically 517 sets an alias based on the last part of the module. For example: 518 519 alias Foo.Bar.Baz 520 521 Is the same as: 522 523 alias Foo.Bar.Baz, as: Baz 524 525 We can also alias multiple modules in one line: 526 527 alias Foo.{Bar, Baz, Biz} 528 529 Is the same as: 530 531 alias Foo.Bar 532 alias Foo.Baz 533 alias Foo.Biz 534 535 ## Lexical scope 536 537 `import/2`, `require/2` and `alias/2` are called directives and all 538 have lexical scope. This means you can set up aliases inside 539 specific functions and it won't affect the overall scope. 540 541 ## Warnings 542 543 If you alias a module and you don't use the alias, Elixir is 544 going to issue a warning implying the alias is not being used. 545 546 In case the alias is generated automatically by a macro, 547 Elixir won't emit any warnings though, since the alias 548 was not explicitly defined. 549 550 Both warning behaviours could be changed by explicitly 551 setting the `:warn` option to `true` or `false`. 552 553 """ 554 defmacro alias(module, opts), do: error!([module, opts]) 555 556 @doc """ 557 Requires a module in order to use its macros. 558 559 ## Examples 560 561 Public functions in modules are globally available, but in order to use 562 macros, you need to opt-in by requiring the module they are defined in. 563 564 Let's suppose you created your own `if/2` implementation in the module 565 `MyMacros`. If you want to invoke it, you need to first explicitly 566 require the `MyMacros`: 567 568 defmodule Math do 569 require MyMacros 570 MyMacros.if do_something, it_works 571 end 572 573 An attempt to call a macro that was not loaded will raise an error. 574 575 ## Alias shortcut 576 577 `require/2` also accepts `:as` as an option so it automatically sets 578 up an alias. Please check `alias/2` for more information. 579 580 """ 581 defmacro require(module, opts), do: error!([module, opts]) 582 583 @doc """ 584 Imports functions and macros from other modules. 585 586 `import/2` allows one to easily access functions or macros from 587 other modules without using the qualified name. 588 589 ## Examples 590 591 If you are using several functions from a given module, you can 592 import those functions and reference them as local functions, 593 for example: 594 595 iex> import List 596 iex> flatten([1, [2], 3]) 597 [1, 2, 3] 598 599 ## Selector 600 601 By default, Elixir imports functions and macros from the given 602 module, except the ones starting with an underscore (which are 603 usually callbacks): 604 605 import List 606 607 A developer can filter to import only macros or functions via 608 the only option: 609 610 import List, only: :functions 611 import List, only: :macros 612 613 Alternatively, Elixir allows a developer to pass pairs of 614 name/arities to `:only` or `:except` as a fine grained control 615 on what to import (or not): 616 617 import List, only: [flatten: 1] 618 import String, except: [split: 2] 619 620 Importing the same module again will erase the previous imports, 621 except when the `except` option is used, which is always exclusive 622 on a previously declared `import/2`. If there is no previous import, 623 then it applies to all functions and macros in the module. For 624 example: 625 626 import List, only: [flatten: 1, keyfind: 4] 627 import List, except: [flatten: 1] 628 629 After the two import calls above, only `List.keyfind/4` will be 630 imported. 631 632 ## Underscore functions 633 634 By default functions starting with `_` are not imported. If you really want 635 to import a function starting with `_` you must explicitly include it in the 636 `:only` selector. 637 638 import File.Stream, only: [__build__: 3] 639 640 ## Lexical scope 641 642 It is important to note that `import/2` is lexical. This means you 643 can import specific macros inside specific functions: 644 645 defmodule Math do 646 def some_function do 647 # 1) Disable "if/2" from Kernel 648 import Kernel, except: [if: 2] 649 650 # 2) Require the new "if/2" macro from MyMacros 651 import MyMacros 652 653 # 3) Use the new macro 654 if do_something, it_works 655 end 656 end 657 658 In the example above, we imported macros from `MyMacros`, 659 replacing the original `if/2` implementation by our own 660 within that specific function. All other functions in that 661 module will still be able to use the original one. 662 663 ## Warnings 664 665 If you import a module and you don't use any of the imported 666 functions or macros from this module, Elixir is going to issue 667 a warning implying the import is not being used. 668 669 In case the import is generated automatically by a macro, 670 Elixir won't emit any warnings though, since the import 671 was not explicitly defined. 672 673 Both warning behaviours could be changed by explicitly 674 setting the `:warn` option to `true` or `false`. 675 676 ## Ambiguous function/macro names 677 678 If two modules `A` and `B` are imported and they both contain 679 a `foo` function with an arity of `1`, an error is only emitted 680 if an ambiguous call to `foo/1` is actually made; that is, the 681 errors are emitted lazily, not eagerly. 682 """ 683 defmacro import(module, opts), do: error!([module, opts]) 684 685 @doc """ 686 Returns the current environment information as a `Macro.Env` struct. 687 688 In the environment you can access the current filename, 689 line numbers, set up aliases, the current function and others. 690 """ 691 defmacro __ENV__, do: error!([]) 692 693 @doc """ 694 Returns the current module name as an atom or `nil` otherwise. 695 696 Although the module can be accessed in the `__ENV__/0`, this macro 697 is a convenient shortcut. 698 """ 699 defmacro __MODULE__, do: error!([]) 700 701 @doc """ 702 Returns the absolute path of the directory of the current file as a binary. 703 704 Although the directory can be accessed as `Path.dirname(__ENV__.file)`, 705 this macro is a convenient shortcut. 706 """ 707 defmacro __DIR__, do: error!([]) 708 709 @doc """ 710 Returns the current calling environment as a `Macro.Env` struct. 711 712 In the environment you can access the filename, line numbers, 713 set up aliases, the function and others. 714 """ 715 defmacro __CALLER__, do: error!([]) 716 717 @doc """ 718 Returns the stacktrace for the currently handled exception. 719 720 It is available only in the `catch` and `rescue` clauses of `try/1` 721 expressions. 722 723 To retrieve the stacktrace of the current process, use 724 `Process.info(self(), :current_stacktrace)` instead. 725 """ 726 @doc since: "1.7.0" 727 defmacro __STACKTRACE__, do: error!([]) 728 729 @doc """ 730 Pin operator. Accesses an already bound variable in match clauses. 731 732 ## Examples 733 734 Elixir allows variables to be rebound via static single assignment: 735 736 iex> x = 1 737 iex> x = x + 1 738 iex> x 739 2 740 741 However, in some situations, it is useful to match against an existing 742 value, instead of rebinding. This can be done with the `^` special form, 743 colloquially known as the pin operator: 744 745 iex> x = 1 746 iex> ^x = List.first([1]) 747 iex> ^x = List.first([2]) 748 ** (MatchError) no match of right hand side value: 2 749 750 Note that `^x` always refers to the value of `x` prior to the match. The 751 following example will match: 752 753 iex> x = 0 754 iex> {x, ^x} = {1, 0} 755 iex> x 756 1 757 758 """ 759 defmacro ^var, do: error!([var]) 760 761 @doc """ 762 Match operator. Matches the value on the right against the pattern on the left. 763 """ 764 defmacro left = right, do: error!([left, right]) 765 766 @doc """ 767 Type operator. Used by types and bitstrings to specify types. 768 769 This operator is used in two distinct occasions in Elixir. 770 It is used in typespecs to specify the type of a variable, 771 function or of a type itself: 772 773 @type number :: integer | float 774 @spec add(number, number) :: number 775 776 It may also be used in bit strings to specify the type 777 of a given bit segment: 778 779 <<int::integer-little, rest::bits>> = bits 780 781 Read the documentation on the `Typespec` page and 782 `<<>>/1` for more information on typespecs and 783 bitstrings respectively. 784 """ 785 defmacro left :: right, do: error!([left, right]) 786 787 @doc ~S""" 788 Gets the representation of any expression. 789 790 ## Examples 791 792 iex> quote do 793 ...> sum(1, 2, 3) 794 ...> end 795 {:sum, [], [1, 2, 3]} 796 797 ## Elixir's AST (Abstract Syntax Tree) 798 799 Any Elixir code can be represented using Elixir data structures. 800 The building block of Elixir macros is a tuple with three elements, 801 for example: 802 803 {:sum, [], [1, 2, 3]} 804 805 The tuple above represents a function call to `sum` passing 1, 2 and 806 3 as arguments. The tuple elements are: 807 808 * The first element of the tuple is always an atom or 809 another tuple in the same representation. 810 811 * The second element of the tuple represents [metadata](`t:Macro.metadata/0`). 812 813 * The third element of the tuple are the arguments for the 814 function call. The third argument may be an atom, which is 815 usually a variable (or a local call). 816 817 Besides the tuple described above, Elixir has a few literals that 818 are also part of its AST. Those literals return themselves when 819 quoted. They are: 820 821 :sum #=> Atoms 822 1 #=> Integers 823 2.0 #=> Floats 824 [1, 2] #=> Lists 825 "strings" #=> Strings 826 {key, value} #=> Tuples with two elements 827 828 Any other value, such as a map or a four-element tuple, must be escaped 829 (`Macro.escape/1`) before being introduced into an AST. 830 831 ## Options 832 833 * `:bind_quoted` - passes a binding to the macro. Whenever a binding is 834 given, `unquote/1` is automatically disabled. 835 836 * `:context` - sets the resolution context. 837 838 * `:generated` - marks the given chunk as generated so it does not emit warnings. 839 Currently it only works on special forms (for example, you can annotate a `case` 840 but not an `if`). 841 842 * `:file` - sets the quoted expressions to have the given file. 843 844 * `:line` - sets the quoted expressions to have the given line. 845 846 * `:location` - when set to `:keep`, keeps the current line and file from 847 quote. Read the "Stacktrace information" section below for more information. 848 849 * `:unquote` - when `false`, disables unquoting. This means any `unquote` 850 call will be kept as is in the AST, instead of replaced by the `unquote` 851 arguments. For example: 852 853 iex> quote do 854 ...> unquote("hello") 855 ...> end 856 "hello" 857 858 iex> quote unquote: false do 859 ...> unquote("hello") 860 ...> end 861 {:unquote, [], ["hello"]} 862 863 ## Quote and macros 864 865 `quote/2` is commonly used with macros for code generation. As an exercise, 866 let's define a macro that multiplies a number by itself (squared). In practice, 867 there is no reason to define such a macro (and it would actually be 868 seen as a bad practice), but it is simple enough that it allows us to focus 869 on the important aspects of quotes and macros: 870 871 defmodule Math do 872 defmacro squared(x) do 873 quote do 874 unquote(x) * unquote(x) 875 end 876 end 877 end 878 879 We can invoke it as: 880 881 import Math 882 IO.puts("Got #{squared(5)}") 883 884 At first, there is nothing in this example that actually reveals it is a 885 macro. But what is happening is that, at compilation time, `squared(5)` 886 becomes `5 * 5`. The argument `5` is duplicated in the produced code, we 887 can see this behaviour in practice though because our macro actually has 888 a bug: 889 890 import Math 891 my_number = fn -> 892 IO.puts("Returning 5") 893 5 894 end 895 IO.puts("Got #{squared(my_number.())}") 896 897 The example above will print: 898 899 Returning 5 900 Returning 5 901 Got 25 902 903 Notice how "Returning 5" was printed twice, instead of just once. This is 904 because a macro receives an expression and not a value (which is what we 905 would expect in a regular function). This means that: 906 907 squared(my_number.()) 908 909 Actually expands to: 910 911 my_number.() * my_number.() 912 913 Which invokes the function twice, explaining why we get the printed value 914 twice! In the majority of the cases, this is actually unexpected behaviour, 915 and that's why one of the first things you need to keep in mind when it 916 comes to macros is to **not unquote the same value more than once**. 917 918 Let's fix our macro: 919 920 defmodule Math do 921 defmacro squared(x) do 922 quote do 923 x = unquote(x) 924 x * x 925 end 926 end 927 end 928 929 Now invoking `squared(my_number.())` as before will print the value just 930 once. 931 932 In fact, this pattern is so common that most of the times you will want 933 to use the `bind_quoted` option with `quote/2`: 934 935 defmodule Math do 936 defmacro squared(x) do 937 quote bind_quoted: [x: x] do 938 x * x 939 end 940 end 941 end 942 943 `:bind_quoted` will translate to the same code as the example above. 944 `:bind_quoted` can be used in many cases and is seen as good practice, 945 not only because it helps prevent us from running into common mistakes, but also 946 because it allows us to leverage other tools exposed by macros, such as 947 unquote fragments discussed in some sections below. 948 949 Before we finish this brief introduction, you will notice that, even though 950 we defined a variable `x` inside our quote: 951 952 quote do 953 x = unquote(x) 954 x * x 955 end 956 957 When we call: 958 959 import Math 960 squared(5) 961 x 962 ** (CompileError) undefined variable x or undefined function x/0 963 964 We can see that `x` did not leak to the user context. This happens 965 because Elixir macros are hygienic, a topic we will discuss at length 966 in the next sections as well. 967 968 ## Hygiene in variables 969 970 Consider the following example: 971 972 defmodule Hygiene do 973 defmacro no_interference do 974 quote do 975 a = 1 976 end 977 end 978 end 979 980 require Hygiene 981 982 a = 10 983 Hygiene.no_interference() 984 a 985 #=> 10 986 987 In the example above, `a` returns 10 even if the macro 988 is apparently setting it to 1 because variables defined 989 in the macro do not affect the context the macro is executed in. 990 If you want to set or get a variable in the caller's context, you 991 can do it with the help of the `var!` macro: 992 993 defmodule NoHygiene do 994 defmacro interference do 995 quote do 996 var!(a) = 1 997 end 998 end 999 end 1000 1001 require NoHygiene 1002 1003 a = 10 1004 NoHygiene.interference() 1005 a 1006 #=> 1 1007 1008 You cannot even access variables defined in the same module unless 1009 you explicitly give it a context: 1010 1011 defmodule Hygiene do 1012 defmacro write do 1013 quote do 1014 a = 1 1015 end 1016 end 1017 1018 defmacro read do 1019 quote do 1020 a 1021 end 1022 end 1023 end 1024 1025 Hygiene.write() 1026 Hygiene.read() 1027 ** (RuntimeError) undefined variable a or undefined function a/0 1028 1029 For such, you can explicitly pass the current module scope as 1030 argument: 1031 1032 defmodule ContextHygiene do 1033 defmacro write do 1034 quote do 1035 var!(a, ContextHygiene) = 1 1036 end 1037 end 1038 1039 defmacro read do 1040 quote do 1041 var!(a, ContextHygiene) 1042 end 1043 end 1044 end 1045 1046 ContextHygiene.write() 1047 ContextHygiene.read() 1048 #=> 1 1049 1050 ## Hygiene in aliases 1051 1052 Aliases inside quote are hygienic by default. 1053 Consider the following example: 1054 1055 defmodule Hygiene do 1056 alias Map, as: M 1057 1058 defmacro no_interference do 1059 quote do 1060 M.new() 1061 end 1062 end 1063 end 1064 1065 require Hygiene 1066 Hygiene.no_interference() 1067 #=> %{} 1068 1069 Note that, even though the alias `M` is not available 1070 in the context the macro is expanded, the code above works 1071 because `M` still expands to `Map`. 1072 1073 Similarly, even if we defined an alias with the same name 1074 before invoking a macro, it won't affect the macro's result: 1075 1076 defmodule Hygiene do 1077 alias Map, as: M 1078 1079 defmacro no_interference do 1080 quote do 1081 M.new() 1082 end 1083 end 1084 end 1085 1086 require Hygiene 1087 alias SomethingElse, as: M 1088 Hygiene.no_interference() 1089 #=> %{} 1090 1091 In some cases, you want to access an alias or a module defined 1092 in the caller. For such, you can use the `alias!` macro: 1093 1094 defmodule Hygiene do 1095 # This will expand to Elixir.Nested.hello() 1096 defmacro no_interference do 1097 quote do 1098 Nested.hello() 1099 end 1100 end 1101 1102 # This will expand to Nested.hello() for 1103 # whatever is Nested in the caller 1104 defmacro interference do 1105 quote do 1106 alias!(Nested).hello() 1107 end 1108 end 1109 end 1110 1111 defmodule Parent do 1112 defmodule Nested do 1113 def hello, do: "world" 1114 end 1115 1116 require Hygiene 1117 Hygiene.no_interference() 1118 ** (UndefinedFunctionError) ... 1119 1120 Hygiene.interference() 1121 #=> "world" 1122 end 1123 1124 ## Hygiene in imports 1125 1126 Similar to aliases, imports in Elixir are hygienic. Consider the 1127 following code: 1128 1129 defmodule Hygiene do 1130 defmacrop get_length do 1131 quote do 1132 length([1, 2, 3]) 1133 end 1134 end 1135 1136 def return_length do 1137 import Kernel, except: [length: 1] 1138 get_length 1139 end 1140 end 1141 1142 Hygiene.return_length() 1143 #=> 3 1144 1145 Notice how `Hygiene.return_length/0` returns `3` even though the `Kernel.length/1` 1146 function is not imported. In fact, even if `return_length/0` 1147 imported a function with the same name and arity from another 1148 module, it wouldn't affect the function result: 1149 1150 def return_length do 1151 import String, only: [length: 1] 1152 get_length 1153 end 1154 1155 Calling this new `return_length/0` will still return `3` as result. 1156 1157 Elixir is smart enough to delay the resolution to the latest 1158 possible moment. So, if you call `length([1, 2, 3])` inside quote, 1159 but no `length/1` function is available, it is then expanded in 1160 the caller: 1161 1162 defmodule Lazy do 1163 defmacrop get_length do 1164 import Kernel, except: [length: 1] 1165 1166 quote do 1167 length("hello") 1168 end 1169 end 1170 1171 def return_length do 1172 import Kernel, except: [length: 1] 1173 import String, only: [length: 1] 1174 get_length 1175 end 1176 end 1177 1178 Lazy.return_length() 1179 #=> 5 1180 1181 ## Stacktrace information 1182 1183 When defining functions via macros, developers have the option of 1184 choosing if runtime errors will be reported from the caller or from 1185 inside the quote. Let's see an example: 1186 1187 # adder.ex 1188 defmodule Adder do 1189 @doc "Defines a function that adds two numbers" 1190 defmacro defadd do 1191 quote location: :keep do 1192 def add(a, b), do: a + b 1193 end 1194 end 1195 end 1196 1197 # sample.ex 1198 defmodule Sample do 1199 import Adder 1200 defadd 1201 end 1202 1203 require Sample 1204 Sample.add(:one, :two) 1205 ** (ArithmeticError) bad argument in arithmetic expression 1206 adder.ex:5: Sample.add/2 1207 1208 When using `location: :keep` and invalid arguments are given to 1209 `Sample.add/2`, the stacktrace information will point to the file 1210 and line inside the quote. Without `location: :keep`, the error is 1211 reported to where `defadd` was invoked. `location: :keep` affects 1212 only definitions inside the quote. 1213 1214 > **Important:** do not use location: :keep if the function definition 1215 > also `unquote`s some of the macro arguments. If you do so, Elixir 1216 > will store the file definition of the current location but the 1217 > unquoted arguments may contain line information of the macro caller, 1218 > leading to erroneous stacktraces. 1219 1220 ## Binding and unquote fragments 1221 1222 Elixir quote/unquote mechanisms provide a functionality called 1223 unquote fragments. Unquote fragments provide an easy way to generate 1224 functions on the fly. Consider this example: 1225 1226 kv = [foo: 1, bar: 2] 1227 Enum.each(kv, fn {k, v} -> 1228 def unquote(k)(), do: unquote(v) 1229 end) 1230 1231 In the example above, we have generated the functions `foo/0` and 1232 `bar/0` dynamically. Now, imagine that we want to convert this 1233 functionality into a macro: 1234 1235 defmacro defkv(kv) do 1236 Enum.map(kv, fn {k, v} -> 1237 quote do 1238 def unquote(k)(), do: unquote(v) 1239 end 1240 end) 1241 end 1242 1243 We can invoke this macro as: 1244 1245 defkv [foo: 1, bar: 2] 1246 1247 However, we can't invoke it as follows: 1248 1249 kv = [foo: 1, bar: 2] 1250 defkv kv 1251 1252 This is because the macro is expecting its arguments to be a 1253 keyword list at **compilation** time. Since in the example above 1254 we are passing the representation of the variable `kv`, our 1255 code fails. 1256 1257 This is actually a common pitfall when developing macros. We are 1258 assuming a particular shape in the macro. We can work around it 1259 by unquoting the variable inside the quoted expression: 1260 1261 defmacro defkv(kv) do 1262 quote do 1263 Enum.each(unquote(kv), fn {k, v} -> 1264 def unquote(k)(), do: unquote(v) 1265 end) 1266 end 1267 end 1268 1269 If you try to run our new macro, you will notice it won't 1270 even compile, complaining that the variables `k` and `v` 1271 do not exist. This is because of the ambiguity: `unquote(k)` 1272 can either be an unquote fragment, as previously, or a regular 1273 unquote as in `unquote(kv)`. 1274 1275 One solution to this problem is to disable unquoting in the 1276 macro, however, doing that would make it impossible to inject the 1277 `kv` representation into the tree. That's when the `:bind_quoted` 1278 option comes to the rescue (again!). By using `:bind_quoted`, we 1279 can automatically disable unquoting while still injecting the 1280 desired variables into the tree: 1281 1282 defmacro defkv(kv) do 1283 quote bind_quoted: [kv: kv] do 1284 Enum.each(kv, fn {k, v} -> 1285 def unquote(k)(), do: unquote(v) 1286 end) 1287 end 1288 end 1289 1290 In fact, the `:bind_quoted` option is recommended every time 1291 one desires to inject a value into the quote. 1292 """ 1293 defmacro quote(opts, block), do: error!([opts, block]) 1294 1295 @doc """ 1296 Unquotes the given expression inside a quoted expression. 1297 1298 This function expects a valid Elixir AST, also known as 1299 quoted expression, as argument. If you would like to `unquote` 1300 any value, such as a map or a four-element tuple, you should 1301 call `Macro.escape/1` before unquoting. 1302 1303 ## Examples 1304 1305 Imagine the situation you have a quoted expression and 1306 you want to inject it inside some quote. The first attempt 1307 would be: 1308 1309 value = 1310 quote do 1311 13 1312 end 1313 1314 quote do 1315 sum(1, value, 3) 1316 end 1317 1318 Which would then return: 1319 1320 {:sum, [], [1, {:value, [], Elixir}, 3]} 1321 1322 Which is not the expected result. For this, we use `unquote`: 1323 1324 iex> value = 1325 ...> quote do 1326 ...> 13 1327 ...> end 1328 iex> quote do 1329 ...> sum(1, unquote(value), 3) 1330 ...> end 1331 {:sum, [], [1, 13, 3]} 1332 1333 If you want to unquote a value that is not a quoted expression, 1334 such as a map, you need to call `Macro.escape/1` before: 1335 1336 iex> value = %{foo: :bar} 1337 iex> quote do 1338 ...> process_map(unquote(Macro.escape(value))) 1339 ...> end 1340 {:process_map, [], [{:%{}, [], [foo: :bar]}]} 1341 1342 If you forget to escape it, Elixir will raise an error 1343 when compiling the code. 1344 """ 1345 defmacro unquote(:unquote)(expr), do: error!([expr]) 1346 1347 @doc """ 1348 Unquotes the given list expanding its arguments. 1349 1350 Similar to `unquote/1`. 1351 1352 ## Examples 1353 1354 iex> values = [2, 3, 4] 1355 iex> quote do 1356 ...> sum(1, unquote_splicing(values), 5) 1357 ...> end 1358 {:sum, [], [1, 2, 3, 4, 5]} 1359 1360 """ 1361 defmacro unquote(:unquote_splicing)(expr), do: error!([expr]) 1362 1363 @doc ~S""" 1364 Comprehensions allow you to quickly build a data structure from 1365 an enumerable or a bitstring. 1366 1367 Let's start with an example: 1368 1369 iex> for n <- [1, 2, 3, 4], do: n * 2 1370 [2, 4, 6, 8] 1371 1372 A comprehension accepts many generators and filters. Enumerable 1373 generators are defined using `<-`: 1374 1375 # A list generator: 1376 iex> for n <- [1, 2, 3, 4], do: n * 2 1377 [2, 4, 6, 8] 1378 1379 # A comprehension with two generators 1380 iex> for x <- [1, 2], y <- [2, 3], do: x * y 1381 [2, 3, 4, 6] 1382 1383 Filters can also be given: 1384 1385 # A comprehension with a generator and a filter 1386 iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n 1387 [2, 4, 6] 1388 1389 Generators can also be used to filter as it removes any value 1390 that doesn't match the pattern on the left side of `<-`: 1391 1392 iex> users = [user: "john", admin: "meg", guest: "barbara"] 1393 iex> for {type, name} when type != :guest <- users do 1394 ...> String.upcase(name) 1395 ...> end 1396 ["JOHN", "MEG"] 1397 1398 Bitstring generators are also supported and are very useful when you 1399 need to organize bitstring streams: 1400 1401 iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>> 1402 iex> for <<r::8, g::8, b::8 <- pixels>>, do: {r, g, b} 1403 [{213, 45, 132}, {64, 76, 32}, {76, 0, 0}, {234, 32, 15}] 1404 1405 Variable assignments inside the comprehension, be it in generators, 1406 filters or inside the block, are not reflected outside of the 1407 comprehension. 1408 1409 ## The `:into` and `:uniq` options 1410 1411 In the examples above, the result returned by the comprehension was 1412 always a list. The returned result can be configured by passing an 1413 `:into` option, that accepts any structure as long as it implements 1414 the `Collectable` protocol. 1415 1416 For example, we can use bitstring generators with the `:into` option 1417 to easily remove all spaces in a string: 1418 1419 iex> for <<c <- " hello world ">>, c != ?\s, into: "", do: <<c>> 1420 "helloworld" 1421 1422 The `IO` module provides streams, that are both `Enumerable` and 1423 `Collectable`, here is an upcase echo server using comprehensions: 1424 1425 for line <- IO.stream(), into: IO.stream() do 1426 String.upcase(line) 1427 end 1428 1429 Similarly, `uniq: true` can also be given to comprehensions to guarantee 1430 the results are only added to the collection if they were not returned 1431 before. For example: 1432 1433 iex> for x <- [1, 1, 2, 3], uniq: true, do: x * 2 1434 [2, 4, 6] 1435 1436 iex> for <<x <- "abcabc">>, uniq: true, into: "", do: <<x - 32>> 1437 "ABC" 1438 1439 ## The `:reduce` option 1440 1441 While the `:into` option allows us to customize the comprehension behaviour 1442 to a given data type, such as putting all of the values inside a map or inside 1443 a binary, it is not always enough. 1444 1445 For example, imagine that you have a binary with letters where you want to 1446 count how many times each lowercase letter happens, ignoring all uppercase 1447 ones. For instance, for the string `"AbCabCABc"`, we want to return the map 1448 `%{"a" => 1, "b" => 2, "c" => 1}`. 1449 1450 If we were to use `:into`, we would need a data type that computes the 1451 frequency of each element it holds. While there is no such data type in 1452 Elixir, you could implement one yourself. 1453 1454 A simpler option would be to use comprehensions for the mapping and 1455 filtering of letters, and then we invoke `Enum.reduce/3` to build a map, 1456 for example: 1457 1458 iex> letters = for <<x <- "AbCabCABc">>, x in ?a..?z, do: <<x>> 1459 iex> Enum.reduce(letters, %{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end) 1460 %{"a" => 1, "b" => 2, "c" => 1} 1461 1462 While the above is straight-forward, it has the downside of traversing the 1463 data at least twice. If you are expecting long strings as inputs, this can 1464 be quite expensive. 1465 1466 Luckily, comprehensions also support the `:reduce` option, which would allow 1467 us to fuse both steps above into a single step: 1468 1469 iex> for <<x <- "AbCabCABc">>, x in ?a..?z, reduce: %{} do 1470 ...> acc -> Map.update(acc, <<x>>, 1, & &1 + 1) 1471 ...> end 1472 %{"a" => 1, "b" => 2, "c" => 1} 1473 1474 When the `:reduce` key is given, its value is used as the initial accumulator 1475 and the `do` block must be changed to use `->` clauses, where the left side 1476 of `->` receives the accumulated value of the previous iteration and the 1477 expression on the right side must return the new accumulator value. Once there are no more 1478 elements, the final accumulated value is returned. If there are no elements 1479 at all, then the initial accumulator value is returned. 1480 """ 1481 defmacro for(args), do: error!([args]) 1482 1483 @doc """ 1484 Used to combine matching clauses. 1485 1486 Let's start with an example: 1487 1488 iex> opts = %{width: 10, height: 15} 1489 iex> with {:ok, width} <- Map.fetch(opts, :width), 1490 ...> {:ok, height} <- Map.fetch(opts, :height) do 1491 ...> {:ok, width * height} 1492 ...> end 1493 {:ok, 150} 1494 1495 If all clauses match, the `do` block is executed, returning its result. 1496 Otherwise the chain is aborted and the non-matched value is returned: 1497 1498 iex> opts = %{width: 10} 1499 iex> with {:ok, width} <- Map.fetch(opts, :width), 1500 ...> {:ok, height} <- Map.fetch(opts, :height) do 1501 ...> {:ok, width * height} 1502 ...> end 1503 :error 1504 1505 Guards can be used in patterns as well: 1506 1507 iex> users = %{"melany" => "guest", "bob" => :admin} 1508 iex> with {:ok, role} when not is_binary(role) <- Map.fetch(users, "bob") do 1509 ...> {:ok, to_string(role)} 1510 ...> end 1511 {:ok, "admin"} 1512 1513 As in `for/1`, variables bound inside `with/1` won't leak. 1514 Expressions without `<-` may also be used in clauses. For instance, 1515 you can perform regular matches with the `=` operator: 1516 1517 iex> width = nil 1518 iex> opts = %{width: 10, height: 15} 1519 iex> with {:ok, width} <- Map.fetch(opts, :width), 1520 ...> double_width = width * 2, 1521 ...> {:ok, height} <- Map.fetch(opts, :height) do 1522 ...> {:ok, double_width * height} 1523 ...> end 1524 {:ok, 300} 1525 iex> width 1526 nil 1527 1528 The behaviour of any expression in a clause is the same as if it was 1529 written outside of `with`. For example, `=` will raise a `MatchError` 1530 instead of returning the non-matched value: 1531 1532 with :foo = :bar, do: :ok 1533 ** (MatchError) no match of right hand side value: :bar 1534 1535 As with any other function or macro call in Elixir, explicit parens can 1536 also be used around the arguments before the `do`-`end` block: 1537 1538 iex> opts = %{width: 10, height: 15} 1539 iex> with( 1540 ...> {:ok, width} <- Map.fetch(opts, :width), 1541 ...> {:ok, height} <- Map.fetch(opts, :height) 1542 ...> ) do 1543 ...> {:ok, width * height} 1544 ...> end 1545 {:ok, 150} 1546 1547 The choice between parens and no parens is a matter of preference. 1548 1549 ## Else clauses 1550 1551 An `else` option can be given to modify what is being returned from 1552 `with` in the case of a failed match: 1553 1554 iex> opts = %{width: 10} 1555 iex> with {:ok, width} <- Map.fetch(opts, :width), 1556 ...> {:ok, height} <- Map.fetch(opts, :height) do 1557 ...> {:ok, width * height} 1558 ...> else 1559 ...> :error -> 1560 ...> {:error, :wrong_data} 1561 ...> 1562 ...> _other_error -> 1563 ...> :unexpected_error 1564 ...> end 1565 {:error, :wrong_data} 1566 1567 The `else` block works like a `case` clause: it can have multiple clauses, 1568 and the first match will be used. Variables bound inside `with` (such as 1569 `width` in this example) are not available in the `else` block. 1570 1571 If an `else` block is used and there are no matching clauses, a `WithClauseError` 1572 exception is raised. 1573 1574 ### Beware! 1575 1576 Keep in mind that, one of potential drawback of `with` is that all 1577 failure clauses are flattened into a single `else` block. For example, 1578 take this code that checks if a given path points to an Elixir file 1579 and that it exists before creating a backup copy: 1580 1581 with ".ex" <- Path.extname(path), 1582 true <- File.exists?(path) do 1583 backup_path = path <> ".backup" 1584 File.cp!(path, backup_path) 1585 {:ok, backup_path} 1586 else 1587 binary when is_binary(binary) -> 1588 {:error, :invalid_extension} 1589 1590 false -> 1591 {:error, :missing_file} 1592 end 1593 1594 Note how we are having to reconstruct the result types of `Path.extname/1` 1595 and `File.exists?/1` to build error messages. In this case, it is better 1596 to change the with clauses to already return the desired format, like this: 1597 1598 with :ok <- validate_extension(path), 1599 :ok <- validate_exists(path) do 1600 backup_path = path <> ".backup" 1601 File.cp!(path, backup_path) 1602 {:ok, backup_path} 1603 end 1604 1605 defp validate_extname(path) do 1606 if Path.extname(path) == ".ex", do: :ok, else: {:error, :invalid_extension} 1607 end 1608 1609 defp validate_exists(path) do 1610 if File.exists?(path), do: :ok, else: {:error, :missing_file} 1611 end 1612 1613 Note how the code above is better organized and clearer once we 1614 make sure each clause in `with` returns a normalize format. 1615 """ 1616 defmacro with(args), do: error!([args]) 1617 1618 @doc """ 1619 Defines an anonymous function. 1620 1621 See `Function` for more information. 1622 1623 ## Examples 1624 1625 iex> add = fn a, b -> a + b end 1626 iex> add.(1, 2) 1627 3 1628 1629 Anonymous functions can also have multiple clauses. All clauses 1630 should expect the same number of arguments: 1631 1632 iex> negate = fn 1633 ...> true -> false 1634 ...> false -> true 1635 ...> end 1636 iex> negate.(false) 1637 true 1638 1639 """ 1640 defmacro unquote(:fn)(clauses), do: error!([clauses]) 1641 1642 @doc """ 1643 Internal special form for block expressions. 1644 1645 This is the special form used whenever we have a block 1646 of expressions in Elixir. This special form is private 1647 and should not be invoked directly: 1648 1649 iex> quote do 1650 ...> 1 1651 ...> 2 1652 ...> 3 1653 ...> end 1654 {:__block__, [], [1, 2, 3]} 1655 1656 """ 1657 defmacro unquote(:__block__)(args), do: error!([args]) 1658 1659 @doc """ 1660 Capture operator. Captures or creates an anonymous function. 1661 1662 ## Capture 1663 1664 The capture operator is most commonly used to capture a 1665 function with given name and arity from a module: 1666 1667 iex> fun = &Kernel.is_atom/1 1668 iex> fun.(:atom) 1669 true 1670 iex> fun.("string") 1671 false 1672 1673 In the example above, we captured `Kernel.is_atom/1` as an 1674 anonymous function and then invoked it. 1675 1676 The capture operator can also be used to capture local functions, 1677 including private ones, and imported functions by omitting the 1678 module name: 1679 1680 &local_function/1 1681 1682 See also `Function.capture/3`. 1683 1684 ## Anonymous functions 1685 1686 The capture operator can also be used to partially apply 1687 functions, where `&1`, `&2` and so on can be used as value 1688 placeholders. For example: 1689 1690 iex> double = &(&1 * 2) 1691 iex> double.(2) 1692 4 1693 1694 In other words, `&(&1 * 2)` is equivalent to `fn x -> x * 2 end`. 1695 1696 We can partially apply a remote function with placeholder: 1697 1698 iex> take_five = &Enum.take(&1, 5) 1699 iex> take_five.(1..10) 1700 [1, 2, 3, 4, 5] 1701 1702 Another example while using an imported or local function: 1703 1704 iex> first_elem = &elem(&1, 0) 1705 iex> first_elem.({0, 1}) 1706 0 1707 1708 The `&` operator can be used with more complex expressions: 1709 1710 iex> fun = &(&1 + &2 + &3) 1711 iex> fun.(1, 2, 3) 1712 6 1713 1714 As well as with lists and tuples: 1715 1716 iex> fun = &{&1, &2} 1717 iex> fun.(1, 2) 1718 {1, 2} 1719 1720 iex> fun = &[&1 | &2] 1721 iex> fun.(1, [2, 3]) 1722 [1, 2, 3] 1723 1724 The only restrictions when creating anonymous functions is that at 1725 least one placeholder must be present, i.e. it must contain at least 1726 `&1`, and that block expressions are not supported: 1727 1728 # No placeholder, fails to compile. 1729 &(:foo) 1730 1731 # Block expression, fails to compile. 1732 &(&1; &2) 1733 1734 """ 1735 defmacro unquote(:&)(expr), do: error!([expr]) 1736 1737 @doc """ 1738 Internal special form to hold aliases information. 1739 1740 It is usually compiled to an atom: 1741 1742 iex> quote do 1743 ...> Foo.Bar 1744 ...> end 1745 {:__aliases__, [alias: false], [:Foo, :Bar]} 1746 1747 Elixir represents `Foo.Bar` as `__aliases__` so calls can be 1748 unambiguously identified by the operator `:.`. For example: 1749 1750 iex> quote do 1751 ...> Foo.bar() 1752 ...> end 1753 {{:., [], [{:__aliases__, [alias: false], [:Foo]}, :bar]}, [], []} 1754 1755 Whenever an expression iterator sees a `:.` as the tuple key, 1756 it can be sure that it represents a call and the second argument 1757 in the list is an atom. 1758 1759 On the other hand, aliases hold some properties: 1760 1761 1. The head element of aliases can be any term that must expand to 1762 an atom at compilation time. 1763 1764 2. The tail elements of aliases are guaranteed to always be atoms. 1765 1766 3. When the head element of aliases is the atom `:Elixir`, no expansion happens. 1767 1768 """ 1769 defmacro unquote(:__aliases__)(args), do: error!([args]) 1770 1771 @doc """ 1772 Calls the overridden function when overriding it with `Kernel.defoverridable/1`. 1773 1774 See `Kernel.defoverridable/1` for more information and documentation. 1775 """ 1776 defmacro super(args), do: error!([args]) 1777 1778 @doc ~S""" 1779 Matches the given expression against the given clauses. 1780 1781 ## Examples 1782 1783 case File.read(file) do 1784 {:ok, contents} when is_binary(contents) -> 1785 String.split(contents, "\n") 1786 1787 {:error, _reason} -> 1788 Logger.warning "could not find #{file}, assuming empty..." 1789 [] 1790 end 1791 1792 In the example above, we match the result of `File.read/1` 1793 against each clause "head" and execute the clause "body" 1794 corresponding to the first clause that matches. 1795 1796 If no clause matches, an error is raised. For this reason, 1797 it may be necessary to add a final catch-all clause (like `_`) 1798 which will always match. 1799 1800 x = 10 1801 1802 case x do 1803 0 -> 1804 "This clause won't match" 1805 1806 _ -> 1807 "This clause would match any value (x = #{x})" 1808 end 1809 #=> "This clause would match any value (x = 10)" 1810 1811 ## Variable handling 1812 1813 Note that variables bound in a clause do not leak to the outer context: 1814 1815 case data do 1816 {:ok, value} -> value 1817 :error -> nil 1818 end 1819 1820 value 1821 #=> unbound variable value 1822 1823 Variables in the outer context cannot be overridden either: 1824 1825 value = 7 1826 1827 case lucky? do 1828 false -> value = 13 1829 true -> true 1830 end 1831 1832 value 1833 #=> 7 1834 1835 In the example above, `value` is going to be `7` regardless of the value of 1836 `lucky?`. The variable `value` bound in the clause and the variable `value` 1837 bound in the outer context are two entirely separate variables. 1838 1839 If you want to pattern match against an existing variable, 1840 you need to use the `^/1` operator: 1841 1842 x = 1 1843 1844 case 10 do 1845 ^x -> "Won't match" 1846 _ -> "Will match" 1847 end 1848 #=> "Will match" 1849 1850 ## Using guards to match against multiple values 1851 1852 While it is not possible to match against multiple patterns in a single 1853 clause, it's possible to match against multiple values by using guards: 1854 1855 case data do 1856 value when value in [:one, :two] -> 1857 "#{value} has been matched" 1858 1859 :three -> 1860 "three has been matched" 1861 end 1862 1863 """ 1864 defmacro case(condition, clauses), do: error!([condition, clauses]) 1865 1866 @doc """ 1867 Evaluates the expression corresponding to the first clause that 1868 evaluates to a truthy value. 1869 1870 cond do 1871 hd([1, 2, 3]) -> 1872 "1 is considered as true" 1873 end 1874 #=> "1 is considered as true" 1875 1876 Raises an error if all conditions evaluate to `nil` or `false`. 1877 For this reason, it may be necessary to add a final always-truthy condition 1878 (anything non-`false` and non-`nil`), which will always match. 1879 1880 ## Examples 1881 1882 cond do 1883 1 + 1 == 1 -> 1884 "This will never match" 1885 2 * 2 != 4 -> 1886 "Nor this" 1887 true -> 1888 "This will" 1889 end 1890 #=> "This will" 1891 1892 """ 1893 defmacro cond(clauses), do: error!([clauses]) 1894 1895 @doc ~S""" 1896 Evaluates the given expressions and handles any error, exit, 1897 or throw that may have happened. 1898 1899 ## Examples 1900 1901 try do 1902 do_something_that_may_fail(some_arg) 1903 rescue 1904 ArgumentError -> 1905 IO.puts("Invalid argument given") 1906 catch 1907 value -> 1908 IO.puts("Caught #{inspect(value)}") 1909 else 1910 value -> 1911 IO.puts("Success! The result was #{inspect(value)}") 1912 after 1913 IO.puts("This is printed regardless if it failed or succeeded") 1914 end 1915 1916 The `rescue` clause is used to handle exceptions while the `catch` 1917 clause can be used to catch thrown values and exits. 1918 The `else` clause can be used to control flow based on the result of 1919 the expression. `catch`, `rescue`, and `else` clauses work based on 1920 pattern matching (similar to the `case` special form). 1921 1922 Calls inside `try/1` are not tail recursive since the VM needs to keep 1923 the stacktrace in case an exception happens. To retrieve the stacktrace, 1924 access `__STACKTRACE__/0` inside the `rescue` or `catch` clause. 1925 1926 ## `rescue` clauses 1927 1928 Besides relying on pattern matching, `rescue` clauses provide some 1929 conveniences around exceptions that allow one to rescue an 1930 exception by its name. All the following formats are valid patterns 1931 in `rescue` clauses: 1932 1933 # Rescue a single exception without binding the exception 1934 # to a variable 1935 try do 1936 UndefinedModule.undefined_function 1937 rescue 1938 UndefinedFunctionError -> nil 1939 end 1940 1941 # Rescue any of the given exception without binding 1942 try do 1943 UndefinedModule.undefined_function 1944 rescue 1945 [UndefinedFunctionError, ArgumentError] -> nil 1946 end 1947 1948 # Rescue and bind the exception to the variable "x" 1949 try do 1950 UndefinedModule.undefined_function 1951 rescue 1952 x in [UndefinedFunctionError] -> nil 1953 end 1954 1955 # Rescue all kinds of exceptions and bind the rescued exception 1956 # to the variable "x" 1957 try do 1958 UndefinedModule.undefined_function 1959 rescue 1960 x -> nil 1961 end 1962 1963 ### Erlang errors 1964 1965 Erlang errors are transformed into Elixir ones when rescuing: 1966 1967 try do 1968 :erlang.error(:badarg) 1969 rescue 1970 ArgumentError -> :ok 1971 end 1972 #=> :ok 1973 1974 The most common Erlang errors will be transformed into their 1975 Elixir counterpart. Those which are not will be transformed 1976 into the more generic `ErlangError`: 1977 1978 try do 1979 :erlang.error(:unknown) 1980 rescue 1981 ErlangError -> :ok 1982 end 1983 #=> :ok 1984 1985 In fact, `ErlangError` can be used to rescue any error that is 1986 not a proper Elixir error. For example, it can be used to rescue 1987 the earlier `:badarg` error too, prior to transformation: 1988 1989 try do 1990 :erlang.error(:badarg) 1991 rescue 1992 ErlangError -> :ok 1993 end 1994 #=> :ok 1995 1996 ## `catch` clauses 1997 1998 The `catch` clause can be used to catch thrown values, exits, and errors. 1999 2000 ### Catching thrown values 2001 2002 `catch` can be used to catch values thrown by `Kernel.throw/1`: 2003 2004 try do 2005 throw(:some_value) 2006 catch 2007 thrown_value -> 2008 IO.puts("A value was thrown: #{inspect(thrown_value)}") 2009 end 2010 2011 ### Catching values of any kind 2012 2013 The `catch` clause also supports catching exits and errors. To do that, it 2014 allows matching on both the *kind* of the caught value as well as the value 2015 itself: 2016 2017 try do 2018 exit(:shutdown) 2019 catch 2020 :exit, value -> 2021 IO.puts("Exited with value #{inspect(value)}") 2022 end 2023 2024 try do 2025 exit(:shutdown) 2026 catch 2027 kind, value when kind in [:exit, :throw] -> 2028 IO.puts("Caught exit or throw with value #{inspect(value)}") 2029 end 2030 2031 The `catch` clause also supports `:error` alongside `:exit` and `:throw` as 2032 in Erlang, although this is commonly avoided in favor of `raise`/`rescue` control 2033 mechanisms. One reason for this is that when catching `:error`, the error is 2034 not automatically transformed into an Elixir error: 2035 2036 try do 2037 :erlang.error(:badarg) 2038 catch 2039 :error, :badarg -> :ok 2040 end 2041 #=> :ok 2042 2043 ## `after` clauses 2044 2045 An `after` clause allows you to define cleanup logic that will be invoked both 2046 when the block of code passed to `try/1` succeeds and also when an error is raised. Note 2047 that the process will exit as usual when receiving an exit signal that causes 2048 it to exit abruptly and so the `after` clause is not guaranteed to be executed. 2049 Luckily, most resources in Elixir (such as open files, ETS tables, ports, sockets, 2050 and so on) are linked to or monitor the owning process and will automatically clean 2051 themselves up if that process exits. 2052 2053 File.write!("tmp/story.txt", "Hello, World") 2054 try do 2055 do_something_with("tmp/story.txt") 2056 after 2057 File.rm("tmp/story.txt") 2058 end 2059 2060 ## `else` clauses 2061 2062 `else` clauses allow the result of the body passed to `try/1` to be pattern 2063 matched on: 2064 2065 x = 2 2066 try do 2067 1 / x 2068 rescue 2069 ArithmeticError -> 2070 :infinity 2071 else 2072 y when y < 1 and y > -1 -> 2073 :small 2074 _ -> 2075 :large 2076 end 2077 2078 If an `else` clause is not present and no exceptions are raised, 2079 the result of the expression will be returned: 2080 2081 x = 1 2082 ^x = 2083 try do 2084 1 / x 2085 rescue 2086 ArithmeticError -> 2087 :infinity 2088 end 2089 2090 However, when an `else` clause is present but the result of the expression 2091 does not match any of the patterns then an exception will be raised. This 2092 exception will not be caught by a `catch` or `rescue` in the same `try`: 2093 2094 x = 1 2095 try do 2096 try do 2097 1 / x 2098 rescue 2099 # The TryClauseError cannot be rescued here: 2100 TryClauseError -> 2101 :error_a 2102 else 2103 0 -> 2104 :small 2105 end 2106 rescue 2107 # The TryClauseError is rescued here: 2108 TryClauseError -> 2109 :error_b 2110 end 2111 2112 Similarly, an exception inside an `else` clause is not caught or rescued 2113 inside the same `try`: 2114 2115 try do 2116 try do 2117 nil 2118 catch 2119 # The exit(1) call below can not be caught here: 2120 :exit, _ -> 2121 :exit_a 2122 else 2123 _ -> 2124 exit(1) 2125 end 2126 catch 2127 # The exit is caught here: 2128 :exit, _ -> 2129 :exit_b 2130 end 2131 2132 This means the VM no longer needs to keep the stacktrace once inside 2133 an `else` clause and so tail recursion is possible when using a `try` 2134 with a tail call as the final call inside an `else` clause. The same 2135 is true for `rescue` and `catch` clauses. 2136 2137 Only the result of the tried expression falls down to the `else` clause. 2138 If the `try` ends up in the `rescue` or `catch` clauses, their result 2139 will not fall down to `else`: 2140 2141 try do 2142 throw(:catch_this) 2143 catch 2144 :throw, :catch_this -> 2145 :it_was_caught 2146 else 2147 # :it_was_caught will not fall down to this "else" clause. 2148 other -> 2149 {:else, other} 2150 end 2151 2152 ## Variable handling 2153 2154 Since an expression inside `try` may not have been evaluated 2155 due to an exception, any variable created inside `try` cannot 2156 be accessed externally. For instance: 2157 2158 try do 2159 x = 1 2160 do_something_that_may_fail(same_arg) 2161 :ok 2162 catch 2163 _, _ -> :failed 2164 end 2165 2166 x 2167 #=> unbound variable "x" 2168 2169 In the example above, `x` cannot be accessed since it was defined 2170 inside the `try` clause. A common practice to address this issue 2171 is to return the variables defined inside `try`: 2172 2173 x = 2174 try do 2175 x = 1 2176 do_something_that_may_fail(same_arg) 2177 x 2178 catch 2179 _, _ -> :failed 2180 end 2181 2182 """ 2183 defmacro try(args), do: error!([args]) 2184 2185 @doc """ 2186 Checks if there is a message matching the given clauses 2187 in the current process mailbox. 2188 2189 In case there is no such message, the current process hangs 2190 until a message arrives or waits until a given timeout value. 2191 2192 ## Examples 2193 2194 receive do 2195 {:selector, number, name} when is_integer(number) -> 2196 name 2197 name when is_atom(name) -> 2198 name 2199 _ -> 2200 IO.puts(:stderr, "Unexpected message received") 2201 end 2202 2203 An optional `after` clause can be given in case the message was not 2204 received after the given timeout period, specified in milliseconds: 2205 2206 receive do 2207 {:selector, number, name} when is_integer(number) -> 2208 name 2209 name when is_atom(name) -> 2210 name 2211 _ -> 2212 IO.puts(:stderr, "Unexpected message received") 2213 after 2214 5000 -> 2215 IO.puts(:stderr, "No message in 5 seconds") 2216 end 2217 2218 The `after` clause can be specified even if there are no match clauses. 2219 The timeout value given to `after` can be any expression evaluating to 2220 one of the allowed values: 2221 2222 * `:infinity` - the process should wait indefinitely for a matching 2223 message, this is the same as not using the after clause 2224 2225 * `0` - if there is no matching message in the mailbox, the timeout 2226 will occur immediately 2227 2228 * positive integer smaller than or equal to `4_294_967_295` (`0xFFFFFFFF` 2229 in hexadecimal notation) - it should be possible to represent the timeout 2230 value as an unsigned 32-bit integer. 2231 2232 ## Variable handling 2233 2234 The `receive/1` special form handles variables exactly as the `case/2` 2235 special macro. For more information, check the docs for `case/2`. 2236 """ 2237 defmacro receive(args), do: error!([args]) 2238end 2239