1# Use elixir_bootstrap module to be able to bootstrap Kernel. 2# The bootstrap module provides simpler implementations of the 3# functions removed, simple enough to bootstrap. 4import Kernel, 5 except: [@: 1, defmodule: 2, def: 1, def: 2, defp: 2, defmacro: 1, defmacro: 2, defmacrop: 2] 6 7import :elixir_bootstrap 8 9defmodule Kernel do 10 @moduledoc """ 11 `Kernel` is Elixir's default environment. 12 13 It mainly consists of: 14 15 * basic language primitives, such as arithmetic operators, spawning of processes, 16 data type handling, and others 17 * macros for control-flow and defining new functionality (modules, functions, and the like) 18 * guard checks for augmenting pattern matching 19 20 You can invoke `Kernel` functions and macros anywhere in Elixir code 21 without the use of the `Kernel.` prefix since they have all been 22 automatically imported. For example, in IEx, you can call: 23 24 iex> is_number(13) 25 true 26 27 If you don't want to import a function or macro from `Kernel`, use the `:except` 28 option and then list the function/macro by arity: 29 30 import Kernel, except: [if: 2, unless: 2] 31 32 See `Kernel.SpecialForms.import/2` for more information on importing. 33 34 Elixir also has special forms that are always imported and 35 cannot be skipped. These are described in `Kernel.SpecialForms`. 36 37 ## The standard library 38 39 `Kernel` provides the basic capabilities the Elixir standard library 40 is built on top of. It is recommended to explore the standard library 41 for advanced functionality. Here are the main groups of modules in the 42 standard library (this list is not a complete reference, see the 43 documentation sidebar for all entries). 44 45 ### Built-in types 46 47 The following modules handle Elixir built-in data types: 48 49 * `Atom` - literal constants with a name (`true`, `false`, and `nil` are atoms) 50 * `Float` - numbers with floating point precision 51 * `Function` - a reference to code chunk, created with the `fn/1` special form 52 * `Integer` - whole numbers (not fractions) 53 * `List` - collections of a variable number of elements (linked lists) 54 * `Map` - collections of key-value pairs 55 * `Process` - light-weight threads of execution 56 * `Port` - mechanisms to interact with the external world 57 * `Tuple` - collections of a fixed number of elements 58 59 There are two data types without an accompanying module: 60 61 * Bitstring - a sequence of bits, created with `Kernel.SpecialForms.<<>>/1`. 62 When the number of bits is divisible by 8, they are called binaries and can 63 be manipulated with Erlang's `:binary` module 64 * Reference - a unique value in the runtime system, created with `make_ref/0` 65 66 ### Data types 67 68 Elixir also provides other data types that are built on top of the types 69 listed above. Some of them are: 70 71 * `Date` - `year-month-day` structs in a given calendar 72 * `DateTime` - date and time with time zone in a given calendar 73 * `Exception` - data raised from errors and unexpected scenarios 74 * `MapSet` - unordered collections of unique elements 75 * `NaiveDateTime` - date and time without time zone in a given calendar 76 * `Keyword` - lists of two-element tuples, often representing optional values 77 * `Range` - inclusive ranges between two integers 78 * `Regex` - regular expressions 79 * `String` - UTF-8 encoded binaries representing characters 80 * `Time` - `hour:minute:second` structs in a given calendar 81 * `URI` - representation of URIs that identify resources 82 * `Version` - representation of versions and requirements 83 84 ### System modules 85 86 Modules that interface with the underlying system, such as: 87 88 * `IO` - handles input and output 89 * `File` - interacts with the underlying file system 90 * `Path` - manipulates file system paths 91 * `System` - reads and writes system information 92 93 ### Protocols 94 95 Protocols add polymorphic dispatch to Elixir. They are contracts 96 implementable by data types. See `Protocol` for more information on 97 protocols. Elixir provides the following protocols in the standard library: 98 99 * `Collectable` - collects data into a data type 100 * `Enumerable` - handles collections in Elixir. The `Enum` module 101 provides eager functions for working with collections, the `Stream` 102 module provides lazy functions 103 * `Inspect` - converts data types into their programming language 104 representation 105 * `List.Chars` - converts data types to their outside world 106 representation as charlists (non-programming based) 107 * `String.Chars` - converts data types to their outside world 108 representation as strings (non-programming based) 109 110 ### Process-based and application-centric functionality 111 112 The following modules build on top of processes to provide concurrency, 113 fault-tolerance, and more. 114 115 * `Agent` - a process that encapsulates mutable state 116 * `Application` - functions for starting, stopping and configuring 117 applications 118 * `GenServer` - a generic client-server API 119 * `Registry` - a key-value process-based storage 120 * `Supervisor` - a process that is responsible for starting, 121 supervising and shutting down other processes 122 * `Task` - a process that performs computations 123 * `Task.Supervisor` - a supervisor for managing tasks exclusively 124 125 ### Supporting documents 126 127 Elixir documentation also includes supporting documents under the 128 "Pages" section. Those are: 129 130 * [Compatibility and deprecations](compatibility-and-deprecations.md) - lists 131 compatibility between every Elixir version and Erlang/OTP, release schema; 132 lists all deprecated functions, when they were deprecated and alternatives 133 * [Library guidelines](library-guidelines.md) - general guidelines, anti-patterns, 134 and rules for those writing libraries 135 * [Naming conventions](naming-conventions.md) - naming conventions for Elixir code 136 * [Operators](operators.md) - lists all Elixir operators and their precedences 137 * [Patterns and guards](patterns-and-guards.md) - an introduction to patterns, 138 guards, and extensions 139 * [Syntax reference](syntax-reference.md) - the language syntax reference 140 * [Typespecs](typespecs.md)- types and function specifications, including list of types 141 * [Unicode syntax](unicode-syntax.md) - outlines Elixir support for Unicode 142 * [Writing documentation](writing-documentation.md) - guidelines for writing 143 documentation in Elixir 144 145 ## Guards 146 147 This module includes the built-in guards used by Elixir developers. 148 They are a predefined set of functions and macros that augment pattern 149 matching, typically invoked after the `when` operator. For example: 150 151 def drive(%User{age: age}) when age >= 16 do 152 ... 153 end 154 155 The clause above will only be invoked if the user's age is more than 156 or equal to 16. Guards also support joining multiple conditions with 157 `and` and `or`. The whole guard is true if all guard expressions will 158 evaluate to `true`. A more complete introduction to guards is available 159 in the [Patterns and guards](patterns-and-guards.md) page. 160 161 ## Structural comparison 162 163 The comparison functions in this module perform structural comparison. 164 This means structures are compared based on their representation and 165 not on their semantic value. This is specially important for functions 166 that are meant to provide ordering, such as `>/2`, `</2`, `>=/2`, 167 `<=/2`, `min/2`, and `max/2`. For example: 168 169 ~D[2017-03-31] > ~D[2017-04-01] 170 171 will return `true` because structural comparison compares the `:day` 172 field before `:month` or `:year`. Therefore, when comparing structs, 173 you often use the `compare/2` function made available by the structs 174 modules themselves: 175 176 iex> Date.compare(~D[2017-03-31], ~D[2017-04-01]) 177 :lt 178 179 Alternatively, you can use the functions in the `Enum` module to 180 sort or compute a maximum/minimum: 181 182 iex> Enum.sort([~D[2017-03-31], ~D[2017-04-01]], Date) 183 [~D[2017-03-31], ~D[2017-04-01]] 184 iex> Enum.max([~D[2017-03-31], ~D[2017-04-01]], Date) 185 ~D[2017-04-01] 186 187 ## Truthy and falsy values 188 189 Besides the booleans `true` and `false`, Elixir has the 190 concept of a "truthy" or "falsy" value. 191 192 * a value is truthy when it is neither `false` nor `nil` 193 * a value is falsy when it is either `false` or `nil` 194 195 Elixir has functions, like `and/2`, that *only* work with 196 booleans, but also functions that work with these 197 truthy/falsy values, like `&&/2` and `!/1`. 198 199 ### Examples 200 201 We can check the truthiness of a value by using the `!/1` 202 function twice. 203 204 Truthy values: 205 206 iex> !!true 207 true 208 iex> !!5 209 true 210 iex> !![1,2] 211 true 212 iex> !!"foo" 213 true 214 215 Falsy values (of which there are exactly two): 216 217 iex> !!false 218 false 219 iex> !!nil 220 false 221 222 ## Inlining 223 224 Some of the functions described in this module are inlined by 225 the Elixir compiler into their Erlang counterparts in the 226 [`:erlang`](`:erlang`) module. 227 Those functions are called BIFs (built-in internal functions) 228 in Erlang-land and they exhibit interesting properties, as some 229 of them are allowed in guards and others are used for compiler 230 optimizations. 231 232 Most of the inlined functions can be seen in effect when 233 capturing the function: 234 235 iex> &Kernel.is_atom/1 236 &:erlang.is_atom/1 237 238 Those functions will be explicitly marked in their docs as 239 "inlined by the compiler". 240 """ 241 242 # We need this check only for bootstrap purposes. 243 # Once Kernel is loaded and we recompile, it is a no-op. 244 @compile {:inline, bootstrapped?: 1} 245 case :code.ensure_loaded(Kernel) do 246 {:module, _} -> 247 defp bootstrapped?(_), do: true 248 249 {:error, _} -> 250 defp bootstrapped?(module), do: :code.ensure_loaded(module) == {:module, module} 251 end 252 253 ## Delegations to Erlang with inlining (macros) 254 255 @doc """ 256 Returns an integer or float which is the arithmetical absolute value of `number`. 257 258 Allowed in guard tests. Inlined by the compiler. 259 260 ## Examples 261 262 iex> abs(-3.33) 263 3.33 264 265 iex> abs(-3) 266 3 267 268 """ 269 @doc guard: true 270 @spec abs(number) :: number 271 def abs(number) do 272 :erlang.abs(number) 273 end 274 275 @doc """ 276 Invokes the given anonymous function `fun` with the list of 277 arguments `args`. 278 279 If the number of arguments is known at compile time, prefer 280 `fun.(arg_1, arg_2, ..., arg_n)` as it is clearer than 281 `apply(fun, [arg_1, arg_2, ..., arg_n])`. 282 283 Inlined by the compiler. 284 285 ## Examples 286 287 iex> apply(fn x -> x * 2 end, [2]) 288 4 289 290 """ 291 @spec apply(fun, [any]) :: any 292 def apply(fun, args) do 293 :erlang.apply(fun, args) 294 end 295 296 @doc """ 297 Invokes the given function from `module` with the list of 298 arguments `args`. 299 300 `apply/3` is used to invoke functions where the module, function 301 name or arguments are defined dynamically at runtime. For this 302 reason, you can't invoke macros using `apply/3`, only functions. 303 304 If the number of arguments and the function name are known at compile time, 305 prefer `module.function(arg_1, arg_2, ..., arg_n)` as it is clearer than 306 `apply(module, :function, [arg_1, arg_2, ..., arg_n])`. 307 308 Inlined by the compiler. 309 310 ## Examples 311 312 iex> apply(Enum, :reverse, [[1, 2, 3]]) 313 [3, 2, 1] 314 315 """ 316 @spec apply(module, function_name :: atom, [any]) :: any 317 def apply(module, function_name, args) do 318 :erlang.apply(module, function_name, args) 319 end 320 321 @doc """ 322 Extracts the part of the binary starting at `start` with length `length`. 323 Binaries are zero-indexed. 324 325 If `start` or `length` reference in any way outside the binary, an 326 `ArgumentError` exception is raised. 327 328 Allowed in guard tests. Inlined by the compiler. 329 330 ## Examples 331 332 iex> binary_part("foo", 1, 2) 333 "oo" 334 335 A negative `length` can be used to extract bytes that come *before* the byte 336 at `start`: 337 338 iex> binary_part("Hello", 5, -3) 339 "llo" 340 341 An `ArgumentError` is raised when the length is outside of the binary: 342 343 binary_part("Hello", 0, 10) 344 ** (ArgumentError) argument error 345 346 """ 347 @doc guard: true 348 @spec binary_part(binary, non_neg_integer, integer) :: binary 349 def binary_part(binary, start, length) do 350 :erlang.binary_part(binary, start, length) 351 end 352 353 @doc """ 354 Returns an integer which is the size in bits of `bitstring`. 355 356 Allowed in guard tests. Inlined by the compiler. 357 358 ## Examples 359 360 iex> bit_size(<<433::16, 3::3>>) 361 19 362 363 iex> bit_size(<<1, 2, 3>>) 364 24 365 366 """ 367 @doc guard: true 368 @spec bit_size(bitstring) :: non_neg_integer 369 def bit_size(bitstring) do 370 :erlang.bit_size(bitstring) 371 end 372 373 @doc """ 374 Returns the number of bytes needed to contain `bitstring`. 375 376 That is, if the number of bits in `bitstring` is not divisible by 8, the 377 resulting number of bytes will be rounded up (by excess). This operation 378 happens in constant time. 379 380 Allowed in guard tests. Inlined by the compiler. 381 382 ## Examples 383 384 iex> byte_size(<<433::16, 3::3>>) 385 3 386 387 iex> byte_size(<<1, 2, 3>>) 388 3 389 390 """ 391 @doc guard: true 392 @spec byte_size(bitstring) :: non_neg_integer 393 def byte_size(bitstring) do 394 :erlang.byte_size(bitstring) 395 end 396 397 @doc """ 398 Returns the smallest integer greater than or equal to `number`. 399 400 If you want to perform ceil operation on other decimal places, 401 use `Float.ceil/2` instead. 402 403 Allowed in guard tests. Inlined by the compiler. 404 """ 405 @doc since: "1.8.0", guard: true 406 @spec ceil(number) :: integer 407 def ceil(number) do 408 :erlang.ceil(number) 409 end 410 411 @doc """ 412 Performs an integer division. 413 414 Raises an `ArithmeticError` exception if one of the arguments is not an 415 integer, or when the `divisor` is `0`. 416 417 `div/2` performs *truncated* integer division. This means that 418 the result is always rounded towards zero. 419 420 If you want to perform floored integer division (rounding towards negative infinity), 421 use `Integer.floor_div/2` instead. 422 423 Allowed in guard tests. Inlined by the compiler. 424 425 ## Examples 426 427 div(5, 2) 428 #=> 2 429 430 div(6, -4) 431 #=> -1 432 433 div(-99, 2) 434 #=> -49 435 436 div(100, 0) 437 ** (ArithmeticError) bad argument in arithmetic expression 438 439 """ 440 @doc guard: true 441 @spec div(integer, neg_integer | pos_integer) :: integer 442 def div(dividend, divisor) do 443 :erlang.div(dividend, divisor) 444 end 445 446 @doc """ 447 Stops the execution of the calling process with the given reason. 448 449 Since evaluating this function causes the process to terminate, 450 it has no return value. 451 452 Inlined by the compiler. 453 454 ## Examples 455 456 When a process reaches its end, by default it exits with 457 reason `:normal`. You can also call `exit/1` explicitly if you 458 want to terminate a process but not signal any failure: 459 460 exit(:normal) 461 462 In case something goes wrong, you can also use `exit/1` with 463 a different reason: 464 465 exit(:seems_bad) 466 467 If the exit reason is not `:normal`, all the processes linked to the process 468 that exited will crash (unless they are trapping exits). 469 470 ## OTP exits 471 472 Exits are used by the OTP to determine if a process exited abnormally 473 or not. The following exits are considered "normal": 474 475 * `exit(:normal)` 476 * `exit(:shutdown)` 477 * `exit({:shutdown, term})` 478 479 Exiting with any other reason is considered abnormal and treated 480 as a crash. This means the default supervisor behaviour kicks in, 481 error reports are emitted, and so forth. 482 483 This behaviour is relied on in many different places. For example, 484 `ExUnit` uses `exit(:shutdown)` when exiting the test process to 485 signal linked processes, supervision trees and so on to politely 486 shut down too. 487 488 ## CLI exits 489 490 Building on top of the exit signals mentioned above, if the 491 process started by the command line exits with any of the three 492 reasons above, its exit is considered normal and the Operating 493 System process will exit with status 0. 494 495 It is, however, possible to customize the operating system exit 496 signal by invoking: 497 498 exit({:shutdown, integer}) 499 500 This will cause the operating system process to exit with the status given by 501 `integer` while signaling all linked Erlang processes to politely 502 shut down. 503 504 Any other exit reason will cause the operating system process to exit with 505 status `1` and linked Erlang processes to crash. 506 """ 507 @spec exit(term) :: no_return 508 def exit(reason) do 509 :erlang.exit(reason) 510 end 511 512 @doc """ 513 Returns the largest integer smaller than or equal to `number`. 514 515 If you want to perform floor operation on other decimal places, 516 use `Float.floor/2` instead. 517 518 Allowed in guard tests. Inlined by the compiler. 519 """ 520 @doc since: "1.8.0", guard: true 521 @spec floor(number) :: integer 522 def floor(number) do 523 :erlang.floor(number) 524 end 525 526 @doc """ 527 Returns the head of a list. Raises `ArgumentError` if the list is empty. 528 529 It works with improper lists. 530 531 Allowed in guard tests. Inlined by the compiler. 532 533 ## Examples 534 535 hd([1, 2, 3, 4]) 536 #=> 1 537 538 hd([1 | 2]) 539 #=> 1 540 541 Giving it an empty list raises: 542 543 tl([]) 544 #=> ** (ArgumentError) argument error 545 546 """ 547 @doc guard: true 548 @spec hd(nonempty_maybe_improper_list(elem, any)) :: elem when elem: term 549 def hd(list) do 550 :erlang.hd(list) 551 end 552 553 @doc """ 554 Returns `true` if `term` is an atom; otherwise returns `false`. 555 556 Allowed in guard tests. Inlined by the compiler. 557 """ 558 @doc guard: true 559 @spec is_atom(term) :: boolean 560 def is_atom(term) do 561 :erlang.is_atom(term) 562 end 563 564 @doc """ 565 Returns `true` if `term` is a binary; otherwise returns `false`. 566 567 A binary always contains a complete number of bytes. 568 569 Allowed in guard tests. Inlined by the compiler. 570 571 ## Examples 572 573 iex> is_binary("foo") 574 true 575 iex> is_binary(<<1::3>>) 576 false 577 578 """ 579 @doc guard: true 580 @spec is_binary(term) :: boolean 581 def is_binary(term) do 582 :erlang.is_binary(term) 583 end 584 585 @doc """ 586 Returns `true` if `term` is a bitstring (including a binary); otherwise returns `false`. 587 588 Allowed in guard tests. Inlined by the compiler. 589 590 ## Examples 591 592 iex> is_bitstring("foo") 593 true 594 iex> is_bitstring(<<1::3>>) 595 true 596 597 """ 598 @doc guard: true 599 @spec is_bitstring(term) :: boolean 600 def is_bitstring(term) do 601 :erlang.is_bitstring(term) 602 end 603 604 @doc """ 605 Returns `true` if `term` is either the atom `true` or the atom `false` (i.e., 606 a boolean); otherwise returns `false`. 607 608 Allowed in guard tests. Inlined by the compiler. 609 """ 610 @doc guard: true 611 @spec is_boolean(term) :: boolean 612 def is_boolean(term) do 613 :erlang.is_boolean(term) 614 end 615 616 @doc """ 617 Returns `true` if `term` is a floating-point number; otherwise returns `false`. 618 619 Allowed in guard tests. Inlined by the compiler. 620 """ 621 @doc guard: true 622 @spec is_float(term) :: boolean 623 def is_float(term) do 624 :erlang.is_float(term) 625 end 626 627 @doc """ 628 Returns `true` if `term` is a function; otherwise returns `false`. 629 630 Allowed in guard tests. Inlined by the compiler. 631 """ 632 @doc guard: true 633 @spec is_function(term) :: boolean 634 def is_function(term) do 635 :erlang.is_function(term) 636 end 637 638 @doc """ 639 Returns `true` if `term` is a function that can be applied with `arity` number of arguments; 640 otherwise returns `false`. 641 642 Allowed in guard tests. Inlined by the compiler. 643 644 ## Examples 645 646 iex> is_function(fn x -> x * 2 end, 1) 647 true 648 iex> is_function(fn x -> x * 2 end, 2) 649 false 650 651 """ 652 @doc guard: true 653 @spec is_function(term, non_neg_integer) :: boolean 654 def is_function(term, arity) do 655 :erlang.is_function(term, arity) 656 end 657 658 @doc """ 659 Returns `true` if `term` is an integer; otherwise returns `false`. 660 661 Allowed in guard tests. Inlined by the compiler. 662 """ 663 @doc guard: true 664 @spec is_integer(term) :: boolean 665 def is_integer(term) do 666 :erlang.is_integer(term) 667 end 668 669 @doc """ 670 Returns `true` if `term` is a list with zero or more elements; otherwise returns `false`. 671 672 Allowed in guard tests. Inlined by the compiler. 673 """ 674 @doc guard: true 675 @spec is_list(term) :: boolean 676 def is_list(term) do 677 :erlang.is_list(term) 678 end 679 680 @doc """ 681 Returns `true` if `term` is either an integer or a floating-point number; 682 otherwise returns `false`. 683 684 Allowed in guard tests. Inlined by the compiler. 685 """ 686 @doc guard: true 687 @spec is_number(term) :: boolean 688 def is_number(term) do 689 :erlang.is_number(term) 690 end 691 692 @doc """ 693 Returns `true` if `term` is a PID (process identifier); otherwise returns `false`. 694 695 Allowed in guard tests. Inlined by the compiler. 696 """ 697 @doc guard: true 698 @spec is_pid(term) :: boolean 699 def is_pid(term) do 700 :erlang.is_pid(term) 701 end 702 703 @doc """ 704 Returns `true` if `term` is a port identifier; otherwise returns `false`. 705 706 Allowed in guard tests. Inlined by the compiler. 707 """ 708 @doc guard: true 709 @spec is_port(term) :: boolean 710 def is_port(term) do 711 :erlang.is_port(term) 712 end 713 714 @doc """ 715 Returns `true` if `term` is a reference; otherwise returns `false`. 716 717 Allowed in guard tests. Inlined by the compiler. 718 """ 719 @doc guard: true 720 @spec is_reference(term) :: boolean 721 def is_reference(term) do 722 :erlang.is_reference(term) 723 end 724 725 @doc """ 726 Returns `true` if `term` is a tuple; otherwise returns `false`. 727 728 Allowed in guard tests. Inlined by the compiler. 729 """ 730 @doc guard: true 731 @spec is_tuple(term) :: boolean 732 def is_tuple(term) do 733 :erlang.is_tuple(term) 734 end 735 736 @doc """ 737 Returns `true` if `term` is a map; otherwise returns `false`. 738 739 Allowed in guard tests. Inlined by the compiler. 740 """ 741 @doc guard: true 742 @spec is_map(term) :: boolean 743 def is_map(term) do 744 :erlang.is_map(term) 745 end 746 747 @doc """ 748 Returns `true` if `key` is a key in `map`; otherwise returns `false`. 749 750 It raises `BadMapError` if the first element is not a map. 751 752 Allowed in guard tests. Inlined by the compiler. 753 """ 754 @doc guard: true, since: "1.10.0" 755 @spec is_map_key(map, term) :: boolean 756 def is_map_key(map, key) do 757 :erlang.is_map_key(key, map) 758 end 759 760 @doc """ 761 Returns the length of `list`. 762 763 Allowed in guard tests. Inlined by the compiler. 764 765 ## Examples 766 767 iex> length([1, 2, 3, 4, 5, 6, 7, 8, 9]) 768 9 769 770 """ 771 @doc guard: true 772 @spec length(list) :: non_neg_integer 773 def length(list) do 774 :erlang.length(list) 775 end 776 777 @doc """ 778 Returns an almost unique reference. 779 780 The returned reference will re-occur after approximately 2^82 calls; 781 therefore it is unique enough for practical purposes. 782 783 Inlined by the compiler. 784 785 ## Examples 786 787 make_ref() 788 #=> #Reference<0.0.0.135> 789 790 """ 791 @spec make_ref() :: reference 792 def make_ref() do 793 :erlang.make_ref() 794 end 795 796 @doc """ 797 Returns the size of a map. 798 799 The size of a map is the number of key-value pairs that the map contains. 800 801 This operation happens in constant time. 802 803 Allowed in guard tests. Inlined by the compiler. 804 805 ## Examples 806 807 iex> map_size(%{a: "foo", b: "bar"}) 808 2 809 810 """ 811 @doc guard: true 812 @spec map_size(map) :: non_neg_integer 813 def map_size(map) do 814 :erlang.map_size(map) 815 end 816 817 @doc """ 818 Returns the biggest of the two given terms according to 819 their structural comparison. 820 821 If the terms compare equal, the first one is returned. 822 823 This performs a structural comparison where all Elixir 824 terms can be compared with each other. See the ["Structural 825 comparison" section](#module-structural-comparison) section 826 for more information. 827 828 Inlined by the compiler. 829 830 ## Examples 831 832 iex> max(1, 2) 833 2 834 iex> max(:a, :b) 835 :b 836 837 """ 838 @spec max(first, second) :: first | second when first: term, second: term 839 def max(first, second) do 840 :erlang.max(first, second) 841 end 842 843 @doc """ 844 Returns the smallest of the two given terms according to 845 their structural comparison. 846 847 If the terms compare equal, the first one is returned. 848 849 This performs a structural comparison where all Elixir 850 terms can be compared with each other. See the ["Structural 851 comparison" section](#module-structural-comparison) section 852 for more information. 853 854 Inlined by the compiler. 855 856 ## Examples 857 858 iex> min(1, 2) 859 1 860 iex> min("foo", "bar") 861 "bar" 862 863 """ 864 @spec min(first, second) :: first | second when first: term, second: term 865 def min(first, second) do 866 :erlang.min(first, second) 867 end 868 869 @doc """ 870 Returns an atom representing the name of the local node. 871 If the node is not alive, `:nonode@nohost` is returned instead. 872 873 Allowed in guard tests. Inlined by the compiler. 874 """ 875 @doc guard: true 876 @spec node() :: node 877 def node do 878 :erlang.node() 879 end 880 881 @doc """ 882 Returns the node where the given argument is located. 883 The argument can be a PID, a reference, or a port. 884 If the local node is not alive, `:nonode@nohost` is returned. 885 886 Allowed in guard tests. Inlined by the compiler. 887 """ 888 @doc guard: true 889 @spec node(pid | reference | port) :: node 890 def node(arg) do 891 :erlang.node(arg) 892 end 893 894 @doc """ 895 Computes the remainder of an integer division. 896 897 `rem/2` uses truncated division, which means that 898 the result will always have the sign of the `dividend`. 899 900 Raises an `ArithmeticError` exception if one of the arguments is not an 901 integer, or when the `divisor` is `0`. 902 903 Allowed in guard tests. Inlined by the compiler. 904 905 ## Examples 906 907 iex> rem(5, 2) 908 1 909 iex> rem(6, -4) 910 2 911 912 """ 913 @doc guard: true 914 @spec rem(integer, neg_integer | pos_integer) :: integer 915 def rem(dividend, divisor) do 916 :erlang.rem(dividend, divisor) 917 end 918 919 @doc """ 920 Rounds a number to the nearest integer. 921 922 If the number is equidistant to the two nearest integers, rounds away from zero. 923 924 Allowed in guard tests. Inlined by the compiler. 925 926 ## Examples 927 928 iex> round(5.6) 929 6 930 931 iex> round(5.2) 932 5 933 934 iex> round(-9.9) 935 -10 936 937 iex> round(-9) 938 -9 939 940 iex> round(2.5) 941 3 942 943 iex> round(-2.5) 944 -3 945 946 """ 947 @doc guard: true 948 @spec round(number) :: integer 949 def round(number) do 950 :erlang.round(number) 951 end 952 953 @doc """ 954 Sends a message to the given `dest` and returns the message. 955 956 `dest` may be a remote or local PID, a local port, a locally 957 registered name, or a tuple in the form of `{registered_name, node}` for a 958 registered name at another node. 959 960 Inlined by the compiler. 961 962 ## Examples 963 964 iex> send(self(), :hello) 965 :hello 966 967 """ 968 @spec send(dest :: Process.dest(), message) :: message when message: any 969 def send(dest, message) do 970 :erlang.send(dest, message) 971 end 972 973 @doc """ 974 Returns the PID (process identifier) of the calling process. 975 976 Allowed in guard clauses. Inlined by the compiler. 977 """ 978 @doc guard: true 979 @spec self() :: pid 980 def self() do 981 :erlang.self() 982 end 983 984 @doc """ 985 Spawns the given function and returns its PID. 986 987 Typically developers do not use the `spawn` functions, instead they use 988 abstractions such as `Task`, `GenServer` and `Agent`, built on top of 989 `spawn`, that spawns processes with more conveniences in terms of 990 introspection and debugging. 991 992 Check the `Process` module for more process-related functions. 993 994 The anonymous function receives 0 arguments, and may return any value. 995 996 Inlined by the compiler. 997 998 ## Examples 999 1000 current = self() 1001 child = spawn(fn -> send(current, {self(), 1 + 2}) end) 1002 1003 receive do 1004 {^child, 3} -> IO.puts("Received 3 back") 1005 end 1006 1007 """ 1008 @spec spawn((() -> any)) :: pid 1009 def spawn(fun) do 1010 :erlang.spawn(fun) 1011 end 1012 1013 @doc """ 1014 Spawns the given function `fun` from the given `module` passing it the given 1015 `args` and returns its PID. 1016 1017 Typically developers do not use the `spawn` functions, instead they use 1018 abstractions such as `Task`, `GenServer` and `Agent`, built on top of 1019 `spawn`, that spawns processes with more conveniences in terms of 1020 introspection and debugging. 1021 1022 Check the `Process` module for more process-related functions. 1023 1024 Inlined by the compiler. 1025 1026 ## Examples 1027 1028 spawn(SomeModule, :function, [1, 2, 3]) 1029 1030 """ 1031 @spec spawn(module, atom, list) :: pid 1032 def spawn(module, fun, args) do 1033 :erlang.spawn(module, fun, args) 1034 end 1035 1036 @doc """ 1037 Spawns the given function, links it to the current process, and returns its PID. 1038 1039 Typically developers do not use the `spawn` functions, instead they use 1040 abstractions such as `Task`, `GenServer` and `Agent`, built on top of 1041 `spawn`, that spawns processes with more conveniences in terms of 1042 introspection and debugging. 1043 1044 Check the `Process` module for more process-related functions. For more 1045 information on linking, check `Process.link/1`. 1046 1047 The anonymous function receives 0 arguments, and may return any value. 1048 1049 Inlined by the compiler. 1050 1051 ## Examples 1052 1053 current = self() 1054 child = spawn_link(fn -> send(current, {self(), 1 + 2}) end) 1055 1056 receive do 1057 {^child, 3} -> IO.puts("Received 3 back") 1058 end 1059 1060 """ 1061 @spec spawn_link((() -> any)) :: pid 1062 def spawn_link(fun) do 1063 :erlang.spawn_link(fun) 1064 end 1065 1066 @doc """ 1067 Spawns the given function `fun` from the given `module` passing it the given 1068 `args`, links it to the current process, and returns its PID. 1069 1070 Typically developers do not use the `spawn` functions, instead they use 1071 abstractions such as `Task`, `GenServer` and `Agent`, built on top of 1072 `spawn`, that spawns processes with more conveniences in terms of 1073 introspection and debugging. 1074 1075 Check the `Process` module for more process-related functions. For more 1076 information on linking, check `Process.link/1`. 1077 1078 Inlined by the compiler. 1079 1080 ## Examples 1081 1082 spawn_link(SomeModule, :function, [1, 2, 3]) 1083 1084 """ 1085 @spec spawn_link(module, atom, list) :: pid 1086 def spawn_link(module, fun, args) do 1087 :erlang.spawn_link(module, fun, args) 1088 end 1089 1090 @doc """ 1091 Spawns the given function, monitors it and returns its PID 1092 and monitoring reference. 1093 1094 Typically developers do not use the `spawn` functions, instead they use 1095 abstractions such as `Task`, `GenServer` and `Agent`, built on top of 1096 `spawn`, that spawns processes with more conveniences in terms of 1097 introspection and debugging. 1098 1099 Check the `Process` module for more process-related functions. 1100 1101 The anonymous function receives 0 arguments, and may return any value. 1102 1103 Inlined by the compiler. 1104 1105 ## Examples 1106 1107 current = self() 1108 spawn_monitor(fn -> send(current, {self(), 1 + 2}) end) 1109 1110 """ 1111 @spec spawn_monitor((() -> any)) :: {pid, reference} 1112 def spawn_monitor(fun) do 1113 :erlang.spawn_monitor(fun) 1114 end 1115 1116 @doc """ 1117 Spawns the given module and function passing the given args, 1118 monitors it and returns its PID and monitoring reference. 1119 1120 Typically developers do not use the `spawn` functions, instead they use 1121 abstractions such as `Task`, `GenServer` and `Agent`, built on top of 1122 `spawn`, that spawns processes with more conveniences in terms of 1123 introspection and debugging. 1124 1125 Check the `Process` module for more process-related functions. 1126 1127 Inlined by the compiler. 1128 1129 ## Examples 1130 1131 spawn_monitor(SomeModule, :function, [1, 2, 3]) 1132 1133 """ 1134 @spec spawn_monitor(module, atom, list) :: {pid, reference} 1135 def spawn_monitor(module, fun, args) do 1136 :erlang.spawn_monitor(module, fun, args) 1137 end 1138 1139 @doc """ 1140 Pipes `value` to the given `fun` and returns the `value` itself. 1141 1142 Useful for running synchronous side effects in a pipeline. 1143 1144 ## Examples 1145 1146 iex> tap(1, fn x -> x + 1 end) 1147 1 1148 1149 Most commonly, this is used in pipelines. For example, 1150 let's suppose you want to inspect part of a data structure. 1151 You could write: 1152 1153 %{a: 1} 1154 |> Map.update!(:a, & &1 + 2) 1155 |> tap(&IO.inspect(&1.a)) 1156 |> Map.update!(:a, & &1 * 2) 1157 1158 """ 1159 @doc since: "1.12.0" 1160 defmacro tap(value, fun) do 1161 quote bind_quoted: [fun: fun, value: value] do 1162 fun.(value) 1163 value 1164 end 1165 end 1166 1167 @doc """ 1168 A non-local return from a function. 1169 1170 Check `Kernel.SpecialForms.try/1` for more information. 1171 1172 Inlined by the compiler. 1173 """ 1174 @spec throw(term) :: no_return 1175 def throw(term) do 1176 :erlang.throw(term) 1177 end 1178 1179 @doc """ 1180 Returns the tail of a list. Raises `ArgumentError` if the list is empty. 1181 1182 It works with improper lists. 1183 1184 Allowed in guard tests. Inlined by the compiler. 1185 1186 ## Examples 1187 1188 tl([1, 2, 3, :go]) 1189 #=> [2, 3, :go] 1190 1191 tl([:one]) 1192 #=> [] 1193 1194 tl([:a, :b | :c]) 1195 #=> [:b | :c] 1196 1197 tl([:a | %{b: 1}]) 1198 #=> %{b: 1} 1199 1200 Giving it an empty list raises: 1201 1202 tl([]) 1203 #=> ** (ArgumentError) argument error 1204 1205 """ 1206 @doc guard: true 1207 @spec tl(nonempty_maybe_improper_list(elem, tail)) :: maybe_improper_list(elem, tail) | tail 1208 when elem: term, tail: term 1209 def tl(list) do 1210 :erlang.tl(list) 1211 end 1212 1213 @doc """ 1214 Returns the integer part of `number`. 1215 1216 Allowed in guard tests. Inlined by the compiler. 1217 1218 ## Examples 1219 1220 iex> trunc(5.4) 1221 5 1222 1223 iex> trunc(-5.99) 1224 -5 1225 1226 iex> trunc(-5) 1227 -5 1228 1229 """ 1230 @doc guard: true 1231 @spec trunc(number) :: integer 1232 def trunc(number) do 1233 :erlang.trunc(number) 1234 end 1235 1236 @doc """ 1237 Returns the size of a tuple. 1238 1239 This operation happens in constant time. 1240 1241 Allowed in guard tests. Inlined by the compiler. 1242 1243 ## Examples 1244 1245 iex> tuple_size({:a, :b, :c}) 1246 3 1247 1248 """ 1249 @doc guard: true 1250 @spec tuple_size(tuple) :: non_neg_integer 1251 def tuple_size(tuple) do 1252 :erlang.tuple_size(tuple) 1253 end 1254 1255 @doc """ 1256 Arithmetic addition operator. 1257 1258 Allowed in guard tests. Inlined by the compiler. 1259 1260 ## Examples 1261 1262 iex> 1 + 2 1263 3 1264 1265 """ 1266 @doc guard: true 1267 @spec integer + integer :: integer 1268 @spec float + float :: float 1269 @spec integer + float :: float 1270 @spec float + integer :: float 1271 def left + right do 1272 :erlang.+(left, right) 1273 end 1274 1275 @doc """ 1276 Arithmetic subtraction operator. 1277 1278 Allowed in guard tests. Inlined by the compiler. 1279 1280 ## Examples 1281 1282 iex> 1 - 2 1283 -1 1284 1285 """ 1286 @doc guard: true 1287 @spec integer - integer :: integer 1288 @spec float - float :: float 1289 @spec integer - float :: float 1290 @spec float - integer :: float 1291 def left - right do 1292 :erlang.-(left, right) 1293 end 1294 1295 @doc """ 1296 Arithmetic positive unary operator. 1297 1298 Allowed in guard tests. Inlined by the compiler. 1299 1300 ## Examples 1301 1302 iex> +1 1303 1 1304 1305 """ 1306 @doc guard: true 1307 @spec +integer :: integer 1308 @spec +float :: float 1309 def +value do 1310 :erlang.+(value) 1311 end 1312 1313 @doc """ 1314 Arithmetic negative unary operator. 1315 1316 Allowed in guard tests. Inlined by the compiler. 1317 1318 ## Examples 1319 1320 iex> -2 1321 -2 1322 1323 """ 1324 @doc guard: true 1325 @spec -0 :: 0 1326 @spec -pos_integer :: neg_integer 1327 @spec -neg_integer :: pos_integer 1328 @spec -float :: float 1329 def -value do 1330 :erlang.-(value) 1331 end 1332 1333 @doc """ 1334 Arithmetic multiplication operator. 1335 1336 Allowed in guard tests. Inlined by the compiler. 1337 1338 ## Examples 1339 1340 iex> 1 * 2 1341 2 1342 1343 """ 1344 @doc guard: true 1345 @spec integer * integer :: integer 1346 @spec float * float :: float 1347 @spec integer * float :: float 1348 @spec float * integer :: float 1349 def left * right do 1350 :erlang.*(left, right) 1351 end 1352 1353 @doc """ 1354 Arithmetic division operator. 1355 1356 The result is always a float. Use `div/2` and `rem/2` if you want 1357 an integer division or the remainder. 1358 1359 Raises `ArithmeticError` if `right` is 0 or 0.0. 1360 1361 Allowed in guard tests. Inlined by the compiler. 1362 1363 ## Examples 1364 1365 1 / 2 1366 #=> 0.5 1367 1368 -3.0 / 2.0 1369 #=> -1.5 1370 1371 5 / 1 1372 #=> 5.0 1373 1374 7 / 0 1375 ** (ArithmeticError) bad argument in arithmetic expression 1376 1377 """ 1378 @doc guard: true 1379 @spec number / number :: float 1380 def left / right do 1381 :erlang./(left, right) 1382 end 1383 1384 @doc """ 1385 List concatenation operator. Concatenates a proper list and a term, returning a list. 1386 1387 The complexity of `a ++ b` is proportional to `length(a)`, so avoid repeatedly 1388 appending to lists of arbitrary length, for example, `list ++ [element]`. 1389 Instead, consider prepending via `[element | rest]` and then reversing. 1390 1391 If the `right` operand is not a proper list, it returns an improper list. 1392 If the `left` operand is not a proper list, it raises `ArgumentError`. 1393 1394 Inlined by the compiler. 1395 1396 ## Examples 1397 1398 iex> [1] ++ [2, 3] 1399 [1, 2, 3] 1400 1401 iex> 'foo' ++ 'bar' 1402 'foobar' 1403 1404 # returns an improper list 1405 iex> [1] ++ 2 1406 [1 | 2] 1407 1408 # returns a proper list 1409 iex> [1] ++ [2] 1410 [1, 2] 1411 1412 # improper list on the right will return an improper list 1413 iex> [1] ++ [2 | 3] 1414 [1, 2 | 3] 1415 1416 """ 1417 @spec list ++ term :: maybe_improper_list 1418 def left ++ right do 1419 :erlang.++(left, right) 1420 end 1421 1422 @doc """ 1423 List subtraction operator. Removes the first occurrence of an element on the left list 1424 for each element on the right. 1425 1426 Before Erlang/OTP 22, the complexity of `a -- b` was proportional to 1427 `length(a) * length(b)`, meaning that it would be very slow if 1428 both `a` and `b` were long lists. In such cases, consider 1429 converting each list to a `MapSet` and using `MapSet.difference/2`. 1430 1431 As of Erlang/OTP 22, this operation is significantly faster even if both 1432 lists are very long, and using `--/2` is usually faster and uses less 1433 memory than using the `MapSet`-based alternative mentioned above. 1434 See also the [Erlang efficiency 1435 guide](https://erlang.org/doc/efficiency_guide/retired_myths.html). 1436 1437 Inlined by the compiler. 1438 1439 ## Examples 1440 1441 iex> [1, 2, 3] -- [1, 2] 1442 [3] 1443 1444 iex> [1, 2, 3, 2, 1] -- [1, 2, 2] 1445 [3, 1] 1446 1447 The `--/2` operator is right associative, meaning: 1448 1449 iex> [1, 2, 3] -- [2] -- [3] 1450 [1, 3] 1451 1452 As it is equivalent to: 1453 1454 iex> [1, 2, 3] -- ([2] -- [3]) 1455 [1, 3] 1456 1457 """ 1458 @spec list -- list :: list 1459 def left -- right do 1460 :erlang.--(left, right) 1461 end 1462 1463 @doc """ 1464 Strictly boolean "not" operator. 1465 1466 `value` must be a boolean; if it's not, an `ArgumentError` exception is raised. 1467 1468 Allowed in guard tests. Inlined by the compiler. 1469 1470 ## Examples 1471 1472 iex> not false 1473 true 1474 1475 """ 1476 @doc guard: true 1477 @spec not true :: false 1478 @spec not false :: true 1479 def not value do 1480 :erlang.not(value) 1481 end 1482 1483 @doc """ 1484 Less-than operator. 1485 1486 Returns `true` if `left` is less than `right`. 1487 1488 This performs a structural comparison where all Elixir 1489 terms can be compared with each other. See the ["Structural 1490 comparison" section](#module-structural-comparison) section 1491 for more information. 1492 1493 Allowed in guard tests. Inlined by the compiler. 1494 1495 ## Examples 1496 1497 iex> 1 < 2 1498 true 1499 1500 """ 1501 @doc guard: true 1502 @spec term < term :: boolean 1503 def left < right do 1504 :erlang.<(left, right) 1505 end 1506 1507 @doc """ 1508 Greater-than operator. 1509 1510 Returns `true` if `left` is more than `right`. 1511 1512 This performs a structural comparison where all Elixir 1513 terms can be compared with each other. See the ["Structural 1514 comparison" section](#module-structural-comparison) section 1515 for more information. 1516 1517 Allowed in guard tests. Inlined by the compiler. 1518 1519 ## Examples 1520 1521 iex> 1 > 2 1522 false 1523 1524 """ 1525 @doc guard: true 1526 @spec term > term :: boolean 1527 def left > right do 1528 :erlang.>(left, right) 1529 end 1530 1531 @doc """ 1532 Less-than or equal to operator. 1533 1534 Returns `true` if `left` is less than or equal to `right`. 1535 1536 This performs a structural comparison where all Elixir 1537 terms can be compared with each other. See the ["Structural 1538 comparison" section](#module-structural-comparison) section 1539 for more information. 1540 1541 Allowed in guard tests. Inlined by the compiler. 1542 1543 ## Examples 1544 1545 iex> 1 <= 2 1546 true 1547 1548 """ 1549 @doc guard: true 1550 @spec term <= term :: boolean 1551 def left <= right do 1552 :erlang."=<"(left, right) 1553 end 1554 1555 @doc """ 1556 Greater-than or equal to operator. 1557 1558 Returns `true` if `left` is more than or equal to `right`. 1559 1560 This performs a structural comparison where all Elixir 1561 terms can be compared with each other. See the ["Structural 1562 comparison" section](#module-structural-comparison) section 1563 for more information. 1564 1565 Allowed in guard tests. Inlined by the compiler. 1566 1567 ## Examples 1568 1569 iex> 1 >= 2 1570 false 1571 1572 """ 1573 @doc guard: true 1574 @spec term >= term :: boolean 1575 def left >= right do 1576 :erlang.>=(left, right) 1577 end 1578 1579 @doc """ 1580 Equal to operator. Returns `true` if the two terms are equal. 1581 1582 This operator considers 1 and 1.0 to be equal. For stricter 1583 semantics, use `===/2` instead. 1584 1585 All terms in Elixir can be compared with each other. 1586 1587 Allowed in guard tests. Inlined by the compiler. 1588 1589 ## Examples 1590 1591 iex> 1 == 2 1592 false 1593 1594 iex> 1 == 1.0 1595 true 1596 1597 """ 1598 @doc guard: true 1599 @spec term == term :: boolean 1600 def left == right do 1601 :erlang.==(left, right) 1602 end 1603 1604 @doc """ 1605 Not equal to operator. 1606 1607 Returns `true` if the two terms are not equal. 1608 1609 This operator considers 1 and 1.0 to be equal. For match 1610 comparison, use `!==/2` instead. 1611 1612 All terms in Elixir can be compared with each other. 1613 1614 Allowed in guard tests. Inlined by the compiler. 1615 1616 ## Examples 1617 1618 iex> 1 != 2 1619 true 1620 1621 iex> 1 != 1.0 1622 false 1623 1624 """ 1625 @doc guard: true 1626 @spec term != term :: boolean 1627 def left != right do 1628 :erlang."/="(left, right) 1629 end 1630 1631 @doc """ 1632 Strictly equal to operator. 1633 1634 Returns `true` if the two terms are exactly equal. 1635 1636 The terms are only considered to be exactly equal if they 1637 have the same value and are of the same type. For example, 1638 `1 == 1.0` returns `true`, but since they are of different 1639 types, `1 === 1.0` returns `false`. 1640 1641 All terms in Elixir can be compared with each other. 1642 1643 Allowed in guard tests. Inlined by the compiler. 1644 1645 ## Examples 1646 1647 iex> 1 === 2 1648 false 1649 1650 iex> 1 === 1.0 1651 false 1652 1653 """ 1654 @doc guard: true 1655 @spec term === term :: boolean 1656 def left === right do 1657 :erlang."=:="(left, right) 1658 end 1659 1660 @doc """ 1661 Strictly not equal to operator. 1662 1663 Returns `true` if the two terms are not exactly equal. 1664 See `===/2` for a definition of what is considered "exactly equal". 1665 1666 All terms in Elixir can be compared with each other. 1667 1668 Allowed in guard tests. Inlined by the compiler. 1669 1670 ## Examples 1671 1672 iex> 1 !== 2 1673 true 1674 1675 iex> 1 !== 1.0 1676 true 1677 1678 """ 1679 @doc guard: true 1680 @spec term !== term :: boolean 1681 def left !== right do 1682 :erlang."=/="(left, right) 1683 end 1684 1685 @doc """ 1686 Gets the element at the zero-based `index` in `tuple`. 1687 1688 It raises `ArgumentError` when index is negative or it is out of range of the tuple elements. 1689 1690 Allowed in guard tests. Inlined by the compiler. 1691 1692 ## Examples 1693 1694 tuple = {:foo, :bar, 3} 1695 elem(tuple, 1) 1696 #=> :bar 1697 1698 elem({}, 0) 1699 ** (ArgumentError) argument error 1700 1701 elem({:foo, :bar}, 2) 1702 ** (ArgumentError) argument error 1703 1704 """ 1705 @doc guard: true 1706 @spec elem(tuple, non_neg_integer) :: term 1707 def elem(tuple, index) do 1708 :erlang.element(index + 1, tuple) 1709 end 1710 1711 @doc """ 1712 Puts `value` at the given zero-based `index` in `tuple`. 1713 1714 Inlined by the compiler. 1715 1716 ## Examples 1717 1718 iex> tuple = {:foo, :bar, 3} 1719 iex> put_elem(tuple, 0, :baz) 1720 {:baz, :bar, 3} 1721 1722 """ 1723 @spec put_elem(tuple, non_neg_integer, term) :: tuple 1724 def put_elem(tuple, index, value) do 1725 :erlang.setelement(index + 1, tuple, value) 1726 end 1727 1728 ## Implemented in Elixir 1729 1730 defp optimize_boolean({:case, meta, args}) do 1731 {:case, [{:optimize_boolean, true} | meta], args} 1732 end 1733 1734 @doc """ 1735 Strictly boolean "or" operator. 1736 1737 If `left` is `true`, returns `true`; otherwise returns `right`. 1738 1739 Requires only the `left` operand to be a boolean since it short-circuits. 1740 If the `left` operand is not a boolean, a `BadBooleanError` exception is 1741 raised. 1742 1743 Allowed in guard tests. 1744 1745 ## Examples 1746 1747 iex> true or false 1748 true 1749 1750 iex> false or 42 1751 42 1752 1753 iex> 42 or false 1754 ** (BadBooleanError) expected a boolean on left-side of "or", got: 42 1755 1756 """ 1757 @doc guard: true 1758 defmacro left or right do 1759 case __CALLER__.context do 1760 nil -> build_boolean_check(:or, left, true, right) 1761 :match -> invalid_match!(:or) 1762 :guard -> quote(do: :erlang.orelse(unquote(left), unquote(right))) 1763 end 1764 end 1765 1766 @doc """ 1767 Strictly boolean "and" operator. 1768 1769 If `left` is `false`, returns `false`; otherwise returns `right`. 1770 1771 Requires only the `left` operand to be a boolean since it short-circuits. If 1772 the `left` operand is not a boolean, a `BadBooleanError` exception is raised. 1773 1774 Allowed in guard tests. 1775 1776 ## Examples 1777 1778 iex> true and false 1779 false 1780 1781 iex> true and "yay!" 1782 "yay!" 1783 1784 iex> "yay!" and true 1785 ** (BadBooleanError) expected a boolean on left-side of "and", got: "yay!" 1786 1787 """ 1788 @doc guard: true 1789 defmacro left and right do 1790 case __CALLER__.context do 1791 nil -> build_boolean_check(:and, left, right, false) 1792 :match -> invalid_match!(:and) 1793 :guard -> quote(do: :erlang.andalso(unquote(left), unquote(right))) 1794 end 1795 end 1796 1797 defp build_boolean_check(operator, check, true_clause, false_clause) do 1798 optimize_boolean( 1799 quote do 1800 case unquote(check) do 1801 false -> unquote(false_clause) 1802 true -> unquote(true_clause) 1803 other -> :erlang.error({:badbool, unquote(operator), other}) 1804 end 1805 end 1806 ) 1807 end 1808 1809 @doc """ 1810 Boolean "not" operator. 1811 1812 Receives any value (not just booleans) and returns `true` if `value` 1813 is `false` or `nil`; returns `false` otherwise. 1814 1815 Not allowed in guard clauses. 1816 1817 ## Examples 1818 1819 iex> !Enum.empty?([]) 1820 false 1821 1822 iex> !List.first([]) 1823 true 1824 1825 """ 1826 defmacro !value 1827 1828 defmacro !{:!, _, [value]} do 1829 assert_no_match_or_guard_scope(__CALLER__.context, "!") 1830 1831 optimize_boolean( 1832 quote do 1833 case unquote(value) do 1834 x when :"Elixir.Kernel".in(x, [false, nil]) -> false 1835 _ -> true 1836 end 1837 end 1838 ) 1839 end 1840 1841 defmacro !value do 1842 assert_no_match_or_guard_scope(__CALLER__.context, "!") 1843 1844 optimize_boolean( 1845 quote do 1846 case unquote(value) do 1847 x when :"Elixir.Kernel".in(x, [false, nil]) -> true 1848 _ -> false 1849 end 1850 end 1851 ) 1852 end 1853 1854 @doc """ 1855 Binary concatenation operator. Concatenates two binaries. 1856 1857 ## Examples 1858 1859 iex> "foo" <> "bar" 1860 "foobar" 1861 1862 The `<>/2` operator can also be used in pattern matching (and guard clauses) as 1863 long as the left argument is a literal binary: 1864 1865 iex> "foo" <> x = "foobar" 1866 iex> x 1867 "bar" 1868 1869 `x <> "bar" = "foobar"` would have resulted in a `CompileError` exception. 1870 1871 """ 1872 defmacro left <> right do 1873 concats = extract_concatenations({:<>, [], [left, right]}, __CALLER__) 1874 quote(do: <<unquote_splicing(concats)>>) 1875 end 1876 1877 # Extracts concatenations in order to optimize many 1878 # concatenations into one single clause. 1879 defp extract_concatenations({:<>, _, [left, right]}, caller) do 1880 [wrap_concatenation(left, :left, caller) | extract_concatenations(right, caller)] 1881 end 1882 1883 defp extract_concatenations(other, caller) do 1884 [wrap_concatenation(other, :right, caller)] 1885 end 1886 1887 defp wrap_concatenation(binary, _side, _caller) when is_binary(binary) do 1888 binary 1889 end 1890 1891 defp wrap_concatenation(literal, _side, _caller) 1892 when is_list(literal) or is_atom(literal) or is_integer(literal) or is_float(literal) do 1893 :erlang.error( 1894 ArgumentError.exception( 1895 "expected binary argument in <> operator but got: #{Macro.to_string(literal)}" 1896 ) 1897 ) 1898 end 1899 1900 defp wrap_concatenation(other, side, caller) do 1901 expanded = expand_concat_argument(other, side, caller) 1902 {:"::", [], [expanded, {:binary, [], nil}]} 1903 end 1904 1905 defp expand_concat_argument(arg, :left, %{context: :match} = caller) do 1906 expanded_arg = 1907 case bootstrapped?(Macro) do 1908 true -> Macro.expand(arg, caller) 1909 false -> arg 1910 end 1911 1912 case expanded_arg do 1913 {var, _, nil} when is_atom(var) -> 1914 invalid_concat_left_argument_error(Atom.to_string(var)) 1915 1916 {:^, _, [{var, _, nil}]} when is_atom(var) -> 1917 invalid_concat_left_argument_error("^#{Atom.to_string(var)}") 1918 1919 _ -> 1920 expanded_arg 1921 end 1922 end 1923 1924 defp expand_concat_argument(arg, _, _) do 1925 arg 1926 end 1927 1928 defp invalid_concat_left_argument_error(arg) do 1929 :erlang.error( 1930 ArgumentError.exception( 1931 "the left argument of <> operator inside a match should always be a literal " <> 1932 "binary because its size can't be verified. Got: #{arg}" 1933 ) 1934 ) 1935 end 1936 1937 @doc """ 1938 Raises an exception. 1939 1940 If `message` is a string, it raises a `RuntimeError` exception with it. 1941 1942 If `message` is an atom, it just calls `raise/2` with the atom as the first 1943 argument and `[]` as the second one. 1944 1945 If `message` is an exception struct, it is raised as is. 1946 1947 If `message` is anything else, `raise` will fail with an `ArgumentError` 1948 exception. 1949 1950 ## Examples 1951 1952 iex> raise "oops" 1953 ** (RuntimeError) oops 1954 1955 try do 1956 1 + :foo 1957 rescue 1958 x in [ArithmeticError] -> 1959 IO.puts("that was expected") 1960 raise x 1961 end 1962 1963 """ 1964 defmacro raise(message) do 1965 # Try to figure out the type at compilation time 1966 # to avoid dead code and make Dialyzer happy. 1967 message = 1968 case not is_binary(message) and bootstrapped?(Macro) do 1969 true -> Macro.expand(message, __CALLER__) 1970 false -> message 1971 end 1972 1973 case message do 1974 message when is_binary(message) -> 1975 quote do 1976 :erlang.error(RuntimeError.exception(unquote(message))) 1977 end 1978 1979 {:<<>>, _, _} = message -> 1980 quote do 1981 :erlang.error(RuntimeError.exception(unquote(message))) 1982 end 1983 1984 alias when is_atom(alias) -> 1985 quote do 1986 :erlang.error(unquote(alias).exception([])) 1987 end 1988 1989 _ -> 1990 quote do 1991 :erlang.error(Kernel.Utils.raise(unquote(message))) 1992 end 1993 end 1994 end 1995 1996 @doc """ 1997 Raises an exception. 1998 1999 Calls the `exception/1` function on the given argument (which has to be a 2000 module name like `ArgumentError` or `RuntimeError`) passing `attributes` 2001 in order to retrieve the exception struct. 2002 2003 Any module that contains a call to the `defexception/1` macro automatically 2004 implements the `c:Exception.exception/1` callback expected by `raise/2`. 2005 For more information, see `defexception/1`. 2006 2007 ## Examples 2008 2009 iex> raise(ArgumentError, "Sample") 2010 ** (ArgumentError) Sample 2011 2012 """ 2013 defmacro raise(exception, attributes) do 2014 quote do 2015 :erlang.error(unquote(exception).exception(unquote(attributes))) 2016 end 2017 end 2018 2019 @doc """ 2020 Raises an exception preserving a previous stacktrace. 2021 2022 Works like `raise/1` but does not generate a new stacktrace. 2023 2024 Note that `__STACKTRACE__` can be used inside catch/rescue 2025 to retrieve the current stacktrace. 2026 2027 ## Examples 2028 2029 try do 2030 raise "oops" 2031 rescue 2032 exception -> 2033 reraise exception, __STACKTRACE__ 2034 end 2035 2036 """ 2037 defmacro reraise(message, stacktrace) do 2038 # Try to figure out the type at compilation time 2039 # to avoid dead code and make Dialyzer happy. 2040 case Macro.expand(message, __CALLER__) do 2041 message when is_binary(message) -> 2042 quote do 2043 :erlang.error( 2044 :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) 2045 ) 2046 end 2047 2048 {:<<>>, _, _} = message -> 2049 quote do 2050 :erlang.error( 2051 :erlang.raise(:error, RuntimeError.exception(unquote(message)), unquote(stacktrace)) 2052 ) 2053 end 2054 2055 alias when is_atom(alias) -> 2056 quote do 2057 :erlang.error(:erlang.raise(:error, unquote(alias).exception([]), unquote(stacktrace))) 2058 end 2059 2060 message -> 2061 quote do 2062 :erlang.error( 2063 :erlang.raise(:error, Kernel.Utils.raise(unquote(message)), unquote(stacktrace)) 2064 ) 2065 end 2066 end 2067 end 2068 2069 @doc """ 2070 Raises an exception preserving a previous stacktrace. 2071 2072 `reraise/3` works like `reraise/2`, except it passes arguments to the 2073 `exception/1` function as explained in `raise/2`. 2074 2075 ## Examples 2076 2077 try do 2078 raise "oops" 2079 rescue 2080 exception -> 2081 reraise WrapperError, [exception: exception], __STACKTRACE__ 2082 end 2083 2084 """ 2085 defmacro reraise(exception, attributes, stacktrace) do 2086 quote do 2087 :erlang.raise( 2088 :error, 2089 unquote(exception).exception(unquote(attributes)), 2090 unquote(stacktrace) 2091 ) 2092 end 2093 end 2094 2095 @doc """ 2096 Text-based match operator. Matches the term on the `left` 2097 against the regular expression or string on the `right`. 2098 2099 If `right` is a regular expression, returns `true` if `left` matches right. 2100 2101 If `right` is a string, returns `true` if `left` contains `right`. 2102 2103 ## Examples 2104 2105 iex> "abcd" =~ ~r/c(d)/ 2106 true 2107 2108 iex> "abcd" =~ ~r/e/ 2109 false 2110 2111 iex> "abcd" =~ ~r// 2112 true 2113 2114 iex> "abcd" =~ "bc" 2115 true 2116 2117 iex> "abcd" =~ "ad" 2118 false 2119 2120 iex> "abcd" =~ "abcd" 2121 true 2122 2123 iex> "abcd" =~ "" 2124 true 2125 2126 """ 2127 @spec String.t() =~ (String.t() | Regex.t()) :: boolean 2128 def left =~ "" when is_binary(left), do: true 2129 2130 def left =~ right when is_binary(left) and is_binary(right) do 2131 :binary.match(left, right) != :nomatch 2132 end 2133 2134 def left =~ right when is_binary(left) do 2135 Regex.match?(right, left) 2136 end 2137 2138 @doc ~S""" 2139 Inspects the given argument according to the `Inspect` protocol. 2140 The second argument is a keyword list with options to control 2141 inspection. 2142 2143 ## Options 2144 2145 `inspect/2` accepts a list of options that are internally 2146 translated to an `Inspect.Opts` struct. Check the docs for 2147 `Inspect.Opts` to see the supported options. 2148 2149 ## Examples 2150 2151 iex> inspect(:foo) 2152 ":foo" 2153 2154 iex> inspect([1, 2, 3, 4, 5], limit: 3) 2155 "[1, 2, 3, ...]" 2156 2157 iex> inspect([1, 2, 3], pretty: true, width: 0) 2158 "[1,\n 2,\n 3]" 2159 2160 iex> inspect("olá" <> <<0>>) 2161 "<<111, 108, 195, 161, 0>>" 2162 2163 iex> inspect("olá" <> <<0>>, binaries: :as_strings) 2164 "\"olá\\0\"" 2165 2166 iex> inspect("olá", binaries: :as_binaries) 2167 "<<111, 108, 195, 161>>" 2168 2169 iex> inspect('bar') 2170 "'bar'" 2171 2172 iex> inspect([0 | 'bar']) 2173 "[0, 98, 97, 114]" 2174 2175 iex> inspect(100, base: :octal) 2176 "0o144" 2177 2178 iex> inspect(100, base: :hex) 2179 "0x64" 2180 2181 Note that the `Inspect` protocol does not necessarily return a valid 2182 representation of an Elixir term. In such cases, the inspected result 2183 must start with `#`. For example, inspecting a function will return: 2184 2185 inspect(fn a, b -> a + b end) 2186 #=> #Function<...> 2187 2188 The `Inspect` protocol can be derived to hide certain fields 2189 from structs, so they don't show up in logs, inspects and similar. 2190 See the "Deriving" section of the documentation of the `Inspect` 2191 protocol for more information. 2192 """ 2193 @spec inspect(Inspect.t(), keyword) :: String.t() 2194 def inspect(term, opts \\ []) when is_list(opts) do 2195 opts = struct(Inspect.Opts, opts) 2196 2197 limit = 2198 case opts.pretty do 2199 true -> opts.width 2200 false -> :infinity 2201 end 2202 2203 doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(term, opts)) 2204 IO.iodata_to_binary(Inspect.Algebra.format(doc, limit)) 2205 end 2206 2207 @doc """ 2208 Creates and updates a struct. 2209 2210 The `struct` argument may be an atom (which defines `defstruct`) 2211 or a `struct` itself. The second argument is any `Enumerable` that 2212 emits two-element tuples (key-value pairs) during enumeration. 2213 2214 Keys in the `Enumerable` that don't exist in the struct are automatically 2215 discarded. Note that keys must be atoms, as only atoms are allowed when 2216 defining a struct. If keys in the `Enumerable` are duplicated, the last 2217 entry will be taken (same behaviour as `Map.new/1`). 2218 2219 This function is useful for dynamically creating and updating structs, as 2220 well as for converting maps to structs; in the latter case, just inserting 2221 the appropriate `:__struct__` field into the map may not be enough and 2222 `struct/2` should be used instead. 2223 2224 ## Examples 2225 2226 defmodule User do 2227 defstruct name: "john" 2228 end 2229 2230 struct(User) 2231 #=> %User{name: "john"} 2232 2233 opts = [name: "meg"] 2234 user = struct(User, opts) 2235 #=> %User{name: "meg"} 2236 2237 struct(user, unknown: "value") 2238 #=> %User{name: "meg"} 2239 2240 struct(User, %{name: "meg"}) 2241 #=> %User{name: "meg"} 2242 2243 # String keys are ignored 2244 struct(User, %{"name" => "meg"}) 2245 #=> %User{name: "john"} 2246 2247 """ 2248 @spec struct(module | struct, Enum.t()) :: struct 2249 def struct(struct, fields \\ []) do 2250 struct(struct, fields, fn 2251 {:__struct__, _val}, acc -> 2252 acc 2253 2254 {key, val}, acc -> 2255 case acc do 2256 %{^key => _} -> %{acc | key => val} 2257 _ -> acc 2258 end 2259 end) 2260 end 2261 2262 @doc """ 2263 Similar to `struct/2` but checks for key validity. 2264 2265 The function `struct!/2` emulates the compile time behaviour 2266 of structs. This means that: 2267 2268 * when building a struct, as in `struct!(SomeStruct, key: :value)`, 2269 it is equivalent to `%SomeStruct{key: :value}` and therefore this 2270 function will check if every given key-value belongs to the struct. 2271 If the struct is enforcing any key via `@enforce_keys`, those will 2272 be enforced as well; 2273 2274 * when updating a struct, as in `struct!(%SomeStruct{}, key: :value)`, 2275 it is equivalent to `%SomeStruct{struct | key: :value}` and therefore this 2276 function will check if every given key-value belongs to the struct. 2277 However, updating structs does not enforce keys, as keys are enforced 2278 only when building; 2279 2280 """ 2281 @spec struct!(module | struct, Enum.t()) :: struct 2282 def struct!(struct, fields \\ []) 2283 2284 def struct!(struct, fields) when is_atom(struct) do 2285 validate_struct!(struct.__struct__(fields), struct, 1) 2286 end 2287 2288 def struct!(struct, fields) when is_map(struct) do 2289 struct(struct, fields, fn 2290 {:__struct__, _}, acc -> 2291 acc 2292 2293 {key, val}, acc -> 2294 Map.replace!(acc, key, val) 2295 end) 2296 end 2297 2298 defp struct(struct, [], _fun) when is_atom(struct) do 2299 validate_struct!(struct.__struct__(), struct, 0) 2300 end 2301 2302 defp struct(struct, fields, fun) when is_atom(struct) do 2303 struct(validate_struct!(struct.__struct__(), struct, 0), fields, fun) 2304 end 2305 2306 defp struct(%_{} = struct, [], _fun) do 2307 struct 2308 end 2309 2310 defp struct(%_{} = struct, fields, fun) do 2311 Enum.reduce(fields, struct, fun) 2312 end 2313 2314 defp validate_struct!(%{__struct__: module} = struct, module, _arity) do 2315 struct 2316 end 2317 2318 defp validate_struct!(%{__struct__: struct_name}, module, arity) when is_atom(struct_name) do 2319 error_message = 2320 "expected struct name returned by #{inspect(module)}.__struct__/#{arity} to be " <> 2321 "#{inspect(module)}, got: #{inspect(struct_name)}" 2322 2323 :erlang.error(ArgumentError.exception(error_message)) 2324 end 2325 2326 defp validate_struct!(expr, module, arity) do 2327 error_message = 2328 "expected #{inspect(module)}.__struct__/#{arity} to return a map with a :__struct__ " <> 2329 "key that holds the name of the struct (atom), got: #{inspect(expr)}" 2330 2331 :erlang.error(ArgumentError.exception(error_message)) 2332 end 2333 2334 @doc """ 2335 Returns true if `term` is a struct; otherwise returns `false`. 2336 2337 Allowed in guard tests. 2338 2339 ## Examples 2340 2341 iex> is_struct(URI.parse("/")) 2342 true 2343 2344 iex> is_struct(%{}) 2345 false 2346 2347 """ 2348 @doc since: "1.10.0", guard: true 2349 defmacro is_struct(term) do 2350 case __CALLER__.context do 2351 nil -> 2352 quote do 2353 case unquote(term) do 2354 %_{} -> true 2355 _ -> false 2356 end 2357 end 2358 2359 :match -> 2360 invalid_match!(:is_struct) 2361 2362 :guard -> 2363 quote do 2364 is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and 2365 is_atom(:erlang.map_get(:__struct__, unquote(term))) 2366 end 2367 end 2368 end 2369 2370 @doc """ 2371 Returns true if `term` is a struct of `name`; otherwise returns `false`. 2372 2373 Allowed in guard tests. 2374 2375 ## Examples 2376 2377 iex> is_struct(URI.parse("/"), URI) 2378 true 2379 2380 iex> is_struct(URI.parse("/"), Macro.Env) 2381 false 2382 2383 """ 2384 @doc since: "1.11.0", guard: true 2385 defmacro is_struct(term, name) do 2386 case __CALLER__.context do 2387 nil -> 2388 quote generated: true do 2389 case unquote(name) do 2390 name when is_atom(name) -> 2391 case unquote(term) do 2392 %{__struct__: ^name} -> true 2393 _ -> false 2394 end 2395 2396 _ -> 2397 raise ArgumentError 2398 end 2399 end 2400 2401 :match -> 2402 invalid_match!(:is_struct) 2403 2404 :guard -> 2405 quote do 2406 is_map(unquote(term)) and 2407 (is_atom(unquote(name)) or :fail) and 2408 :erlang.is_map_key(:__struct__, unquote(term)) and 2409 :erlang.map_get(:__struct__, unquote(term)) == unquote(name) 2410 end 2411 end 2412 end 2413 2414 @doc """ 2415 Returns true if `term` is an exception; otherwise returns `false`. 2416 2417 Allowed in guard tests. 2418 2419 ## Examples 2420 2421 iex> is_exception(%RuntimeError{}) 2422 true 2423 2424 iex> is_exception(%{}) 2425 false 2426 2427 """ 2428 @doc since: "1.11.0", guard: true 2429 defmacro is_exception(term) do 2430 case __CALLER__.context do 2431 nil -> 2432 quote do 2433 case unquote(term) do 2434 %_{__exception__: true} -> true 2435 _ -> false 2436 end 2437 end 2438 2439 :match -> 2440 invalid_match!(:is_exception) 2441 2442 :guard -> 2443 quote do 2444 is_map(unquote(term)) and :erlang.is_map_key(:__struct__, unquote(term)) and 2445 is_atom(:erlang.map_get(:__struct__, unquote(term))) and 2446 :erlang.is_map_key(:__exception__, unquote(term)) and 2447 :erlang.map_get(:__exception__, unquote(term)) == true 2448 end 2449 end 2450 end 2451 2452 @doc """ 2453 Returns true if `term` is an exception of `name`; otherwise returns `false`. 2454 2455 Allowed in guard tests. 2456 2457 ## Examples 2458 2459 iex> is_exception(%RuntimeError{}, RuntimeError) 2460 true 2461 2462 iex> is_exception(%RuntimeError{}, Macro.Env) 2463 false 2464 2465 """ 2466 @doc since: "1.11.0", guard: true 2467 defmacro is_exception(term, name) do 2468 case __CALLER__.context do 2469 nil -> 2470 quote do 2471 case unquote(name) do 2472 name when is_atom(name) -> 2473 case unquote(term) do 2474 %{__struct__: ^name, __exception__: true} -> true 2475 _ -> false 2476 end 2477 2478 _ -> 2479 raise ArgumentError 2480 end 2481 end 2482 2483 :match -> 2484 invalid_match!(:is_exception) 2485 2486 :guard -> 2487 quote do 2488 is_map(unquote(term)) and 2489 (is_atom(unquote(name)) or :fail) and 2490 :erlang.is_map_key(:__struct__, unquote(term)) and 2491 :erlang.map_get(:__struct__, unquote(term)) == unquote(name) and 2492 :erlang.is_map_key(:__exception__, unquote(term)) and 2493 :erlang.map_get(:__exception__, unquote(term)) == true 2494 end 2495 end 2496 end 2497 2498 @doc """ 2499 Pipes `value` into the given `fun`. 2500 2501 In other words, it invokes `fun` with `value` as argument. 2502 This is most commonly used in pipelines, allowing you 2503 to pipe a value to a function outside of its first argument. 2504 2505 ### Examples 2506 2507 iex> 1 |> then(fn x -> x * 2 end) 2508 2 2509 """ 2510 @doc since: "1.12.0" 2511 defmacro then(value, fun) do 2512 quote do 2513 unquote(fun).(unquote(value)) 2514 end 2515 end 2516 2517 @doc """ 2518 Gets a value from a nested structure. 2519 2520 Uses the `Access` module to traverse the structures 2521 according to the given `keys`, unless the `key` is a 2522 function, which is detailed in a later section. 2523 2524 ## Examples 2525 2526 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2527 iex> get_in(users, ["john", :age]) 2528 27 2529 2530 In case any of the keys returns `nil`, `nil` will be returned: 2531 2532 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2533 iex> get_in(users, ["unknown", :age]) 2534 nil 2535 2536 Note that `get_in` exists mostly for convenience and parity with 2537 functionality found in `put_in` and `update_in`. Given Elixir 2538 provides pattern matching, it can often be more expressive for 2539 deep data traversal, for example: 2540 2541 case users do 2542 %{"unknown" => %{age: age}} -> age 2543 _ -> default_value 2544 end 2545 2546 ## Functions as keys 2547 2548 If a key is a function, the function will be invoked passing three 2549 arguments: 2550 2551 * the operation (`:get`) 2552 * the data to be accessed 2553 * a function to be invoked next 2554 2555 This means `get_in/2` can be extended to provide custom lookups. 2556 In the example below, we use a function to get all the maps inside 2557 a list: 2558 2559 iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] 2560 iex> all = fn :get, data, next -> Enum.map(data, next) end 2561 iex> get_in(users, [all, :age]) 2562 [27, 23] 2563 2564 If the previous value before invoking the function is `nil`, 2565 the function *will* receive `nil` as a value and must handle it 2566 accordingly. 2567 2568 The `Access` module ships with many convenience accessor functions, 2569 like the `all` anonymous function defined above. See `Access.all/0`, 2570 `Access.key/2`, and others as examples. 2571 2572 ## Working with structs 2573 2574 By default, structs do not implement the `Access` behaviour required 2575 by this function. Therefore, you can't do this: 2576 2577 get_in(some_struct, [:some_key, :nested_key]) 2578 2579 The good news is that structs have predefined shape. Therefore, 2580 you can write instead: 2581 2582 some_struct.some_key.nested_key 2583 2584 If, by any chance, `some_key` can return nil, you can always 2585 fallback to pattern matching to provide nested struct handling: 2586 2587 case some_struct do 2588 %{some_key: %{nested_key: value}} -> value 2589 %{} -> nil 2590 end 2591 2592 """ 2593 @spec get_in(Access.t(), nonempty_list(term)) :: term 2594 def get_in(data, keys) 2595 2596 def get_in(data, [h]) when is_function(h), do: h.(:get, data, & &1) 2597 def get_in(data, [h | t]) when is_function(h), do: h.(:get, data, &get_in(&1, t)) 2598 2599 def get_in(nil, [_]), do: nil 2600 def get_in(nil, [_ | t]), do: get_in(nil, t) 2601 2602 def get_in(data, [h]), do: Access.get(data, h) 2603 def get_in(data, [h | t]), do: get_in(Access.get(data, h), t) 2604 2605 @doc """ 2606 Puts a value in a nested structure. 2607 2608 Uses the `Access` module to traverse the structures 2609 according to the given `keys`, unless the `key` is a 2610 function. If the key is a function, it will be invoked 2611 as specified in `get_and_update_in/3`. 2612 2613 ## Examples 2614 2615 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2616 iex> put_in(users, ["john", :age], 28) 2617 %{"john" => %{age: 28}, "meg" => %{age: 23}} 2618 2619 In case any of the entries in the middle returns `nil`, 2620 an error will be raised when trying to access it next. 2621 """ 2622 @spec put_in(Access.t(), nonempty_list(term), term) :: Access.t() 2623 def put_in(data, [_ | _] = keys, value) do 2624 elem(get_and_update_in(data, keys, fn _ -> {nil, value} end), 1) 2625 end 2626 2627 @doc """ 2628 Updates a key in a nested structure. 2629 2630 Uses the `Access` module to traverse the structures 2631 according to the given `keys`, unless the `key` is a 2632 function. If the key is a function, it will be invoked 2633 as specified in `get_and_update_in/3`. 2634 2635 `data` is a nested structure (that is, a map, keyword 2636 list, or struct that implements the `Access` behaviour). 2637 The `fun` argument receives the value of `key` (or `nil` 2638 if `key` is not present) and the result replaces the value 2639 in the structure. 2640 2641 ## Examples 2642 2643 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2644 iex> update_in(users, ["john", :age], &(&1 + 1)) 2645 %{"john" => %{age: 28}, "meg" => %{age: 23}} 2646 2647 In case any of the entries in the middle returns `nil`, 2648 an error will be raised when trying to access it next. 2649 """ 2650 @spec update_in(Access.t(), nonempty_list(term), (term -> term)) :: Access.t() 2651 def update_in(data, [_ | _] = keys, fun) when is_function(fun) do 2652 elem(get_and_update_in(data, keys, fn x -> {nil, fun.(x)} end), 1) 2653 end 2654 2655 @doc """ 2656 Gets a value and updates a nested structure. 2657 2658 `data` is a nested structure (that is, a map, keyword 2659 list, or struct that implements the `Access` behaviour). 2660 2661 The `fun` argument receives the value of `key` (or `nil` if `key` 2662 is not present) and must return one of the following values: 2663 2664 * a two-element tuple `{current_value, new_value}`. In this case, 2665 `current_value` is the retrieved value which can possibly be operated on before 2666 being returned. `new_value` is the new value to be stored under `key`. 2667 2668 * `:pop`, which implies that the current value under `key` 2669 should be removed from the structure and returned. 2670 2671 This function uses the `Access` module to traverse the structures 2672 according to the given `keys`, unless the `key` is a function, 2673 which is detailed in a later section. 2674 2675 ## Examples 2676 2677 This function is useful when there is a need to retrieve the current 2678 value (or something calculated in function of the current value) and 2679 update it at the same time. For example, it could be used to read the 2680 current age of a user while increasing it by one in one pass: 2681 2682 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2683 iex> get_and_update_in(users, ["john", :age], &{&1, &1 + 1}) 2684 {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} 2685 2686 ## Functions as keys 2687 2688 If a key is a function, the function will be invoked passing three 2689 arguments: 2690 2691 * the operation (`:get_and_update`) 2692 * the data to be accessed 2693 * a function to be invoked next 2694 2695 This means `get_and_update_in/3` can be extended to provide custom 2696 lookups. The downside is that functions cannot be stored as keys 2697 in the accessed data structures. 2698 2699 When one of the keys is a function, the function is invoked. 2700 In the example below, we use a function to get and increment all 2701 ages inside a list: 2702 2703 iex> users = [%{name: "john", age: 27}, %{name: "meg", age: 23}] 2704 iex> all = fn :get_and_update, data, next -> 2705 ...> data |> Enum.map(next) |> Enum.unzip() 2706 ...> end 2707 iex> get_and_update_in(users, [all, :age], &{&1, &1 + 1}) 2708 {[27, 23], [%{name: "john", age: 28}, %{name: "meg", age: 24}]} 2709 2710 If the previous value before invoking the function is `nil`, 2711 the function *will* receive `nil` as a value and must handle it 2712 accordingly (be it by failing or providing a sane default). 2713 2714 The `Access` module ships with many convenience accessor functions, 2715 like the `all` anonymous function defined above. See `Access.all/0`, 2716 `Access.key/2`, and others as examples. 2717 """ 2718 @spec get_and_update_in( 2719 structure, 2720 keys, 2721 (term | nil -> {current_value, new_value} | :pop) 2722 ) :: {current_value, new_structure :: structure} 2723 when structure: Access.t(), 2724 keys: nonempty_list(any), 2725 current_value: Access.value(), 2726 new_value: Access.value() 2727 def get_and_update_in(data, keys, fun) 2728 2729 def get_and_update_in(data, [head], fun) when is_function(head, 3), 2730 do: head.(:get_and_update, data, fun) 2731 2732 def get_and_update_in(data, [head | tail], fun) when is_function(head, 3), 2733 do: head.(:get_and_update, data, &get_and_update_in(&1, tail, fun)) 2734 2735 def get_and_update_in(data, [head], fun) when is_function(fun, 1), 2736 do: Access.get_and_update(data, head, fun) 2737 2738 def get_and_update_in(data, [head | tail], fun) when is_function(fun, 1), 2739 do: Access.get_and_update(data, head, &get_and_update_in(&1, tail, fun)) 2740 2741 @doc """ 2742 Pops a key from the given nested structure. 2743 2744 Uses the `Access` protocol to traverse the structures 2745 according to the given `keys`, unless the `key` is a 2746 function. If the key is a function, it will be invoked 2747 as specified in `get_and_update_in/3`. 2748 2749 ## Examples 2750 2751 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2752 iex> pop_in(users, ["john", :age]) 2753 {27, %{"john" => %{}, "meg" => %{age: 23}}} 2754 2755 In case any entry returns `nil`, its key will be removed 2756 and the deletion will be considered a success. 2757 2758 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2759 iex> pop_in(users, ["jane", :age]) 2760 {nil, %{"john" => %{age: 27}, "meg" => %{age: 23}}} 2761 2762 """ 2763 @spec pop_in(data, nonempty_list(Access.get_and_update_fun(term, data) | term)) :: {term, data} 2764 when data: Access.container() 2765 def pop_in(data, keys) 2766 2767 def pop_in(nil, [key | _]) do 2768 raise ArgumentError, "could not pop key #{inspect(key)} on a nil value" 2769 end 2770 2771 def pop_in(data, [_ | _] = keys) do 2772 pop_in_data(data, keys) 2773 end 2774 2775 defp pop_in_data(nil, [_ | _]), do: :pop 2776 2777 defp pop_in_data(data, [fun]) when is_function(fun), 2778 do: fun.(:get_and_update, data, fn _ -> :pop end) 2779 2780 defp pop_in_data(data, [fun | tail]) when is_function(fun), 2781 do: fun.(:get_and_update, data, &pop_in_data(&1, tail)) 2782 2783 defp pop_in_data(data, [key]), do: Access.pop(data, key) 2784 2785 defp pop_in_data(data, [key | tail]), 2786 do: Access.get_and_update(data, key, &pop_in_data(&1, tail)) 2787 2788 @doc """ 2789 Puts a value in a nested structure via the given `path`. 2790 2791 This is similar to `put_in/3`, except the path is extracted via 2792 a macro rather than passing a list. For example: 2793 2794 put_in(opts[:foo][:bar], :baz) 2795 2796 Is equivalent to: 2797 2798 put_in(opts, [:foo, :bar], :baz) 2799 2800 This also works with nested structs and the `struct.path.to.value` way to specify 2801 paths: 2802 2803 put_in(struct.foo.bar, :baz) 2804 2805 Note that in order for this macro to work, the complete path must always 2806 be visible by this macro. For more information about the supported path 2807 expressions, please check `get_and_update_in/2` docs. 2808 2809 ## Examples 2810 2811 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2812 iex> put_in(users["john"][:age], 28) 2813 %{"john" => %{age: 28}, "meg" => %{age: 23}} 2814 2815 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2816 iex> put_in(users["john"].age, 28) 2817 %{"john" => %{age: 28}, "meg" => %{age: 23}} 2818 2819 """ 2820 defmacro put_in(path, value) do 2821 case unnest(path, [], true, "put_in/2") do 2822 {[h | t], true} -> 2823 nest_update_in(h, t, quote(do: fn _ -> unquote(value) end)) 2824 2825 {[h | t], false} -> 2826 expr = nest_get_and_update_in(h, t, quote(do: fn _ -> {nil, unquote(value)} end)) 2827 quote(do: :erlang.element(2, unquote(expr))) 2828 end 2829 end 2830 2831 @doc """ 2832 Pops a key from the nested structure via the given `path`. 2833 2834 This is similar to `pop_in/2`, except the path is extracted via 2835 a macro rather than passing a list. For example: 2836 2837 pop_in(opts[:foo][:bar]) 2838 2839 Is equivalent to: 2840 2841 pop_in(opts, [:foo, :bar]) 2842 2843 Note that in order for this macro to work, the complete path must always 2844 be visible by this macro. For more information about the supported path 2845 expressions, please check `get_and_update_in/2` docs. 2846 2847 ## Examples 2848 2849 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2850 iex> pop_in(users["john"][:age]) 2851 {27, %{"john" => %{}, "meg" => %{age: 23}}} 2852 2853 iex> users = %{john: %{age: 27}, meg: %{age: 23}} 2854 iex> pop_in(users.john[:age]) 2855 {27, %{john: %{}, meg: %{age: 23}}} 2856 2857 In case any entry returns `nil`, its key will be removed 2858 and the deletion will be considered a success. 2859 """ 2860 defmacro pop_in(path) do 2861 {[h | t], _} = unnest(path, [], true, "pop_in/1") 2862 nest_pop_in(:map, h, t) 2863 end 2864 2865 @doc """ 2866 Updates a nested structure via the given `path`. 2867 2868 This is similar to `update_in/3`, except the path is extracted via 2869 a macro rather than passing a list. For example: 2870 2871 update_in(opts[:foo][:bar], &(&1 + 1)) 2872 2873 Is equivalent to: 2874 2875 update_in(opts, [:foo, :bar], &(&1 + 1)) 2876 2877 This also works with nested structs and the `struct.path.to.value` way to specify 2878 paths: 2879 2880 update_in(struct.foo.bar, &(&1 + 1)) 2881 2882 Note that in order for this macro to work, the complete path must always 2883 be visible by this macro. For more information about the supported path 2884 expressions, please check `get_and_update_in/2` docs. 2885 2886 ## Examples 2887 2888 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2889 iex> update_in(users["john"][:age], &(&1 + 1)) 2890 %{"john" => %{age: 28}, "meg" => %{age: 23}} 2891 2892 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2893 iex> update_in(users["john"].age, &(&1 + 1)) 2894 %{"john" => %{age: 28}, "meg" => %{age: 23}} 2895 2896 """ 2897 defmacro update_in(path, fun) do 2898 case unnest(path, [], true, "update_in/2") do 2899 {[h | t], true} -> 2900 nest_update_in(h, t, fun) 2901 2902 {[h | t], false} -> 2903 expr = nest_get_and_update_in(h, t, quote(do: fn x -> {nil, unquote(fun).(x)} end)) 2904 quote(do: :erlang.element(2, unquote(expr))) 2905 end 2906 end 2907 2908 @doc """ 2909 Gets a value and updates a nested data structure via the given `path`. 2910 2911 This is similar to `get_and_update_in/3`, except the path is extracted 2912 via a macro rather than passing a list. For example: 2913 2914 get_and_update_in(opts[:foo][:bar], &{&1, &1 + 1}) 2915 2916 Is equivalent to: 2917 2918 get_and_update_in(opts, [:foo, :bar], &{&1, &1 + 1}) 2919 2920 This also works with nested structs and the `struct.path.to.value` way to specify 2921 paths: 2922 2923 get_and_update_in(struct.foo.bar, &{&1, &1 + 1}) 2924 2925 Note that in order for this macro to work, the complete path must always 2926 be visible by this macro. See the "Paths" section below. 2927 2928 ## Examples 2929 2930 iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}} 2931 iex> get_and_update_in(users["john"].age, &{&1, &1 + 1}) 2932 {27, %{"john" => %{age: 28}, "meg" => %{age: 23}}} 2933 2934 ## Paths 2935 2936 A path may start with a variable, local or remote call, and must be 2937 followed by one or more: 2938 2939 * `foo[bar]` - accesses the key `bar` in `foo`; in case `foo` is nil, 2940 `nil` is returned 2941 2942 * `foo.bar` - accesses a map/struct field; in case the field is not 2943 present, an error is raised 2944 2945 Here are some valid paths: 2946 2947 users["john"][:age] 2948 users["john"].age 2949 User.all()["john"].age 2950 all_users()["john"].age 2951 2952 Here are some invalid ones: 2953 2954 # Does a remote call after the initial value 2955 users["john"].do_something(arg1, arg2) 2956 2957 # Does not access any key or field 2958 users 2959 2960 """ 2961 defmacro get_and_update_in(path, fun) do 2962 {[h | t], _} = unnest(path, [], true, "get_and_update_in/2") 2963 nest_get_and_update_in(h, t, fun) 2964 end 2965 2966 defp nest_update_in([], fun), do: fun 2967 2968 defp nest_update_in(list, fun) do 2969 quote do 2970 fn x -> unquote(nest_update_in(quote(do: x), list, fun)) end 2971 end 2972 end 2973 2974 defp nest_update_in(h, [{:map, key} | t], fun) do 2975 quote do 2976 Map.update!(unquote(h), unquote(key), unquote(nest_update_in(t, fun))) 2977 end 2978 end 2979 2980 defp nest_get_and_update_in([], fun), do: fun 2981 2982 defp nest_get_and_update_in(list, fun) do 2983 quote do 2984 fn x -> unquote(nest_get_and_update_in(quote(do: x), list, fun)) end 2985 end 2986 end 2987 2988 defp nest_get_and_update_in(h, [{:access, key} | t], fun) do 2989 quote do 2990 Access.get_and_update(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) 2991 end 2992 end 2993 2994 defp nest_get_and_update_in(h, [{:map, key} | t], fun) do 2995 quote do 2996 Map.get_and_update!(unquote(h), unquote(key), unquote(nest_get_and_update_in(t, fun))) 2997 end 2998 end 2999 3000 defp nest_pop_in(kind, list) do 3001 quote do 3002 fn x -> unquote(nest_pop_in(kind, quote(do: x), list)) end 3003 end 3004 end 3005 3006 defp nest_pop_in(:map, h, [{:access, key}]) do 3007 quote do 3008 case unquote(h) do 3009 nil -> {nil, nil} 3010 h -> Access.pop(h, unquote(key)) 3011 end 3012 end 3013 end 3014 3015 defp nest_pop_in(_, _, [{:map, key}]) do 3016 raise ArgumentError, 3017 "cannot use pop_in when the last segment is a map/struct field. " <> 3018 "This would effectively remove the field #{inspect(key)} from the map/struct" 3019 end 3020 3021 defp nest_pop_in(_, h, [{:map, key} | t]) do 3022 quote do 3023 Map.get_and_update!(unquote(h), unquote(key), unquote(nest_pop_in(:map, t))) 3024 end 3025 end 3026 3027 defp nest_pop_in(_, h, [{:access, key}]) do 3028 quote do 3029 case unquote(h) do 3030 nil -> :pop 3031 h -> Access.pop(h, unquote(key)) 3032 end 3033 end 3034 end 3035 3036 defp nest_pop_in(_, h, [{:access, key} | t]) do 3037 quote do 3038 Access.get_and_update(unquote(h), unquote(key), unquote(nest_pop_in(:access, t))) 3039 end 3040 end 3041 3042 defp unnest({{:., _, [Access, :get]}, _, [expr, key]}, acc, _all_map?, kind) do 3043 unnest(expr, [{:access, key} | acc], false, kind) 3044 end 3045 3046 defp unnest({{:., _, [expr, key]}, _, []}, acc, all_map?, kind) 3047 when is_tuple(expr) and :erlang.element(1, expr) != :__aliases__ and 3048 :erlang.element(1, expr) != :__MODULE__ do 3049 unnest(expr, [{:map, key} | acc], all_map?, kind) 3050 end 3051 3052 defp unnest(other, [], _all_map?, kind) do 3053 raise ArgumentError, 3054 "expected expression given to #{kind} to access at least one element, " <> 3055 "got: #{Macro.to_string(other)}" 3056 end 3057 3058 defp unnest(other, acc, all_map?, kind) do 3059 case proper_start?(other) do 3060 true -> 3061 {[other | acc], all_map?} 3062 3063 false -> 3064 raise ArgumentError, 3065 "expression given to #{kind} must start with a variable, local or remote call " <> 3066 "and be followed by an element access, got: #{Macro.to_string(other)}" 3067 end 3068 end 3069 3070 defp proper_start?({{:., _, [expr, _]}, _, _args}) 3071 when is_atom(expr) 3072 when :erlang.element(1, expr) == :__aliases__ 3073 when :erlang.element(1, expr) == :__MODULE__, 3074 do: true 3075 3076 defp proper_start?({atom, _, _args}) 3077 when is_atom(atom), 3078 do: true 3079 3080 defp proper_start?(other), do: not is_tuple(other) 3081 3082 @doc """ 3083 Converts the argument to a string according to the 3084 `String.Chars` protocol. 3085 3086 This is the function invoked when there is string interpolation. 3087 3088 ## Examples 3089 3090 iex> to_string(:foo) 3091 "foo" 3092 3093 """ 3094 defmacro to_string(term) do 3095 quote(do: :"Elixir.String.Chars".to_string(unquote(term))) 3096 end 3097 3098 @doc """ 3099 Converts the given term to a charlist according to the `List.Chars` protocol. 3100 3101 ## Examples 3102 3103 iex> to_charlist(:foo) 3104 'foo' 3105 3106 """ 3107 defmacro to_charlist(term) do 3108 quote(do: List.Chars.to_charlist(unquote(term))) 3109 end 3110 3111 @doc """ 3112 Returns `true` if `term` is `nil`, `false` otherwise. 3113 3114 Allowed in guard clauses. 3115 3116 ## Examples 3117 3118 iex> is_nil(1) 3119 false 3120 3121 iex> is_nil(nil) 3122 true 3123 3124 """ 3125 @doc guard: true 3126 defmacro is_nil(term) do 3127 quote(do: unquote(term) == nil) 3128 end 3129 3130 @doc """ 3131 A convenience macro that checks if the right side (an expression) matches the 3132 left side (a pattern). 3133 3134 ## Examples 3135 3136 iex> match?(1, 1) 3137 true 3138 3139 iex> match?({1, _}, {1, 2}) 3140 true 3141 3142 iex> map = %{a: 1, b: 2} 3143 iex> match?(%{a: _}, map) 3144 true 3145 3146 iex> a = 1 3147 iex> match?(^a, 1) 3148 true 3149 3150 `match?/2` is very useful when filtering or finding a value in an enumerable: 3151 3152 iex> list = [a: 1, b: 2, a: 3] 3153 iex> Enum.filter(list, &match?({:a, _}, &1)) 3154 [a: 1, a: 3] 3155 3156 Guard clauses can also be given to the match: 3157 3158 iex> list = [a: 1, b: 2, a: 3] 3159 iex> Enum.filter(list, &match?({:a, x} when x < 2, &1)) 3160 [a: 1] 3161 3162 However, variables assigned in the match will not be available 3163 outside of the function call (unlike regular pattern matching with the `=` 3164 operator): 3165 3166 iex> match?(_x, 1) 3167 true 3168 iex> binding() 3169 [] 3170 3171 """ 3172 defmacro match?(pattern, expr) do 3173 success = 3174 quote do 3175 unquote(pattern) -> true 3176 end 3177 3178 failure = 3179 quote generated: true do 3180 _ -> false 3181 end 3182 3183 {:case, [], [expr, [do: success ++ failure]]} 3184 end 3185 3186 @doc """ 3187 Module attribute unary operator. 3188 3189 Reads and writes attributes in the current module. 3190 3191 The canonical example for attributes is annotating that a module 3192 implements an OTP behaviour, such as `GenServer`: 3193 3194 defmodule MyServer do 3195 @behaviour GenServer 3196 # ... callbacks ... 3197 end 3198 3199 By default Elixir supports all the module attributes supported by Erlang, but 3200 custom attributes can be used as well: 3201 3202 defmodule MyServer do 3203 @my_data 13 3204 IO.inspect(@my_data) 3205 #=> 13 3206 end 3207 3208 Unlike Erlang, such attributes are not stored in the module by default since 3209 it is common in Elixir to use custom attributes to store temporary data that 3210 will be available at compile-time. Custom attributes may be configured to 3211 behave closer to Erlang by using `Module.register_attribute/3`. 3212 3213 Finally, note that attributes can also be read inside functions: 3214 3215 defmodule MyServer do 3216 @my_data 11 3217 def first_data, do: @my_data 3218 @my_data 13 3219 def second_data, do: @my_data 3220 end 3221 3222 MyServer.first_data() 3223 #=> 11 3224 3225 MyServer.second_data() 3226 #=> 13 3227 3228 It is important to note that reading an attribute takes a snapshot of 3229 its current value. In other words, the value is read at compilation 3230 time and not at runtime. Check the `Module` module for other functions 3231 to manipulate module attributes. 3232 3233 ## Compile-time considerations 3234 3235 One thing to keep in mind is that references to other modules, even 3236 in module attributes, generate compile-time dependencies to said 3237 modules. 3238 3239 For example, take this common pattern: 3240 3241 @values [:foo, :bar, :baz] 3242 3243 def handle_arg(arg) when arg in @values do 3244 ... 3245 end 3246 3247 While the above is fine, imagine if instead you have actual 3248 module names in the module attribute, like this: 3249 3250 @values [Foo, Bar, Baz] 3251 3252 def handle_arg(arg) when arg in @values do 3253 ... 3254 end 3255 3256 The code above will define a compile-time dependency on the modules 3257 `Foo`, `Bar`, and `Baz`, in a way that, if any of them change, the 3258 current module will have to recompile. In such cases, it may be 3259 preferred to avoid the module attribute altogether: 3260 3261 def handle_arg(arg) when arg in [Foo, Bar, Baz] do 3262 ... 3263 end 3264 3265 """ 3266 defmacro @expr 3267 3268 defmacro @{:__aliases__, _meta, _args} do 3269 raise ArgumentError, "module attributes set via @ cannot start with an uppercase letter" 3270 end 3271 3272 defmacro @{name, meta, args} do 3273 assert_module_scope(__CALLER__, :@, 1) 3274 function? = __CALLER__.function != nil 3275 3276 cond do 3277 # Check for Macro as it is compiled later than Kernel 3278 not bootstrapped?(Macro) -> 3279 nil 3280 3281 not function? and __CALLER__.context == :match -> 3282 raise ArgumentError, 3283 """ 3284 invalid write attribute syntax. If you want to define an attribute, don't do this: 3285 3286 @foo = :value 3287 3288 Instead, do this: 3289 3290 @foo :value 3291 """ 3292 3293 # Typespecs attributes are currently special cased by the compiler 3294 is_list(args) and typespec?(name) -> 3295 case bootstrapped?(Kernel.Typespec) do 3296 false -> 3297 :ok 3298 3299 true -> 3300 pos = :elixir_locals.cache_env(__CALLER__) 3301 %{line: line, file: file, module: module} = __CALLER__ 3302 3303 quote do 3304 Kernel.Typespec.deftypespec( 3305 unquote(name), 3306 unquote(Macro.escape(hd(args), unquote: true)), 3307 unquote(line), 3308 unquote(file), 3309 unquote(module), 3310 unquote(pos) 3311 ) 3312 end 3313 end 3314 3315 true -> 3316 do_at(args, meta, name, function?, __CALLER__) 3317 end 3318 end 3319 3320 # @attribute(value) 3321 defp do_at([arg], meta, name, function?, env) do 3322 line = 3323 case :lists.keymember(:context, 1, meta) do 3324 true -> nil 3325 false -> env.line 3326 end 3327 3328 cond do 3329 function? -> 3330 raise ArgumentError, "cannot set attribute @#{name} inside function/macro" 3331 3332 name == :behavior -> 3333 warn_message = "@behavior attribute is not supported, please use @behaviour instead" 3334 IO.warn(warn_message, Macro.Env.stacktrace(env)) 3335 3336 :lists.member(name, [:moduledoc, :typedoc, :doc]) -> 3337 arg = {env.line, arg} 3338 3339 quote do 3340 Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) 3341 end 3342 3343 true -> 3344 arg = expand_attribute(name, arg, env) 3345 3346 quote do 3347 Module.__put_attribute__(__MODULE__, unquote(name), unquote(arg), unquote(line)) 3348 end 3349 end 3350 end 3351 3352 # @attribute() 3353 defp do_at([], meta, name, function?, env) do 3354 IO.warn( 3355 "the @#{name}() notation (with parenthesis) is deprecated, please use @#{name} (without parenthesis) instead", 3356 Macro.Env.stacktrace(env) 3357 ) 3358 3359 do_at(nil, meta, name, function?, env) 3360 end 3361 3362 # @attribute 3363 defp do_at(args, _meta, name, function?, env) when is_atom(args) do 3364 line = env.line 3365 doc_attr? = :lists.member(name, [:moduledoc, :typedoc, :doc]) 3366 3367 case function? do 3368 true -> 3369 value = 3370 case Module.__get_attribute__(env.module, name, line) do 3371 {_, doc} when doc_attr? -> doc 3372 other -> other 3373 end 3374 3375 try do 3376 :elixir_quote.escape(value, :default, false) 3377 rescue 3378 ex in [ArgumentError] -> 3379 raise ArgumentError, 3380 "cannot inject attribute @#{name} into function/macro because " <> 3381 Exception.message(ex) 3382 end 3383 3384 false when doc_attr? -> 3385 quote do 3386 case Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) do 3387 {_, doc} -> doc 3388 other -> other 3389 end 3390 end 3391 3392 false -> 3393 quote do 3394 Module.__get_attribute__(__MODULE__, unquote(name), unquote(line)) 3395 end 3396 end 3397 end 3398 3399 # Error cases 3400 defp do_at([{call, meta, ctx_or_args}, [{:do, _} | _] = kw], _meta, name, _function?, _env) do 3401 args = 3402 case is_atom(ctx_or_args) do 3403 true -> [] 3404 false -> ctx_or_args 3405 end 3406 3407 code = "\n@#{name} (#{Macro.to_string({call, meta, args ++ [kw]})})" 3408 3409 raise ArgumentError, """ 3410 expected 0 or 1 argument for @#{name}, got 2. 3411 3412 It seems you are trying to use the do-syntax with @module attributes \ 3413 but the do-block is binding to the attribute name. You probably want \ 3414 to wrap the argument value in parentheses, like this: 3415 #{String.replace(code, "\n", "\n ")} 3416 """ 3417 end 3418 3419 defp do_at(args, _meta, name, _function?, _env) do 3420 raise ArgumentError, "expected 0 or 1 argument for @#{name}, got: #{length(args)}" 3421 end 3422 3423 defp expand_attribute(:compile, arg, env) do 3424 Macro.prewalk(arg, fn 3425 # {:no_warn_undefined, alias} 3426 {elem, {:__aliases__, _, _} = alias} -> 3427 {elem, Macro.expand(alias, %{env | function: {:__info__, 1}})} 3428 3429 # {alias, fun, arity} 3430 {:{}, meta, [{:__aliases__, _, _} = alias, fun, arity]} -> 3431 {:{}, meta, [Macro.expand(alias, %{env | function: {:__info__, 1}}), fun, arity]} 3432 3433 node -> 3434 node 3435 end) 3436 end 3437 3438 defp expand_attribute(_, arg, _), do: arg 3439 3440 defp typespec?(:type), do: true 3441 defp typespec?(:typep), do: true 3442 defp typespec?(:opaque), do: true 3443 defp typespec?(:spec), do: true 3444 defp typespec?(:callback), do: true 3445 defp typespec?(:macrocallback), do: true 3446 defp typespec?(_), do: false 3447 3448 @doc """ 3449 Returns the binding for the given context as a keyword list. 3450 3451 In the returned result, keys are variable names and values are the 3452 corresponding variable values. 3453 3454 If the given `context` is `nil` (by default it is), the binding for the 3455 current context is returned. 3456 3457 ## Examples 3458 3459 iex> x = 1 3460 iex> binding() 3461 [x: 1] 3462 iex> x = 2 3463 iex> binding() 3464 [x: 2] 3465 3466 iex> binding(:foo) 3467 [] 3468 iex> var!(x, :foo) = 1 3469 1 3470 iex> binding(:foo) 3471 [x: 1] 3472 3473 """ 3474 defmacro binding(context \\ nil) do 3475 in_match? = Macro.Env.in_match?(__CALLER__) 3476 3477 bindings = 3478 for {v, c} <- Macro.Env.vars(__CALLER__), c == context do 3479 {v, wrap_binding(in_match?, {v, [generated: true], c})} 3480 end 3481 3482 :lists.sort(bindings) 3483 end 3484 3485 defp wrap_binding(true, var) do 3486 quote(do: ^unquote(var)) 3487 end 3488 3489 defp wrap_binding(_, var) do 3490 var 3491 end 3492 3493 @doc """ 3494 Provides an `if/2` macro. 3495 3496 This macro expects the first argument to be a condition and the second 3497 argument to be a keyword list. 3498 3499 ## One-liner examples 3500 3501 if(foo, do: bar) 3502 3503 In the example above, `bar` will be returned if `foo` evaluates to 3504 a truthy value (neither `false` nor `nil`). Otherwise, `nil` will be 3505 returned. 3506 3507 An `else` option can be given to specify the opposite: 3508 3509 if(foo, do: bar, else: baz) 3510 3511 ## Blocks examples 3512 3513 It's also possible to pass a block to the `if/2` macro. The first 3514 example above would be translated to: 3515 3516 if foo do 3517 bar 3518 end 3519 3520 Note that `do/end` become delimiters. The second example would 3521 translate to: 3522 3523 if foo do 3524 bar 3525 else 3526 baz 3527 end 3528 3529 In order to compare more than two clauses, the `cond/1` macro has to be used. 3530 """ 3531 defmacro if(condition, clauses) do 3532 build_if(condition, clauses) 3533 end 3534 3535 defp build_if(condition, do: do_clause) do 3536 build_if(condition, do: do_clause, else: nil) 3537 end 3538 3539 defp build_if(condition, do: do_clause, else: else_clause) do 3540 optimize_boolean( 3541 quote do 3542 case unquote(condition) do 3543 x when :"Elixir.Kernel".in(x, [false, nil]) -> unquote(else_clause) 3544 _ -> unquote(do_clause) 3545 end 3546 end 3547 ) 3548 end 3549 3550 defp build_if(_condition, _arguments) do 3551 raise ArgumentError, 3552 "invalid or duplicate keys for if, only \"do\" and an optional \"else\" are permitted" 3553 end 3554 3555 @doc """ 3556 Provides an `unless` macro. 3557 3558 This macro evaluates and returns the `do` block passed in as the second 3559 argument if `condition` evaluates to a falsy value (`false` or `nil`). 3560 Otherwise, it returns the value of the `else` block if present or `nil` if not. 3561 3562 See also `if/2`. 3563 3564 ## Examples 3565 3566 iex> unless(Enum.empty?([]), do: "Hello") 3567 nil 3568 3569 iex> unless(Enum.empty?([1, 2, 3]), do: "Hello") 3570 "Hello" 3571 3572 iex> unless Enum.sum([2, 2]) == 5 do 3573 ...> "Math still works" 3574 ...> else 3575 ...> "Math is broken" 3576 ...> end 3577 "Math still works" 3578 3579 """ 3580 defmacro unless(condition, clauses) do 3581 build_unless(condition, clauses) 3582 end 3583 3584 defp build_unless(condition, do: do_clause) do 3585 build_unless(condition, do: do_clause, else: nil) 3586 end 3587 3588 defp build_unless(condition, do: do_clause, else: else_clause) do 3589 quote do 3590 if(unquote(condition), do: unquote(else_clause), else: unquote(do_clause)) 3591 end 3592 end 3593 3594 defp build_unless(_condition, _arguments) do 3595 raise ArgumentError, 3596 "invalid or duplicate keys for unless, " <> 3597 "only \"do\" and an optional \"else\" are permitted" 3598 end 3599 3600 @doc """ 3601 Destructures two lists, assigning each term in the 3602 right one to the matching term in the left one. 3603 3604 Unlike pattern matching via `=`, if the sizes of the left 3605 and right lists don't match, destructuring simply stops 3606 instead of raising an error. 3607 3608 ## Examples 3609 3610 iex> destructure([x, y, z], [1, 2, 3, 4, 5]) 3611 iex> {x, y, z} 3612 {1, 2, 3} 3613 3614 In the example above, even though the right list has more entries than the 3615 left one, destructuring works fine. If the right list is smaller, the 3616 remaining elements are simply set to `nil`: 3617 3618 iex> destructure([x, y, z], [1]) 3619 iex> {x, y, z} 3620 {1, nil, nil} 3621 3622 The left-hand side supports any expression you would use 3623 on the left-hand side of a match: 3624 3625 x = 1 3626 destructure([^x, y, z], [1, 2, 3]) 3627 3628 The example above will only work if `x` matches the first value in the right 3629 list. Otherwise, it will raise a `MatchError` (like the `=` operator would 3630 do). 3631 """ 3632 defmacro destructure(left, right) when is_list(left) do 3633 quote do 3634 unquote(left) = Kernel.Utils.destructure(unquote(right), unquote(length(left))) 3635 end 3636 end 3637 3638 @doc """ 3639 Creates a range from `first` to `last`. 3640 3641 If first is less than last, the range will be increasing from 3642 first to last. If first is equal to last, the range will contain 3643 one element, which is the number itself. 3644 3645 If first is more than last, the range will be decreasing from first 3646 to last, albeit this behaviour is deprecated. Instead prefer to 3647 explicitly list the step with `first..last//-1`. 3648 3649 See the `Range` module for more information. 3650 3651 ## Examples 3652 3653 iex> 0 in 1..3 3654 false 3655 iex> 2 in 1..3 3656 true 3657 3658 iex> Enum.to_list(1..3) 3659 [1, 2, 3] 3660 3661 """ 3662 defmacro first..last do 3663 case bootstrapped?(Macro) do 3664 true -> 3665 first = Macro.expand(first, __CALLER__) 3666 last = Macro.expand(last, __CALLER__) 3667 validate_range!(first, last) 3668 range(__CALLER__.context, first, last) 3669 3670 false -> 3671 range(__CALLER__.context, first, last) 3672 end 3673 end 3674 3675 defp range(_context, first, last) when is_integer(first) and is_integer(last) do 3676 # TODO: Deprecate inferring a range with a step of -1 on Elixir v1.17 3677 step = if first <= last, do: 1, else: -1 3678 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: step]} 3679 end 3680 3681 defp range(nil, first, last) do 3682 quote(do: Elixir.Range.new(unquote(first), unquote(last))) 3683 end 3684 3685 defp range(:guard, first, last) do 3686 # TODO: Deprecate me inside guard when sides are not integers on Elixir v1.17 3687 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: nil]} 3688 end 3689 3690 defp range(:match, first, last) do 3691 # TODO: Deprecate me inside match in all occasions (including literals) on Elixir v1.17 3692 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last]} 3693 end 3694 3695 @doc """ 3696 Creates a range from `first` to `last` with `step`. 3697 3698 See the `Range` module for more information. 3699 3700 ## Examples 3701 3702 iex> 0 in 1..3//1 3703 false 3704 iex> 2 in 1..3//1 3705 true 3706 iex> 2 in 1..3//2 3707 false 3708 3709 iex> Enum.to_list(1..3//1) 3710 [1, 2, 3] 3711 iex> Enum.to_list(1..3//2) 3712 [1, 3] 3713 iex> Enum.to_list(3..1//-1) 3714 [3, 2, 1] 3715 iex> Enum.to_list(1..0//1) 3716 [] 3717 3718 """ 3719 @doc since: "1.12.0" 3720 defmacro first..last//step do 3721 case bootstrapped?(Macro) do 3722 true -> 3723 first = Macro.expand(first, __CALLER__) 3724 last = Macro.expand(last, __CALLER__) 3725 step = Macro.expand(step, __CALLER__) 3726 validate_range!(first, last) 3727 validate_step!(step) 3728 range(__CALLER__.context, first, last, step) 3729 3730 false -> 3731 range(__CALLER__.context, first, last, step) 3732 end 3733 end 3734 3735 defp range(context, first, last, step) 3736 when is_integer(first) and is_integer(last) and is_integer(step) 3737 when context != nil do 3738 {:%{}, [], [__struct__: Elixir.Range, first: first, last: last, step: step]} 3739 end 3740 3741 defp range(nil, first, last, step) do 3742 quote(do: Elixir.Range.new(unquote(first), unquote(last), unquote(step))) 3743 end 3744 3745 defp validate_range!(first, last) 3746 when is_float(first) or is_float(last) or is_atom(first) or is_atom(last) or 3747 is_binary(first) or is_binary(last) or is_list(first) or is_list(last) do 3748 raise ArgumentError, 3749 "ranges (first..last//step) expect both sides to be integers, " <> 3750 "got: #{Macro.to_string({:.., [], [first, last]})}" 3751 end 3752 3753 defp validate_range!(_, _), do: :ok 3754 3755 defp validate_step!(step) 3756 when is_float(step) or is_atom(step) or is_binary(step) or is_list(step) or step == 0 do 3757 raise ArgumentError, 3758 "ranges (first..last//step) expect the step to be a non-zero integer, " <> 3759 "got: #{Macro.to_string(step)}" 3760 end 3761 3762 defp validate_step!(_), do: :ok 3763 3764 @doc """ 3765 Boolean "and" operator. 3766 3767 Provides a short-circuit operator that evaluates and returns 3768 the second expression only if the first one evaluates to a truthy value 3769 (neither `false` nor `nil`). Returns the first expression 3770 otherwise. 3771 3772 Not allowed in guard clauses. 3773 3774 ## Examples 3775 3776 iex> Enum.empty?([]) && Enum.empty?([]) 3777 true 3778 3779 iex> List.first([]) && true 3780 nil 3781 3782 iex> Enum.empty?([]) && List.first([1]) 3783 1 3784 3785 iex> false && throw(:bad) 3786 false 3787 3788 Note that, unlike `and/2`, this operator accepts any expression 3789 as the first argument, not only booleans. 3790 """ 3791 defmacro left && right do 3792 assert_no_match_or_guard_scope(__CALLER__.context, "&&") 3793 3794 quote do 3795 case unquote(left) do 3796 x when :"Elixir.Kernel".in(x, [false, nil]) -> 3797 x 3798 3799 _ -> 3800 unquote(right) 3801 end 3802 end 3803 end 3804 3805 @doc """ 3806 Boolean "or" operator. 3807 3808 Provides a short-circuit operator that evaluates and returns the second 3809 expression only if the first one does not evaluate to a truthy value (that is, 3810 it is either `nil` or `false`). Returns the first expression otherwise. 3811 3812 Not allowed in guard clauses. 3813 3814 ## Examples 3815 3816 iex> Enum.empty?([1]) || Enum.empty?([1]) 3817 false 3818 3819 iex> List.first([]) || true 3820 true 3821 3822 iex> Enum.empty?([1]) || 1 3823 1 3824 3825 iex> Enum.empty?([]) || throw(:bad) 3826 true 3827 3828 Note that, unlike `or/2`, this operator accepts any expression 3829 as the first argument, not only booleans. 3830 """ 3831 defmacro left || right do 3832 assert_no_match_or_guard_scope(__CALLER__.context, "||") 3833 3834 quote do 3835 case unquote(left) do 3836 x when :"Elixir.Kernel".in(x, [false, nil]) -> 3837 unquote(right) 3838 3839 x -> 3840 x 3841 end 3842 end 3843 end 3844 3845 @doc """ 3846 Pipe operator. 3847 3848 This operator introduces the expression on the left-hand side as 3849 the first argument to the function call on the right-hand side. 3850 3851 ## Examples 3852 3853 iex> [1, [2], 3] |> List.flatten() 3854 [1, 2, 3] 3855 3856 The example above is the same as calling `List.flatten([1, [2], 3])`. 3857 3858 The `|>` operator is mostly useful when there is a desire to execute a series 3859 of operations resembling a pipeline: 3860 3861 iex> [1, [2], 3] |> List.flatten() |> Enum.map(fn x -> x * 2 end) 3862 [2, 4, 6] 3863 3864 In the example above, the list `[1, [2], 3]` is passed as the first argument 3865 to the `List.flatten/1` function, then the flattened list is passed as the 3866 first argument to the `Enum.map/2` function which doubles each element of the 3867 list. 3868 3869 In other words, the expression above simply translates to: 3870 3871 Enum.map(List.flatten([1, [2], 3]), fn x -> x * 2 end) 3872 3873 ## Pitfalls 3874 3875 There are two common pitfalls when using the pipe operator. 3876 3877 The first one is related to operator precedence. For example, 3878 the following expression: 3879 3880 String.graphemes "Hello" |> Enum.reverse 3881 3882 Translates to: 3883 3884 String.graphemes("Hello" |> Enum.reverse()) 3885 3886 which results in an error as the `Enumerable` protocol is not defined 3887 for binaries. Adding explicit parentheses resolves the ambiguity: 3888 3889 String.graphemes("Hello") |> Enum.reverse() 3890 3891 Or, even better: 3892 3893 "Hello" |> String.graphemes() |> Enum.reverse() 3894 3895 The second limitation is that Elixir always pipes to a function 3896 call. Therefore, to pipe into an anonymous function, you need to 3897 invoke it: 3898 3899 some_fun = &Regex.replace(~r/l/, &1, "L") 3900 "Hello" |> some_fun.() 3901 3902 Alternatively, you can use `then/2` for the same effect: 3903 3904 some_fun = &Regex.replace(~r/l/, &1, "L") 3905 "Hello" |> then(some_fun) 3906 3907 `then/2` is most commonly used when you want to pipe to a function 3908 but the value is expected outside of the first argument, such as 3909 above. By replacing `some_fun` by its value, we get: 3910 3911 "Hello" |> then(&Regex.replace(~r/l/,&1, "L")) 3912 3913 """ 3914 defmacro left |> right do 3915 [{h, _} | t] = Macro.unpipe({:|>, [], [left, right]}) 3916 3917 fun = fn {x, pos}, acc -> 3918 Macro.pipe(acc, x, pos) 3919 end 3920 3921 :lists.foldl(fun, h, t) 3922 end 3923 3924 @doc """ 3925 Returns `true` if `module` is loaded and contains a 3926 public `function` with the given `arity`, otherwise `false`. 3927 3928 Note that this function does not load the module in case 3929 it is not loaded. Check `Code.ensure_loaded/1` for more 3930 information. 3931 3932 Inlined by the compiler. 3933 3934 ## Examples 3935 3936 iex> function_exported?(Enum, :map, 2) 3937 true 3938 3939 iex> function_exported?(Enum, :map, 10) 3940 false 3941 3942 iex> function_exported?(List, :to_string, 1) 3943 true 3944 """ 3945 @spec function_exported?(module, atom, arity) :: boolean 3946 def function_exported?(module, function, arity) do 3947 :erlang.function_exported(module, function, arity) 3948 end 3949 3950 @doc """ 3951 Returns `true` if `module` is loaded and contains a 3952 public `macro` with the given `arity`, otherwise `false`. 3953 3954 Note that this function does not load the module in case 3955 it is not loaded. Check `Code.ensure_loaded/1` for more 3956 information. 3957 3958 If `module` is an Erlang module (as opposed to an Elixir module), this 3959 function always returns `false`. 3960 3961 ## Examples 3962 3963 iex> macro_exported?(Kernel, :use, 2) 3964 true 3965 3966 iex> macro_exported?(:erlang, :abs, 1) 3967 false 3968 3969 """ 3970 @spec macro_exported?(module, atom, arity) :: boolean 3971 def macro_exported?(module, macro, arity) 3972 when is_atom(module) and is_atom(macro) and is_integer(arity) and 3973 (arity >= 0 and arity <= 255) do 3974 function_exported?(module, :__info__, 1) and 3975 :lists.member({macro, arity}, module.__info__(:macros)) 3976 end 3977 3978 @doc """ 3979 Membership operator. Checks if the element on the left-hand side is a member of the 3980 collection on the right-hand side. 3981 3982 ## Examples 3983 3984 iex> x = 1 3985 iex> x in [1, 2, 3] 3986 true 3987 3988 This operator (which is a macro) simply translates to a call to 3989 `Enum.member?/2`. The example above would translate to: 3990 3991 Enum.member?([1, 2, 3], x) 3992 3993 Elixir also supports `left not in right`, which evaluates to 3994 `not(left in right)`: 3995 3996 iex> x = 1 3997 iex> x not in [1, 2, 3] 3998 false 3999 4000 ## Guards 4001 4002 The `in/2` operator (as well as `not in`) can be used in guard clauses as 4003 long as the right-hand side is a range or a list. In such cases, Elixir will 4004 expand the operator to a valid guard expression. For example: 4005 4006 when x in [1, 2, 3] 4007 4008 translates to: 4009 4010 when x === 1 or x === 2 or x === 3 4011 4012 When using ranges: 4013 4014 when x in 1..3 4015 4016 translates to: 4017 4018 when is_integer(x) and x >= 1 and x <= 3 4019 4020 Note that only integers can be considered inside a range by `in`. 4021 4022 ### AST considerations 4023 4024 `left not in right` is parsed by the compiler into the AST: 4025 4026 {:not, _, [{:in, _, [left, right]}]} 4027 4028 This is the same AST as `not(left in right)`. 4029 4030 Additionally, `Macro.to_string/2` and `Code.format_string!/2` 4031 will translate all occurrences of this AST to `left not in right`. 4032 """ 4033 @doc guard: true 4034 defmacro left in right do 4035 in_body? = __CALLER__.context == nil 4036 4037 expand = 4038 case bootstrapped?(Macro) do 4039 true -> &Macro.expand(&1, __CALLER__) 4040 false -> & &1 4041 end 4042 4043 case expand.(right) do 4044 [] when not in_body? -> 4045 false 4046 4047 [] -> 4048 quote do 4049 _ = unquote(left) 4050 false 4051 end 4052 4053 [head | tail] = list when not in_body? -> 4054 in_list(left, head, tail, expand, list, in_body?) 4055 4056 [_ | _] = list when in_body? -> 4057 case ensure_evaled(list, {0, []}, expand) do 4058 {[head | tail], {_, []}} -> 4059 in_var(in_body?, left, &in_list(&1, head, tail, expand, list, in_body?)) 4060 4061 {[head | tail], {_, vars_values}} -> 4062 {vars, values} = :lists.unzip(:lists.reverse(vars_values)) 4063 is_in_list = &in_list(&1, head, tail, expand, list, in_body?) 4064 4065 quote do 4066 {unquote_splicing(vars)} = {unquote_splicing(values)} 4067 unquote(in_var(in_body?, left, is_in_list)) 4068 end 4069 end 4070 4071 {:%{}, _meta, [__struct__: Elixir.Range, first: first, last: last, step: step]} -> 4072 in_var(in_body?, left, &in_range(&1, expand.(first), expand.(last), expand.(step))) 4073 4074 right when in_body? -> 4075 quote(do: Elixir.Enum.member?(unquote(right), unquote(left))) 4076 4077 %{__struct__: Elixir.Range, first: _, last: _, step: _} -> 4078 raise ArgumentError, "non-literal range in guard should be escaped with Macro.escape/2" 4079 4080 right -> 4081 raise_on_invalid_args_in_2(right) 4082 end 4083 end 4084 4085 defp raise_on_invalid_args_in_2(right) do 4086 raise ArgumentError, << 4087 "invalid right argument for operator \"in\", it expects a compile-time proper list ", 4088 "or compile-time range on the right side when used in guard expressions, got: ", 4089 Macro.to_string(right)::binary 4090 >> 4091 end 4092 4093 defp in_var(false, ast, fun), do: fun.(ast) 4094 4095 defp in_var(true, {atom, _, context} = var, fun) when is_atom(atom) and is_atom(context), 4096 do: fun.(var) 4097 4098 defp in_var(true, ast, fun) do 4099 quote do 4100 var = unquote(ast) 4101 unquote(fun.(quote(do: var))) 4102 end 4103 end 4104 4105 # Called as ensure_evaled(list, {0, []}). Note acc is reversed. 4106 defp ensure_evaled(list, acc, expand) do 4107 fun = fn 4108 {:|, meta, [head, tail]}, acc -> 4109 {head, acc} = ensure_evaled_element(head, acc) 4110 {tail, acc} = ensure_evaled_tail(expand.(tail), acc, expand) 4111 {{:|, meta, [head, tail]}, acc} 4112 4113 elem, acc -> 4114 ensure_evaled_element(elem, acc) 4115 end 4116 4117 :lists.mapfoldl(fun, acc, list) 4118 end 4119 4120 defp ensure_evaled_element(elem, acc) 4121 when is_number(elem) or is_atom(elem) or is_binary(elem) do 4122 {elem, acc} 4123 end 4124 4125 defp ensure_evaled_element(elem, acc) do 4126 ensure_evaled_var(elem, acc) 4127 end 4128 4129 defp ensure_evaled_tail(elem, acc, expand) when is_list(elem) do 4130 ensure_evaled(elem, acc, expand) 4131 end 4132 4133 defp ensure_evaled_tail(elem, acc, _expand) do 4134 ensure_evaled_var(elem, acc) 4135 end 4136 4137 defp ensure_evaled_var(elem, {index, ast}) do 4138 var = {String.to_atom("arg" <> Integer.to_string(index + 1)), [], __MODULE__} 4139 {var, {index + 1, [{var, elem} | ast]}} 4140 end 4141 4142 defp in_range(left, first, last, nil) do 4143 # TODO: nil steps are only supported due to x..y in guards. Remove me on Elixir 2.0. 4144 quote do 4145 :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and 4146 :erlang.is_integer(unquote(last)) and 4147 ((:erlang."=<"(unquote(first), unquote(last)) and 4148 unquote(increasing_compare(left, first, last))) or 4149 (:erlang.<(unquote(last), unquote(first)) and 4150 unquote(decreasing_compare(left, first, last)))) 4151 end 4152 end 4153 4154 defp in_range(left, first, last, step) when is_integer(step) do 4155 in_range_literal(left, first, last, step) 4156 end 4157 4158 defp in_range(left, first, last, step) do 4159 quoted = 4160 quote do 4161 :erlang.is_integer(unquote(left)) and :erlang.is_integer(unquote(first)) and 4162 :erlang.is_integer(unquote(last)) and 4163 ((:erlang.>(unquote(step), 0) and 4164 unquote(increasing_compare(left, first, last))) or 4165 (:erlang.<(unquote(step), 0) and 4166 unquote(decreasing_compare(left, first, last)))) 4167 end 4168 4169 in_range_step(quoted, left, first, step) 4170 end 4171 4172 defp in_range_literal(left, first, first, _step) when is_integer(first) do 4173 quote do: :erlang."=:="(unquote(left), unquote(first)) 4174 end 4175 4176 defp in_range_literal(left, first, last, step) when step > 0 do 4177 quoted = 4178 quote do 4179 :erlang.andalso( 4180 :erlang.is_integer(unquote(left)), 4181 unquote(increasing_compare(left, first, last)) 4182 ) 4183 end 4184 4185 in_range_step(quoted, left, first, step) 4186 end 4187 4188 defp in_range_literal(left, first, last, step) when step < 0 do 4189 quoted = 4190 quote do 4191 :erlang.andalso( 4192 :erlang.is_integer(unquote(left)), 4193 unquote(decreasing_compare(left, first, last)) 4194 ) 4195 end 4196 4197 in_range_step(quoted, left, first, step) 4198 end 4199 4200 defp in_range_step(quoted, _left, _first, step) when step == 1 or step == -1 do 4201 quoted 4202 end 4203 4204 defp in_range_step(quoted, left, first, step) do 4205 quote do 4206 :erlang.andalso( 4207 unquote(quoted), 4208 :erlang."=:="(:erlang.rem(unquote(left) - unquote(first), unquote(step)), 0) 4209 ) 4210 end 4211 end 4212 4213 defp in_list(left, head, tail, expand, right, in_body?) do 4214 [head | tail] = :lists.map(&comp(left, &1, expand, right, in_body?), [head | tail]) 4215 :lists.foldl("e(do: :erlang.orelse(unquote(&2), unquote(&1))), head, tail) 4216 end 4217 4218 defp comp(left, {:|, _, [head, tail]}, expand, right, in_body?) do 4219 case expand.(tail) do 4220 [] -> 4221 quote(do: :erlang."=:="(unquote(left), unquote(head))) 4222 4223 [tail_head | tail] -> 4224 quote do 4225 :erlang.orelse( 4226 :erlang."=:="(unquote(left), unquote(head)), 4227 unquote(in_list(left, tail_head, tail, expand, right, in_body?)) 4228 ) 4229 end 4230 4231 tail when in_body? -> 4232 quote do 4233 :erlang.orelse( 4234 :erlang."=:="(unquote(left), unquote(head)), 4235 :lists.member(unquote(left), unquote(tail)) 4236 ) 4237 end 4238 4239 _ -> 4240 raise_on_invalid_args_in_2(right) 4241 end 4242 end 4243 4244 defp comp(left, right, _expand, _right, _in_body?) do 4245 quote(do: :erlang."=:="(unquote(left), unquote(right))) 4246 end 4247 4248 defp increasing_compare(var, first, last) do 4249 quote do 4250 :erlang.andalso( 4251 :erlang.>=(unquote(var), unquote(first)), 4252 :erlang."=<"(unquote(var), unquote(last)) 4253 ) 4254 end 4255 end 4256 4257 defp decreasing_compare(var, first, last) do 4258 quote do 4259 :erlang.andalso( 4260 :erlang."=<"(unquote(var), unquote(first)), 4261 :erlang.>=(unquote(var), unquote(last)) 4262 ) 4263 end 4264 end 4265 4266 @doc """ 4267 Marks that the given variable should not be hygienized. 4268 4269 This macro expects a variable and it is typically invoked 4270 inside `Kernel.SpecialForms.quote/2` to mark that a variable 4271 should not be hygienized. See `Kernel.SpecialForms.quote/2` 4272 for more information. 4273 4274 ## Examples 4275 4276 iex> Kernel.var!(example) = 1 4277 1 4278 iex> Kernel.var!(example) 4279 1 4280 4281 """ 4282 defmacro var!(var, context \\ nil) 4283 4284 defmacro var!({name, meta, atom}, context) when is_atom(name) and is_atom(atom) do 4285 # Remove counter and force them to be vars 4286 meta = :lists.keydelete(:counter, 1, meta) 4287 meta = :lists.keystore(:var, 1, meta, {:var, true}) 4288 4289 case Macro.expand(context, __CALLER__) do 4290 context when is_atom(context) -> 4291 {name, meta, context} 4292 4293 other -> 4294 raise ArgumentError, 4295 "expected var! context to expand to an atom, got: #{Macro.to_string(other)}" 4296 end 4297 end 4298 4299 defmacro var!(other, _context) do 4300 raise ArgumentError, "expected a variable to be given to var!, got: #{Macro.to_string(other)}" 4301 end 4302 4303 @doc """ 4304 When used inside quoting, marks that the given alias should not 4305 be hygienized. This means the alias will be expanded when 4306 the macro is expanded. 4307 4308 Check `Kernel.SpecialForms.quote/2` for more information. 4309 """ 4310 defmacro alias!(alias) when is_atom(alias) do 4311 alias 4312 end 4313 4314 defmacro alias!({:__aliases__, meta, args}) do 4315 # Simply remove the alias metadata from the node 4316 # so it does not affect expansion. 4317 {:__aliases__, :lists.keydelete(:alias, 1, meta), args} 4318 end 4319 4320 ## Definitions implemented in Elixir 4321 4322 @doc ~S""" 4323 Defines a module given by name with the given contents. 4324 4325 This macro defines a module with the given `alias` as its name and with the 4326 given contents. It returns a tuple with four elements: 4327 4328 * `:module` 4329 * the module name 4330 * the binary contents of the module 4331 * the result of evaluating the contents block 4332 4333 ## Examples 4334 4335 defmodule Number do 4336 def one, do: 1 4337 def two, do: 2 4338 end 4339 #=> {:module, Number, <<70, 79, 82, ...>>, {:two, 0}} 4340 4341 Number.one() 4342 #=> 1 4343 4344 Number.two() 4345 #=> 2 4346 4347 ## Nesting 4348 4349 Nesting a module inside another module affects the name of the nested module: 4350 4351 defmodule Foo do 4352 defmodule Bar do 4353 end 4354 end 4355 4356 In the example above, two modules - `Foo` and `Foo.Bar` - are created. 4357 When nesting, Elixir automatically creates an alias to the inner module, 4358 allowing the second module `Foo.Bar` to be accessed as `Bar` in the same 4359 lexical scope where it's defined (the `Foo` module). This only happens 4360 if the nested module is defined via an alias. 4361 4362 If the `Foo.Bar` module is moved somewhere else, the references to `Bar` in 4363 the `Foo` module need to be updated to the fully-qualified name (`Foo.Bar`) or 4364 an alias has to be explicitly set in the `Foo` module with the help of 4365 `Kernel.SpecialForms.alias/2`. 4366 4367 defmodule Foo.Bar do 4368 # code 4369 end 4370 4371 defmodule Foo do 4372 alias Foo.Bar 4373 # code here can refer to "Foo.Bar" as just "Bar" 4374 end 4375 4376 ## Dynamic names 4377 4378 Elixir module names can be dynamically generated. This is very 4379 useful when working with macros. For instance, one could write: 4380 4381 defmodule String.to_atom("Foo#{1}") do 4382 # contents ... 4383 end 4384 4385 Elixir will accept any module name as long as the expression passed as the 4386 first argument to `defmodule/2` evaluates to an atom. 4387 Note that, when a dynamic name is used, Elixir won't nest the name under 4388 the current module nor automatically set up an alias. 4389 4390 ## Reserved module names 4391 4392 If you attempt to define a module that already exists, you will get a 4393 warning saying that a module has been redefined. 4394 4395 There are some modules that Elixir does not currently implement but it 4396 may be implement in the future. Those modules are reserved and defining 4397 them will result in a compilation error: 4398 4399 defmodule Any do 4400 # code 4401 end 4402 ** (CompileError) iex:1: module Any is reserved and cannot be defined 4403 4404 Elixir reserves the following module names: `Elixir`, `Any`, `BitString`, 4405 `PID`, and `Reference`. 4406 """ 4407 defmacro defmodule(alias, do_block) 4408 4409 defmacro defmodule(alias, do: block) do 4410 env = __CALLER__ 4411 boot? = bootstrapped?(Macro) 4412 4413 expanded = 4414 case boot? do 4415 true -> Macro.expand(alias, env) 4416 false -> alias 4417 end 4418 4419 {expanded, with_alias} = 4420 case boot? and is_atom(expanded) do 4421 true -> 4422 # Expand the module considering the current environment/nesting 4423 {full, old, new} = expand_module(alias, expanded, env) 4424 meta = [defined: full, context: env.module] ++ alias_meta(alias) 4425 {full, {:alias, meta, [old, [as: new, warn: false]]}} 4426 4427 false -> 4428 {expanded, nil} 4429 end 4430 4431 # We do this so that the block is not tail-call optimized and stacktraces 4432 # are not messed up. Basically, we just insert something between the return 4433 # value of the block and what is returned by defmodule. Using just ":ok" or 4434 # similar doesn't work because it's likely optimized away by the compiler. 4435 block = 4436 quote do 4437 result = unquote(block) 4438 :elixir_utils.noop() 4439 result 4440 end 4441 4442 escaped = 4443 case env do 4444 %{function: nil, lexical_tracker: pid} when is_pid(pid) -> 4445 integer = Kernel.LexicalTracker.write_cache(pid, block) 4446 quote(do: Kernel.LexicalTracker.read_cache(unquote(pid), unquote(integer))) 4447 4448 %{} -> 4449 :elixir_quote.escape(block, :default, false) 4450 end 4451 4452 module_vars = :lists.map(&module_var/1, :maps.keys(elem(env.current_vars, 0))) 4453 4454 quote do 4455 unquote(with_alias) 4456 :elixir_module.compile(unquote(expanded), unquote(escaped), unquote(module_vars), __ENV__) 4457 end 4458 end 4459 4460 defp alias_meta({:__aliases__, meta, _}), do: meta 4461 defp alias_meta(_), do: [] 4462 4463 # defmodule Elixir.Alias 4464 defp expand_module({:__aliases__, _, [:"Elixir", _ | _]}, module, _env), 4465 do: {module, module, nil} 4466 4467 # defmodule Alias in root 4468 defp expand_module({:__aliases__, _, _}, module, %{module: nil}), 4469 do: {module, module, nil} 4470 4471 # defmodule Alias nested 4472 defp expand_module({:__aliases__, _, [h | t]}, _module, env) when is_atom(h) do 4473 module = :elixir_aliases.concat([env.module, h]) 4474 alias = String.to_atom("Elixir." <> Atom.to_string(h)) 4475 4476 case t do 4477 [] -> {module, module, alias} 4478 _ -> {String.to_atom(Enum.join([module | t], ".")), module, alias} 4479 end 4480 end 4481 4482 # defmodule _ 4483 defp expand_module(_raw, module, _env) do 4484 {module, module, nil} 4485 end 4486 4487 defp module_var({name, kind}) when is_atom(kind), do: {name, [generated: true], kind} 4488 defp module_var({name, kind}), do: {name, [counter: kind, generated: true], nil} 4489 4490 @doc ~S""" 4491 Defines a public function with the given name and body. 4492 4493 ## Examples 4494 4495 defmodule Foo do 4496 def bar, do: :baz 4497 end 4498 4499 Foo.bar() 4500 #=> :baz 4501 4502 A function that expects arguments can be defined as follows: 4503 4504 defmodule Foo do 4505 def sum(a, b) do 4506 a + b 4507 end 4508 end 4509 4510 In the example above, a `sum/2` function is defined; this function receives 4511 two arguments and returns their sum. 4512 4513 ## Default arguments 4514 4515 `\\` is used to specify a default value for a parameter of a function. For 4516 example: 4517 4518 defmodule MyMath do 4519 def multiply_by(number, factor \\ 2) do 4520 number * factor 4521 end 4522 end 4523 4524 MyMath.multiply_by(4, 3) 4525 #=> 12 4526 4527 MyMath.multiply_by(4) 4528 #=> 8 4529 4530 The compiler translates this into multiple functions with different arities, 4531 here `MyMath.multiply_by/1` and `MyMath.multiply_by/2`, that represent cases when 4532 arguments for parameters with default values are passed or not passed. 4533 4534 When defining a function with default arguments as well as multiple 4535 explicitly declared clauses, you must write a function head that declares the 4536 defaults. For example: 4537 4538 defmodule MyString do 4539 def join(string1, string2 \\ nil, separator \\ " ") 4540 4541 def join(string1, nil, _separator) do 4542 string1 4543 end 4544 4545 def join(string1, string2, separator) do 4546 string1 <> separator <> string2 4547 end 4548 end 4549 4550 Note that `\\` can't be used with anonymous functions because they 4551 can only have a sole arity. 4552 4553 ### Keyword lists with default arguments 4554 4555 Functions containing many arguments can benefit from using `Keyword` 4556 lists to group and pass attributes as a single value. 4557 4558 defmodule MyConfiguration do 4559 @default_opts [storage: "local"] 4560 4561 def configure(resource, opts \\ []) do 4562 opts = Keyword.merge(@default_opts, opts) 4563 storage = opts[:storage] 4564 # ... 4565 end 4566 end 4567 4568 The difference between using `Map` and `Keyword` to store many 4569 arguments is `Keyword`'s keys: 4570 4571 * must be atoms 4572 * can be given more than once 4573 * ordered, as specified by the developer 4574 4575 ## Function and variable names 4576 4577 Function and variable names have the following syntax: 4578 A _lowercase ASCII letter_ or an _underscore_, followed by any number of 4579 _lowercase or uppercase ASCII letters_, _numbers_, or _underscores_. 4580 Optionally they can end in either an _exclamation mark_ or a _question mark_. 4581 4582 For variables, any identifier starting with an underscore should indicate an 4583 unused variable. For example: 4584 4585 def foo(bar) do 4586 [] 4587 end 4588 #=> warning: variable bar is unused 4589 4590 def foo(_bar) do 4591 [] 4592 end 4593 #=> no warning 4594 4595 def foo(_bar) do 4596 _bar 4597 end 4598 #=> warning: the underscored variable "_bar" is used after being set 4599 4600 ## `rescue`/`catch`/`after`/`else` 4601 4602 Function bodies support `rescue`, `catch`, `after`, and `else` as `Kernel.SpecialForms.try/1` 4603 does (known as "implicit try"). For example, the following two functions are equivalent: 4604 4605 def convert(number) do 4606 try do 4607 String.to_integer(number) 4608 rescue 4609 e in ArgumentError -> {:error, e.message} 4610 end 4611 end 4612 4613 def convert(number) do 4614 String.to_integer(number) 4615 rescue 4616 e in ArgumentError -> {:error, e.message} 4617 end 4618 4619 """ 4620 defmacro def(call, expr \\ nil) do 4621 define(:def, call, expr, __CALLER__) 4622 end 4623 4624 @doc """ 4625 Defines a private function with the given name and body. 4626 4627 Private functions are only accessible from within the module in which they are 4628 defined. Trying to access a private function from outside the module it's 4629 defined in results in an `UndefinedFunctionError` exception. 4630 4631 Check `def/2` for more information. 4632 4633 ## Examples 4634 4635 defmodule Foo do 4636 def bar do 4637 sum(1, 2) 4638 end 4639 4640 defp sum(a, b), do: a + b 4641 end 4642 4643 Foo.bar() 4644 #=> 3 4645 4646 Foo.sum(1, 2) 4647 ** (UndefinedFunctionError) undefined function Foo.sum/2 4648 4649 """ 4650 defmacro defp(call, expr \\ nil) do 4651 define(:defp, call, expr, __CALLER__) 4652 end 4653 4654 @doc """ 4655 Defines a public macro with the given name and body. 4656 4657 Macros must be defined before its usage. 4658 4659 Check `def/2` for rules on naming and default arguments. 4660 4661 ## Examples 4662 4663 defmodule MyLogic do 4664 defmacro unless(expr, opts) do 4665 quote do 4666 if !unquote(expr), unquote(opts) 4667 end 4668 end 4669 end 4670 4671 require MyLogic 4672 4673 MyLogic.unless false do 4674 IO.puts("It works") 4675 end 4676 4677 """ 4678 defmacro defmacro(call, expr \\ nil) do 4679 define(:defmacro, call, expr, __CALLER__) 4680 end 4681 4682 @doc """ 4683 Defines a private macro with the given name and body. 4684 4685 Private macros are only accessible from the same module in which they are 4686 defined. 4687 4688 Private macros must be defined before its usage. 4689 4690 Check `defmacro/2` for more information, and check `def/2` for rules on 4691 naming and default arguments. 4692 4693 """ 4694 defmacro defmacrop(call, expr \\ nil) do 4695 define(:defmacrop, call, expr, __CALLER__) 4696 end 4697 4698 defp define(kind, call, expr, env) do 4699 module = assert_module_scope(env, kind, 2) 4700 assert_no_function_scope(env, kind, 2) 4701 4702 unquoted_call = :elixir_quote.has_unquotes(call) 4703 unquoted_expr = :elixir_quote.has_unquotes(expr) 4704 escaped_call = :elixir_quote.escape(call, :default, true) 4705 4706 escaped_expr = 4707 case unquoted_expr do 4708 true -> 4709 :elixir_quote.escape(expr, :default, true) 4710 4711 false -> 4712 key = :erlang.unique_integer() 4713 :elixir_module.write_cache(module, key, expr) 4714 quote(do: :elixir_module.read_cache(unquote(module), unquote(key))) 4715 end 4716 4717 # Do not check clauses if any expression was unquoted 4718 check_clauses = not (unquoted_expr or unquoted_call) 4719 pos = :elixir_locals.cache_env(env) 4720 4721 quote do 4722 :elixir_def.store_definition( 4723 unquote(kind), 4724 unquote(check_clauses), 4725 unquote(escaped_call), 4726 unquote(escaped_expr), 4727 unquote(pos) 4728 ) 4729 end 4730 end 4731 4732 @doc """ 4733 Defines a struct. 4734 4735 A struct is a tagged map that allows developers to provide 4736 default values for keys, tags to be used in polymorphic 4737 dispatches and compile time assertions. 4738 4739 To define a struct, a developer must define both `__struct__/0` and 4740 `__struct__/1` functions. `defstruct/1` is a convenience macro which 4741 defines such functions with some conveniences. 4742 4743 For more information about structs, please check `Kernel.SpecialForms.%/2`. 4744 4745 ## Examples 4746 4747 defmodule User do 4748 defstruct name: nil, age: nil 4749 end 4750 4751 Struct fields are evaluated at compile-time, which allows 4752 them to be dynamic. In the example below, `10 + 11` is 4753 evaluated at compile-time and the age field is stored 4754 with value `21`: 4755 4756 defmodule User do 4757 defstruct name: nil, age: 10 + 11 4758 end 4759 4760 The `fields` argument is usually a keyword list with field names 4761 as atom keys and default values as corresponding values. `defstruct/1` 4762 also supports a list of atoms as its argument: in that case, the atoms 4763 in the list will be used as the struct's field names and they will all 4764 default to `nil`. 4765 4766 defmodule Post do 4767 defstruct [:title, :content, :author] 4768 end 4769 4770 ## Deriving 4771 4772 Although structs are maps, by default structs do not implement 4773 any of the protocols implemented for maps. For example, attempting 4774 to use a protocol with the `User` struct leads to an error: 4775 4776 john = %User{name: "John"} 4777 MyProtocol.call(john) 4778 ** (Protocol.UndefinedError) protocol MyProtocol not implemented for %User{...} 4779 4780 `defstruct/1`, however, allows protocol implementations to be 4781 *derived*. This can be done by defining a `@derive` attribute as a 4782 list before invoking `defstruct/1`: 4783 4784 defmodule User do 4785 @derive [MyProtocol] 4786 defstruct name: nil, age: 10 + 11 4787 end 4788 4789 MyProtocol.call(john) # it works! 4790 4791 For each protocol in the `@derive` list, Elixir will assert the protocol has 4792 been implemented for `Any`. If the `Any` implementation defines a 4793 `__deriving__/3` callback, the callback will be invoked and it should define 4794 the implementation module. Otherwise an implementation that simply points to 4795 the `Any` implementation is automatically derived. For more information on 4796 the `__deriving__/3` callback, see `Protocol.derive/3`. 4797 4798 ## Enforcing keys 4799 4800 When building a struct, Elixir will automatically guarantee all keys 4801 belongs to the struct: 4802 4803 %User{name: "john", unknown: :key} 4804 ** (KeyError) key :unknown not found in: %User{age: 21, name: nil} 4805 4806 Elixir also allows developers to enforce certain keys must always be 4807 given when building the struct: 4808 4809 defmodule User do 4810 @enforce_keys [:name] 4811 defstruct name: nil, age: 10 + 11 4812 end 4813 4814 Now trying to build a struct without the name key will fail: 4815 4816 %User{age: 21} 4817 ** (ArgumentError) the following keys must also be given when building struct User: [:name] 4818 4819 Keep in mind `@enforce_keys` is a simple compile-time guarantee 4820 to aid developers when building structs. It is not enforced on 4821 updates and it does not provide any sort of value-validation. 4822 4823 ## Types 4824 4825 It is recommended to define types for structs. By convention such type 4826 is called `t`. To define a struct inside a type, the struct literal syntax 4827 is used: 4828 4829 defmodule User do 4830 defstruct name: "John", age: 25 4831 @type t :: %__MODULE__{name: String.t(), age: non_neg_integer} 4832 end 4833 4834 It is recommended to only use the struct syntax when defining the struct's 4835 type. When referring to another struct it's better to use `User.t` instead of 4836 `%User{}`. 4837 4838 The types of the struct fields that are not included in `%User{}` default to 4839 `term()` (see `t:term/0`). 4840 4841 Structs whose internal structure is private to the local module (pattern 4842 matching them or directly accessing their fields should not be allowed) should 4843 use the `@opaque` attribute. Structs whose internal structure is public should 4844 use `@type`. 4845 """ 4846 defmacro defstruct(fields) do 4847 builder = 4848 case bootstrapped?(Enum) do 4849 true -> 4850 quote do 4851 case @enforce_keys do 4852 [] -> 4853 def __struct__(kv) do 4854 Enum.reduce(kv, @__struct__, fn {key, val}, map -> 4855 Map.replace!(map, key, val) 4856 end) 4857 end 4858 4859 _ -> 4860 def __struct__(kv) do 4861 {map, keys} = 4862 Enum.reduce(kv, {@__struct__, @enforce_keys}, fn {key, val}, {map, keys} -> 4863 {Map.replace!(map, key, val), List.delete(keys, key)} 4864 end) 4865 4866 case keys do 4867 [] -> 4868 map 4869 4870 _ -> 4871 raise ArgumentError, 4872 "the following keys must also be given when building " <> 4873 "struct #{inspect(__MODULE__)}: #{inspect(keys)}" 4874 end 4875 end 4876 end 4877 end 4878 4879 false -> 4880 quote do 4881 _ = @enforce_keys 4882 4883 def __struct__(kv) do 4884 :lists.foldl(fn {key, val}, acc -> Map.replace!(acc, key, val) end, @__struct__, kv) 4885 end 4886 end 4887 end 4888 4889 quote do 4890 if Module.has_attribute?(__MODULE__, :__struct__) do 4891 raise ArgumentError, 4892 "defstruct has already been called for " <> 4893 "#{Kernel.inspect(__MODULE__)}, defstruct can only be called once per module" 4894 end 4895 4896 {struct, keys, derive} = Kernel.Utils.defstruct(__MODULE__, unquote(fields)) 4897 @__struct__ struct 4898 @enforce_keys keys 4899 4900 case derive do 4901 [] -> :ok 4902 _ -> Protocol.__derive__(derive, __MODULE__, __ENV__) 4903 end 4904 4905 def __struct__() do 4906 @__struct__ 4907 end 4908 4909 unquote(builder) 4910 Kernel.Utils.announce_struct(__MODULE__) 4911 struct 4912 end 4913 end 4914 4915 @doc ~S""" 4916 Defines an exception. 4917 4918 Exceptions are structs backed by a module that implements 4919 the `Exception` behaviour. The `Exception` behaviour requires 4920 two functions to be implemented: 4921 4922 * [`exception/1`](`c:Exception.exception/1`) - receives the arguments given to `raise/2` 4923 and returns the exception struct. The default implementation 4924 accepts either a set of keyword arguments that is merged into 4925 the struct or a string to be used as the exception's message. 4926 4927 * [`message/1`](`c:Exception.message/1`) - receives the exception struct and must return its 4928 message. Most commonly exceptions have a message field which 4929 by default is accessed by this function. However, if an exception 4930 does not have a message field, this function must be explicitly 4931 implemented. 4932 4933 Since exceptions are structs, the API supported by `defstruct/1` 4934 is also available in `defexception/1`. 4935 4936 ## Raising exceptions 4937 4938 The most common way to raise an exception is via `raise/2`: 4939 4940 defmodule MyAppError do 4941 defexception [:message] 4942 end 4943 4944 value = [:hello] 4945 4946 raise MyAppError, 4947 message: "did not get what was expected, got: #{inspect(value)}" 4948 4949 In many cases it is more convenient to pass the expected value to 4950 `raise/2` and generate the message in the `c:Exception.exception/1` callback: 4951 4952 defmodule MyAppError do 4953 defexception [:message] 4954 4955 @impl true 4956 def exception(value) do 4957 msg = "did not get what was expected, got: #{inspect(value)}" 4958 %MyAppError{message: msg} 4959 end 4960 end 4961 4962 raise MyAppError, value 4963 4964 The example above shows the preferred strategy for customizing 4965 exception messages. 4966 """ 4967 defmacro defexception(fields) do 4968 quote bind_quoted: [fields: fields] do 4969 @behaviour Exception 4970 struct = defstruct([__exception__: true] ++ fields) 4971 4972 if Map.has_key?(struct, :message) do 4973 @impl true 4974 def message(exception) do 4975 exception.message 4976 end 4977 4978 defoverridable message: 1 4979 4980 @impl true 4981 def exception(msg) when Kernel.is_binary(msg) do 4982 exception(message: msg) 4983 end 4984 end 4985 4986 # Calls to Kernel functions must be fully-qualified to ensure 4987 # reproducible builds; otherwise, this macro will generate ASTs 4988 # with different metadata (:import, :context) depending on if 4989 # it is the bootstrapped version or not. 4990 # TODO: Change the implementation on v2.0 to simply call Kernel.struct!/2 4991 @impl true 4992 def exception(args) when Kernel.is_list(args) do 4993 struct = __struct__() 4994 {valid, invalid} = Enum.split_with(args, fn {k, _} -> Map.has_key?(struct, k) end) 4995 4996 case invalid do 4997 [] -> 4998 :ok 4999 5000 _ -> 5001 IO.warn( 5002 "the following fields are unknown when raising " <> 5003 "#{Kernel.inspect(__MODULE__)}: #{Kernel.inspect(invalid)}. " <> 5004 "Please make sure to only give known fields when raising " <> 5005 "or redefine #{Kernel.inspect(__MODULE__)}.exception/1 to " <> 5006 "discard unknown fields. Future Elixir versions will raise on " <> 5007 "unknown fields given to raise/2" 5008 ) 5009 end 5010 5011 Kernel.struct!(struct, valid) 5012 end 5013 5014 defoverridable exception: 1 5015 end 5016 end 5017 5018 @doc """ 5019 Defines a protocol. 5020 5021 See the `Protocol` module for more information. 5022 """ 5023 defmacro defprotocol(name, do_block) 5024 5025 defmacro defprotocol(name, do: block) do 5026 Protocol.__protocol__(name, do: block) 5027 end 5028 5029 @doc """ 5030 Defines an implementation for the given protocol. 5031 5032 See the `Protocol` module for more information. 5033 """ 5034 defmacro defimpl(name, opts, do_block \\ []) do 5035 merged = Keyword.merge(opts, do_block) 5036 merged = Keyword.put_new(merged, :for, __CALLER__.module) 5037 5038 if Keyword.fetch!(merged, :for) == nil do 5039 raise ArgumentError, "defimpl/3 expects a :for option when declared outside a module" 5040 end 5041 5042 Protocol.__impl__(name, merged) 5043 end 5044 5045 @doc """ 5046 Makes the given functions in the current module overridable. 5047 5048 An overridable function is lazily defined, allowing a developer to override 5049 it. 5050 5051 Macros cannot be overridden as functions and vice-versa. 5052 5053 ## Example 5054 5055 defmodule DefaultMod do 5056 defmacro __using__(_opts) do 5057 quote do 5058 def test(x, y) do 5059 x + y 5060 end 5061 5062 defoverridable test: 2 5063 end 5064 end 5065 end 5066 5067 defmodule InheritMod do 5068 use DefaultMod 5069 5070 def test(x, y) do 5071 x * y + super(x, y) 5072 end 5073 end 5074 5075 As seen as in the example above, `super` can be used to call the default 5076 implementation. 5077 5078 If `@behaviour` has been defined, `defoverridable` can also be called with a 5079 module as an argument. All implemented callbacks from the behaviour above the 5080 call to `defoverridable` will be marked as overridable. 5081 5082 ## Example 5083 5084 defmodule Behaviour do 5085 @callback foo :: any 5086 end 5087 5088 defmodule DefaultMod do 5089 defmacro __using__(_opts) do 5090 quote do 5091 @behaviour Behaviour 5092 5093 def foo do 5094 "Override me" 5095 end 5096 5097 defoverridable Behaviour 5098 end 5099 end 5100 end 5101 5102 defmodule InheritMod do 5103 use DefaultMod 5104 5105 def foo do 5106 "Overridden" 5107 end 5108 end 5109 5110 """ 5111 defmacro defoverridable(keywords_or_behaviour) do 5112 quote do 5113 Module.make_overridable(__MODULE__, unquote(keywords_or_behaviour)) 5114 end 5115 end 5116 5117 @doc """ 5118 Generates a macro suitable for use in guard expressions. 5119 5120 It raises at compile time if the definition uses expressions that aren't 5121 allowed in guards, and otherwise creates a macro that can be used both inside 5122 or outside guards. 5123 5124 Note the convention in Elixir is to name functions/macros allowed in 5125 guards with the `is_` prefix, such as `is_list/1`. If, however, the 5126 function/macro returns a boolean and is not allowed in guards, it should 5127 have no prefix and end with a question mark, such as `Keyword.keyword?/1`. 5128 5129 ## Example 5130 5131 defmodule Integer.Guards do 5132 defguard is_even(value) when is_integer(value) and rem(value, 2) == 0 5133 end 5134 5135 defmodule Collatz do 5136 @moduledoc "Tools for working with the Collatz sequence." 5137 import Integer.Guards 5138 5139 @doc "Determines the number of steps `n` takes to reach `1`." 5140 # If this function never converges, please let me know what `n` you used. 5141 def converge(n) when n > 0, do: step(n, 0) 5142 5143 defp step(1, step_count) do 5144 step_count 5145 end 5146 5147 defp step(n, step_count) when is_even(n) do 5148 step(div(n, 2), step_count + 1) 5149 end 5150 5151 defp step(n, step_count) do 5152 step(3 * n + 1, step_count + 1) 5153 end 5154 end 5155 5156 """ 5157 @doc since: "1.6.0" 5158 @spec defguard(Macro.t()) :: Macro.t() 5159 defmacro defguard(guard) do 5160 define_guard(:defmacro, guard, __CALLER__) 5161 end 5162 5163 @doc """ 5164 Generates a private macro suitable for use in guard expressions. 5165 5166 It raises at compile time if the definition uses expressions that aren't 5167 allowed in guards, and otherwise creates a private macro that can be used 5168 both inside or outside guards in the current module. 5169 5170 Similar to `defmacrop/2`, `defguardp/1` must be defined before its use 5171 in the current module. 5172 """ 5173 @doc since: "1.6.0" 5174 @spec defguardp(Macro.t()) :: Macro.t() 5175 defmacro defguardp(guard) do 5176 define_guard(:defmacrop, guard, __CALLER__) 5177 end 5178 5179 defp define_guard(kind, guard, env) do 5180 case :elixir_utils.extract_guards(guard) do 5181 {call, [_, _ | _]} -> 5182 raise ArgumentError, 5183 "invalid syntax in defguard #{Macro.to_string(call)}, " <> 5184 "only a single when clause is allowed" 5185 5186 {call, impls} -> 5187 case Macro.decompose_call(call) do 5188 {_name, args} -> 5189 validate_variable_only_args!(call, args) 5190 5191 macro_definition = 5192 case impls do 5193 [] -> 5194 define(kind, call, nil, env) 5195 5196 [guard] -> 5197 quoted = 5198 quote do 5199 require Kernel.Utils 5200 Kernel.Utils.defguard(unquote(args), unquote(guard)) 5201 end 5202 5203 define(kind, call, [do: quoted], env) 5204 end 5205 5206 quote do 5207 @doc guard: true 5208 unquote(macro_definition) 5209 end 5210 5211 _invalid_definition -> 5212 raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" 5213 end 5214 end 5215 end 5216 5217 defp validate_variable_only_args!(call, args) do 5218 Enum.each(args, fn 5219 {ref, _meta, context} when is_atom(ref) and is_atom(context) -> 5220 :ok 5221 5222 {:\\, _m1, [{ref, _m2, context}, _default]} when is_atom(ref) and is_atom(context) -> 5223 :ok 5224 5225 _match -> 5226 raise ArgumentError, "invalid syntax in defguard #{Macro.to_string(call)}" 5227 end) 5228 end 5229 5230 @doc """ 5231 Uses the given module in the current context. 5232 5233 When calling: 5234 5235 use MyModule, some: :options 5236 5237 the `__using__/1` macro from the `MyModule` module is invoked with the second 5238 argument passed to `use` as its argument. Since `__using__/1` is a macro, all 5239 the usual macro rules apply, and its return value should be quoted code 5240 that is then inserted where `use/2` is called. 5241 5242 ## Examples 5243 5244 For example, to write test cases using the `ExUnit` framework provided 5245 with Elixir, a developer should `use` the `ExUnit.Case` module: 5246 5247 defmodule AssertionTest do 5248 use ExUnit.Case, async: true 5249 5250 test "always pass" do 5251 assert true 5252 end 5253 end 5254 5255 In this example, Elixir will call the `__using__/1` macro in the 5256 `ExUnit.Case` module with the keyword list `[async: true]` as its 5257 argument. 5258 5259 In other words, `use/2` translates to: 5260 5261 defmodule AssertionTest do 5262 require ExUnit.Case 5263 ExUnit.Case.__using__(async: true) 5264 5265 test "always pass" do 5266 assert true 5267 end 5268 end 5269 5270 where `ExUnit.Case` defines the `__using__/1` macro: 5271 5272 defmodule ExUnit.Case do 5273 defmacro __using__(opts) do 5274 # do something with opts 5275 quote do 5276 # return some code to inject in the caller 5277 end 5278 end 5279 end 5280 5281 ## Best practices 5282 5283 `__using__/1` is typically used when there is a need to set some state (via 5284 module attributes) or callbacks (like `@before_compile`, see the documentation 5285 for `Module` for more information) into the caller. 5286 5287 `__using__/1` may also be used to alias, require, or import functionality 5288 from different modules: 5289 5290 defmodule MyModule do 5291 defmacro __using__(_opts) do 5292 quote do 5293 import MyModule.Foo 5294 import MyModule.Bar 5295 import MyModule.Baz 5296 5297 alias MyModule.Repo 5298 end 5299 end 5300 end 5301 5302 However, do not provide `__using__/1` if all it does is to import, 5303 alias or require the module itself. For example, avoid this: 5304 5305 defmodule MyModule do 5306 defmacro __using__(_opts) do 5307 quote do 5308 import MyModule 5309 end 5310 end 5311 end 5312 5313 In such cases, developers should instead import or alias the module 5314 directly, so that they can customize those as they wish, 5315 without the indirection behind `use/2`. 5316 5317 Finally, developers should also avoid defining functions inside 5318 the `__using__/1` callback, unless those functions are the default 5319 implementation of a previously defined `@callback` or are functions 5320 meant to be overridden (see `defoverridable/1`). Even in these cases, 5321 defining functions should be seen as a "last resort". 5322 5323 In case you want to provide some existing functionality to the user module, 5324 please define it in a module which will be imported accordingly; for example, 5325 `ExUnit.Case` doesn't define the `test/3` macro in the module that calls 5326 `use ExUnit.Case`, but it defines `ExUnit.Case.test/3` and just imports that 5327 into the caller when used. 5328 """ 5329 defmacro use(module, opts \\ []) do 5330 calls = 5331 Enum.map(expand_aliases(module, __CALLER__), fn 5332 expanded when is_atom(expanded) -> 5333 quote do 5334 require unquote(expanded) 5335 unquote(expanded).__using__(unquote(opts)) 5336 end 5337 5338 _otherwise -> 5339 raise ArgumentError, 5340 "invalid arguments for use, " <> 5341 "expected a compile time atom or alias, got: #{Macro.to_string(module)}" 5342 end) 5343 5344 quote(do: (unquote_splicing(calls))) 5345 end 5346 5347 defp expand_aliases({{:., _, [base, :{}]}, _, refs}, env) do 5348 base = Macro.expand(base, env) 5349 5350 Enum.map(refs, fn 5351 {:__aliases__, _, ref} -> 5352 Module.concat([base | ref]) 5353 5354 ref when is_atom(ref) -> 5355 Module.concat(base, ref) 5356 5357 other -> 5358 other 5359 end) 5360 end 5361 5362 defp expand_aliases(module, env) do 5363 [Macro.expand(module, env)] 5364 end 5365 5366 @doc """ 5367 Defines a function that delegates to another module. 5368 5369 Functions defined with `defdelegate/2` are public and can be invoked from 5370 outside the module they're defined in, as if they were defined using `def/2`. 5371 Therefore, `defdelegate/2` is about extending the current module's public API. 5372 If what you want is to invoke a function defined in another module without 5373 using its full module name, then use `alias/2` to shorten the module name or use 5374 `import/2` to be able to invoke the function without the module name altogether. 5375 5376 Delegation only works with functions; delegating macros is not supported. 5377 5378 Check `def/2` for rules on naming and default arguments. 5379 5380 ## Options 5381 5382 * `:to` - the module to dispatch to. 5383 5384 * `:as` - the function to call on the target given in `:to`. 5385 This parameter is optional and defaults to the name being 5386 delegated (`funs`). 5387 5388 ## Examples 5389 5390 defmodule MyList do 5391 defdelegate reverse(list), to: Enum 5392 defdelegate other_reverse(list), to: Enum, as: :reverse 5393 end 5394 5395 MyList.reverse([1, 2, 3]) 5396 #=> [3, 2, 1] 5397 5398 MyList.other_reverse([1, 2, 3]) 5399 #=> [3, 2, 1] 5400 5401 """ 5402 defmacro defdelegate(funs, opts) do 5403 funs = Macro.escape(funs, unquote: true) 5404 5405 # don't add compile-time dependency on :to 5406 opts = 5407 with true <- is_list(opts), 5408 {:ok, target} <- Keyword.fetch(opts, :to), 5409 {:__aliases__, _, _} <- target do 5410 target = Macro.expand(target, %{__CALLER__ | function: {:__info__, 1}}) 5411 Keyword.replace!(opts, :to, target) 5412 else 5413 _ -> 5414 opts 5415 end 5416 5417 quote bind_quoted: [funs: funs, opts: opts] do 5418 target = 5419 Keyword.get(opts, :to) || raise ArgumentError, "expected to: to be given as argument" 5420 5421 if is_list(funs) do 5422 IO.warn( 5423 "passing a list to Kernel.defdelegate/2 is deprecated, please define each delegate separately", 5424 Macro.Env.stacktrace(__ENV__) 5425 ) 5426 end 5427 5428 if Keyword.has_key?(opts, :append_first) do 5429 IO.warn( 5430 "Kernel.defdelegate/2 :append_first option is deprecated", 5431 Macro.Env.stacktrace(__ENV__) 5432 ) 5433 end 5434 5435 for fun <- List.wrap(funs) do 5436 {name, args, as, as_args} = Kernel.Utils.defdelegate(fun, opts) 5437 5438 @doc delegate_to: {target, as, :erlang.length(as_args)} 5439 5440 # Build the call AST by hand so it doesn't get a 5441 # context and it warns on things like missing @impl 5442 def unquote({name, [line: __ENV__.line], args}) do 5443 unquote(target).unquote(as)(unquote_splicing(as_args)) 5444 end 5445 end 5446 end 5447 end 5448 5449 ## Sigils 5450 5451 @doc ~S""" 5452 Handles the sigil `~S` for strings. 5453 5454 It returns a string without interpolations and without escape 5455 characters, except for the escaping of the closing sigil character 5456 itself. 5457 5458 ## Examples 5459 5460 iex> ~S(foo) 5461 "foo" 5462 iex> ~S(f#{o}o) 5463 "f\#{o}o" 5464 iex> ~S(\o/) 5465 "\\o/" 5466 5467 However, if you want to re-use the sigil character itself on 5468 the string, you need to escape it: 5469 5470 iex> ~S((\)) 5471 "()" 5472 5473 """ 5474 defmacro sigil_S(term, modifiers) 5475 defmacro sigil_S({:<<>>, _, [binary]}, []) when is_binary(binary), do: binary 5476 5477 @doc ~S""" 5478 Handles the sigil `~s` for strings. 5479 5480 It returns a string as if it was a double quoted string, unescaping characters 5481 and replacing interpolations. 5482 5483 ## Examples 5484 5485 iex> ~s(foo) 5486 "foo" 5487 5488 iex> ~s(f#{:o}o) 5489 "foo" 5490 5491 iex> ~s(f\#{:o}o) 5492 "f\#{:o}o" 5493 5494 """ 5495 defmacro sigil_s(term, modifiers) 5496 5497 defmacro sigil_s({:<<>>, _, [piece]}, []) when is_binary(piece) do 5498 :elixir_interpolation.unescape_string(piece) 5499 end 5500 5501 defmacro sigil_s({:<<>>, line, pieces}, []) do 5502 {:<<>>, line, unescape_tokens(pieces)} 5503 end 5504 5505 @doc ~S""" 5506 Handles the sigil `~C` for charlists. 5507 5508 It returns a charlist without interpolations and without escape 5509 characters, except for the escaping of the closing sigil character 5510 itself. 5511 5512 ## Examples 5513 5514 iex> ~C(foo) 5515 'foo' 5516 5517 iex> ~C(f#{o}o) 5518 'f\#{o}o' 5519 5520 """ 5521 defmacro sigil_C(term, modifiers) 5522 5523 defmacro sigil_C({:<<>>, _meta, [string]}, []) when is_binary(string) do 5524 String.to_charlist(string) 5525 end 5526 5527 @doc ~S""" 5528 Handles the sigil `~c` for charlists. 5529 5530 It returns a charlist as if it was a single quoted string, unescaping 5531 characters and replacing interpolations. 5532 5533 ## Examples 5534 5535 iex> ~c(foo) 5536 'foo' 5537 5538 iex> ~c(f#{:o}o) 5539 'foo' 5540 5541 iex> ~c(f\#{:o}o) 5542 'f\#{:o}o' 5543 5544 """ 5545 defmacro sigil_c(term, modifiers) 5546 5547 # We can skip the runtime conversion if we are 5548 # creating a binary made solely of series of chars. 5549 defmacro sigil_c({:<<>>, _meta, [string]}, []) when is_binary(string) do 5550 String.to_charlist(:elixir_interpolation.unescape_string(string)) 5551 end 5552 5553 defmacro sigil_c({:<<>>, _meta, pieces}, []) do 5554 quote(do: List.to_charlist(unquote(unescape_list_tokens(pieces)))) 5555 end 5556 5557 @doc ~S""" 5558 Handles the sigil `~r` for regular expressions. 5559 5560 It returns a regular expression pattern, unescaping characters and replacing 5561 interpolations. 5562 5563 More information on regular expressions can be found in the `Regex` module. 5564 5565 ## Examples 5566 5567 iex> Regex.match?(~r/foo/, "foo") 5568 true 5569 5570 iex> Regex.match?(~r/a#{:b}c/, "abc") 5571 true 5572 5573 While the `~r` sigil allows parens and brackets to be used as delimiters, 5574 it is preferred to use `"` or `/` to avoid escaping conflicts with reserved 5575 regex characters. 5576 """ 5577 defmacro sigil_r(term, modifiers) 5578 5579 defmacro sigil_r({:<<>>, _meta, [string]}, options) when is_binary(string) do 5580 binary = :elixir_interpolation.unescape_string(string, &Regex.unescape_map/1) 5581 regex = Regex.compile!(binary, :binary.list_to_bin(options)) 5582 Macro.escape(regex) 5583 end 5584 5585 defmacro sigil_r({:<<>>, meta, pieces}, options) do 5586 binary = {:<<>>, meta, unescape_tokens(pieces, &Regex.unescape_map/1)} 5587 quote(do: Regex.compile!(unquote(binary), unquote(:binary.list_to_bin(options)))) 5588 end 5589 5590 @doc ~S""" 5591 Handles the sigil `~R` for regular expressions. 5592 5593 It returns a regular expression pattern without interpolations and 5594 without escape characters. Note it still supports escape of Regex 5595 tokens (such as escaping `+` or `?`) and it also requires you to 5596 escape the closing sigil character itself if it appears on the Regex. 5597 5598 More information on regexes can be found in the `Regex` module. 5599 5600 ## Examples 5601 5602 iex> Regex.match?(~R(f#{1,3}o), "f#o") 5603 true 5604 5605 """ 5606 defmacro sigil_R(term, modifiers) 5607 5608 defmacro sigil_R({:<<>>, _meta, [string]}, options) when is_binary(string) do 5609 regex = Regex.compile!(string, :binary.list_to_bin(options)) 5610 Macro.escape(regex) 5611 end 5612 5613 @doc ~S""" 5614 Handles the sigil `~D` for dates. 5615 5616 By default, this sigil uses the built-in `Calendar.ISO`, which 5617 requires dates to be written in the ISO8601 format: 5618 5619 ~D[yyyy-mm-dd] 5620 5621 such as: 5622 5623 ~D[2015-01-13] 5624 5625 If you are using alternative calendars, any representation can 5626 be used as long as you follow the representation by a single space 5627 and the calendar name: 5628 5629 ~D[SOME-REPRESENTATION My.Alternative.Calendar] 5630 5631 The lower case `~d` variant does not exist as interpolation 5632 and escape characters are not useful for date sigils. 5633 5634 More information on dates can be found in the `Date` module. 5635 5636 ## Examples 5637 5638 iex> ~D[2015-01-13] 5639 ~D[2015-01-13] 5640 5641 """ 5642 defmacro sigil_D(date_string, modifiers) 5643 5644 defmacro sigil_D({:<<>>, _, [string]}, []) do 5645 {{:ok, {year, month, day}}, calendar} = parse_with_calendar!(string, :parse_date, "Date") 5646 to_calendar_struct(Date, calendar: calendar, year: year, month: month, day: day) 5647 end 5648 5649 @doc ~S""" 5650 Handles the sigil `~T` for times. 5651 5652 By default, this sigil uses the built-in `Calendar.ISO`, which 5653 requires times to be written in the ISO8601 format: 5654 5655 ~T[hh:mm:ss] 5656 ~T[hh:mm:ss.ssssss] 5657 5658 such as: 5659 5660 ~T[13:00:07] 5661 ~T[13:00:07.123] 5662 5663 If you are using alternative calendars, any representation can 5664 be used as long as you follow the representation by a single space 5665 and the calendar name: 5666 5667 ~T[SOME-REPRESENTATION My.Alternative.Calendar] 5668 5669 The lower case `~t` variant does not exist as interpolation 5670 and escape characters are not useful for time sigils. 5671 5672 More information on times can be found in the `Time` module. 5673 5674 ## Examples 5675 5676 iex> ~T[13:00:07] 5677 ~T[13:00:07] 5678 iex> ~T[13:00:07.001] 5679 ~T[13:00:07.001] 5680 5681 """ 5682 defmacro sigil_T(time_string, modifiers) 5683 5684 defmacro sigil_T({:<<>>, _, [string]}, []) do 5685 {{:ok, {hour, minute, second, microsecond}}, calendar} = 5686 parse_with_calendar!(string, :parse_time, "Time") 5687 5688 to_calendar_struct(Time, 5689 calendar: calendar, 5690 hour: hour, 5691 minute: minute, 5692 second: second, 5693 microsecond: microsecond 5694 ) 5695 end 5696 5697 @doc ~S""" 5698 Handles the sigil `~N` for naive date times. 5699 5700 By default, this sigil uses the built-in `Calendar.ISO`, which 5701 requires naive date times to be written in the ISO8601 format: 5702 5703 ~N[yyyy-mm-dd hh:mm:ss] 5704 ~N[yyyy-mm-dd hh:mm:ss.ssssss] 5705 ~N[yyyy-mm-ddThh:mm:ss.ssssss] 5706 5707 such as: 5708 5709 ~N[2015-01-13 13:00:07] 5710 ~N[2015-01-13T13:00:07.123] 5711 5712 If you are using alternative calendars, any representation can 5713 be used as long as you follow the representation by a single space 5714 and the calendar name: 5715 5716 ~N[SOME-REPRESENTATION My.Alternative.Calendar] 5717 5718 The lower case `~n` variant does not exist as interpolation 5719 and escape characters are not useful for date time sigils. 5720 5721 More information on naive date times can be found in the 5722 `NaiveDateTime` module. 5723 5724 ## Examples 5725 5726 iex> ~N[2015-01-13 13:00:07] 5727 ~N[2015-01-13 13:00:07] 5728 iex> ~N[2015-01-13T13:00:07.001] 5729 ~N[2015-01-13 13:00:07.001] 5730 5731 """ 5732 defmacro sigil_N(naive_datetime_string, modifiers) 5733 5734 defmacro sigil_N({:<<>>, _, [string]}, []) do 5735 {{:ok, {year, month, day, hour, minute, second, microsecond}}, calendar} = 5736 parse_with_calendar!(string, :parse_naive_datetime, "NaiveDateTime") 5737 5738 to_calendar_struct(NaiveDateTime, 5739 calendar: calendar, 5740 year: year, 5741 month: month, 5742 day: day, 5743 hour: hour, 5744 minute: minute, 5745 second: second, 5746 microsecond: microsecond 5747 ) 5748 end 5749 5750 @doc ~S""" 5751 Handles the sigil `~U` to create a UTC `DateTime`. 5752 5753 By default, this sigil uses the built-in `Calendar.ISO`, which 5754 requires UTC date times to be written in the ISO8601 format: 5755 5756 ~U[yyyy-mm-dd hh:mm:ssZ] 5757 ~U[yyyy-mm-dd hh:mm:ss.ssssssZ] 5758 ~U[yyyy-mm-ddThh:mm:ss.ssssss+00:00] 5759 5760 such as: 5761 5762 ~U[2015-01-13 13:00:07Z] 5763 ~U[2015-01-13T13:00:07.123+00:00] 5764 5765 If you are using alternative calendars, any representation can 5766 be used as long as you follow the representation by a single space 5767 and the calendar name: 5768 5769 ~U[SOME-REPRESENTATION My.Alternative.Calendar] 5770 5771 The given `datetime_string` must include "Z" or "00:00" offset 5772 which marks it as UTC, otherwise an error is raised. 5773 5774 The lower case `~u` variant does not exist as interpolation 5775 and escape characters are not useful for date time sigils. 5776 5777 More information on date times can be found in the `DateTime` module. 5778 5779 ## Examples 5780 5781 iex> ~U[2015-01-13 13:00:07Z] 5782 ~U[2015-01-13 13:00:07Z] 5783 iex> ~U[2015-01-13T13:00:07.001+00:00] 5784 ~U[2015-01-13 13:00:07.001Z] 5785 5786 """ 5787 @doc since: "1.9.0" 5788 defmacro sigil_U(datetime_string, modifiers) 5789 5790 defmacro sigil_U({:<<>>, _, [string]}, []) do 5791 {{:ok, {year, month, day, hour, minute, second, microsecond}, offset}, calendar} = 5792 parse_with_calendar!(string, :parse_utc_datetime, "UTC DateTime") 5793 5794 if offset != 0 do 5795 raise ArgumentError, 5796 "cannot parse #{inspect(string)} as UTC DateTime for #{inspect(calendar)}, reason: :non_utc_offset" 5797 end 5798 5799 to_calendar_struct(DateTime, 5800 calendar: calendar, 5801 year: year, 5802 month: month, 5803 day: day, 5804 hour: hour, 5805 minute: minute, 5806 second: second, 5807 microsecond: microsecond, 5808 time_zone: "Etc/UTC", 5809 zone_abbr: "UTC", 5810 utc_offset: 0, 5811 std_offset: 0 5812 ) 5813 end 5814 5815 defp parse_with_calendar!(string, fun, context) do 5816 {calendar, string} = extract_calendar(string) 5817 result = apply(calendar, fun, [string]) 5818 {maybe_raise!(result, calendar, context, string), calendar} 5819 end 5820 5821 defp extract_calendar(string) do 5822 case :binary.split(string, " ", [:global]) do 5823 [_] -> {Calendar.ISO, string} 5824 parts -> maybe_atomize_calendar(List.last(parts), string) 5825 end 5826 end 5827 5828 defp maybe_atomize_calendar(<<alias, _::binary>> = last_part, string) 5829 when alias >= ?A and alias <= ?Z do 5830 string = binary_part(string, 0, byte_size(string) - byte_size(last_part) - 1) 5831 {String.to_atom("Elixir." <> last_part), string} 5832 end 5833 5834 defp maybe_atomize_calendar(_last_part, string) do 5835 {Calendar.ISO, string} 5836 end 5837 5838 defp maybe_raise!({:error, reason}, calendar, type, string) do 5839 raise ArgumentError, 5840 "cannot parse #{inspect(string)} as #{type} for #{inspect(calendar)}, " <> 5841 "reason: #{inspect(reason)}" 5842 end 5843 5844 defp maybe_raise!(other, _calendar, _type, _string), do: other 5845 5846 defp to_calendar_struct(type, fields) do 5847 quote do 5848 %{unquote_splicing([__struct__: type] ++ fields)} 5849 end 5850 end 5851 5852 @doc ~S""" 5853 Handles the sigil `~w` for list of words. 5854 5855 It returns a list of "words" split by whitespace. Character unescaping and 5856 interpolation happens for each word. 5857 5858 ## Modifiers 5859 5860 * `s`: words in the list are strings (default) 5861 * `a`: words in the list are atoms 5862 * `c`: words in the list are charlists 5863 5864 ## Examples 5865 5866 iex> ~w(foo #{:bar} baz) 5867 ["foo", "bar", "baz"] 5868 5869 iex> ~w(foo #{" bar baz "}) 5870 ["foo", "bar", "baz"] 5871 5872 iex> ~w(--source test/enum_test.exs) 5873 ["--source", "test/enum_test.exs"] 5874 5875 iex> ~w(foo bar baz)a 5876 [:foo, :bar, :baz] 5877 5878 """ 5879 defmacro sigil_w(term, modifiers) 5880 5881 defmacro sigil_w({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do 5882 split_words(:elixir_interpolation.unescape_string(string), modifiers, __CALLER__) 5883 end 5884 5885 defmacro sigil_w({:<<>>, meta, pieces}, modifiers) do 5886 binary = {:<<>>, meta, unescape_tokens(pieces)} 5887 split_words(binary, modifiers, __CALLER__) 5888 end 5889 5890 @doc ~S""" 5891 Handles the sigil `~W` for list of words. 5892 5893 It returns a list of "words" split by whitespace without interpolations 5894 and without escape characters, except for the escaping of the closing 5895 sigil character itself. 5896 5897 ## Modifiers 5898 5899 * `s`: words in the list are strings (default) 5900 * `a`: words in the list are atoms 5901 * `c`: words in the list are charlists 5902 5903 ## Examples 5904 5905 iex> ~W(foo #{bar} baz) 5906 ["foo", "\#{bar}", "baz"] 5907 5908 """ 5909 defmacro sigil_W(term, modifiers) 5910 5911 defmacro sigil_W({:<<>>, _meta, [string]}, modifiers) when is_binary(string) do 5912 split_words(string, modifiers, __CALLER__) 5913 end 5914 5915 defp split_words(string, [], caller) do 5916 split_words(string, [?s], caller) 5917 end 5918 5919 defp split_words(string, [mod], caller) 5920 when mod == ?s or mod == ?a or mod == ?c do 5921 case is_binary(string) do 5922 true -> 5923 parts = String.split(string) 5924 5925 parts_with_trailing_comma = 5926 :lists.filter(&(byte_size(&1) > 1 and :binary.last(&1) == ?,), parts) 5927 5928 if parts_with_trailing_comma != [] do 5929 stacktrace = Macro.Env.stacktrace(caller) 5930 5931 IO.warn( 5932 "the sigils ~w/~W do not allow trailing commas at the end of each word. " <> 5933 "If the comma is necessary, define a regular list with [...], otherwise remove the comma.", 5934 stacktrace 5935 ) 5936 end 5937 5938 case mod do 5939 ?s -> parts 5940 ?a -> :lists.map(&String.to_atom/1, parts) 5941 ?c -> :lists.map(&String.to_charlist/1, parts) 5942 end 5943 5944 false -> 5945 parts = quote(do: String.split(unquote(string))) 5946 5947 case mod do 5948 ?s -> parts 5949 ?a -> quote(do: :lists.map(&String.to_atom/1, unquote(parts))) 5950 ?c -> quote(do: :lists.map(&String.to_charlist/1, unquote(parts))) 5951 end 5952 end 5953 end 5954 5955 defp split_words(_string, _mods, _caller) do 5956 raise ArgumentError, "modifier must be one of: s, a, c" 5957 end 5958 5959 ## Shared functions 5960 5961 defp assert_module_scope(env, fun, arity) do 5962 case env.module do 5963 nil -> raise ArgumentError, "cannot invoke #{fun}/#{arity} outside module" 5964 mod -> mod 5965 end 5966 end 5967 5968 defp assert_no_function_scope(env, fun, arity) do 5969 case env.function do 5970 nil -> :ok 5971 _ -> raise ArgumentError, "cannot invoke #{fun}/#{arity} inside function/macro" 5972 end 5973 end 5974 5975 defp assert_no_match_or_guard_scope(context, exp) do 5976 case context do 5977 :match -> 5978 invalid_match!(exp) 5979 5980 :guard -> 5981 raise ArgumentError, 5982 "invalid expression in guard, #{exp} is not allowed in guards. " <> 5983 "To learn more about guards, visit: https://hexdocs.pm/elixir/patterns-and-guards.html" 5984 5985 _ -> 5986 :ok 5987 end 5988 end 5989 5990 defp invalid_match!(exp) do 5991 raise ArgumentError, 5992 "invalid expression in match, #{exp} is not allowed in patterns " <> 5993 "such as function clauses, case clauses or on the left side of the = operator" 5994 end 5995 5996 # Helper to handle the :ok | :error tuple returned from :elixir_interpolation.unescape_tokens 5997 # We need to do this for bootstrapping purposes, actual code can use Macro.unescape_string. 5998 defp unescape_tokens(tokens) do 5999 :lists.map( 6000 fn token -> 6001 case is_binary(token) do 6002 true -> :elixir_interpolation.unescape_string(token) 6003 false -> token 6004 end 6005 end, 6006 tokens 6007 ) 6008 end 6009 6010 defp unescape_tokens(tokens, unescape_map) do 6011 :lists.map( 6012 fn token -> 6013 case is_binary(token) do 6014 true -> :elixir_interpolation.unescape_string(token, unescape_map) 6015 false -> token 6016 end 6017 end, 6018 tokens 6019 ) 6020 end 6021 6022 defp unescape_list_tokens(tokens) do 6023 escape = fn 6024 {:"::", _, [expr, _]} -> expr 6025 binary when is_binary(binary) -> :elixir_interpolation.unescape_string(binary) 6026 end 6027 6028 :lists.map(escape, tokens) 6029 end 6030 6031 @doc false 6032 defmacro to_char_list(arg) do 6033 IO.warn( 6034 "Kernel.to_char_list/1 is deprecated, use Kernel.to_charlist/1 instead", 6035 Macro.Env.stacktrace(__CALLER__) 6036 ) 6037 6038 quote(do: Kernel.to_charlist(unquote(arg))) 6039 end 6040end 6041