Skip to content

Commit 1fbb687

Browse files
author
José Valim
committed
Add more hygiene examples
1 parent c74f203 commit 1fbb687

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

lib/elixir/lib/kernel/special_forms.ex

Lines changed: 26 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -737,10 +737,24 @@ defmodule Kernel.SpecialForms do
737737
in the context the macro is expanded, the code above works
738738
because `D` still expands to `HashDict`.
739739
740+
Similarly, even if we defined an alias with the same name
741+
before invoking a macro, it won't affect the macro result:
742+
743+
defmodule Hygiene do
744+
alias HashDict, as: D
745+
746+
defmacro no_interference do
747+
quote do: D.new
748+
end
749+
end
750+
751+
require Hygiene
752+
alias SomethingElse, as: D
753+
Hygiene.no_interference #=> #HashDict<[]>
754+
740755
In some particular cases you may want to access an alias
741756
or a module defined in the caller. In such scenarios, you
742-
can access it by disabling hygiene with `hygiene: [aliases: false]`
743-
or by using the `alias!` macro inside the quote:
757+
can access it by using the `alias!` macro inside the quote:
744758
745759
defmodule Hygiene do
746760
# This will expand to Elixir.Nested.hello
@@ -789,7 +803,16 @@ defmodule Kernel.SpecialForms do
789803
Hygiene.return_size #=> 5
790804
791805
Notice how `return_size` returns 5 even though the `size/1`
792-
function is not imported.
806+
function is not imported. In fact, even if `return_size` imported
807+
a function from another module, it wouldn't affect the function
808+
result:
809+
810+
def return_size do
811+
import Dict, only: [size: 1]
812+
get_size
813+
end
814+
815+
Calling this new `return_size` will still return 5 as result.
793816
794817
Elixir is smart enough to delay the resolution to the latest
795818
moment possible. So, if you call `size("hello")` inside quote,

0 commit comments

Comments
 (0)