1defmodule Code do 2 @moduledoc ~S""" 3 Utilities for managing code compilation, code evaluation, and code loading. 4 5 This module complements Erlang's [`:code` module](`:code`) 6 to add behaviour which is specific to Elixir. Almost all of the functions in this module 7 have global side effects on the behaviour of Elixir. 8 9 ## Working with files 10 11 This module contains three functions for compiling and evaluating files. 12 Here is a summary of them and their behaviour: 13 14 * `require_file/2` - compiles a file and tracks its name. It does not 15 compile the file again if it has been previously required. 16 17 * `compile_file/2` - compiles a file without tracking its name. Compiles the 18 file multiple times when invoked multiple times. 19 20 * `eval_file/2` - evaluates the file contents without tracking its name. It 21 returns the result of the last expression in the file, instead of the modules 22 defined in it. Evaluated files do not trigger the compilation tracers described 23 in the next section. 24 25 In a nutshell, the first must be used when you want to keep track of the files 26 handled by the system, to avoid the same file from being compiled multiple 27 times. This is common in scripts. 28 29 `compile_file/2` must be used when you are interested in the modules defined in a 30 file, without tracking. `eval_file/2` should be used when you are interested in 31 the result of evaluating the file rather than the modules it defines. 32 33 The functions above work with Elixir source. If you want to work 34 with modules compiled to bytecode, which have the `.beam` extension 35 and are typically found below the _build directory of a Mix project, 36 see the functions in Erlang's [`:code`](`:code`) module. 37 38 ## Code loading on the Erlang VM 39 40 Erlang has two modes to load code: interactive and embedded. 41 42 By default, the Erlang VM runs in interactive mode, where modules 43 are loaded as needed. In embedded mode the opposite happens, as all 44 modules need to be loaded upfront or explicitly. 45 46 You can use `ensure_loaded/1` (as well as `ensure_loaded?/1` and 47 `ensure_loaded!/1`) to check if a module is loaded before using it and 48 act. 49 50 ## `ensure_compiled/1` and `ensure_compiled!/1` 51 52 Elixir also includes `ensure_compiled/1` and `ensure_compiled!/1` 53 functions that are a superset of `ensure_loaded/1`. 54 55 Since Elixir's compilation happens in parallel, in some situations 56 you may need to use a module that was not yet compiled, therefore 57 it can't even be loaded. 58 59 When invoked, `ensure_compiled/1` and `ensure_compiled!/1` halt the 60 compilation of the caller until the module becomes available. Note 61 the distinction between `ensure_compiled/1` and `ensure_compiled!/1` 62 is important: if you are using `ensure_compiled!/1`, you are 63 indicating to the compiler that you can only continue if said module 64 is available. 65 66 If you are using `Code.ensure_compiled/1`, you are implying you may 67 continue without the module and therefore Elixir may return 68 `{:error, :unavailable}` for cases where the module is not yet available 69 (but may be available later on). 70 71 For those reasons, developers must typically use `Code.ensure_compiled!/1`. 72 In particular, do not do this: 73 74 case Code.ensure_compiled(module) do 75 {:module, _} -> module 76 {:error, _} -> raise ... 77 end 78 79 Finally, note you only need `ensure_compiled!/1` to check for modules 80 being defined within the same project. It does not apply to modules from 81 dependencies as dependencies are always compiled upfront. 82 83 In most cases, `ensure_loaded/1` is enough. `ensure_compiled!/1` 84 must be used in rare cases, usually involving macros that need to 85 invoke a module for callback information. The use of `ensure_compiled/1` 86 is even less likely. 87 88 ## Compilation tracers 89 90 Elixir supports compilation tracers, which allows modules to observe constructs 91 handled by the Elixir compiler when compiling files. A tracer is a module 92 that implements the `trace/2` function. The function receives the event name 93 as first argument and `Macro.Env` as second and it must return `:ok`. It is 94 very important for a tracer to do as little work as possible synchronously 95 and dispatch the bulk of the work to a separate process. **Slow tracers will 96 slow down compilation**. 97 98 You can configure your list of tracers via `put_compiler_option/2`. The 99 following events are available to tracers: 100 101 * `:start` - (since v1.11.0) invoked whenever the compiler starts to trace 102 a new lexical context, such as a new file. Keep in mind the compiler runs 103 in parallel, so multiple files may invoke `:start` and run at the same 104 time. The value of the `lexical_tracker` of the macro environment, albeit 105 opaque, can be used to uniquely identify the environment. 106 107 * `:stop` - (since v1.11.0) invoked whenever the compiler stops tracing a 108 new lexical context, such as a new file. 109 110 * `{:import, meta, module, opts}` - traced whenever `module` is imported. 111 `meta` is the import AST metadata and `opts` are the import options. 112 113 * `{:imported_function, meta, module, name, arity}` and 114 `{:imported_macro, meta, module, name, arity}` - traced whenever an 115 imported function or macro is invoked. `meta` is the call AST metadata, 116 `module` is the module the import is from, followed by the `name` and `arity` 117 of the imported function/macro. 118 119 * `{:alias, meta, alias, as, opts}` - traced whenever `alias` is aliased 120 to `as`. `meta` is the alias AST metadata and `opts` are the alias options. 121 122 * `{:alias_expansion, meta, as, alias}` traced whenever there is an alias 123 expansion for a previously defined `alias`, i.e. when the user writes `as` 124 which is expanded to `alias`. `meta` is the alias expansion AST metadata. 125 126 * `{:alias_reference, meta, module}` - traced whenever there is an alias 127 in the code, i.e. whenever the user writes `MyModule.Foo.Bar` in the code, 128 regardless if it was expanded or not. 129 130 * `{:require, meta, module, opts}` - traced whenever `module` is required. 131 `meta` is the require AST metadata and `opts` are the require options. 132 133 * `{:struct_expansion, meta, module, keys}` - traced whenever `module`'s struct 134 is expanded. `meta` is the struct AST metadata and `keys` are the keys being 135 used by expansion 136 137 * `{:remote_function, meta, module, name, arity}` and 138 `{:remote_macro, meta, module, name, arity}` - traced whenever a remote 139 function or macro is referenced. `meta` is the call AST metadata, `module` 140 is the invoked module, followed by the `name` and `arity`. 141 142 * `{:local_function, meta, name, arity}` and 143 `{:local_macro, meta, name, arity}` - traced whenever a local 144 function or macro is referenced. `meta` is the call AST metadata, followed by 145 the `name` and `arity`. 146 147 * `{:compile_env, app, path, return}` - traced whenever `Application.compile_env/3` 148 or `Application.compile_env!/2` are called. `app` is an atom, `path` is a list 149 of keys to traverse in the application environment and `return` is either 150 `{:ok, value}` or `:error`. 151 152 * `{:on_module, bytecode, :none}` - (since v1.11.0) traced whenever a module 153 is defined. This is equivalent to the `@after_compile` callback and invoked 154 after any `@after_compile` in the given module. The third element is currently 155 `:none` but it may provide more metadata in the future. It is best to ignore 156 it at the moment. 157 158 The `:tracers` compiler option can be combined with the `:parser_options` 159 compiler option to enrich the metadata of the traced events above. 160 161 New events may be added at any time in the future, therefore it is advised 162 for the `trace/2` function to have a "catch-all" clause. 163 164 Below is an example tracer that prints all remote function invocations: 165 166 defmodule MyTracer do 167 def trace({:remote_function, _meta, module, name, arity}, env) do 168 IO.puts "#{env.file}:#{env.line} #{inspect(module)}.#{name}/#{arity}" 169 :ok 170 end 171 172 def trace(_event, _env) do 173 :ok 174 end 175 end 176 """ 177 178 @typedoc """ 179 A list with all variable bindings. 180 181 The binding keys are usually atoms, but they may be a tuple for variables 182 defined in a different context. 183 """ 184 @type binding :: [{atom() | tuple(), any}] 185 186 @boolean_compiler_options [ 187 :docs, 188 :debug_info, 189 :ignore_module_conflict, 190 :relative_paths, 191 :warnings_as_errors 192 ] 193 194 @list_compiler_options [:no_warn_undefined, :tracers, :parser_options] 195 196 @available_compiler_options @boolean_compiler_options ++ @list_compiler_options 197 198 @doc """ 199 Lists all required files. 200 201 ## Examples 202 203 Code.require_file("../eex/test/eex_test.exs") 204 List.first(Code.required_files()) =~ "eex_test.exs" 205 #=> true 206 207 """ 208 @doc since: "1.7.0" 209 @spec required_files() :: [binary] 210 def required_files do 211 :elixir_code_server.call(:required) 212 end 213 214 @deprecated "Use Code.required_files/0 instead" 215 @doc false 216 def loaded_files do 217 required_files() 218 end 219 220 @doc false 221 @deprecated "Use Code.Fragment.cursor_context/2 instead" 222 def cursor_context(code, options \\ []) do 223 Code.Fragment.cursor_context(code, options) 224 end 225 226 @doc """ 227 Removes files from the required files list. 228 229 The modules defined in the file are not removed; 230 calling this function only removes them from the list, 231 allowing them to be required again. 232 233 ## Examples 234 235 # Require EEx test code 236 Code.require_file("../eex/test/eex_test.exs") 237 238 # Now unrequire all files 239 Code.unrequire_files(Code.required_files()) 240 241 # Note that modules are still available 242 function_exported?(EExTest.Compiled, :before_compile, 0) 243 #=> true 244 245 """ 246 @doc since: "1.7.0" 247 @spec unrequire_files([binary]) :: :ok 248 def unrequire_files(files) when is_list(files) do 249 :elixir_code_server.cast({:unrequire_files, files}) 250 end 251 252 @deprecated "Use Code.unrequire_files/1 instead" 253 @doc false 254 def unload_files(files) do 255 unrequire_files(files) 256 end 257 258 @doc """ 259 Appends a path to the end of the Erlang VM code path list. 260 261 This is the list of directories the Erlang VM uses for 262 finding module code. 263 264 The path is expanded with `Path.expand/1` before being appended. 265 If this path does not exist, an error is returned. 266 267 ## Examples 268 269 Code.append_path(".") 270 #=> true 271 272 Code.append_path("/does_not_exist") 273 #=> {:error, :bad_directory} 274 275 """ 276 @spec append_path(Path.t()) :: true | {:error, :bad_directory} 277 def append_path(path) do 278 :code.add_pathz(to_charlist(Path.expand(path))) 279 end 280 281 @doc """ 282 Prepends a path to the beginning of the Erlang VM code path list. 283 284 This is the list of directories the Erlang VM uses for finding 285 module code. 286 287 The path is expanded with `Path.expand/1` before being prepended. 288 If this path does not exist, an error is returned. 289 290 ## Examples 291 292 Code.prepend_path(".") 293 #=> true 294 295 Code.prepend_path("/does_not_exist") 296 #=> {:error, :bad_directory} 297 298 """ 299 @spec prepend_path(Path.t()) :: true | {:error, :bad_directory} 300 def prepend_path(path) do 301 :code.add_patha(to_charlist(Path.expand(path))) 302 end 303 304 @doc """ 305 Deletes a path from the Erlang VM code path list. This is the list of 306 directories the Erlang VM uses for finding module code. 307 308 The path is expanded with `Path.expand/1` before being deleted. If the 309 path does not exist, this function returns `false`. 310 311 ## Examples 312 313 Code.prepend_path(".") 314 Code.delete_path(".") 315 #=> true 316 317 Code.delete_path("/does_not_exist") 318 #=> false 319 320 """ 321 @spec delete_path(Path.t()) :: boolean 322 def delete_path(path) do 323 :code.del_path(to_charlist(Path.expand(path))) 324 end 325 326 @doc """ 327 Evaluates the contents given by `string`. 328 329 The `binding` argument is a list of variable bindings. 330 The `opts` argument is a keyword list of environment options. 331 332 **Warning**: `string` can be any Elixir code and will be executed with 333 the same privileges as the Erlang VM: this means that such code could 334 compromise the machine (for example by executing system commands). 335 Don't use `eval_string/3` with untrusted input (such as strings coming 336 from the network). 337 338 ## Options 339 340 Options can be: 341 342 * `:file` - the file to be considered in the evaluation 343 344 * `:line` - the line on which the script starts 345 346 Additionally, you may also pass an environment as second argument, 347 so the evaluation happens within that environment. However, if the evaluated 348 code requires or compiles another file, the environment given to this function 349 will not apply to said files. 350 351 Returns a tuple of the form `{value, binding}`, where `value` is the value 352 returned from evaluating `string`. If an error occurs while evaluating 353 `string` an exception will be raised. 354 355 `binding` is a list with all variable bindings after evaluating `string`. 356 The binding keys are usually atoms, but they may be a tuple for variables 357 defined in a different context. 358 359 ## Examples 360 361 iex> {result, binding} = Code.eval_string("a + b", [a: 1, b: 2], file: __ENV__.file, line: __ENV__.line) 362 iex> result 363 3 364 iex> Enum.sort(binding) 365 [a: 1, b: 2] 366 367 iex> {result, binding} = Code.eval_string("c = a + b", [a: 1, b: 2], __ENV__) 368 iex> result 369 3 370 iex> Enum.sort(binding) 371 [a: 1, b: 2, c: 3] 372 373 iex> {result, binding} = Code.eval_string("a = a + b", [a: 1, b: 2]) 374 iex> result 375 3 376 iex> Enum.sort(binding) 377 [a: 3, b: 2] 378 379 For convenience, you can pass `__ENV__/0` as the `opts` argument and 380 all imports, requires and aliases defined in the current environment 381 will be automatically carried over: 382 383 iex> {result, binding} = Code.eval_string("a + b", [a: 1, b: 2], __ENV__) 384 iex> result 385 3 386 iex> Enum.sort(binding) 387 [a: 1, b: 2] 388 389 """ 390 @spec eval_string(List.Chars.t(), binding, Macro.Env.t() | keyword) :: {term, binding} 391 def eval_string(string, binding \\ [], opts \\ []) 392 393 def eval_string(string, binding, %Macro.Env{} = env) do 394 validated_eval_string(string, binding, env) 395 end 396 397 def eval_string(string, binding, opts) when is_list(opts) do 398 validated_eval_string(string, binding, opts) 399 end 400 401 defp validated_eval_string(string, binding, opts_or_env) do 402 %{line: line, file: file} = env = :elixir.env_for_eval(opts_or_env) 403 forms = :elixir.string_to_quoted!(to_charlist(string), line, 1, file, []) 404 {value, binding, _env} = :elixir.eval_forms(forms, binding, env) 405 {value, binding} 406 end 407 408 @doc ~S""" 409 Formats the given code `string`. 410 411 The formatter receives a string representing Elixir code and 412 returns iodata representing the formatted code according to 413 pre-defined rules. 414 415 ## Options 416 417 * `:file` - the file which contains the string, used for error 418 reporting 419 420 * `:line` - the line the string starts, used for error reporting 421 422 * `:line_length` - the line length to aim for when formatting 423 the document. Defaults to 98. Note this value is used as 424 guideline but there are situations where it is not enforced. 425 See the "Line length" section below for more information 426 427 * `:locals_without_parens` - a keyword list of name and arity 428 pairs that should be kept without parens whenever possible. 429 The arity may be the atom `:*`, which implies all arities of 430 that name. The formatter already includes a list of functions 431 and this option augments this list. 432 433 * `:force_do_end_blocks` (since v1.9.0) - when `true`, converts all 434 inline usages of `do: ...`, `else: ...` and friends into `do`-`end` 435 blocks. Defaults to `false`. Note that this option is convergent: 436 once you set it to `true`, **all keywords** will be converted. 437 If you set it to `false` later on, `do`-`end` blocks won't be 438 converted back to keywords. 439 440 ## Design principles 441 442 The formatter was designed under three principles. 443 444 First, the formatter never changes the semantics of the code by 445 default. This means the input AST and the output AST are equivalent. 446 447 The second principle is to provide as little configuration as possible. 448 This eases the formatter adoption by removing contention points while 449 making sure a single style is followed consistently by the community as 450 a whole. 451 452 The formatter does not hard code names. The formatter will not behave 453 specially because a function is named `defmodule`, `def`, or the like. This 454 principle mirrors Elixir's goal of being an extensible language where 455 developers can extend the language with new constructs as if they were 456 part of the language. When it is absolutely necessary to change behaviour 457 based on the name, this behaviour should be configurable, such as the 458 `:locals_without_parens` option. 459 460 ## Running the formatter 461 462 The formatter attempts to fit the most it can on a single line and 463 introduces line breaks wherever possible when it cannot. 464 465 In some cases, this may lead to undesired formatting. Therefore, **some 466 code generated by the formatter may not be aesthetically pleasing and 467 may require explicit intervention from the developer**. That's why we 468 do not recommend to run the formatter blindly in an existing codebase. 469 Instead you should format and sanity check each formatted file. 470 471 For example, the formatter may break a long function definition over 472 multiple clauses: 473 474 def my_function( 475 %User{name: name, age: age, ...}, 476 arg1, 477 arg2 478 ) do 479 ... 480 end 481 482 While the code above is completely valid, you may prefer to match on 483 the struct variables inside the function body in order to keep the 484 definition on a single line: 485 486 def my_function(%User{} = user, arg1, arg2) do 487 %{name: name, age: age, ...} = user 488 ... 489 end 490 491 In some situations, you can use the fact the formatter does not generate 492 elegant code as a hint for refactoring. Take this code: 493 494 def board?(board_id, %User{} = user, available_permissions, required_permissions) do 495 Tracker.OrganizationMembers.user_in_organization?(user.id, board.organization_id) and 496 required_permissions == Enum.to_list(MapSet.intersection(MapSet.new(required_permissions), MapSet.new(available_permissions))) 497 end 498 499 The code above has very long lines and running the formatter is not going 500 to address this issue. In fact, the formatter may make it more obvious that 501 you have complex expressions: 502 503 def board?(board_id, %User{} = user, available_permissions, required_permissions) do 504 Tracker.OrganizationMembers.user_in_organization?(user.id, board.organization_id) and 505 required_permissions == 506 Enum.to_list( 507 MapSet.intersection( 508 MapSet.new(required_permissions), 509 MapSet.new(available_permissions) 510 ) 511 ) 512 end 513 514 Take such cases as a suggestion that your code should be refactored: 515 516 def board?(board_id, %User{} = user, available_permissions, required_permissions) do 517 Tracker.OrganizationMembers.user_in_organization?(user.id, board.organization_id) and 518 matching_permissions?(required_permissions, available_permissions) 519 end 520 521 defp matching_permissions?(required_permissions, available_permissions) do 522 intersection = 523 required_permissions 524 |> MapSet.new() 525 |> MapSet.intersection(MapSet.new(available_permissions)) 526 |> Enum.to_list() 527 528 required_permissions == intersection 529 end 530 531 To sum it up: since the formatter cannot change the semantics of your 532 code, sometimes it is necessary to tweak or refactor the code to get 533 optimal formatting. To help better understand how to control the formatter, 534 we describe in the next sections the cases where the formatter keeps the 535 user encoding and how to control multiline expressions. 536 537 ## Line length 538 539 Another point about the formatter is that the `:line_length` configuration 540 is a guideline. In many cases, it is not possible for the formatter to break 541 your code apart, which means it will go over the line length. For example, 542 if you have a long string: 543 544 "this is a very long string that will go over the line length" 545 546 The formatter doesn't know how to break it apart without changing the 547 code underlying syntax representation, so it is up to you to step in: 548 549 "this is a very long string " <> 550 "that will go over the line length" 551 552 The string concatenation makes the code fit on a single line and also 553 gives more options to the formatter. 554 555 This may also appear in do/end blocks, where the `do` keyword (or `->`) 556 may go over the line length because there is no opportunity for the 557 formatter to introduce a line break in a readable way. For example, 558 if you do: 559 560 case very_long_expression() do 561 end 562 563 And only the `do` keyword is above the line length, Elixir **will not** 564 emit this: 565 566 case very_long_expression() 567 do 568 end 569 570 So it prefers to not touch the line at all and leave `do` above the 571 line limit. 572 573 ## Keeping user's formatting 574 575 The formatter respects the input format in some cases. Those are 576 listed below: 577 578 * Insignificant digits in numbers are kept as is. The formatter 579 however always inserts underscores for decimal numbers with more 580 than 5 digits and converts hexadecimal digits to uppercase 581 582 * Strings, charlists, atoms and sigils are kept as is. No character 583 is automatically escaped or unescaped. The choice of delimiter is 584 also respected from the input 585 586 * Newlines inside blocks are kept as in the input except for: 587 1) expressions that take multiple lines will always have an empty 588 line before and after and 2) empty lines are always squeezed 589 together into a single empty line 590 591 * The choice between `:do` keyword and `do`-`end` blocks is left 592 to the user 593 594 * Lists, tuples, bitstrings, maps, structs and function calls will be 595 broken into multiple lines if they are followed by a newline in the 596 opening bracket and preceded by a new line in the closing bracket 597 598 * Newlines before certain operators (such as the pipeline operators) 599 and before other operators (such as comparison operators) 600 601 The behaviours above are not guaranteed. We may remove or add new 602 rules in the future. The goal of documenting them is to provide better 603 understanding on what to expect from the formatter. 604 605 ### Multi-line lists, maps, tuples, and the like 606 607 You can force lists, tuples, bitstrings, maps, structs and function 608 calls to have one entry per line by adding a newline after the opening 609 bracket and a new line before the closing bracket lines. For example: 610 611 [ 612 foo, 613 bar 614 ] 615 616 If there are no newlines around the brackets, then the formatter will 617 try to fit everything on a single line, such that the snippet below 618 619 [foo, 620 bar] 621 622 will be formatted as 623 624 [foo, bar] 625 626 You can also force function calls and keywords to be rendered on multiple 627 lines by having each entry on its own line: 628 629 defstruct name: nil, 630 age: 0 631 632 The code above will be kept with one keyword entry per line by the 633 formatter. To avoid that, just squash everything into a single line. 634 635 ### Parens and no parens in function calls 636 637 Elixir has two syntaxes for function calls. With parens and no parens. 638 By default, Elixir will add parens to all calls except for: 639 640 1. calls that have `do`-`end` blocks 641 2. local calls without parens where the name and arity of the local 642 call is also listed under `:locals_without_parens` (except for 643 calls with arity 0, where the compiler always require parens) 644 645 The choice of parens and no parens also affects indentation. When a 646 function call with parens doesn't fit on the same line, the formatter 647 introduces a newline around parens and indents the arguments with two 648 spaces: 649 650 some_call( 651 arg1, 652 arg2, 653 arg3 654 ) 655 656 On the other hand, function calls without parens are always indented 657 by the function call length itself, like this: 658 659 some_call arg1, 660 arg2, 661 arg3 662 663 If the last argument is a data structure, such as maps and lists, and 664 the beginning of the data structure fits on the same line as the function 665 call, then no indentation happens, this allows code like this: 666 667 Enum.reduce(some_collection, initial_value, fn element, acc -> 668 # code 669 end) 670 671 some_function_without_parens %{ 672 foo: :bar, 673 baz: :bat 674 } 675 676 ## Code comments 677 678 The formatter also handles code comments in a way to guarantee a space 679 is always added between the beginning of the comment (#) and the next 680 character. 681 682 The formatter also extracts all trailing comments to their previous line. 683 For example, the code below 684 685 hello #world 686 687 will be rewritten to 688 689 # world 690 hello 691 692 Because code comments are handled apart from the code representation (AST), 693 there are some situations where code comments are seen as ambiguous by the 694 code formatter. For example, the comment in the anonymous function below 695 696 fn 697 arg1 -> 698 body1 699 # comment 700 701 arg2 -> 702 body2 703 end 704 705 and in this one 706 707 fn 708 arg1 -> 709 body1 710 711 # comment 712 arg2 -> 713 body2 714 end 715 716 are considered equivalent (the nesting is discarded alongside most of 717 user formatting). In such cases, the code formatter will always format to 718 the latter. 719 720 ## Newlines 721 722 The formatter converts all newlines in code from `\r\n` to `\n`. 723 """ 724 @doc since: "1.6.0" 725 @spec format_string!(binary, keyword) :: iodata 726 def format_string!(string, opts \\ []) when is_binary(string) and is_list(opts) do 727 line_length = Keyword.get(opts, :line_length, 98) 728 729 to_quoted_opts = 730 [ 731 unescape: false, 732 warn_on_unnecessary_quotes: false, 733 literal_encoder: &{:ok, {:__block__, &2, [&1]}}, 734 token_metadata: true 735 ] ++ opts 736 737 {forms, comments} = string_to_quoted_with_comments!(string, to_quoted_opts) 738 739 to_algebra_opts = 740 [ 741 comments: comments 742 ] ++ opts 743 744 doc = Code.Formatter.to_algebra(forms, to_algebra_opts) 745 746 Inspect.Algebra.format(doc, line_length) 747 end 748 749 @doc """ 750 Formats a file. 751 752 See `format_string!/2` for more information on code formatting and 753 available options. 754 """ 755 @doc since: "1.6.0" 756 @spec format_file!(binary, keyword) :: iodata 757 def format_file!(file, opts \\ []) when is_binary(file) and is_list(opts) do 758 string = File.read!(file) 759 formatted = format_string!(string, [file: file, line: 1] ++ opts) 760 [formatted, ?\n] 761 end 762 763 @doc """ 764 Evaluates the quoted contents. 765 766 **Warning**: Calling this function inside a macro is considered bad 767 practice as it will attempt to evaluate runtime values at compile time. 768 Macro arguments are typically transformed by unquoting them into the 769 returned quoted expressions (instead of evaluated). 770 771 See `eval_string/3` for a description of `binding` and `opts`. 772 773 ## Examples 774 775 iex> contents = quote(do: var!(a) + var!(b)) 776 iex> {result, binding} = Code.eval_quoted(contents, [a: 1, b: 2], file: __ENV__.file, line: __ENV__.line) 777 iex> result 778 3 779 iex> Enum.sort(binding) 780 [a: 1, b: 2] 781 782 For convenience, you can pass `__ENV__/0` as the `opts` argument and 783 all options will be automatically extracted from the current environment: 784 785 iex> contents = quote(do: var!(a) + var!(b)) 786 iex> {result, binding} = Code.eval_quoted(contents, [a: 1, b: 2], __ENV__) 787 iex> result 788 3 789 iex> Enum.sort(binding) 790 [a: 1, b: 2] 791 792 """ 793 @spec eval_quoted(Macro.t(), binding, Macro.Env.t() | keyword) :: {term, binding} 794 def eval_quoted(quoted, binding \\ [], opts \\ []) 795 796 def eval_quoted(quoted, binding, %Macro.Env{} = env) do 797 {value, binding, _env} = :elixir.eval_quoted(quoted, binding, :elixir.env_for_eval(env)) 798 {value, binding} 799 end 800 801 def eval_quoted(quoted, binding, opts) when is_list(opts) do 802 {value, binding, _env} = :elixir.eval_quoted(quoted, binding, :elixir.env_for_eval(opts)) 803 {value, binding} 804 end 805 806 @doc ~S""" 807 Converts the given string to its quoted form. 808 809 Returns `{:ok, quoted_form}` if it succeeds, 810 `{:error, {meta, message_info, token}}` otherwise. 811 812 ## Options 813 814 * `:file` - the filename to be reported in case of parsing errors. 815 Defaults to `"nofile"`. 816 817 * `:line` - the starting line of the string being parsed. 818 Defaults to 1. 819 820 * `:column` - (since v1.11.0) the starting column of the string being parsed. 821 Defaults to 1. 822 823 * `:columns` - when `true`, attach a `:column` key to the quoted 824 metadata. Defaults to `false`. 825 826 * `:unescape` (since v1.10.0) - when `false`, preserves escaped sequences. 827 For example, `"null byte\\t\\x00"` will be kept as is instead of being 828 converted to a bitstring literal. Note if you set this option to false, the 829 resulting AST is no longer valid, but it can be useful to analyze/transform 830 source code, typically in in combination with `quoted_to_algebra/2`. 831 Defaults to `true`. 832 833 * `:existing_atoms_only` - when `true`, raises an error 834 when non-existing atoms are found by the tokenizer. 835 Defaults to `false`. 836 837 * `:token_metadata` (since v1.10.0) - when `true`, includes token-related 838 metadata in the expression AST, such as metadata for `do` and `end` 839 tokens, for closing tokens, end of expressions, as well as delimiters 840 for sigils. See `t:Macro.metadata/0`. Defaults to `false`. 841 842 * `:literal_encoder` (since v1.10.0) - how to encode literals in the AST. 843 It must be a function that receives two arguments, the literal and its 844 metadata, and it must return `{:ok, ast :: Macro.t}` or 845 `{:error, reason :: binary}`. If you return anything than the literal 846 itself as the `term`, then the AST is no longer valid. This option 847 may still useful for textual analysis of the source code. 848 849 * `:static_atoms_encoder` - the static atom encoder function, see 850 "The `:static_atoms_encoder` function" section below. Note this 851 option overrides the `:existing_atoms_only` behaviour for static 852 atoms but `:existing_atoms_only` is still used for dynamic atoms, 853 such as atoms with interpolations. 854 855 * `:warn_on_unnecessary_quotes` - when `false`, does not warn 856 when atoms, keywords or calls have unnecessary quotes on 857 them. Defaults to `true`. 858 859 ## `Macro.to_string/2` 860 861 The opposite of converting a string to its quoted form is 862 `Macro.to_string/2`, which converts a quoted form to a string/binary 863 representation. 864 865 ## The `:static_atoms_encoder` function 866 867 When `static_atoms_encoder: &my_encoder/2` is passed as an argument, 868 `my_encoder/2` is called every time the tokenizer needs to create a 869 "static" atom. Static atoms are atoms in the AST that function as 870 aliases, remote calls, local calls, variable names, regular atoms 871 and keyword lists. 872 873 The encoder function will receive the atom name (as a binary) and a 874 keyword list with the current file, line and column. It must return 875 `{:ok, token :: term} | {:error, reason :: binary}`. 876 877 The encoder function is supposed to create an atom from the given 878 string. To produce a valid AST, it is required to return `{:ok, term}`, 879 where `term` is an atom. It is possible to return something other than an atom, 880 however, in that case the AST is no longer "valid" in that it cannot 881 be used to compile or evaluate Elixir code. A use case for this is 882 if you want to use the Elixir parser in a user-facing situation, but 883 you don't want to exhaust the atom table. 884 885 The atom encoder is not called for *all* atoms that are present in 886 the AST. It won't be invoked for the following atoms: 887 888 * operators (`:+`, `:-`, and so on) 889 890 * syntax keywords (`fn`, `do`, `else`, and so on) 891 892 * atoms containing interpolation (`:"#{1 + 1} is two"`), as these 893 atoms are constructed at runtime. 894 895 """ 896 @spec string_to_quoted(List.Chars.t(), keyword) :: 897 {:ok, Macro.t()} | {:error, {location :: keyword, binary | {binary, binary}, binary}} 898 def string_to_quoted(string, opts \\ []) when is_list(opts) do 899 file = Keyword.get(opts, :file, "nofile") 900 line = Keyword.get(opts, :line, 1) 901 column = Keyword.get(opts, :column, 1) 902 903 case :elixir.string_to_tokens(to_charlist(string), line, column, file, opts) do 904 {:ok, tokens} -> 905 :elixir.tokens_to_quoted(tokens, file, opts) 906 907 {:error, _error_msg} = error -> 908 error 909 end 910 end 911 912 @doc """ 913 Converts the given string to its quoted form. 914 915 It returns the AST if it succeeds, 916 raises an exception otherwise. The exception is a `TokenMissingError` 917 in case a token is missing (usually because the expression is incomplete), 918 `SyntaxError` otherwise. 919 920 Check `string_to_quoted/2` for options information. 921 """ 922 @spec string_to_quoted!(List.Chars.t(), keyword) :: Macro.t() 923 def string_to_quoted!(string, opts \\ []) when is_list(opts) do 924 file = Keyword.get(opts, :file, "nofile") 925 line = Keyword.get(opts, :line, 1) 926 column = Keyword.get(opts, :column, 1) 927 :elixir.string_to_quoted!(to_charlist(string), line, column, file, opts) 928 end 929 930 @doc """ 931 Converts the given string to its quoted form and a list of comments. 932 933 This function is useful when performing textual changes to the source code, 934 while preserving information like comments and literals position. 935 936 Returns `{:ok, quoted_form, comments}` if it succeeds, 937 `{:error, {line, error, token}}` otherwise. 938 939 Comments are maps with the following fields: 940 941 * `:line` - The line number the source code 942 943 * `:text` - The full text of the comment, including the leading `#` 944 945 * `:previous_eol_count` - How many end of lines there are between the comment and the previous AST node or comment 946 947 * `:next_eol_count` - How many end of lines there are between the comment and the next AST node or comment 948 949 Check `string_to_quoted/2` for options information. 950 951 ## Examples 952 953 iex> Code.string_to_quoted_with_comments("\"" 954 ...> :foo 955 ...> 956 ...> # Hello, world! 957 ...> 958 ...> 959 ...> # Some more comments! 960 ...> "\"") 961 {:ok, :foo, [ 962 %{line: 3, column: 1, previous_eol_count: 2, next_eol_count: 3, text: "\# Hello, world!"}, 963 %{line: 6, column: 1, previous_eol_count: 3, next_eol_count: 1, text: "\# Some more comments!"}, 964 ]} 965 966 iex> Code.string_to_quoted_with_comments(":foo # :bar") 967 {:ok, :foo, [ 968 %{line: 1, column: 6, previous_eol_count: 0, next_eol_count: 0, text: "\# :bar"} 969 ]} 970 971 """ 972 @doc since: "1.13.0" 973 @spec string_to_quoted_with_comments(List.Chars.t(), keyword) :: 974 {:ok, Macro.t(), list(map())} | {:error, {location :: keyword, term, term}} 975 def string_to_quoted_with_comments(string, opts \\ []) when is_list(opts) do 976 charlist = to_charlist(string) 977 file = Keyword.get(opts, :file, "nofile") 978 line = Keyword.get(opts, :line, 1) 979 column = Keyword.get(opts, :column, 1) 980 981 Process.put(:code_formatter_comments, []) 982 opts = [preserve_comments: &preserve_comments/5] ++ opts 983 984 with {:ok, tokens} <- :elixir.string_to_tokens(charlist, line, column, file, opts), 985 {:ok, forms} <- :elixir.tokens_to_quoted(tokens, file, opts) do 986 comments = Enum.reverse(Process.get(:code_formatter_comments)) 987 {:ok, forms, comments} 988 end 989 after 990 Process.delete(:code_formatter_comments) 991 end 992 993 @doc """ 994 Converts the given string to its quoted form and a list of comments. 995 996 Returns the AST and a list of comments if it succeeds, raises an exception 997 otherwise. The exception is a `TokenMissingError` in case a token is missing 998 (usually because the expression is incomplete), `SyntaxError` otherwise. 999 1000 Check `string_to_quoted/2` for options information. 1001 """ 1002 @doc since: "1.13.0" 1003 @spec string_to_quoted_with_comments!(List.Chars.t(), keyword) :: {Macro.t(), list(map())} 1004 def string_to_quoted_with_comments!(string, opts \\ []) do 1005 charlist = to_charlist(string) 1006 1007 case string_to_quoted_with_comments(charlist, opts) do 1008 {:ok, forms, comments} -> 1009 {forms, comments} 1010 1011 {:error, {location, error, token}} -> 1012 :elixir_errors.parse_error( 1013 location, 1014 Keyword.get(opts, :file, "nofile"), 1015 error, 1016 token, 1017 {charlist, Keyword.get(opts, :line, 1), Keyword.get(opts, :column, 1)} 1018 ) 1019 end 1020 end 1021 1022 defp preserve_comments(line, column, tokens, comment, rest) do 1023 comments = Process.get(:code_formatter_comments) 1024 1025 comment = %{ 1026 line: line, 1027 column: column, 1028 previous_eol_count: previous_eol_count(tokens), 1029 next_eol_count: next_eol_count(rest, 0), 1030 text: List.to_string(comment) 1031 } 1032 1033 Process.put(:code_formatter_comments, [comment | comments]) 1034 end 1035 1036 defp next_eol_count('\s' ++ rest, count), do: next_eol_count(rest, count) 1037 defp next_eol_count('\t' ++ rest, count), do: next_eol_count(rest, count) 1038 defp next_eol_count('\n' ++ rest, count), do: next_eol_count(rest, count + 1) 1039 defp next_eol_count('\r\n' ++ rest, count), do: next_eol_count(rest, count + 1) 1040 defp next_eol_count(_, count), do: count 1041 1042 defp previous_eol_count([{token, {_, _, count}} | _]) 1043 when token in [:eol, :",", :";"] and count > 0 do 1044 count 1045 end 1046 1047 defp previous_eol_count([]), do: 1 1048 defp previous_eol_count(_), do: 0 1049 1050 @doc ~S""" 1051 Converts a quoted expression to an algebra document using Elixir's formatter rules. 1052 1053 The algebra document can be converted into a string by calling: 1054 1055 doc 1056 |> Inspect.Algebra.format(:infinity) 1057 |> IO.iodata_to_binary() 1058 1059 For a high-level function that does the same, see `Macro.to_string/1`. 1060 1061 ## Formatting considerations 1062 1063 The Elixir AST does not contain metadata for literals like strings, lists, or 1064 tuples with two elements, which means that the produced algebra document will 1065 not respect all of the user preferences and comments may be misplaced. 1066 To get better results, you can use the `:token_metadata`, `:unescape` and 1067 `:literal_encoder` options to `string_to_quoted/2` to provide additional 1068 information to the formatter: 1069 1070 [ 1071 literal_encoder: &{:ok, {:__block__, &2, [&1]}}, 1072 token_metadata: true, 1073 unescape: false 1074 ] 1075 1076 This will produce an AST that contains information such as `do` blocks start 1077 and end lines or sigil delimiters, and by wrapping literals in blocks they can 1078 now hold metadata like line number, string delimiter and escaped sequences, or 1079 integer formatting (such as `0x2a` instead of `47`). However, **note this AST is 1080 not valid**. If you evaluate it, it won't have the same semantics as the regular 1081 Elixir AST due to the `:unescape` and `:literal_encoder` options. However, 1082 those options are useful if you're doing source code manipulation, where it's 1083 important to preserve user choices and comments placing. 1084 1085 ## Options 1086 1087 * `:comments` - the list of comments associated with the quoted expression. 1088 Defaults to `[]`. It is recommended that both `:token_metadata` and 1089 `:literal_encoder` options are given to `string_to_quoted_with_comments/2` 1090 in order to get proper placement for comments 1091 1092 * `:escape` - when `true`, escaped sequences like `\n` will be escaped into 1093 `\\n`. If the `:unescape` option was set to `false` when using 1094 `string_to_quoted/2`, setting this option to `false` will prevent it from 1095 escaping the sequences twice. Defaults to `true`. 1096 1097 * `:locals_without_parens` - a keyword list of name and arity 1098 pairs that should be kept without parens whenever possible. 1099 The arity may be the atom `:*`, which implies all arities of 1100 that name. The formatter already includes a list of functions 1101 and this option augments this list. 1102 """ 1103 @doc since: "1.13.0" 1104 @spec quoted_to_algebra(Macro.t(), keyword) :: Inspect.Algebra.t() 1105 def quoted_to_algebra(quoted, opts \\ []) do 1106 quoted 1107 |> Code.Normalizer.normalize(opts) 1108 |> Code.Formatter.to_algebra(opts) 1109 end 1110 1111 @doc """ 1112 Evaluates the given file. 1113 1114 Accepts `relative_to` as an argument to tell where the file is located. 1115 1116 While `require_file/2` and `compile_file/2` return the loaded modules and their 1117 bytecode, `eval_file/2` simply evaluates the file contents and returns the 1118 evaluation result and its binding (exactly the same return value as `eval_string/3`). 1119 """ 1120 @spec eval_file(binary, nil | binary) :: {term, binding} 1121 def eval_file(file, relative_to \\ nil) when is_binary(file) do 1122 file = find_file(file, relative_to) 1123 eval_string(File.read!(file), [], file: file, line: 1) 1124 end 1125 1126 @deprecated "Use Code.require_file/2 or Code.compile_file/2 instead" 1127 @doc false 1128 def load_file(file, relative_to \\ nil) when is_binary(file) do 1129 file = find_file(file, relative_to) 1130 :elixir_code_server.call({:acquire, file}) 1131 1132 loaded = 1133 Module.ParallelChecker.verify(fn -> 1134 :elixir_compiler.file(file, fn _, _ -> :ok end) 1135 end) 1136 1137 :elixir_code_server.cast({:required, file}) 1138 loaded 1139 end 1140 1141 @doc """ 1142 Requires the given `file`. 1143 1144 Accepts `relative_to` as an argument to tell where the file is located. 1145 If the file was already required, `require_file/2` doesn't do anything and 1146 returns `nil`. 1147 1148 Note that if `require_file/2` is invoked by different processes concurrently, 1149 the first process to invoke `require_file/2` acquires a lock and the remaining 1150 ones will block until the file is available. This means that if `require_file/2` 1151 is called more than once with a given file, that file will be compiled only once. 1152 The first process to call `require_file/2` will get the list of loaded modules, 1153 others will get `nil`. 1154 1155 See `compile_file/2` if you would like to compile a file without tracking its 1156 filenames. Finally, if you would like to get the result of evaluating a file rather 1157 than the modules defined in it, see `eval_file/2`. 1158 1159 ## Examples 1160 1161 If the file has not been required, it returns the list of modules: 1162 1163 modules = Code.require_file("eex_test.exs", "../eex/test") 1164 List.first(modules) 1165 #=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>} 1166 1167 If the file has been required, it returns `nil`: 1168 1169 Code.require_file("eex_test.exs", "../eex/test") 1170 #=> nil 1171 1172 """ 1173 @spec require_file(binary, nil | binary) :: [{module, binary}] | nil 1174 def require_file(file, relative_to \\ nil) when is_binary(file) do 1175 file = find_file(file, relative_to) 1176 1177 case :elixir_code_server.call({:acquire, file}) do 1178 :required -> 1179 nil 1180 1181 :proceed -> 1182 loaded = 1183 Module.ParallelChecker.verify(fn -> 1184 :elixir_compiler.file(file, fn _, _ -> :ok end) 1185 end) 1186 1187 :elixir_code_server.cast({:required, file}) 1188 loaded 1189 end 1190 end 1191 1192 @doc """ 1193 Gets all compilation options from the code server. 1194 1195 To get individual options, see `get_compiler_option/1`. 1196 For a description of all options, see `put_compiler_option/2`. 1197 1198 ## Examples 1199 1200 Code.compiler_options() 1201 #=> %{debug_info: true, docs: true, ...} 1202 1203 """ 1204 @spec compiler_options :: map 1205 def compiler_options do 1206 for key <- @available_compiler_options, into: %{} do 1207 {key, :elixir_config.get(key)} 1208 end 1209 end 1210 1211 @doc """ 1212 Stores all given compilation options. 1213 1214 To store individual options and for a description of all 1215 options, see `put_compiler_option/2`. 1216 1217 ## Examples 1218 1219 Code.compiler_options() 1220 #=> %{debug_info: true, docs: true, ...} 1221 1222 """ 1223 @spec compiler_options(Enumerable.t()) :: %{optional(atom) => boolean} 1224 def compiler_options(opts) do 1225 for {key, value} <- opts, into: %{} do 1226 previous = get_compiler_option(key) 1227 put_compiler_option(key, value) 1228 {key, previous} 1229 end 1230 end 1231 1232 @doc """ 1233 Returns the value of a given compiler option. 1234 1235 For a description of all options, see `put_compiler_option/2`. 1236 1237 ## Examples 1238 1239 Code.get_compiler_option(:debug_info) 1240 #=> true 1241 1242 """ 1243 @doc since: "1.10.0" 1244 @spec get_compiler_option(atom) :: term 1245 def get_compiler_option(key) when key in @available_compiler_options do 1246 :elixir_config.get(key) 1247 end 1248 1249 @doc """ 1250 Returns a list with all available compiler options. 1251 1252 For a description of all options, see `put_compiler_option/2`. 1253 1254 ## Examples 1255 1256 Code.available_compiler_options() 1257 #=> [:docs, :debug_info, ...] 1258 1259 """ 1260 @spec available_compiler_options() :: [atom] 1261 def available_compiler_options do 1262 @available_compiler_options 1263 end 1264 1265 @doc """ 1266 Stores a compilation option. 1267 1268 These options are global since they are stored by Elixir's code server. 1269 1270 Available options are: 1271 1272 * `:docs` - when `true`, retain documentation in the compiled module. 1273 Defaults to `true`. 1274 1275 * `:debug_info` - when `true`, retain debug information in the compiled 1276 module. This allows a developer to reconstruct the original source 1277 code. Defaults to `true`. 1278 1279 * `:ignore_module_conflict` - when `true`, override modules that were 1280 already defined without raising errors. Defaults to `false`. 1281 1282 * `:relative_paths` - when `true`, use relative paths in quoted nodes, 1283 warnings and errors generated by the compiler. Note disabling this option 1284 won't affect runtime warnings and errors. Defaults to `true`. 1285 1286 * `:warnings_as_errors` - causes compilation to fail when warnings are 1287 generated. Defaults to `false`. 1288 1289 * `:no_warn_undefined` (since v1.10.0) - list of modules and `{Mod, fun, arity}` 1290 tuples that will not emit warnings that the module or function does not exist 1291 at compilation time. Pass atom `:all` to skip warning for all undefined 1292 functions. This can be useful when doing dynamic compilation. Defaults to `[]`. 1293 1294 * `:tracers` (since v1.10.0) - a list of tracers (modules) to be used during 1295 compilation. See the module docs for more information. Defaults to `[]`. 1296 1297 * `:parser_options` (since v1.10.0) - a keyword list of options to be given 1298 to the parser when compiling files. It accepts the same options as 1299 `string_to_quoted/2` (except by the options that change the AST itself). 1300 This can be used in combination with the tracer to retrieve localized 1301 information about events happening during compilation. Defaults to `[]`. 1302 1303 It always returns `:ok`. Raises an error for invalid options. 1304 1305 ## Examples 1306 1307 Code.put_compiler_option(:debug_info, true) 1308 #=> :ok 1309 1310 """ 1311 @doc since: "1.10.0" 1312 @spec put_compiler_option(atom, term) :: :ok 1313 def put_compiler_option(key, value) when key in @boolean_compiler_options do 1314 if not is_boolean(value) do 1315 raise "compiler option #{inspect(key)} should be a boolean, got: #{inspect(value)}" 1316 end 1317 1318 :elixir_config.put(key, value) 1319 :ok 1320 end 1321 1322 def put_compiler_option(:no_warn_undefined, value) do 1323 if value != :all and not is_list(value) do 1324 raise "compiler option :no_warn_undefined should be a list or the atom :all, " <> 1325 "got: #{inspect(value)}" 1326 end 1327 1328 :elixir_config.put(:no_warn_undefined, value) 1329 :ok 1330 end 1331 1332 def put_compiler_option(key, value) when key in @list_compiler_options do 1333 if not is_list(value) do 1334 raise "compiler option #{inspect(key)} should be a list, got: #{inspect(value)}" 1335 end 1336 1337 if key == :parser_options and not Keyword.keyword?(value) do 1338 raise "compiler option #{inspect(key)} should be a keyword list, " <> 1339 "got: #{inspect(value)}" 1340 end 1341 1342 if key == :tracers and not Enum.all?(value, &is_atom/1) do 1343 raise "compiler option #{inspect(key)} should be a list of modules, " <> 1344 "got: #{inspect(value)}" 1345 end 1346 1347 :elixir_config.put(key, value) 1348 :ok 1349 end 1350 1351 def put_compiler_option(key, _value) do 1352 raise "unknown compiler option: #{inspect(key)}" 1353 end 1354 1355 @doc """ 1356 Purge compiler modules. 1357 1358 The compiler utilizes temporary modules to compile code. For example, 1359 `elixir_compiler_1`, `elixir_compiler_2`, and so on. In case the compiled code 1360 stores references to anonymous functions or similar, the Elixir compiler 1361 may be unable to reclaim those modules, keeping an unnecessary amount of 1362 code in memory and eventually leading to modules such as `elixir_compiler_12345`. 1363 1364 This function purges all modules currently kept by the compiler, allowing 1365 old compiler module names to be reused. If there are any processes running 1366 any code from such modules, they will be terminated too. 1367 1368 It returns `{:ok, number_of_modules_purged}`. 1369 """ 1370 @doc since: "1.7.0" 1371 @spec purge_compiler_modules() :: {:ok, non_neg_integer()} 1372 def purge_compiler_modules() do 1373 :elixir_code_server.call(:purge_compiler_modules) 1374 end 1375 1376 @doc """ 1377 Compiles the given string. 1378 1379 Returns a list of tuples where the first element is the module name 1380 and the second one is its bytecode (as a binary). A `file` can be 1381 given as second argument which will be used for reporting warnings 1382 and errors. 1383 1384 **Warning**: `string` can be any Elixir code and code can be executed with 1385 the same privileges as the Erlang VM: this means that such code could 1386 compromise the machine (for example by executing system commands). 1387 Don't use `compile_string/2` with untrusted input (such as strings coming 1388 from the network). 1389 """ 1390 @spec compile_string(List.Chars.t(), binary) :: [{module, binary}] 1391 def compile_string(string, file \\ "nofile") when is_binary(file) do 1392 loaded = :elixir_compiler.string(to_charlist(string), file, fn _, _ -> :ok end) 1393 Enum.map(loaded, &elem(&1, 0)) 1394 end 1395 1396 @doc """ 1397 Compiles the quoted expression. 1398 1399 Returns a list of tuples where the first element is the module name and 1400 the second one is its bytecode (as a binary). A `file` can be 1401 given as second argument which will be used for reporting warnings 1402 and errors. 1403 """ 1404 @spec compile_quoted(Macro.t(), binary) :: [{module, binary}] 1405 def compile_quoted(quoted, file \\ "nofile") when is_binary(file) do 1406 loaded = :elixir_compiler.quoted(quoted, file, fn _, _ -> :ok end) 1407 Enum.map(loaded, &elem(&1, 0)) 1408 end 1409 1410 @doc """ 1411 Compiles the given file. 1412 1413 Accepts `relative_to` as an argument to tell where the file is located. 1414 1415 Returns a list of tuples where the first element is the module name and 1416 the second one is its bytecode (as a binary). Opposite to `require_file/2`, 1417 it does not track the filename of the compiled file. 1418 1419 If you would like to get the result of evaluating file rather than the 1420 modules defined in it, see `eval_file/2`. 1421 1422 For compiling many files concurrently, see `Kernel.ParallelCompiler.compile/2`. 1423 """ 1424 @doc since: "1.7.0" 1425 @spec compile_file(binary, nil | binary) :: [{module, binary}] 1426 def compile_file(file, relative_to \\ nil) when is_binary(file) do 1427 Module.ParallelChecker.verify(fn -> 1428 :elixir_compiler.file(find_file(file, relative_to), fn _, _ -> :ok end) 1429 end) 1430 end 1431 1432 @doc """ 1433 Ensures the given module is loaded. 1434 1435 If the module is already loaded, this works as no-op. If the module 1436 was not yet loaded, it tries to load it. 1437 1438 If it succeeds in loading the module, it returns `{:module, module}`. 1439 If not, returns `{:error, reason}` with the error reason. 1440 1441 See the module documentation for more information on code loading. 1442 1443 ## Examples 1444 1445 iex> Code.ensure_loaded(Atom) 1446 {:module, Atom} 1447 1448 iex> Code.ensure_loaded(DoesNotExist) 1449 {:error, :nofile} 1450 1451 """ 1452 @spec ensure_loaded(module) :: 1453 {:module, module} | {:error, :embedded | :badfile | :nofile | :on_load_failure} 1454 def ensure_loaded(module) when is_atom(module) do 1455 :code.ensure_loaded(module) 1456 end 1457 1458 @doc """ 1459 Ensures the given module is loaded. 1460 1461 Similar to `ensure_loaded/1`, but returns `true` if the module 1462 is already loaded or was successfully loaded. Returns `false` 1463 otherwise. 1464 1465 ## Examples 1466 1467 iex> Code.ensure_loaded?(Atom) 1468 true 1469 1470 """ 1471 @spec ensure_loaded?(module) :: boolean 1472 def ensure_loaded?(module) when is_atom(module) do 1473 match?({:module, ^module}, ensure_loaded(module)) 1474 end 1475 1476 @doc """ 1477 Same as `ensure_loaded/1` but raises if the module cannot be loaded. 1478 """ 1479 @doc since: "1.12.0" 1480 @spec ensure_loaded!(module) :: module 1481 def ensure_loaded!(module) do 1482 case ensure_loaded(module) do 1483 {:module, module} -> 1484 module 1485 1486 {:error, reason} -> 1487 raise ArgumentError, 1488 "could not load module #{inspect(module)} due to reason #{inspect(reason)}" 1489 end 1490 end 1491 1492 @doc """ 1493 Similar to `ensure_compiled!/1` but indicates you can continue without said module. 1494 1495 While `ensure_compiled!/1` indicates to the Elixir compiler you can 1496 only continue when said module is available, this function indicates 1497 you may continue compilation without said module. 1498 1499 If it succeeds in loading the module, it returns `{:module, module}`. 1500 If not, returns `{:error, reason}` with the error reason. 1501 If the module being checked is currently in a compiler deadlock, 1502 this function returns `{:error, :unavailable}`. Unavailable doesn't 1503 necessarily mean the module doesn't exist, just that it is not currently 1504 available, but it (or may not) become available in the future. 1505 1506 Therefore, if you can only continue if the module is available, use 1507 `ensure_compiled!/1` instead. In particular, do not do this: 1508 1509 case Code.ensure_compiled(module) do 1510 {:module, _} -> module 1511 {:error, _} -> raise ... 1512 end 1513 1514 See the module documentation for more information on code loading. 1515 """ 1516 @spec ensure_compiled(module) :: 1517 {:module, module} 1518 | {:error, :embedded | :badfile | :nofile | :on_load_failure | :unavailable} 1519 def ensure_compiled(module) when is_atom(module) do 1520 ensure_compiled(module, :soft) 1521 end 1522 1523 @doc """ 1524 Ensures the given module is compiled and loaded. 1525 1526 If the module is already loaded, it works as no-op. If the module was 1527 not compiled yet, `ensure_compiled!/1` halts the compilation of the caller 1528 until the module given to `ensure_compiled!/1` becomes available or 1529 all files for the current project have been compiled. If compilation 1530 finishes and the module is not available or is in a deadlock, an error 1531 is raised. 1532 1533 Given this function halts compilation, use it carefully. In particular, 1534 avoid using it to guess which modules are in the system. Overuse of this 1535 function can also lead to deadlocks, where two modules check at the same time 1536 if the other is compiled. This returns a specific unavailable error code, 1537 where we cannot successfully verify a module is available or not. 1538 1539 See the module documentation for more information on code loading. 1540 """ 1541 @doc since: "1.12.0" 1542 @spec ensure_compiled!(module) :: module 1543 def ensure_compiled!(module) do 1544 case ensure_compiled(module, :hard) do 1545 {:module, module} -> 1546 module 1547 1548 {:error, reason} -> 1549 raise ArgumentError, 1550 "could not load module #{inspect(module)} due to reason #{inspect(reason)}" 1551 end 1552 end 1553 1554 defp ensure_compiled(module, mode) do 1555 case :code.ensure_loaded(module) do 1556 {:error, :nofile} = error -> 1557 if can_await_module_compilation?() do 1558 case Kernel.ErrorHandler.ensure_compiled(module, :module, mode) do 1559 :found -> {:module, module} 1560 :deadlock -> {:error, :unavailable} 1561 :not_found -> {:error, :nofile} 1562 end 1563 else 1564 error 1565 end 1566 1567 other -> 1568 other 1569 end 1570 end 1571 1572 @doc """ 1573 Returns true if the current process can await for module compilation. 1574 1575 When compiling Elixir code via `Kernel.ParallelCompiler`, which is 1576 used by Mix and `elixirc`, calling a module that has not yet been 1577 compiled will block the caller until the module becomes available. 1578 Executing Elixir scripts, such as passing a filename to `elixir`, 1579 does not await. 1580 """ 1581 @doc since: "1.11.0" 1582 @spec can_await_module_compilation? :: boolean 1583 def can_await_module_compilation? do 1584 :erlang.process_info(self(), :error_handler) == {:error_handler, Kernel.ErrorHandler} 1585 end 1586 1587 @doc false 1588 @deprecated "Use Code.ensure_compiled/1 instead (see the proper disclaimers in its docs)" 1589 def ensure_compiled?(module) when is_atom(module) do 1590 match?({:module, ^module}, ensure_compiled(module)) 1591 end 1592 1593 @doc ~S""" 1594 Returns the docs for the given module or path to `.beam` file. 1595 1596 When given a module name, it finds its BEAM code and reads the docs from it. 1597 1598 When given a path to a `.beam` file, it will load the docs directly from that 1599 file. 1600 1601 It returns the term stored in the documentation chunk in the format defined by 1602 [EEP 48](https://www.erlang.org/eeps/eep-0048.html) or `{:error, reason}` if 1603 the chunk is not available. 1604 1605 ## Examples 1606 1607 # Module documentation of an existing module 1608 iex> {:docs_v1, _, :elixir, _, %{"en" => module_doc}, _, _} = Code.fetch_docs(Atom) 1609 iex> module_doc |> String.split("\n") |> Enum.at(0) 1610 "Atoms are constants whose values are their own name." 1611 1612 # A module that doesn't exist 1613 iex> Code.fetch_docs(ModuleNotGood) 1614 {:error, :module_not_found} 1615 1616 """ 1617 @doc since: "1.7.0" 1618 @spec fetch_docs(module | String.t()) :: 1619 {:docs_v1, annotation, beam_language, format, module_doc :: doc_content, metadata, 1620 docs :: [doc_element]} 1621 | {:error, :module_not_found | :chunk_not_found | {:invalid_chunk, binary}} 1622 when annotation: :erl_anno.anno(), 1623 beam_language: :elixir | :erlang | atom(), 1624 doc_content: %{optional(binary) => binary} | :none | :hidden, 1625 doc_element: 1626 {{kind :: atom, function_name :: atom, arity}, annotation, signature, doc_content, 1627 metadata}, 1628 format: binary, 1629 signature: [binary], 1630 metadata: map 1631 def fetch_docs(module_or_path) 1632 1633 def fetch_docs(module) when is_atom(module) do 1634 case :code.get_object_code(module) do 1635 {_module, bin, beam_path} -> 1636 case fetch_docs_from_beam(bin) do 1637 {:error, :chunk_not_found} -> 1638 app_root = Path.expand(Path.join(["..", ".."]), beam_path) 1639 path = Path.join([app_root, "doc", "chunks", "#{module}.chunk"]) 1640 fetch_docs_from_chunk(path) 1641 1642 other -> 1643 other 1644 end 1645 1646 :error -> 1647 case :code.which(module) do 1648 :preloaded -> 1649 # The erts directory is not necessarily included in releases 1650 # unless it is listed as an extra application. 1651 case :code.lib_dir(:erts) do 1652 path when is_list(path) -> 1653 path = Path.join([path, "doc", "chunks", "#{module}.chunk"]) 1654 fetch_docs_from_chunk(path) 1655 1656 {:error, _} -> 1657 {:error, :chunk_not_found} 1658 end 1659 1660 _ -> 1661 {:error, :module_not_found} 1662 end 1663 end 1664 end 1665 1666 def fetch_docs(path) when is_binary(path) do 1667 fetch_docs_from_beam(String.to_charlist(path)) 1668 end 1669 1670 @docs_chunk 'Docs' 1671 1672 defp fetch_docs_from_beam(bin_or_path) do 1673 case :beam_lib.chunks(bin_or_path, [@docs_chunk]) do 1674 {:ok, {_module, [{@docs_chunk, bin}]}} -> 1675 load_docs_chunk(bin) 1676 1677 {:error, :beam_lib, {:missing_chunk, _, @docs_chunk}} -> 1678 {:error, :chunk_not_found} 1679 1680 {:error, :beam_lib, {:file_error, _, :enoent}} -> 1681 {:error, :module_not_found} 1682 end 1683 end 1684 1685 defp fetch_docs_from_chunk(path) do 1686 case File.read(path) do 1687 {:ok, bin} -> 1688 load_docs_chunk(bin) 1689 1690 {:error, _} -> 1691 {:error, :chunk_not_found} 1692 end 1693 end 1694 1695 defp load_docs_chunk(bin) do 1696 :erlang.binary_to_term(bin) 1697 rescue 1698 _ -> 1699 {:error, {:invalid_chunk, bin}} 1700 end 1701 1702 @doc ~S""" 1703 Deprecated function to retrieve old documentation format. 1704 1705 Elixir v1.7 adopts [EEP 48](https://www.erlang.org/eeps/eep-0048.html) 1706 which is a new documentation format meant to be shared across all 1707 BEAM languages. The old format, used by `Code.get_docs/2`, is no 1708 longer available, and therefore this function always returns `nil`. 1709 Use `Code.fetch_docs/1` instead. 1710 """ 1711 @deprecated "Code.get_docs/2 always returns nil as its outdated documentation is no longer stored on BEAM files. Use Code.fetch_docs/1 instead" 1712 @spec get_docs(module, :moduledoc | :docs | :callback_docs | :type_docs | :all) :: nil 1713 def get_docs(_module, _kind) do 1714 nil 1715 end 1716 1717 ## Helpers 1718 1719 # Finds the file given the relative_to path. 1720 # 1721 # If the file is found, returns its path in binary, fails otherwise. 1722 defp find_file(file, relative_to) do 1723 file = 1724 if relative_to do 1725 Path.expand(file, relative_to) 1726 else 1727 Path.expand(file) 1728 end 1729 1730 if File.regular?(file) do 1731 file 1732 else 1733 raise Code.LoadError, file: file 1734 end 1735 end 1736end 1737