Compare commits

..
186 Commits
Author SHA1 Message Date
José Valim 9033b217d9 Support canonical URLs 2016-02-21 21:33:30 +01:00
José Valim 1d9548fd28 Merge pull request #3475 from siscia/fixIntTake
Ensure integer in guards in Enum/Stream.take
2015-07-12 17:58:49 +02:00
siscia 9a6c195880 add test for integer passed as argument in {Enum,Stream}.take #3473 2015-07-12 17:40:16 +02:00
José Valim 3eb938a0ba Release v1.0.5 2015-06-29 09:56:28 +02:00
José Valim 66f1e74e0c Run badkey and badmap only on 18
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-25 18:01:05 +02:00
José Valim 7c382b94af Ensure we also normalize badmap and badkey in rescue 2015-06-25 16:49:30 +02:00
Boris Mühmer 9297a9167e fix for Erlang R18.0 changes in maps module
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-25 16:12:34 +02:00
James Fish 0410a1cec9 Fix logger translating process exit 2015-06-25 13:06:38 +01:00
James Fish b545a1e491 Translate emulator logged process crashes in 18.0+
Signed-off-by: James Fish <james@fishcakez.com>
2015-06-25 11:57:49 +01:00
José Valim c08b5b11c6 Move tests to Erlang 18 which has proper logger behaviour
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-25 13:01:04 +02:00
José Valim 8939b39fc2 Update to Erlang 18 2015-06-25 12:47:55 +02:00
José Valim e12a0c561e Backport improvements to <<>>' docs 2015-06-22 13:47:27 +02:00
José Valim 61c3e82123 Improve wording
Signed-off-by: James Fish <james@fishcakez.com>
2015-06-18 16:14:58 +01:00
José Valim d43b41695d Also document exit reasons
Signed-off-by: James Fish <james@fishcakez.com>
2015-06-18 16:14:34 +01:00
José Valim fdca8b2657 Add docs for simple one for one
Signed-off-by: James Fish <james@fishcakez.com>
2015-06-18 16:14:03 +01:00
José Valim dec06d8c82 Update CHANGELOG 2015-06-13 18:47:53 +02:00
José Valim 11c84cbd2e Delegate to :erlang.binary_to_float on Float.parse/1
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-13 18:45:45 +02:00
José Valim 67501bcddc Avoid non-fixed table errors on autocomplete 2015-06-08 16:56:22 +02:00
José Valim 1f05e7ce73 Rely on loaded_applications instead of running ones
If the application is loaded, it is enough for its
modules to be available for autocompletion. This also
simplifies the code and makes completion faster.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-08 16:08:43 +02:00
James Fish 02c279af12 Really fix race condition in logger translator test
Signed-off-by: James Fish <james@fishcakez.com>
2015-06-08 12:08:26 +01:00
José Valim 2c2fb820ab Update CHANGELOG 2015-06-08 09:45:01 +02:00
James Fish 1ad1d6d6b0 Merge pull request #3382 from lexmag/string_io-fixes
Fix `StringIO` processes leakage in the `ExUnit.CaptureIO`

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-08 09:33:46 +02:00
James Fish 83d8161959 Fix race condition in logger translator test 2015-06-07 22:07:36 +01:00
Eric Meadows-Jönsson b87ea61713 Join pre-release parts with "."
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2015-06-07 22:13:05 +02:00
Eric Meadows-Jönsson c355ab6482 Fix to_string for Version with numeric pre
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2015-06-07 22:12:43 +02:00
Eric Meadows-Jönsson f0ed2d48ce Fix Version.pre typespec
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2015-06-07 22:10:35 +02:00
Eric Meadows-Jönsson d23a46fa9f Add more documentation for ~> requirements
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2015-06-07 22:10:31 +02:00
Alexei Sholik 6c0cbbd73e Handle :undefined arity in Logger.Translator
We get :undefined when a temporary worker of a simple_one_for_one
supervisor crashes.

Thanks to @fishcakez for feedback
2015-06-07 23:03:54 +03:00
José Valim d58ef57e13 Ensure take/1 does not consume more than required
Kudos to @hamiltop for the idea and initial work on this fix.

Closes #3381 #3379

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-06 19:09:04 +02:00
James Fish 1a9493534e Fix GenEvent detecting module that isn't loaded
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-06 19:07:41 +02:00
Eric Meadows-Jönsson 45fe1cb084 Expand attributes and macros in record extractor
Achieved by using :epp.parse_file/2 instead of
:epp_dodger.quick_parse_file/1.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 22:52:49 +02:00
José Valim 3f0e7c5613 Only consider outer halts in flat_map when the op is not halt itself
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 22:51:36 +02:00
José Valim 49e76833d6 Ensure blocks do not clobber eex buffer
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 13:17:05 +02:00
José Valim 7963e44a5e Speed up upcase and downcase for large strings
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 13:16:15 +02:00
José Valim 3ba5e44dae Ensure we properly underscore acronyms followed by paths
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 13:15:56 +02:00
José Valim 1d74ddac78 Handle corner cases for small strings in rstrp
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 13:15:43 +02:00
José Valim c1e3d4f976 Optimize rstrip
This new implementation is no longer linear without affecting
smaller samples. For a string that is 100 bytes long, it is
25x faster than the previous implementation.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 13:15:12 +02:00
Michael Sokolnicki b4fc2b35fc Add unit test for IO.binread with :all option
Unit test checks correct handling of 0x0D0A (CR+LF) when reading entire
binary file

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 13:14:22 +02:00
Michael Sokolnicki 18a5d8affb Read 4K blocks instead of lines in IO.binread
Fix for incorrect handling of 0x0D0A (CR+LF) sequence when reading
binary files with option :all

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-06-05 13:14:15 +02:00
José Valim cd80994a70 Ensure we escape config before injecting into escript
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-04-14 15:23:13 +02:00
José Valim e02d7bf913 Release v1.0.4 2015-04-07 23:35:13 +02:00
José Valim fe5ff41514 Tag async tests as such 2015-04-07 11:35:31 +02:00
José Valim e9887a760e Wait until test process is down in ExUnit runner
This should fix a race condition where the next test would
start before all linked processes in the previous test were
killed, often leading to already registered errors.
2015-04-06 19:13:09 +02:00
Eric Meadows-Jönsson 0559fe5927 Fix doc formatting in ExUnit.Formatter
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2015-04-05 19:27:01 -05:00
José Valim 1a05bff45d Update CHANGELOG 2015-04-05 19:28:53 +02:00
José Valim 4d6670342b Fixes for Erlang 18.0-rc1 2015-04-05 18:28:13 +02:00
Eric Meadows-Jönsson 193e85882e Add compatibilty with OTP 18 typespec changes
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-04-05 17:59:29 +02:00
José Valim a58c007e0c Avoid missing behaviour warnings when compiling erlang files 2015-04-04 18:34:58 +02:00
José Valim ce6f4e6d15 Clean up ExUnit.Assertions docs 2015-04-03 17:08:03 +02:00
José Valim 321096665a Do not propagate protocol consolidation to children 2015-04-02 21:39:33 +02:00
José Valim b93aae9f86 Ensure we quote proper file on exceptions
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>

Conflicts:
	lib/elixir/test/elixir/exception_test.exs
2015-04-02 18:40:24 +02:00
José Valim a503069479 Ensure we consolidate only when there was a change 2015-04-02 15:42:56 +02:00
José Valim 120ea0fc8a Start v1.0.4-dev 2015-04-02 15:15:27 +02:00
José Valim d725c66d93 Update CHANGELOG 2015-04-02 15:04:00 +02:00
José Valim fab917dba3 Do not print app name as a filename 2015-04-02 15:00:52 +02:00
José Valim 23fb92f444 Improve error message for IEx.pry/1 2015-04-02 14:57:00 +02:00
José Valim db61109495 Generate build_embedded and start_permanent in new apps 2015-04-02 14:41:58 +02:00
José Valim c4e8ad0d65 Support start_permanent 2015-04-02 14:41:47 +02:00
José Valim ce77fa54b9 Support build_embedded and consolidate_protocols 2015-04-02 14:39:08 +02:00
Paulo Almeida eee921bf7b Support mix help --search PATTERN
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-04-02 09:47:07 +02:00
José Valim 73c6a0be8b Update CHANGELOG 2015-04-02 09:39:05 +02:00
José Valim 7644bd87a5 Merge pull request #3198 from eksperimental/pattern_operator
fix Kernel.=~/2 for "" =~ ""

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-04-02 09:37:05 +02:00
José Valim 9e2c5a29a4 Speed up decode_www_form
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-17 19:02:12 +01:00
José Valim 09498422d0 Speed up URI.decode_query/1
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-17 18:17:29 +01:00
Eric Meadows-Jönsson a697bab7f2 Store relative paths in erlang manifest
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2015-03-13 13:44:16 +01:00
José Valim 36e81d587e Increase elixir_counter timeout
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-12 19:00:56 +01:00
Booker C. Bense 17a0abd57a Added test for markup ending in . and code to pass the test
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-07 00:19:39 +01:00
Or Neeman e6cfc20556 Produce clearer messages for syntax errors before a sigil
Closes #3130

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-07 00:19:20 +01:00
Or Neeman 906f03102b Return value when matching with _ on last line of block
Closes #3125

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-02 14:27:47 +01:00
José Valim 6a594e2bba Ensure changes in child deps forces the parent to recompile
This test fell through the cracks when we changed mix
to no longer compile dependencies on get but during
project compilation.

Therefore, this patch fixes the bug and ensures the test
is up to date to check the original scenario it was supposed
to.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-01 11:03:03 +01:00
José Valim 10dd8f843b Fallback to undocumented API only if necessary
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>

Conflicts:
	lib/elixir/src/elixir.erl
2015-03-01 11:02:51 +01:00
José Valim 53ecea8b03 Do not erase stacktrace on bad configs
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-01 11:02:05 +01:00
Eric Meadows-Jönsson efba8d8bfa Fix httpc proxy option profile
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-03-01 11:00:43 +01:00
José Valim 5a201065dc Update new major.minor instructions
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-02-12 11:17:22 +01:00
José Valim 307675284c Release v1.0.3 2015-02-12 10:57:06 +01:00
José Valim 38a9513111 Fix boundary in Enum.take/2, closes #3042
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-02-01 09:19:30 -02:00
José Valim 578f798cc1 Use which_applications instead of undocumented info
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-31 09:46:53 -02:00
José Valim efbdf4b9b0 Update CHANGELOG 2015-01-31 11:43:06 +01:00
José Valim 9679bed4d7 Revert "Don't ignore escape characters in regex"
This change will be on v1.1 only as it may break applications.

This reverts commit 337c040da8.
2015-01-31 11:32:45 +01:00
José Valim b6c0045fc2 Ensure rebar is quoted when running escript on windows
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-30 11:10:41 +01:00
José Valim 10612ddf22 Always rebuild structures on Windows
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-30 10:13:15 +01:00
José Valim cbcbbcf876 Use :application.info[:loaded] to avoid races 2015-01-29 12:05:09 +01:00
José Valim 95b81c2a13 Merge pull request #3025 from MSch/flush-logger-after-tests
Call Logger.flush in System.at_exit when running mix test.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-29 11:45:32 +01:00
José Valim a525f71e13 Update CHANGELOG 2015-01-29 11:14:40 +01:00
José Valim 750d2a3f7a Ignore exported vars warning
Closes #2798

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-28 21:50:16 +01:00
José Valim 61e9fafb73 Improve error message with invalid structures in maps
Closes #2958

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-27 17:48:50 +01:00
José Valim aa48f6a881 Ensure priv/include are copied on Windows even if source did not change
Closes #2908

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-27 15:29:43 +01:00
José Valim b5e2d45b7d Update CHANGELOG 2015-01-24 14:10:17 +01:00
José Valim 29f2eb7dab Merge pull request #2801 from fishcakez/app_env
Move application state out of application env
2015-01-24 13:57:50 +01:00
José Valim a3754e3841 Do not show aliases and import warnings when code cannot compile
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-24 11:47:45 +01:00
José Valim 337c040da8 Don't ignore escape characters in regex
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-22 11:46:11 +01:00
José Valim b4d465e2ed Merge pull request #3018 from lexmag/logger-metadata-fix
Fix the logging with `metadata[:function]`
2015-01-21 11:47:02 +01:00
James Fish 0bb3d1c6bd Introduce Mix.State to store internal mix state
Moves non-config state from application env to an ETS table that is
updated with an Agent.
2015-01-10 15:20:22 +00:00
James Fish 86476615ef Fix logger to keep config through config_change/3
Store deleted handlers and live config data in ETS table
2015-01-10 15:20:22 +00:00
James Fish 860b3cc5a7 Introduce IEx.Config to store internal iex state
* All config get/put moved to IEx.Config
* after_spawn stored in ETS to prevent config_change deletion
* started? checks for IEx.Config process
* Return full config on IEx.configuration/1
2015-01-10 15:20:21 +00:00
James Fish bb5e6f65f5 Introduce elixir_config to store internal state
Adds ETS table that can only be updated by the gen_server elixir_config,
which means that reads are async and writes are sync.

Stores:
* URI scheme/ports
* Compiler options
* argv
* System.at_exit funs
2015-01-10 15:20:09 +00:00
Samuel Tonini 95127516f7 add missing assert call
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-09 19:09:11 +01:00
James Fish ef0c495f16 Set MIX_ARCHIVES in mix tasks archive tests
Previously archive tests would fail if MIX_ARCHIVES was set.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-09 19:09:08 +01:00
José Valim 2472bb79ab Ensure mix compiler is able to handle nested directories
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-09 15:04:25 +01:00
José Valim 04b9174d75 Update CHANGELOG 2015-01-04 23:44:34 +01:00
Eric Meadows-Jönsson d31a58f0d9 Don't go through hex.pm API server to install Hex
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2015-01-04 20:33:11 +01:00
José Valim f97ab2649c Keep original stacktrace on inspect errors
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-03 20:26:37 +01:00
José Valim d969d42784 Compile docs to doc/
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2015-01-03 10:12:02 +01:00
José Valim 17c4c4d993 Do more strict matching on URI scheme
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-26 23:17:41 +01:00
José Valim 0f7a968389 Copyright requires just the starting year
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-26 21:00:26 +01:00
José Valim 272ec8ca47 Fix mix shell tests when ansi escapes are disabled
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-26 15:39:56 +01:00
José Valim a0e8e1c0fb Further improve URI parse docs
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-26 15:34:28 +01:00
José Valim b477dba34f Improve docs for URI
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-24 11:12:33 +01:00
José Valim 8d524ef971 Fix bootstrap issues
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-23 22:26:32 +01:00
José Valim 83cb5152fd Optimize reduce for maps
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-23 20:05:29 +01:00
José Valim 3c100575a3 Merge pull request #2953 from liveforeverx/fix_compile_error
resolves #2952

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-13 23:12:35 +01:00
José Valim d1b6161f2e Update CHANGELOG 2014-12-12 12:04:02 +01:00
José Valim 785781d089 Merge pull request #2950 from tonini/remove-dumb-terminal-warning
warning about dumb terminal just irritates users

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-12 12:01:03 +01:00
José Valim b2ac4c9394 Only shut down Logger if the application is being actually started
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-12 12:00:52 +01:00
José Valim 50ac792747 Optimize and also add completion for Erlang modules
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-11 09:42:40 +01:00
José Valim 7d433e80e5 Improve IEx autocomplete implementation
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-11 09:42:37 +01:00
José Valim f9cb812bc1 Always use the loaded application modules
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-11 05:01:57 +01:00
José Valim f8711f2e36 Merge pull request #2932 from tonini/add-modules-load-path-to-autocomplete
Fetch module names from load path for autocomplete

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-11 05:01:50 +01:00
José Valim 0251f564d9 Merge pull request #2933 from Kabie/Regex.replace
Fix and enhance &Regex.replace/4

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-08 16:20:59 +01:00
José Valim e4acc08cf5 Improve archive error on Windows
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-07 14:21:17 +01:00
José Valim 2ab5d25787 Update CHANGELOG 2014-12-06 22:14:22 +01:00
José Valim acde8078f8 Clean up IO.ANSI.Docs handling of `
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-06 22:12:56 +01:00
José Valim 487ac9c1c4 Merge pull request #2924 from jw2013/italic
Fix broken IO.ANSI.Docs parser
Conflicts:
	lib/elixir/lib/io/ansi/docs.ex
2014-12-06 22:12:10 +01:00
José Valim f0f65f8bec Use IO.ANSI.format/1 for escaping mix shell messages
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-12-04 22:17:07 +01:00
José Valim 23943b6180 Update CHANGELOG 2014-11-21 17:42:39 +01:00
José Valim d9125b0a81 Ensure compilation does not leave random spurious data on failure
Prior to this patch, the parallel compiler could leave spurious
processes and the module definition could leave stale data
in the elixir_modules table.

The issue has been fixed by emitting the proper exit signals
and by using monitors.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-11-21 17:41:43 +01:00
José Valim d1d46db907 Start v1.0.3-dev 2014-11-13 10:41:38 +01:00
José Valim 02056d1030 Merge pull request #2891 from chrismccord/master
Fix command_to_module_name not converting snakecased names properly

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-11-13 10:40:58 +01:00
José Valim 14a3686a3f Merge pull request #2882 from Frost/no-more-bright-yellow-in-ansi-docs
Make IO.ANSI.Docs readable on white background

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-11-09 20:56:10 -02:00
José Valim c04b182c6c Merge pull request #2886 from jw2013/CRLF
fix wrong CRLF grapheme

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-11-09 20:55:26 -02:00
Eric Meadows-Jönsson f5462d98e0 Don't show hex update message on mix local.hex
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-11-08 22:55:56 +01:00
José Valim 75d0c07b46 Merge pull request #2838 from edgurgel/patch-1
Fix typo on CHANGELOG.md
2014-10-21 21:42:11 -02:00
Eduardo Gurgel 1de8dcb695 Fix typo on CHANGELOG.md
[ci skip]
2014-10-22 10:55:19 +13:00
José Valim 0e167bef27 More updates to instructions
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-21 15:32:48 -02:00
José Valim 34df817638 Release v1.0.2 2014-10-21 15:19:58 -02:00
José Valim 311a5790d6 Update release instructions
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>

Conflicts:
	Makefile
2014-10-21 15:02:37 -02:00
José Valim b4c75f97b4 Fail to compile try without else/catch/after/rescue, closes #2797
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-21 14:57:55 -02:00
José Valim 70692e6618 Improve token errors for aliases, closes #2818
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-21 14:57:47 -02:00
José Valim 529d584262 Unify error reporting from EEx, closes #2833
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>

Conflicts:
	lib/eex/test/eex_test.exs
2014-10-21 14:57:36 -02:00
José Valim c0fb275d5b Properly handle eval_failure warnings, closes #2835
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-21 14:56:55 -02:00
José Valim 24f46be144 Use unamed tables for module compilation
* We have created a main named table that keeps all module information

* We have reduced the amount of tables by storing internal, docs and
  attributes altogether and using table looks for retriving the relevant
  information

* At this moment, creating a module in Elixir defines three tables,
  one for data, another for functions and another for clauses

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-17 13:53:04 +02:00
José Valim 0fe3da9dea Update CHANGELOG 2014-10-15 20:54:31 +02:00
José Valim 03d0ad3f03 No longer inline binary expressions in EEx
String.Chars is now always inlined by the compiler.

Closes #2815

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-15 20:52:48 +02:00
José Valim a87f43701f Merge pull request #2819 from benjamintanweihao/patch-3
Fix missing concatenation operator.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-15 20:52:34 +02:00
k1complete dce3a3a2a5 set null prompt function in dumbterm mode
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-15 20:52:19 +02:00
Eduardo Gurgel 7b20084b28 Add OTP 17.3 to run on Travis CI
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-15 20:51:57 +02:00
José Valim 542808102f Build .beam location from scratch on mix compile.elixir
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-15 20:51:41 +02:00
Eric Meadows-Jönsson fd18b6a41f Fix String.replace/4 typespec
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-10-07 19:41:53 +02:00
Eric Meadows-Jönsson 4c9c95f80f Add task for pushing standalone mix
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-10-07 15:23:47 +02:00
José Valim 89460154bb Release v1.0.1 2014-10-07 13:33:07 +02:00
José Valim b026e8877a --elixirc-paths should be a subset of project paths
Since the manifest is shared, --elixirc-paths must
be a subset as we need to know what to change and what
to not change in the manifest file.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-07 13:25:42 +02:00
José Valim 597381b2e0 Write to manifest when file is removed
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-06 22:10:01 +02:00
José Valim df70729b14 Test that we do purge and delete artifacts
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-06 17:26:26 +02:00
José Valim 61b116c1a5 Also purge and delete during tests
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-06 17:21:31 +02:00
José Valim d37a10bbd0 Purge and delete modules before compiling them
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-06 17:21:25 +02:00
José Valim 5d75c5c861 Refactor and add new rewrite rules
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-10-06 16:46:01 +02:00
Eric Meadows-Jönsson db4089cc71 Don't crash on malformed proxy env var
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-10-06 11:35:24 +02:00
José Valim f9f4f14edf Update CHANGELOG 2014-10-02 21:10:39 +02:00
Eric Meadows-Jönsson 58946ce879 Give higher prio to powershell on windows
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-10-01 18:32:23 +02:00
Eric Meadows-Jönsson de1d5ff793 Send elixir version as parameter when installing hex
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-09-29 21:22:07 +02:00
Eric Meadows-Jönsson a4be8fb260 Fix :stderr_to_stdout option
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-09-29 21:21:58 +02:00
Eric Meadows-Jönsson 031a27f5fa Fix spec for surround_many
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-09-29 21:21:50 +02:00
José Valim f3c1931cac Update CHANGELOG 2014-09-27 11:34:48 +02:00
José Valim 2e48d81c20 Move printing out of copy_path, always create dir
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-27 11:33:03 +02:00
José Valim e7ef3fc95d Merge pull request #2787 from elixir-lang/emj-hex-file-error
Report correct location if local.hex failed

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-27 11:32:52 +02:00
José Valim 2d01aa1c6a Do not pass false into port command
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-27 11:08:04 +02:00
José Valim ae07124550 Merge pull request #2789 from alco/system-cmd-path-resolution
System.cmd path resolution

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-27 11:07:28 +02:00
José Valim 1f744f4dac Also remove elixir_exp from stacktraces
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-25 10:37:10 +02:00
José Valim ad88ac642f Remove :elixir module from stacktraces
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-25 10:30:19 +02:00
Eric Meadows-Jönsson f7956e9d80 Bump Hex requirement
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-09-23 21:44:24 +02:00
Eric Meadows-Jönsson da6892aa96 Add MIX_ENV output to archive.build
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-09-22 23:32:07 +02:00
José Valim 7a3bd20804 Update CHANGELOG 2014-09-20 13:43:52 +02:00
José Valim f7015166dc Filter out :elixir_lexical from stacktraces
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-20 13:41:47 +02:00
José Valim c6f346a355 Change version requirement to be MAJOR.MINOR
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-20 13:41:41 +02:00
José Valim 911a3ba97f Update release instructions
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-19 18:26:40 +02:00
José Valim a1668a6b28 Ensure Mix.Config is deep merged
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-16 19:53:47 +02:00
José Valim a4cb74a83f Include stracktrace on ExUnit timeouts
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-16 19:53:43 +02:00
José Valim bbf9552186 Add tests for add_process_handler/2
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-15 19:33:17 +02:00
Eric Meadows-Jönsson e621b5828e Load dependencies before deps.check compiles
Signed-off-by: Eric Meadows-Jönsson <eric.meadows.jonsson@gmail.com>
2014-09-15 10:40:35 +02:00
José Valim 68e282c50a Do not require {ref, :done}, instead allow sync removal
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-14 23:15:57 +02:00
José Valim 403a50fbcd Ensure chunk/4 is haltable
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-13 16:14:23 +02:00
José Valim 8e98cd4f41 Start v1.0.1-dev 2014-09-12 12:34:52 +02:00
budstein 499c385000 Fix a typo in Code.eval_file's doc
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-12 12:33:37 +02:00
Alexei Sholik aecafc099d Fix a typo in IO.inspect’s doc
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-12 12:33:31 +02:00
Haoming Zhu 785c7d700a fix previous commit typo bug
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-12 12:33:15 +02:00
Bill Gathen cecc8a0f95 Fix my own typo in helpers.ex
Brand-new language, and I put a ding in it. Sorry about that. :-(

Congratulations on 1.0!

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2014-09-12 12:32:53 +02:00
359 changed files with 9655 additions and 17874 deletions
+4 -8
View File
@@ -1,17 +1,13 @@
/.eunit
/.release
/doc
/ebin
/lib/*/ebin/*
/lib/*/tmp
/lib/elixir/src/elixir.app.src
/lib/elixir/src/*_lexer.erl
/lib/elixir/src/*_parser.erl
/lib/elixir/src/elixir.app.src
/lib/elixir/test/ebin
/man/elixir.1
/man/iex.1
/rel/elixir
/Docs-v*.zip
/Precompiled-v*.zip
/.eunit
/.release
.elixir.plt
erl_crash.dump
.elixir.plt
+4 -12
View File
@@ -1,19 +1,11 @@
language: erlang
otp_release:
- 17.0
- 17.3
- 17.4
- 17.5
- 18.0
sudo: false
script: "make compile && rm -rf .git && make test"
notifications:
irc: "irc.freenode.org#elixir-lang"
recipients:
- jose.valim@plataformatec.com.br
- eric.meadows.jonsson@gmail.com
otp_release:
- 17.0
- 17.1
- 17.3
+1375 -167
View File
File diff suppressed because it is too large Load Diff
-22
View File
@@ -1,22 +0,0 @@
# Contributor Code of Conduct
As contributors and maintainers of this project, and in the interest of fostering an open and welcoming community, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities.
We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, religion, or nationality.
Examples of unacceptable behavior by participants include:
* The use of sexualized language or imagery
* Personal attacks
* Trolling or insulting/derogatory comments
* Public or private harassment
* Publishing other's private information, such as physical or electronic addresses, without explicit permission
* Other unethical or unprofessional conduct.
The Elixir Core Team has the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. By adopting this Code of Conduct, we commit ourselves to fairly and consistently applying these principles to every aspect of managing this project. Project maintainers who do not follow or enforce the Code of Conduct may be permanently removed from the project team.
This code of conduct applies both within project spaces and in public spaces when an individual is representing the project or its community.
Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by sending an e-mail to elixir-lang-conduct@googlegroups.com.
This Code of Conduct is adapted from the [Contributor Covenant](http://contributor-covenant.org), version 1.2.0, available at [http://contributor-covenant.org/version/1/2/0/](http://contributor-covenant.org/version/1/2/0/)
+63 -73
View File
@@ -3,23 +3,20 @@
Please take a moment to review this document in order to make the contribution
process easy and effective for everyone involved!
Also make sure you read our [Code of Conduct](CODE_OF_CONDUCT.md) that
outlines our commitment towards an open and welcoming environment.
## Using the issue tracker
Use the issues tracker for:
* [bug reports](#bug-reports)
* [bug reports](#bugs-reports)
* [submitting pull requests](#pull-requests)
Please **do not** use the issue tracker for personal support requests nor feature requests. Support requests should be sent to:
* [the elixir-talk mailing list](https://groups.google.com/group/elixir-lang-talk)
* [the elixir-talk mailing list](http://groups.google.com/group/elixir-lang-talk)
* [Stack Overflow](http://stackoverflow.com/questions/ask?tags=elixir)
* **[#elixir-lang](irc://chat.freenode.net/elixir-lang)** IRC channel on [chat.freenode.net](http://www.freenode.net/)
* [#elixir-lang](irc://chat.freenode.net/elixir-lang)
Feature requests can be discussed on [the elixir-core mailing list](https://groups.google.com/group/elixir-lang-core).
Feature requests can be discussed on [the elixir-core mailing list](http://groups.google.com/group/elixir-lang-core).
We do our best to keep the issue tracker tidy and organized, making it useful
for everyone. For example, we classify open issues per application and perceived
@@ -33,8 +30,8 @@ Good bug reports are extremely helpful - thank you!
Guidelines for bug reports:
1. **Use the GitHub issue search** &mdash; [check if the issue has already been
reported](https://github.com/elixir-lang/elixir/search?type=Issues).
1. **Use the GitHub issue search** &mdash; check if the issue has already been
reported.
2. **Check if the issue has been fixed** &mdash; try to reproduce it using the
`master` branch in the repository.
@@ -67,7 +64,7 @@ Example:
## Feature requests
Feature requests are welcome and should be discussed on [the elixir-core mailing list](https://groups.google.com/group/elixir-lang-core). But take a moment to find
Feature requests are welcome and should be discussed on [the elixir-core mailing list](http://groups.google.com/group/elixir-lang-core). But take a moment to find
out whether your idea fits with the scope and aims of the project. It's up to *you*
to make a strong case to convince the community of the merits of this feature.
Please provide as much detail and context as possible.
@@ -85,9 +82,9 @@ the `lib` folder:
* `ex_unit` - Simple test framework that ships with Elixir
* `iex` - IEx, Elixir's interactive shell
* `iex` — IEx, Elixir's interactive shell
* `mix` - Elixir's build tool
* `mix` — Elixir's build tool
You can run all tests in the root directory with `make test` and you can
also run tests for a specific framework `make test_#{NAME}`, for example,
@@ -97,10 +94,8 @@ In case you are changing a single file, you can compile and run tests only
for that particular file for fast development cycles. For example, if you
are changing the String module, you can compile it and run its tests as:
```sh
bin/elixirc lib/elixir/lib/string.ex -o lib/elixir/ebin
bin/elixir lib/elixir/test/elixir/string_test.exs
```
$ bin/elixirc lib/elixir/lib/string.ex -o lib/elixir/ebin
$ bin/elixir lib/elixir/test/elixir/string_test.exs
After your changes are done, please remember to run the full suite with
`make test`.
@@ -122,7 +117,7 @@ something like:
```elixir
@doc """
Returns only those elements for which `fun` is `true`.
Returns only those elements for which `fun` is true.
...
"""
@@ -148,7 +143,7 @@ Keep in mind that the first paragraph might show up in a summary somewhere, long
texts in the first paragraph create very ugly summaries. As a rule of thumb
anything longer than 80 characters is too long.
Try to keep unnecessary details out of the first paragraph, it's only there to
Try to keep unneccesary details out of the first paragraph, it's only there to
give a user a quick idea of what the documented "thing" does/is. The rest of the
documentation string can contain the details, for example when a value and when
`nil` is returned.
@@ -158,7 +153,7 @@ example:
```elixir
@doc """
Returns only those elements for which `fun` is `true`.
Return only those elements for which `fun` is true.
## Examples
@@ -178,11 +173,6 @@ Good pull requests - patches, improvements, new features - are a fantastic
help. They should remain focused in scope and avoid containing unrelated
commits.
**NOTE**: Do not send code style changes as pull requests like changing
the indentation of some particular code snippet or how a function is called.
Those will not be accepted as they pollute the repository history with non
functional changes and are often based on personal preferences.
**IMPORTANT**: By submitting a patch, you agree that your work will be
licensed under the license used by the project.
@@ -193,83 +183,83 @@ not want to merge into the project.
Please adhere to the coding conventions in the project (indentation,
accurate comments, etc.) and don't forget to add your own tests and
documentation. When working with Git, we recommend the following process
documentation. When working with git, we recommend the following process
in order to craft an excellent pull request:
1. [Fork](https://help.github.com/fork-a-repo/) the project, clone your fork,
and configure the remotes:
1. [Fork](http://help.github.com/fork-a-repo/) the project, clone your fork,
and configure the remotes:
```sh
# Clone your fork of the repo into the current directory
git clone https://github.com/<your-username>/elixir
# Navigate to the newly cloned directory
cd elixir
# Assign the original repo to a remote called "upstream"
git remote add upstream https://github.com/elixir-lang/elixir
```
```bash
# Clone your fork of the repo into the current directory
git clone https://github.com/<your-username>/elixir
# Navigate to the newly cloned directory
cd elixir
# Assign the original repo to a remote called "upstream"
git remote add upstream https://github.com/elixir-lang/elixir
```
2. If you cloned a while ago, get the latest changes from upstream:
```sh
git checkout master
git pull upstream master
```
```bash
git checkout master
git pull upstream master
```
3. Create a new topic branch (off of `master`) to contain your feature, change,
or fix.
or fix.
**IMPORTANT**: Making changes in `master` is discouraged. You should always
keep your local `master` in sync with upstream `master` and make your
changes in topic branches.
**IMPORTANT**: Making changes in `master` is discouraged. You should always
keep your local `master` in sync with upstream `master` and make your
changes in topic branches.
```sh
git checkout -b <topic-branch-name>
```
```bash
git checkout -b <topic-branch-name>
```
4. Commit your changes in logical chunks. Keep your commit messages organized,
with a short description in the first line and more detailed information on
the following lines. Feel free to use Git's
[interactive rebase](https://help.github.com/articles/interactive-rebase)
feature to tidy up your commits before making them public.
with a short description in the first line and more detailed information on
the following lines. Feel free to use Git's
[interactive rebase](https://help.github.com/articles/interactive-rebase)
feature to tidy up your commits before making them public.
5. Make sure all the tests are still passing.
```sh
make test
```
```bash
make test
```
This command will compile the code in your branch and use that
version of Elixir to run the tests. This is needed to ensure your changes can
pass all the tests.
This command will compile the code in your branch and use that
version of Elixir to run the tests. This is needed to ensure your changes can
pass all the tests.
6. Push your topic branch up to your fork:
```sh
git push origin <topic-branch-name>
```
```bash
git push origin <topic-branch-name>
```
7. [Open a Pull Request](https://help.github.com/articles/using-pull-requests/)
with a clear title and description.
with a clear title and description.
8. If you haven't updated your pull request for a while, you should consider
rebasing on master and resolving any conflicts.
rebasing on master and resolving any conflicts.
**IMPORTANT**: _Never ever_ merge upstream `master` into your branches. You
should always `git rebase` on `master` to bring your changes up to date when
necessary.
**IMPORTANT**: _Never ever_ merge upstream `master` into your branches. You
should always `git rebase` on `master` to bring your changes up to date when
necessary.
```sh
git checkout master
git pull upstream master
git checkout <your-topic-branch>
git rebase master
```
```bash
git checkout master
git pull upstream master
git checkout <your-topic-branch>
git rebase master
```
We have saved some excellent pull requests we have received in the past in case
you are looking for some examples:
* [Implement Enum.member? – Pull Request](https://github.com/elixir-lang/elixir/pull/992)
* [Add String.valid? – Pull Request](https://github.com/elixir-lang/elixir/pull/1058)
* [Implement capture_io for ExUnit – Pull Request](https://github.com/elixir-lang/elixir/pull/1059)
* https://github.com/elixir-lang/elixir/pull/992
* https://github.com/elixir-lang/elixir/pull/1058
* https://github.com/elixir-lang/elixir/pull/1059
Thank you for your contributions!
+3 -4
View File
@@ -1,9 +1,8 @@
LEGAL NOTICE INFORMATION
------------------------
All the files in this distribution are copyright (c) 2012 Plataformatec
covered under Elixir's license (see the file LICENSE) except the file
mentioned below that contains sections that are copyright
(c) 1996 Ericsson AB under Erlang's License (EPL):
All the files in this distribution are covered under either Elixir's
license (see the file LICENSE) except the files mentioned below that
contains sections that are under Erlang's License (EPL):
lib/elixir/src/elixir_parser.erl (generated by build scripts)
+16 -82
View File
@@ -1,19 +1,19 @@
REBAR ?= "$(CURDIR)/rebar"
PREFIX ?= /usr/local
DOCS := v1.1
REBAR := rebar
DOCS := v1.0
CANONICAL := stable
ELIXIRC := bin/elixirc --verbose --ignore-module-conflict
ERLC := erlc -I lib/elixir/include
ERL := erl -I lib/elixir/include -noshell -pa lib/elixir/ebin
VERSION := $(strip $(shell cat VERSION))
Q := @
PREFIX := /usr/local
LIBDIR := lib
INSTALL = install
INSTALL_DIR = $(INSTALL) -m755 -d
INSTALL_DATA = $(INSTALL) -m644
INSTALL_PROGRAM = $(INSTALL) -m755
.PHONY: install compile erlang elixir build_plt clean_plt dialyze test clean install_man clean_man docs Docs.zip Precompiled.zip publish_zips publish_docs publish_mix
.PHONY: install compile erlang elixir build_plt clean_plt dialyze test clean docs release_docs release_zip check_erlang_release
.NOTPARALLEL: compile
#==> Functions
@@ -65,7 +65,7 @@ lib/elixir/src/elixir.app.src: src/elixir.app.src
$(Q) cat src/elixir.app.src >>lib/elixir/src/elixir.app.src
erlang:
$(Q) cd lib/elixir && $(REBAR) compile
$(Q) cd lib/elixir && ../../$(REBAR) compile
# Since Mix depends on EEx and EEx depends on
# Mix, we first compile EEx without the .app
@@ -83,7 +83,7 @@ $(KERNEL): lib/elixir/lib/*.ex lib/elixir/lib/*/*.ex lib/elixir/lib/*/*/*.ex
$(Q) cd lib/elixir && ../../$(ELIXIRC) "lib/**/*.ex" -o ebin;
$(Q) $(MAKE) unicode
$(Q) rm -rf lib/elixir/ebin/elixir.app
$(Q) cd lib/elixir && $(REBAR) compile
$(Q) cd lib/elixir && ../../$(REBAR) compile
unicode: $(UNICODE)
$(UNICODE): lib/elixir/unicode/*
@@ -100,7 +100,6 @@ $(eval $(call APP_TEMPLATE,iex,IEx))
install: compile
@ echo "==> elixir (install)"
$(Q) for dir in lib/*; do \
rm -Rf $(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/$$dir/ebin; \
$(INSTALL_DIR) "$(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/$$dir/ebin"; \
$(INSTALL_DATA) $$dir/ebin/* "$(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/$$dir/ebin"; \
done
@@ -110,10 +109,9 @@ install: compile
$(Q) for file in "$(DESTDIR)$(PREFIX)"/$(LIBDIR)/elixir/bin/* ; do \
ln -sf "../$(LIBDIR)/elixir/bin/$${file##*/}" "$(DESTDIR)$(PREFIX)/bin/" ; \
done
$(MAKE) install_man
clean:
cd lib/elixir && $(REBAR) clean
cd lib/elixir && ../../$(REBAR) clean
rm -rf ebin
rm -rf lib/*/ebin
rm -rf lib/elixir/test/ebin
@@ -122,72 +120,36 @@ clean:
rm -rf lib/mix/test/fixtures/deps_on_git_repo
rm -rf lib/mix/test/fixtures/git_rebar
rm -rf lib/elixir/src/elixir.app.src
$(MAKE) clean_man
clean_exbeam:
$(Q) rm -f lib/*/ebin/Elixir.*.beam
#==> Create Documentation
#==> Release tasks
LOGO_PATH = $(shell test -f ../docs/logo.png && echo "--logo ../docs/logo.png")
SOURCE_REF = $(shell head="$$(git rev-parse HEAD)" tag="$$(git tag --points-at $$head | tail -1)" ; echo "$${tag:-$$head}\c")
SOURCE_REF = $(shell tag="$(call GIT_TAG)" revision="$(call GIT_REVISION)"; echo "$${tag:-$$revision}\c")
COMPILE_DOCS = bin/elixir ../ex_doc/bin/ex_doc "$(1)" "$(VERSION)" "lib/$(2)/ebin" -m "$(3)" -u "https://github.com/elixir-lang/elixir" --source-ref "v$(VERSION)" $(call LOGO_PATH) -o doc/$(2) -a http://elixir-lang.org/docs/$(CANONICAL)/$(2)/ -p http://elixir-lang.org/docs.html
docs: compile ../ex_doc/bin/ex_doc docs_elixir docs_eex docs_mix docs_iex docs_ex_unit docs_logger
docs_elixir: compile ../ex_doc/bin/ex_doc
@ echo "==> ex_doc (elixir)"
$(Q) rm -rf doc/elixir
docs: compile ../ex_doc/bin/ex_doc
$(Q) rm -rf doc
$(call COMPILE_DOCS,Elixir,elixir,Kernel)
docs_eex: compile ../ex_doc/bin/ex_doc
@ echo "==> ex_doc (eex)"
$(Q) rm -rf doc/eex
$(call COMPILE_DOCS,EEx,eex,EEx)
docs_mix: compile ../ex_doc/bin/ex_doc
@ echo "==> ex_doc (mix)"
$(Q) rm -rf doc/mix
$(call COMPILE_DOCS,Mix,mix,Mix)
docs_iex: compile ../ex_doc/bin/ex_doc
@ echo "==> ex_doc (iex)"
$(Q) rm -rf doc/iex
$(call COMPILE_DOCS,IEx,iex,IEx)
docs_ex_unit: compile ../ex_doc/bin/ex_doc
@ echo "==> ex_doc (ex_unit)"
$(Q) rm -rf doc/ex_unit
$(call COMPILE_DOCS,ExUnit,ex_unit,ExUnit)
docs_logger: compile ../ex_doc/bin/ex_doc
@ echo "==> ex_doc (logger)"
$(Q) rm -rf doc/logger
$(call COMPILE_DOCS,Logger,logger,Logger)
../ex_doc/bin/ex_doc:
@ echo "ex_doc is not found in ../ex_doc as expected. See README for more information."
@ false
#==> Zips
release_zip: compile
rm -rf v$(VERSION).zip
zip -9 -r v$(VERSION).zip bin CHANGELOG.md LEGAL lib/*/ebin LICENSE Makefile README.md VERSION
Docs.zip: docs
rm -rf Docs-v$(VERSION).zip
zip -9 -r Docs-v$(VERSION).zip doc
@ echo "Docs file created $(CURDIR)/Docs-v$(VERSION).zip"
Precompiled.zip: build_man compile
rm -rf Precompiled-v$(VERSION).zip
zip -9 -r Precompiled-v$(VERSION).zip bin CHANGELOG.md LEGAL lib/*/ebin LICENSE man README.md VERSION
@ echo "Precompiled file created $(CURDIR)/Precompiled-v$(VERSION).zip"
#==> Publish
publish_zips: Precompiled.zip Docs.zip
publish_docs: docs
release_docs: docs
rm -rf ../docs/$(DOCS)/*/
cp -R doc/* ../docs/$(DOCS)
mv doc/* ../docs/$(DOCS)
# This task requires aws-cli to be installed and set up for access to s3.hex.pm
# See: http://docs.aws.amazon.com/cli/latest/userguide/cli-chap-getting-set-up.html
@@ -248,31 +210,3 @@ build_plt: clean_plt $(PLT)
dialyze: compile $(PLT)
@ echo "==> Dialyzing Elixir..."
$(Q) dialyzer --plt $(PLT) $(DIALYZER_OPTS) lib/*/ebin
#==> Man page tasks
build_man: man/iex.1 man/elixir.1
man/iex.1:
$(Q) cp man/iex.1.in man/iex.1
$(Q) sed -i.bak "/{COMMON}/r common" man/iex.1
$(Q) sed -i.bak "/{COMMON}/d" man/iex.1
$(Q) rm man/iex.1.bak
man/elixir.1:
$(Q) cp man/elixir.1.in man/elixir.1
$(Q) sed -i.bak "/{COMMON}/r common" man/elixir.1
$(Q) sed -i.bak "/{COMMON}/d" man/elixir.1
$(Q) rm man/elixir.1.bak
clean_man:
rm -f man/elixir.1
rm -f man/iex.1
install_man: build_man
$(Q) mkdir -p $(DESTDIR)$(PREFIX)/share/man/man1
$(Q) $(INSTALL_DATA) man/elixir.1 $(DESTDIR)$(PREFIX)/share/man/man1
$(Q) $(INSTALL_DATA) man/elixirc.1 $(DESTDIR)$(PREFIX)/share/man/man1
$(Q) $(INSTALL_DATA) man/iex.1 $(DESTDIR)$(PREFIX)/share/man/man1
$(Q) $(INSTALL_DATA) man/mix.1 $(DESTDIR)$(PREFIX)/share/man/man1
$(MAKE) clean_man
+16 -24
View File
@@ -1,6 +1,6 @@
![Elixir](https://github.com/elixir-lang/elixir-lang.github.com/raw/master/images/logo/logo.png)
=========
[![Build Status](https://secure.travis-ci.org/elixir-lang/elixir.svg?branch=master "Build Status")](https://travis-ci.org/elixir-lang/elixir)
[![Build Status](https://secure.travis-ci.org/elixir-lang/elixir.svg?branch=master "Build Status")](http://travis-ci.org/elixir-lang/elixir)
For more about Elixir, installation and documentation, [check Elixir's website](http://elixir-lang.org/).
@@ -8,55 +8,47 @@ For more about Elixir, installation and documentation, [check Elixir's website](
If you want to contribute to Elixir or run it from source, clone this repository to your machine, compile and test it:
```sh
git clone https://github.com/elixir-lang/elixir.git
cd elixir
make clean test
```
$ git clone https://github.com/elixir-lang/elixir.git
$ cd elixir
$ make clean test
> Note: if you are running on Windows, [this article includes important notes for compiling Elixir from source on Windows](https://github.com/elixir-lang/elixir/wiki/Windows).
If Elixir fails to build (specifically when pulling in a new version via `git`), be sure to remove any previous build artifacts by running `make clean`, then `make test`.
If Elixir fails to build (specifically when pulling in a new version via git), be sure to remove any previous build artifacts by running `make clean`, then `make test`.
If tests pass, you are ready to move on to the [Getting Started guide][1] or to try Interactive Elixir by running: `bin/iex` in your terminal.
However, if tests fail, it is likely you have an outdated Erlang version (Elixir requires Erlang 17.0 or later). You can check your Erlang version by calling `erl` in the command line. You will see some information as follows:
`Erlang/OTP 17 [erts-6.0] [source-07b8f44] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]`
Erlang/OTP 17 [erts-6.0] [source-07b8f44] [64-bit] [smp:4:4] [async-threads:10] [hipe] [kernel-poll:false]
If you have the correct version and tests still fail, feel free to [open an issue][2].
## Building documentation
Building the documentation requires [ExDoc](https://github.com/elixir-lang/ex_doc) to be installed and built in the same containing folder as Elixir.
Building the documentation requires [ex_doc](https://github.com/elixir-lang/ex_doc) to be installed and built in the same containing folder as elixir.
```sh
# After cloning and compiling Elixir
git clone git://github.com/elixir-lang/ex_doc.git
cd ex_doc && ../elixir/bin/mix do deps.get, compile
cd ../elixir && make docs
```
# After cloning and compiling Elixir
$ git clone git://github.com/elixir-lang/ex_doc.git
$ cd ex_doc && ../elixir/bin/mix compile
$ cd ../elixir && make docs
## Contributing
We appreciate any contribution to Elixir. Check our [CODE_OF_CONDUCT.md](CODE_OF_CONDUCT.md) and [CONTRIBUTING.md](CONTRIBUTING.md) guides for more information. We usually keep a list of features and bugs [in the issue tracker][2].
We appreciate any contribution to Elixir, so check out our [CONTRIBUTING.md](CONTRIBUTING.md) guide for more information. We usually keep a list of features and bugs [in the issue tracker][2].
## Important links
* [Elixir Website][1]
* [Elixir Documentation][7]
* **[#elixir-lang][5]** on [Freenode][6] IRC
* \#elixir-lang on freenode IRC
* [Website][1]
* [Issue tracker][2]
* [elixir-talk Mailing list (questions)][3]
* [elixir-core Mailing list (development)][4]
[1]: http://elixir-lang.org
[2]: https://github.com/elixir-lang/elixir/issues
[3]: https://groups.google.com/group/elixir-lang-talk
[4]: https://groups.google.com/group/elixir-lang-core
[5]: irc://chat.freenode.net/elixir-lang
[6]: http://www.freenode.net/
[7]: http://elixir-lang.org/docs.html
[3]: http://groups.google.com/group/elixir-lang-talk
[4]: http://groups.google.com/group/elixir-lang-core
## License
+3 -3
View File
@@ -14,13 +14,13 @@ This document simply outlines the release process:
5. Run `make clean test` to ensure all tests pass from scratch and the CI is green
6. Recompile an existing project (for example, Ecto) to ensure manifests can be upgraded
6. Ensure minimum supported Hex works with new release (instructions upcoming)
7. Push branch and the new tag
8. Publish new docs with `make publish_docs`, copy docs to `docs/stable` if appropriate, and push to GitHub Pages
8. Release new docs with `make release_docs`, copy docs to `docs/stable` if appropriate, and push
9. Publish new zips with `make publish_zips`, upload `Precompiled.zip` and `Docs.zip` to GitHub Releases
9. Release new zip with `make release_zip`, push `Precompiled.zip` to GitHub Releases
10. Add the release to `elixir.csv` file in `elixir-lang/elixir-lang.github.com`
+1 -1
View File
@@ -1 +1 @@
1.1.1
1.0.5
+4 -13
View File
@@ -10,18 +10,17 @@ if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
-pa \"path\" Prepends the given path to Erlang code path (*)
-pz \"path\" Appends the given path to Erlang code path (*)
--app \"app\" Start the given app and its dependencies (*)
--erl \"switches\" Switches to be passed down to Erlang (*)
--erl \"switches\" Switches to be passed down to erlang (*)
--name \"name\" Makes and assigns a name to the distributed node
--sname \"name\" Makes and assigns a short name to the distributed node
--cookie \"cookie\" Sets a cookie for this distributed node
--hidden Makes a hidden node
--detached Starts the Erlang VM detached from console
--werl Uses Erlang's Windows shell GUI (Windows only)
--no-halt Does not halt the Erlang VM after execution
** Options marked with (*) can be given more than once
** Options given after the .exs file or -- are passed down to the executed code
** Options can be passed to the Erlang runtime using ELIXIR_ERL_OPTIONS or --erl" >&2
** Options can be passed to the erlang runtime using ELIXIR_ERL_OPTIONS or --erl" >&2
exit 1
fi
@@ -36,7 +35,6 @@ readlink_f () {
}
MODE="elixir"
ERL_EXEC="erl"
ERL=""
I=1
@@ -73,9 +71,6 @@ while [ $I -le $# ]; do
eval "VAL=\${$I}"
ERL="$ERL "$VAL""
;;
--werl)
USE_WERL=true
;;
*)
break
;;
@@ -94,15 +89,11 @@ if [ "$OS" != "Windows_NT" ]; then
if test -t 1 -a -t 2; then ERL="-elixir ansi_enabled true $ERL"; fi
fi
if [ "$OS" = "Windows_NT" ] && [ $USE_WERL ]; then
ERL_EXEC="werl"
fi
if [ -z "$ERL_PATH" ]; then
if [ -f "$SCRIPT_PATH/../releases/RELEASES" ] && [ -f "$SCRIPT_PATH/erl" ]; then
ERL_PATH="$SCRIPT_PATH"/"$ERL_EXEC"
ERL_PATH="$SCRIPT_PATH"/erl
else
ERL_PATH="$ERL_EXEC"
ERL_PATH=erl
fi
fi
+6 -6
View File
@@ -1,9 +1,9 @@
@echo off
setlocal
if ""%1""=="""" goto :documentation
if ""%1""==""--help"" goto :documentation
if ""%1""==""-h"" goto :documentation
if ""%1""==""/h"" goto :documentation
if "%1"=="" goto documentation
if "%1"=="--help" goto documentation
if "%1"=="-h" goto documentation
if "%1"=="/h" goto documentation
goto parseopts
:documentation
@@ -95,12 +95,12 @@ for /d %%d in ("%originPath%..\lib\*.") do (
SETLOCAL disabledelayedexpansion
:run
IF NOT %runMode% == "iex" (
set beforeExtra=-noshell -s elixir start_cli %beforeExtra%
set beforeExtra=-s elixir start_cli %beforeExtra%
)
IF %useWerl% EQU 1 (
start werl.exe %ext_libs% %ELIXIR_ERL_OPTIONS% %parsErlang% %beforeExtra% -extra %*
) ELSE (
erl.exe %ext_libs% %ELIXIR_ERL_OPTIONS% %parsErlang% %beforeExtra% -extra %*
erl.exe %ext_libs% -noshell %ELIXIR_ERL_OPTIONS% %parsErlang% %beforeExtra% -extra %*
)
:end
endlocal
+2 -2
View File
@@ -20,7 +20,7 @@ echo --warnings-as-errors Treat warnings as errors and return non-zero exit cod
echo --verbose Print informational messages.
echo.
echo ** Options given after -- are passed down to the executed code
echo ** Options can be passed to the Erlang runtime using ELIXIR_ERL_OPTIONS
echo ** Options can be passed to the Erlang compiler using ERL_COMPILER_OPTIONS >&2
echo ** Options can be passed to the erlang runtime using ELIXIR_ERL_OPTIONS
echo ** Options can be passed to the erlang compiler using ERL_COMPILER_OPTIONS >&2
:run
call "%~dp0\elixir.bat" +elixirc %*
+4 -3
View File
@@ -10,12 +10,11 @@ if [ $# -gt 0 ] && ([ "$1" = "--help" ] || [ "$1" = "-h" ]); then
-pa \"path\" Prepends the given path to Erlang code path (*)
-pz \"path\" Appends the given path to Erlang code path (*)
--app \"app\" Start the given app and its dependencies (*)
--erl \"switches\" Switches to be passed down to Erlang (*)
--erl \"switches\" Switches to be passed down to erlang (*)
--name \"name\" Makes and assigns a name to the distributed node
--sname \"name\" Makes and assigns a short name to the distributed node
--cookie \"cookie\" Sets a cookie for this distributed node
--hidden Makes a hidden node
--werl Uses Erlang's Windows shell GUI (Windows only)
--detached Starts the Erlang VM detached from console
--remsh \"name\" Connects to a node using a remote shell
--dot-iex \"path\" Overrides default .iex.exs file and uses path instead;
@@ -39,4 +38,6 @@ readlink_f () {
SELF=$(readlink_f "$0")
SCRIPT_PATH=$(dirname "$SELF")
exec "$SCRIPT_PATH"/elixir --no-halt --erl "-user Elixir.IEx.CLI" +iex "$@"
if [ "$OS" = "Windows_NT" ]; then NOSHELL="-noshell "; fi
exec "$SCRIPT_PATH"/elixir --no-halt --erl "$NOSHELL -user Elixir.IEx.CLI" +iex "$@"
+1
View File
@@ -1,3 +1,4 @@
#!/usr/bin/env elixir
# Reminder: apply any changes in this file to bin\mix.bat
Mix.start
Mix.CLI.main
+9 -9
View File
@@ -62,9 +62,9 @@ defmodule EEx do
All expressions that output something to the template
**must** use the equals sign (`=`). Since everything in
Elixir is an expression, there are no exceptions for this rule.
For example, while some template languages would special-case
`if` clauses, they are treated the same in EEx and
Elixir is a macro, there are no exceptions for this rule.
For example, while some template languages would special-
case `if` clauses, they are treated the same in EEx and
also require `=` in order to have their result printed:
<%= if true do %>
@@ -162,7 +162,7 @@ defmodule EEx do
end
@doc """
Gets a string `source` and generate a quoted expression
Get a string `source` and generate a quoted expression
that can be evaluated by Elixir or compiled to a function.
"""
def compile_string(source, options \\ []) do
@@ -170,7 +170,7 @@ defmodule EEx do
end
@doc """
Gets a `filename` and generate a quoted expression
Get a `filename` and generate a quoted expression
that can be evaluated by Elixir or compiled to a function.
"""
def compile_file(filename, options \\ []) do
@@ -179,7 +179,7 @@ defmodule EEx do
end
@doc """
Gets a string `source` and evaluate the values using the `bindings`.
Get a string `source` and evaluate the values using the `bindings`.
## Examples
@@ -193,15 +193,15 @@ defmodule EEx do
end
@doc """
Gets a `filename` and evaluate the values using the `bindings`.
Get a `filename` and evaluate the values using the `bindings`.
## Examples
# sample.eex
# sample.ex
foo <%= bar %>
# iex
EEx.eval_file "sample.eex", [bar: "baz"] #=> "foo baz"
EEx.eval_file "sample.ex", [bar: "baz"] #=> "foo baz"
"""
def eval_file(filename, bindings \\ [], options \\ []) do
+3 -4
View File
@@ -12,8 +12,7 @@ defmodule EEx.Compiler do
def compile(source, opts) do
file = opts[:file] || "nofile"
line = opts[:line] || 1
trim = opts[:trim] || false
case EEx.Tokenizer.tokenize(source, line, trim: trim) do
case EEx.Tokenizer.tokenize(source, line) do
{:ok, tokens} ->
state = %{engine: opts[:engine] || @default_engine,
file: file, line: line, quoted: [], start_line: nil}
@@ -32,7 +31,7 @@ defmodule EEx.Compiler do
defp generate_buffer([{:expr, line, mark, chars}|t], buffer, scope, state) do
expr = Code.string_to_quoted!(chars, [line: line, file: state.file])
buffer = state.engine.handle_expr(buffer, IO.chardata_to_string(mark), expr)
buffer = state.engine.handle_expr(buffer, mark, expr)
generate_buffer(t, buffer, scope, state)
end
@@ -40,7 +39,7 @@ defmodule EEx.Compiler do
{contents, line, t} = look_ahead_text(t, start_line, chars)
{contents, t} = generate_buffer(t, "", [contents|scope],
%{state | quoted: [], line: line, start_line: start_line})
buffer = state.engine.handle_expr(buffer, IO.chardata_to_string(mark), contents)
buffer = state.engine.handle_expr(buffer, mark, contents)
generate_buffer(t, buffer, scope, state)
end
+10 -8
View File
@@ -25,9 +25,11 @@ defmodule EEx.Engine do
default implementations for the functions above.
"""
@callback handle_body(Macro.t) :: Macro.t
@callback handle_text(Macro.t, String.t) :: Macro.t
@callback handle_expr(Macro.t, String.t, Macro.t) :: Macro.t
use Behaviour
defcallback handle_body(Macro.t) :: Macro.t
defcallback handle_text(Macro.t, binary) :: Macro.t
defcallback handle_expr(Macro.t, binary, Macro.t) :: Macro.t
@doc false
defmacro __using__(_) do
@@ -42,8 +44,8 @@ defmodule EEx.Engine do
EEx.Engine.handle_text(buffer, text)
end
def handle_expr(buffer, marker, expr) do
EEx.Engine.handle_expr(buffer, marker, expr)
def handle_expr(buffer, mark, expr) do
EEx.Engine.handle_expr(buffer, mark, expr)
end
defoverridable [handle_body: 1, handle_expr: 3, handle_text: 2]
@@ -54,7 +56,7 @@ defmodule EEx.Engine do
Handles assigns in quoted expressions.
This can be added to any custom engine by invoking
`handle_assign/1` with `Macro.prewalk/2`:
`handle_assign/3` with `Macro.prewalk/1`:
def handle_expr(buffer, token, expr) do
expr = Macro.prewalk(expr, &EEx.Engine.handle_assign/1)
@@ -72,7 +74,8 @@ defmodule EEx.Engine do
end
@doc """
The default implementation simply returns the given expression.
The default implementation implementation simply returns the
given expression.
"""
def handle_body(quoted) do
quoted
@@ -93,7 +96,6 @@ defmodule EEx.Engine do
All other markers are not implemented by this engine.
"""
@spec handle_expr(Macro.t, String.t, Macro.t) :: Macro.t
def handle_expr(buffer, "=", expr) do
quote do
tmp1 = unquote(buffer)
+3 -3
View File
@@ -11,9 +11,9 @@ defmodule EEx.SmartEngine do
"1"
In the example above, we can access the value `foo` under
the binding `assigns` using `@foo`. This is useful because
a template, after being compiled, can receive different
assigns and would not require recompilation for each
the binding `assigns` using `@foo`. This is useful when
a template, after compiled, may receive different assigns
and the developer don't want to recompile it for each
variable set.
Assigns can also be used when compiled to a function:
+30 -73
View File
@@ -14,63 +14,63 @@ defmodule EEx.Tokenizer do
Or `{:error, line, error}` in case of errors.
"""
def tokenize(bin, line, opts \\ [])
def tokenize(bin, line, opts) when is_binary(bin) do
tokenize(String.to_char_list(bin), line, opts)
def tokenize(bin, line) when is_binary(bin) do
tokenize(String.to_char_list(bin), line)
end
def tokenize(list, line, opts) do
tokenize(list, line, opts, [], [])
def tokenize(list, line) do
tokenize(list, line, [], [])
end
defp tokenize('<%%' ++ t, line, opts, buffer, acc) do
tokenize t, line, opts, [?%, ?<|buffer], acc
end
defp tokenize('<%#' ++ t, line, opts, buffer, acc) do
case expr(t, line, []) do
defp tokenize('<%%' ++ t, line, buffer, acc) do
case expr(t, line, [?%, ?<|buffer]) do
{:error, _, _} = error -> error
{:ok, _, new_line, rest} ->
{rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
tokenize rest, new_line, opts, buffer, acc
{:ok, buffer, new_line, rest} ->
tokenize rest, new_line, [?>, ?%|buffer], acc
end
end
defp tokenize('<%' ++ t, line, opts, buffer, acc) do
defp tokenize('<%#' ++ t, line, buffer, acc) do
case expr(t, line, []) do
{:error, _, _} = error -> error
{:ok, _, new_line, rest} ->
tokenize rest, new_line, buffer, acc
end
end
defp tokenize('<%' ++ t, line, buffer, acc) do
{marker, t} = retrieve_marker(t)
case expr(t, line, []) do
{:error, _, _} = error -> error
{:ok, expr, new_line, rest} ->
token = token_name(expr)
{rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
acc = tokenize_text(buffer, acc)
final = {token, line, marker, Enum.reverse(expr)}
tokenize rest, new_line, opts, [], [final | acc]
tokenize rest, new_line, [], [final | acc]
end
end
defp tokenize('\n' ++ t, line, opts, buffer, acc) do
tokenize t, line + 1, opts, [?\n|buffer], acc
defp tokenize('\n' ++ t, line, buffer, acc) do
tokenize t, line + 1, [?\n|buffer], acc
end
defp tokenize([h|t], line, opts, buffer, acc) do
tokenize t, line, opts, [h|buffer], acc
defp tokenize([h|t], line, buffer, acc) do
tokenize t, line, [h|buffer], acc
end
defp tokenize([], _line, _opts, buffer, acc) do
defp tokenize([], _line, buffer, acc) do
{:ok, Enum.reverse(tokenize_text(buffer, acc))}
end
# Retrieve marker for <%
defp retrieve_marker('=' ++ t) do
{'=', t}
{"=", t}
end
defp retrieve_marker(t) do
{'', t}
{"", t}
end
# Tokenize an expression until we find %>
@@ -94,11 +94,11 @@ defmodule EEx.Tokenizer do
# Receive an expression content and check
# if it is a start, middle or an end token.
#
# Start tokens finish with "do" and "fn ->"
# Middle tokens are marked with "->" or keywords
# End tokens contain only the end word and optionally ")"
# Start tokens finish with `do` and `fn ->`
# Middle tokens are marked with `->` or keywords
# End tokens contain only the end word
defp token_name([h|t]) when h in [?\s, ?\t, ?)] do
defp token_name([h|t]) when h in [?\s, ?\t] do
token_name(t)
end
@@ -115,7 +115,7 @@ defmodule EEx.Tokenizer do
# token and, if so, it is not followed by an "end"
# token. If this is the case, we are on a start expr.
case :elixir_tokenizer.tokenize(rest, 1, file: "eex", check_terminators: false) do
{:ok, _line, _column, tokens} ->
{:ok, _line, tokens} ->
tokens = Enum.reverse(tokens)
fn_index = fn_index(tokens)
@@ -169,47 +169,4 @@ defmodule EEx.Tokenizer do
defp tokenize_text(buffer, acc) do
[{:text, Enum.reverse(buffer)} | acc]
end
# If trim mode is enabled and the token is on a line with
# only itself and whitespace, trim the whitespace around it,
# including the line break following it if there is one.
defp trim_if_needed(rest, line, opts, buffer, acc) do
original = {rest, line, buffer}
if opts[:trim] do
case {trim_left(buffer, acc), trim_right(rest, line)} do
{{true, new_buffer}, {true, new_rest, new_line}} ->
{new_rest, new_line, new_buffer}
_ ->
original
end
else
original
end
end
defp trim_left(buffer, acc) do
case {trim_whitespace(buffer), acc} do
{[?\n|_] = trimmed_buffer, _} -> {true, trimmed_buffer}
{[], []} -> {true, []}
_ -> {false, buffer}
end
end
defp trim_right(rest, line) do
case trim_whitespace(rest) do
[?\r, ?\n|trimmed_rest] -> {true, trimmed_rest, line + 1}
[?\n|trimmed_rest] -> {true, trimmed_rest, line + 1}
[] -> {true, [], line}
_ -> {false, rest, line}
end
end
defp trim_whitespace([h|t]) when h == ?\s or h == ?\t do
trim_whitespace(t)
end
defp trim_whitespace(list) do
list
end
end
+14 -70
View File
@@ -14,17 +14,17 @@ defmodule EEx.TokenizerTest do
test "strings with embedded code" do
assert T.tokenize('foo <% bar %>', 1) ==
{:ok, [{:text, 'foo '}, {:expr, 1, '', ' bar '}]}
{:ok, [{:text, 'foo '}, {:expr, 1, "", ' bar '}]}
end
test "strings with embedded equals code" do
assert T.tokenize('foo <%= bar %>', 1) ==
{:ok, [{:text, 'foo '}, {:expr, 1, '=', ' bar '}]}
{:ok, [{:text, 'foo '}, {:expr, 1, "=", ' bar '}]}
end
test "strings with more than one line" do
assert T.tokenize('foo\n<%= bar %>', 1) ==
{:ok, [{:text, 'foo\n'}, {:expr, 2, '=', ' bar '}]}
{:ok, [{:text, 'foo\n'}, {:expr, 2, "=", ' bar '}]}
end
test "strings with more than one line and expression with more than one line" do
@@ -37,9 +37,9 @@ baz %>
assert T.tokenize(string, 1) == {:ok, [
{:text, 'foo '},
{:expr, 1, '=', ' bar\n\nbaz '},
{:expr, 1, "=", ' bar\n\nbaz '},
{:text, '\n'},
{:expr, 4, '', ' foo '},
{:expr, 4, "", ' foo '},
{:text, '\n'}
]}
end
@@ -56,20 +56,6 @@ baz %>
]}
end
test "quotation with interpolation" do
assert T.tokenize('a <%% b <%= c %> <%= d %> e %> f', 1) == {:ok, [
{:text, 'a <% b '},
{:expr, 1, '=', ' c '},
{:text, ' '},
{:expr, 1, '=', ' d '},
{:text, ' e %> f'}
]}
assert T.tokenize('<%%% a <%%= b %> c %>', 1) == {:ok, [
{:text, '<%% a <%= b %> c %>'}
]}
end
test "comments" do
assert T.tokenize('foo <%# true %>', 1) == {:ok, [
{:text, 'foo '}
@@ -85,77 +71,35 @@ baz %>
test "strings with embedded do end" do
assert T.tokenize('foo <% if true do %>bar<% end %>', 1) == {:ok, [
{:text, 'foo '},
{:start_expr, 1, '', ' if true do '},
{:start_expr, 1, "", ' if true do '},
{:text, 'bar'},
{:end_expr, 1, '', ' end '}
{:end_expr, 1, "", ' end '}
]}
end
test "strings with embedded -> end" do
assert T.tokenize('foo <% cond do %><% false -> %>bar<% true -> %>baz<% end %>', 1) == {:ok, [
{:text, 'foo '},
{:start_expr, 1, '', ' cond do '},
{:middle_expr, 1, '', ' false -> '},
{:start_expr, 1, "", ' cond do '},
{:middle_expr, 1, "", ' false -> '},
{:text, 'bar'},
{:middle_expr, 1, '', ' true -> '},
{:middle_expr, 1, "", ' true -> '},
{:text, 'baz'},
{:end_expr, 1, '', ' end '}
{:end_expr, 1, "", ' end '}
]}
end
test "strings with embedded keywords blocks" do
assert T.tokenize('foo <% if true do %>bar<% else %>baz<% end %>', 1) == {:ok, [
{:text, 'foo '},
{:start_expr, 1, '', ' if true do '},
{:start_expr, 1, "", ' if true do '},
{:text, 'bar'},
{:middle_expr, 1, '', ' else '},
{:middle_expr, 1, "", ' else '},
{:text, 'baz'},
{:end_expr, 1, '', ' end '}
{:end_expr, 1, "", ' end '}
]}
end
test "trim mode" do
template = '\t<%= if true do %> \n TRUE \n <% else %>\n FALSE \n <% end %> '
assert T.tokenize(template, 1, trim: true) == {:ok, [
{:start_expr, 1, '=', ' if true do '},
{:text, ' TRUE \n'},
{:middle_expr, 3, '', ' else '},
{:text, ' FALSE \n'},
{:end_expr, 5, '', ' end '}
]}
end
test "trim mode with comment" do
assert T.tokenize(' <%# comment %> \n123', 1, trim: true) == {:ok, [
{:text, '123'}
]}
end
test "trim mode with CRLF" do
assert T.tokenize('0\r\n <%= 12 %> \r\n34', 1, trim: true) == {:ok, [
{:text, '0\r\n'},
{:expr, 2, '=', ' 12 '},
{:text, '34'}
]}
end
test "trim mode set to false" do
assert T.tokenize(' <%= 12 %> \n', 1, trim: false) == {:ok, [
{:text, ' '},
{:expr, 1, '=', ' 12 '},
{:text, ' \n'}
]}
end
test "trim mode no false positives" do
assert_not_trimmed = fn x -> assert T.tokenize(x, 1, trim: true) == T.tokenize(x, 1) end
assert_not_trimmed.('foo <%= "bar" %> ')
assert_not_trimmed.('\n <%= "foo" %>bar')
assert_not_trimmed.(' <%% hello %> ')
assert_not_trimmed.(' <%= 01 %><%= 23 %>\n')
end
test "raise syntax error when there is start mark and no end mark" do
assert T.tokenize('foo <% :bar', 1) == {:error, 1, "missing token '%>'"}
end
+2 -13
View File
@@ -98,10 +98,6 @@ defmodule EExTest do
assert_eval "foo baz", "foo <%= if true do %><%= if false do %>bar<% else %>baz<% end %><% end %>"
end
test "evaluates with parentheses after end in end token" do
assert_eval " 101 102 103 ", "<%= Enum.map([1,2,3], (fn x -> %> <%= 100 + x %> <% end) ) %>"
end
test "evaluates with defined variable" do
assert_eval "foo 1", "foo <% bar = 1 %><%= bar %>"
end
@@ -321,12 +317,6 @@ foo
assert result == " • • •\n Jößé Vâlìm Jößé Vâlìm\n"
end
test "trim mode" do
string = "<%= 123 %> \n456\n <%= 789 %>"
expected = "123456\n789"
assert_eval expected, string, [], trim: true
end
test "evaluates the source from a given file" do
filename = Path.join(__DIR__, "fixtures/eex_template.eex")
result = EEx.eval_file(filename)
@@ -409,9 +399,8 @@ foo
assert {:wrapped, "foo"} = EEx.eval_string("foo", [], engine: TestEngine)
end
defp assert_eval(expected, actual, binding \\ [], opts \\ []) do
opts = Enum.into [file: __ENV__.file, engine: EEx.Engine], opts
result = EEx.eval_string(actual, binding, opts)
defp assert_eval(expected, actual, binding \\ []) do
result = EEx.eval_string(actual, binding, file: __ENV__.file, engine: EEx.Engine)
assert result == expected
end
end
+92 -91
View File
@@ -1,15 +1,15 @@
defmodule Access do
defprotocol Access do
@moduledoc """
Dictionary-like access to data structures via the `foo[bar]` syntax.
The Access protocol is used by `foo[bar]` and also
empowers the nested update functions in Kernel.
This module also empowers `Kernel`s nested update functions
For instance, `foo[bar]` translates `Access.get(foo, bar)`.
`Kernel.get_in/2`, `Kernel.put_in/3`, `Kernel.update_in/3` and
`Kernel.get_and_update_in/3`.
`Kernel.get_and_update_in/3` are also all powered by the Access
protocol.
## Examples
Out of the box, Access works with built-in dictionaries: `Keyword`
and `Map`:
This protocol is implemented by default for keywords, maps
and dictionary like types:
iex> keywords = [a: 1, b: 2]
iex> keywords[:a]
@@ -23,113 +23,88 @@ defmodule Access do
iex> star_ratings[1.5]
"★☆"
Furthermore, Access transparently ignores `nil` values:
iex> keywords = [a: 1, b: 2]
iex> keywords[:c][:unknown]
nil
The key comparison must be implemented using the `===` operator.
"""
@type t :: list | map | nil
@type key :: any
@type value :: any
@callback fetch(t, key) :: {:ok, value} | :error
@callback get_and_update(t, key, (value -> {value, value})) :: {value, t}
@doc """
Fetches the container's value for the given key.
Accesses the given key in the container.
"""
@spec fetch(t, term) :: {:ok, term} | :error
def fetch(container, key)
def fetch(%{__struct__: struct} = container, key) do
struct.fetch(container, key)
end
def fetch(%{} = map, key) do
:maps.find(key, map)
end
def fetch(list, key) when is_list(list) do
case :lists.keyfind(key, 1, list) do
{^key, value} -> {:ok, value}
false -> :error
end
end
def fetch(nil, _key) do
:error
end
@spec get(t, term) :: t
def get(container, key)
@doc """
Gets the container's value for the given key.
"""
@spec get(t, term, term) :: term
def get(container, key, default \\ nil) do
case fetch(container, key) do
{:ok, value} -> value
:error -> default
end
end
Gets a value and updates the given `key` in one pass.
@doc """
Gets and updates the container's value for the given key, in a single pass.
The argument function `fun` must receive the value for the given `key` (or
`nil` if the key doesn't exist in `container`). It must return a tuple
containing the `get` value and the new value to be stored in the `container`.
This function returns a two-element tuple.
The first element is the `get` value, as returned by `fun`.
The second element is the container, updated with the value returned by `fun`.
The function must receive the value for the given `key`
(or `nil` if the key doesn't exist in `container`) and
the function must return a tuple containing the `get`
value and the new value to be stored in the `container`.
"""
@spec get_and_update(t, term, (term -> {get, term})) :: {get, t} when get: var
def get_and_update(container, key, fun)
end
def get_and_update(%{__struct__: struct} = container, key, fun) do
struct.get_and_update(container, key, fun)
end
def get_and_update(%{} = map, key, fun) do
current_value = case :maps.find(key, map) do
{:ok, value} -> value
:error -> nil
defimpl Access, for: List do
def get(dict, key) when is_atom(key) do
case :lists.keyfind(key, 1, dict) do
{^key, value} -> value
false -> nil
end
{get, update} = fun.(current_value)
{get, :maps.put(key, update, map)}
end
def get_and_update(list, key, fun) when is_list(list) do
Keyword.get_and_update(list, key, fun)
end
def get_and_update(nil, key, _fun) do
def get(_dict, key) do
raise ArgumentError,
"could not put/update key #{inspect key} on a nil value"
"the access protocol for lists expect the key to be an atom, got: #{inspect key}"
end
def get_and_update(dict, key, fun) when is_atom(key) do
get_and_update(dict, [], key, fun)
end
defp get_and_update([{key, value}|t], acc, key, fun) do
{get, update} = fun.(value)
{get, :lists.reverse(acc, [{key, update}|t])}
end
defp get_and_update([h|t], acc, key, fun) do
get_and_update(t, [h|acc], key, fun)
end
defp get_and_update([], acc, key, fun) do
{get, update} = fun.(nil)
{get, [{key, update}|:lists.reverse(acc)]}
end
end
# Callbacks invoked when inlining code for *_in in Kernel.
# TODO: Remove me on 1.2
defmodule Access.Map do
@moduledoc false
def update!(%{} = map, key, fun) do
defimpl Access, for: Map do
def get(map, key) do
case :maps.find(key, map) do
{:ok, value} ->
:maps.put(key, fun.(value), map)
:error ->
raise KeyError, key: key, term: map
{:ok, value} -> value
:error -> nil
end
end
def update!(other, key, _fun) do
def get_and_update(map, key, fun) do
value =
case :maps.find(key, map) do
{:ok, value} -> value
:error -> nil
end
{get, update} = fun.(value)
{get, :maps.put(key, update, map)}
end
def get!(%{} = map, key) do
case :maps.find(key, map) do
{:ok, value} -> value
:error -> raise KeyError, key: key, term: map
end
end
def get!(other, key) do
raise ArgumentError,
"could not put/update key #{inspect key}. Expected map/struct, got: #{inspect other}"
"could not get key #{inspect key}. Expected map/struct, got: #{inspect other}"
end
def get_and_update!(%{} = map, key, fun) do
@@ -147,3 +122,29 @@ defmodule Access.Map do
"could not put/update key #{inspect key}. Expected map/struct, got: #{inspect other}"
end
end
defimpl Access, for: Atom do
def get(nil, _) do
nil
end
def get(atom, _) do
undefined(atom)
end
def get_and_update(nil, key, _fun) do
raise ArgumentError,
"could not put/update key #{inspect key} on a nil value"
end
def get_and_update(atom, _key, _fun) do
undefined(atom)
end
defp undefined(atom) do
raise Protocol.UndefinedError,
protocol: @protocol,
value: atom,
description: "only the nil atom is supported"
end
end
+11 -18
View File
@@ -33,13 +33,6 @@ defmodule Agent do
item = {task, project}
Agent.update(__MODULE__, &Set.put(&1, item))
end
@doc "Resets the executed tasks and return the previous list of tasks"
def take_all() do
Agent.get_and_update(__MODULE__, fn set ->
{Enum.into(set, []), HashSet.new}
end)
end
end
Note that agents still provide a segregation between the
@@ -61,11 +54,11 @@ defmodule Agent do
Agent.get(agent, &(&1)) |> do_something_expensive()
end
The first function blocks the agent. The second function copies
all the state to the client and then executes the operation in the
client. The difference is whether the data is large enough to require
processing in the server, at least initially, or small enough to be
sent to the client cheaply.
The first one blocks the agent while the second one copies
all the state to the client and executes the operation in the client.
The trade-off here is exactly if the data is small enough to be
sent to the client cheaply or large enough to require processing on
the server (or at least some initial processing).
## Name Registration
@@ -75,8 +68,8 @@ defmodule Agent do
## A word on distributed agents
It is important to consider the limitations of distributed agents. Agents
provide two APIs, one that works with anonymous functions and another
that expects an explicit module, function, and arguments.
provides two APIs, one that works with anonymous functions and another
that expects explicit module, function and arguments.
In a distributed setup with multiple nodes, the API that accepts anonymous
functions only works if the caller (client) and the agent have the same
@@ -89,13 +82,13 @@ defmodule Agent do
In this setup, part of your environment will have one version of a given
module and the other part another version (the newer one) of the same module.
The best solution is to simply use the explicit module, function, and arguments
The best solution is to simply use the explicit module, function and arguments
APIs when working with distributed agents.
## Hot code swapping
An agent can have its code hot swapped live by simply passing a module,
function, and args tuple to the update instruction. For example, imagine
function and args tuple to the update instruction. For example, imagine
you have an agent named `:sample` and you want to convert its inner state
from some dict structure to a map. It can be done with the following
instruction:
@@ -144,8 +137,8 @@ defmodule Agent do
## Return values
If the server is successfully created and initialized, the function returns
`{:ok, pid}`, where `pid` is the pid of the server. If an agent with the
specified name already exists, the function returns
`{:ok, pid}`, where `pid` is the pid of the server. If there already exists
an agent with the specified name, the function returns
`{:error, {:already_started, pid}}` with the pid of that process.
If the given function callback fails with `reason`, the function returns
+2 -20
View File
@@ -4,7 +4,6 @@ defmodule Agent.Server do
use GenServer
def init(fun) do
_ = initial_call(fun)
{:ok, run(fun, [])}
end
@@ -13,10 +12,8 @@ defmodule Agent.Server do
end
def handle_call({:get_and_update, fun}, _from, state) do
case run(fun, [state]) do
{reply, state} -> {:reply, reply, state}
other -> {:stop, {:bad_return_value, other}, state}
end
{reply, state} = run(fun, [state])
{:reply, reply, state}
end
def handle_call({:update, fun}, _from, state) do
@@ -54,21 +51,6 @@ defmodule Agent.Server do
:ok
end
defp initial_call(mfa) do
_ = Process.put(:"$initial_call", get_initial_call(mfa))
:ok
end
defp get_initial_call(fun) when is_function(fun, 0) do
{:module, module} = :erlang.fun_info(fun, :module)
{:name, name} = :erlang.fun_info(fun, :name)
{module, name, 0}
end
defp get_initial_call({mod, fun, args}) do
{mod, fun, length(args)}
end
defp run({m, f, a}, extra), do: apply(m, f, extra ++ a)
defp run(fun, extra), do: apply(fun, extra)
end
+35 -64
View File
@@ -4,29 +4,29 @@ defmodule Application do
In Elixir (actually, in Erlang/OTP), an application is a component
implementing some specific functionality, that can be started and stopped
as a unit, and which can be re-used in other systems.
as a unit, and which can be re-used in other systems as well.
Applications are defined with an application file named `APP.app` where
`APP` is the application name, usually in `underscore_case`. The application
file must reside in the same `ebin` directory as the compiled modules of the
application.
`APP` is the APP name, usually in `underscore_case` convention. The
application file must reside in the same `ebin` directory as the
application's modules bytecode.
In Elixir, Mix is responsible for compiling your source code and
generating your application `.app` file. Furthermore, Mix is also
responsible for configuring, starting and stopping your application
and its dependencies. For this reason, this documentation will focus
on the remaining aspects of your application: the application environment
on the remaining aspects of your application: the application environment,
and the application callback module.
You can learn more about Mix generation of `.app` files by typing
You can learn more about Mix compilation of `.app` files by typing
`mix help compile.app`.
## Application environment
Once an application is started, OTP provides an application environment
that can be used to configure the application.
that can be used to configure applications.
Assuming you are inside a Mix project, you can edit the `application`
Assuming you are inside a Mix project, you can edit your application
function in the `mix.exs` file to the following:
def application do
@@ -38,18 +38,18 @@ defmodule Application do
can access the default value:
Application.get_env(:APP_NAME, :hello)
#=> :world
#=> {:ok, :hello}
It is also possible to put and delete values from the application value,
including new values that are not defined in the environment file (although
this should be avoided).
those should be avoided).
In the future, we plan to support configuration files which allow
In the future, we plan to support configuration files which allows
developers to configure the environment of their dependencies.
Keep in mind that each application is responsible for its environment.
Do not use the functions in this module for directly accessing or modifying
the environment of other applications (as it may lead to inconsistent
Do not use the functions in this module for directly access or modify
the environment of other application (as it may lead to inconsistent
data in the application environment).
## Application module callback
@@ -64,8 +64,8 @@ defmodule Application do
end
Our application now requires the `MyApp` module to provide an application
callback. This can be done by invoking `use Application` in that module and
defining a `start/2` callback, for example:
callback. This can be done by invoking `use Application` in that module
and defining a `start/2` callback, for example:
defmodule MyApp do
use Application
@@ -75,22 +75,21 @@ defmodule Application do
end
end
`start/2` typically returns `{:ok, pid}` or `{:ok, pid, state}` where
`pid` identifies the supervision tree and `state` is the application state.
`args` is the second element of the tuple given to the `:mod` option.
`start/2` most commonly returns `{:ok, pid}` or `{:ok, pid, state}` where
`pid` identifies the supervision tree and the state is the application state.
`args` is second element of the tuple given to the `:mod` option.
The `type` argument passed to `start/2` is usually `:normal` unless in a
distributed setup where application takeovers and failovers are configured.
This particular aspect of applications is explained in more detail in the
OTP documentation:
The `type` passed into `start/2` is usually `:normal` unless in a distributed
setup where applications takeover and failovers are configured. This particular
aspect of applications can be read with more detail in the OTP documentation:
* [`:application` module](http://www.erlang.org/doc/man/application.html)
* [Applications – OTP Design Principles](http://www.erlang.org/doc/design_principles/applications.html)
* http://www.erlang.org/doc/man/application.html
* http://www.erlang.org/doc/design_principles/applications.html
A developer may also implement the `stop/1` callback (automatically defined
by `use Application`) which does any application cleanup. It receives the
application state and can return any value. Note that shutting down the
supervisor is automatically handled by the VM.
application state and can return any value. Notice that shutting down the
supervisor is automatically handled by the VM;
"""
@doc false
@@ -115,7 +114,7 @@ defmodule Application do
@doc """
Returns all key-value pairs for `app`.
"""
@spec get_all_env(app) :: [{key, value}]
@spec get_all_env(app) :: [{key,value}]
def get_all_env(app) do
:application.get_all_env(app)
end
@@ -123,18 +122,22 @@ defmodule Application do
@doc """
Returns the value for `key` in `app`'s environment.
If the configuration parameter does not exist, the function returns the
`default` value.
If the specified application is not loaded, or the configuration parameter
does not exist, the function returns the `default` value.
"""
@spec get_env(app, key, value) :: value
def get_env(app, key, default \\ nil) do
:application.get_env(app, key, default)
case :application.get_env(app, key) do
{:ok, value} -> value
:undefined -> default
end
end
@doc """
Returns the value for `key` in `app`'s environment in a tuple.
If the configuration parameter does not exist, the function returns `:error`.
If the specified application is not loaded, or the configuration parameter
does not exist, the function returns `:error`.
"""
@spec fetch_env(app, key) :: {:ok, value} | :error
def fetch_env(app, key) do
@@ -144,22 +147,6 @@ defmodule Application do
end
end
@doc """
Returns the value for `key` in `app`'s environment.
If the configuration parameter does not exist, raises `ArgumentError`.
"""
@spec fetch_env!(app, key) :: value | no_return
def fetch_env!(app, key) do
case fetch_env(app, key) do
{:ok, value} -> value
:error ->
raise ArgumentError,
"application #{inspect app} is not loaded, " <>
"or the configuration parameter #{inspect key} is not set"
end
end
@doc """
Puts the `value` in `key` for the given `app`.
@@ -172,7 +159,7 @@ defmodule Application do
environment values specified in the `.app` file will override the ones
previously set.
The persistent option can be set to `true` when there is a need to guarantee
The persistent option can be set to true when there is a need to guarantee
parameters set with this function will not be overridden by the ones defined
in the application resource file on load. This means persistent values will
stick after the application is loaded and also on application reload.
@@ -333,22 +320,6 @@ defmodule Application do
Path.join(app_dir(app), path)
end
@doc """
Returns a list with information about the applications which are currently running.
"""
@spec started_applications(timeout) :: [tuple]
def started_applications(timeout \\ 5000) do
:application.which_applications(timeout)
end
@doc """
Returns a list with information about the applications which have been loaded.
"""
@spec loaded_applications :: [tuple]
def loaded_applications do
:application.loaded_applications
end
@doc """
Formats the error reason returned by `start/2`,
`ensure_started/2`, `stop/1`, `load/1` and `unload/1`,
+2 -16
View File
@@ -1,20 +1,12 @@
defmodule Atom do
@moduledoc """
@doc """
Convenience functions for working with atoms.
See also `Kernel.is_atom/1`.
"""
@doc """
Converts an atom to a string.
Converts an atom to string.
Inlined by the compiler.
## Examples
iex> Atom.to_string(:foo)
"foo"
"""
@spec to_string(atom) :: String.t
def to_string(atom) do
@@ -25,12 +17,6 @@ defmodule Atom do
Converts an atom to a char list.
Inlined by the compiler.
## Examples
iex> Atom.to_char_list(:"An atom")
'An atom'
"""
@spec to_char_list(atom) :: char_list
def to_char_list(atom) do
+3 -3
View File
@@ -276,7 +276,7 @@ defmodule Base do
## Examples
iex> Base.url_encode64(<<255, 127, 254, 252>>)
iex> Base.url_encode64(<<255,127,254,252>>)
"_3_-_A=="
"""
@@ -292,7 +292,7 @@ defmodule Base do
## Examples
iex> Base.url_decode64("_3_-_A==")
{:ok, <<255, 127, 254, 252>>}
{:ok, <<255,127,254,252>>}
"""
@spec url_decode64(binary) :: {:ok, binary} | :error
@@ -312,7 +312,7 @@ defmodule Base do
## Examples
iex> Base.url_decode64!("_3_-_A==")
<<255, 127, 254, 252>>
<<255,127,254,252>>
"""
@spec url_decode64!(binary) :: binary
+85 -33
View File
@@ -1,27 +1,60 @@
defmodule Behaviour do
@moduledoc """
This module has been deprecated.
Utilities for defining behaviour interfaces.
Instead of `defcallback`, one can simply use `@callback`.
Instead of `defmacrocallback`, one can simply use `@macrocallback`.
Instead of `__behaviour__(:callbacks)`, one can simply use `behaviour_info(:callbacks)`.
Behaviours can be referenced by other modules
to ensure they implement required callbacks.
For example, you can specify the `URI.Parser`
behaviour as follows:
defmodule URI.Parser do
use Behaviour
@doc "Parses the given URL"
defcallback parse(uri_info :: URI.t) :: URI.t
@doc "Defines a default port"
defcallback default_port() :: integer
end
And then a module may use it as:
defmodule URI.HTTP do
@behaviour URI.Parser
def default_port(), do: 80
def parse(info), do: info
end
If the behaviour changes or `URI.HTTP` does
not implement one of the callbacks, a warning
will be raised.
## Implementation
Since Erlang R15, behaviours must be defined via
`@callback` attributes. `defcallback` is a simple
mechanism that defines the `@callback` attribute
according to the given type specification. `defcallback` allows
documentation to be created for the callback and defines
a custom function signature.
The callbacks and their documentation can be retrieved
via the `__behaviour__` callback function.
"""
# TODO: Deprecate by 1.2
# TODO: Remove by 2.0
@doc """
Defines a function callback according to the given type specification.
Define a function callback according to the given type specification.
"""
defmacro defcallback(spec) do
do_defcallback(:def, split_spec(spec, quote(do: term)))
do_defcallback(split_spec(spec, quote(do: term)), __CALLER__)
end
@doc """
Defines a macro callback according to the given type specification.
Define a macro callback according to the given type specification.
"""
defmacro defmacrocallback(spec) do
do_defcallback(:defmacro, split_spec(spec, quote(do: Macro.t)))
do_defmacrocallback(split_spec(spec, quote(do: Macro.t)), __CALLER__)
end
defp split_spec({:when, _, [{:::, _, [spec, return]}, guard]}, _default) do
@@ -40,17 +73,27 @@ defmodule Behaviour do
{spec, default, []}
end
defp do_defcallback(kind, {spec, return, guards}) do
defp do_defcallback({spec, return, guards}, caller) do
case Macro.decompose_call(spec) do
{name, args} ->
do_callback(kind, name, args, return, guards)
do_callback(:def, name, args, name, length(args), args, return, guards, caller)
_ ->
raise ArgumentError, "invalid syntax in #{kind}callback #{Macro.to_string(spec)}"
raise ArgumentError, "invalid syntax in defcallback #{Macro.to_string(spec)}"
end
end
defp do_callback(kind, name, args, return, guards) do
:lists.foreach fn
defp do_defmacrocallback({spec, return, guards}, caller) do
case Macro.decompose_call(spec) do
{name, args} ->
do_callback(:defmacro, :"MACRO-#{name}", [quote(do: env :: Macro.Env.t)|args],
name, length(args), args, return, guards, caller)
_ ->
raise ArgumentError, "invalid syntax in defmacrocallback #{Macro.to_string(spec)}"
end
end
defp do_callback(kind, name, args, docs_name, docs_arity, _docs_args, return, guards, caller) do
Enum.each args, fn
{:::, _, [left, right]} ->
ensure_not_default(left)
ensure_not_default(right)
@@ -58,16 +101,12 @@ defmodule Behaviour do
other ->
ensure_not_default(other)
other
end, args
end
spec =
quote do
unquote(name)(unquote_splicing(args)) :: unquote(return) when unquote(guards)
end
case kind do
:def -> quote(do: @callback unquote(spec))
:defmacro -> quote(do: @macrocallback unquote(spec))
quote do
@callback unquote(name)(unquote_splicing(args)) :: unquote(return) when unquote(guards)
Behaviour.store_docs(__MODULE__, unquote(caller.line), unquote(kind),
unquote(docs_name), unquote(docs_arity))
end
end
@@ -77,8 +116,28 @@ defmodule Behaviour do
defp ensure_not_default(_), do: :ok
@doc false
def store_docs(module, line, kind, name, arity) do
doc = Module.get_attribute module, :doc
Module.delete_attribute module, :doc
Module.put_attribute module, :behaviour_docs, {{name, arity}, line, kind, doc}
end
@doc false
defmacro __using__(_) do
quote do
Module.register_attribute(__MODULE__, :behaviour_docs, accumulate: true)
@before_compile unquote(__MODULE__)
import unquote(__MODULE__)
end
end
@doc false
defmacro __before_compile__(env) do
docs = if Code.compiler_options[:docs] do
Enum.reverse Module.get_attribute(env.module, :behaviour_docs)
end
quote do
@doc false
def __behaviour__(:callbacks) do
@@ -86,15 +145,8 @@ defmodule Behaviour do
end
def __behaviour__(:docs) do
for {tuple, line, kind, docs} <- Code.get_docs(__MODULE__, :callback_docs) do
case kind do
:callback -> {tuple, line, :def, docs}
:macrocallback -> {tuple, line, :defmacro, docs}
end
end
unquote(Macro.escape(docs))
end
import unquote(__MODULE__)
end
end
end
+26 -104
View File
@@ -1,8 +1,10 @@
defmodule Bitwise do
@moduledoc """
This module provides macro-based operators that perform calculations
on (sets of) bits. In general, you should `use` the Bitwise module
as a whole:
This module provides macros and operators for bitwise operators.
These macros can be used in guards.
The easiest way to use is to simply import them into
your module:
iex> use Bitwise
iex> bnot 1
@@ -10,26 +12,22 @@ defmodule Bitwise do
iex> 1 &&& 1
1
When used, it accepts the following options:
* `:only_operators` - include only operators
* `:skip_operators` - skip operators
You can select to include only or skip operators by passing options:
iex> use Bitwise, only_operators: true
iex> 1 &&& 1
1
These macros can be used in guards:
iex> use Bitwise
iex> odd? = fn(int) when band(int, 1) == 1 -> true; (_) -> false end
iex> odd?.(1)
true
"""
@doc false
@doc """
Allow a developer to use this module in their programs with
the following options:
* `:only_operators` - include only operators
* `:skip_operators` - skip operators
"""
defmacro __using__(options) do
except = cond do
Keyword.get(options, :only_operators) ->
@@ -45,160 +43,84 @@ defmodule Bitwise do
end
@doc """
Calculates the bitwise NOT of its argument.
iex> bnot(2)
-3
iex> bnot(2) &&& 3
1
Bitwise not.
"""
defmacro bnot(expr) do
quote do: :erlang.bnot(unquote(expr))
end
@doc """
Prefix (unary) operator; calculates the bitwise NOT of its argument.
iex> ~~~2
-3
iex> ~~~2 &&& 3
1
Bitwise not as operator.
"""
defmacro ~~~expr do
quote do: :erlang.bnot(unquote(expr))
end
@doc """
Calculates the bitwise AND of its arguments.
iex> band(9, 3)
1
Bitwise and.
"""
defmacro band(left, right) do
quote do: :erlang.band(unquote(left), unquote(right))
end
@doc """
Infix operator; calculates the bitwise AND of its arguments.
iex> 9 &&& 3
1
Bitwise and as operator.
"""
defmacro left &&& right do
quote do: :erlang.band(unquote(left), unquote(right))
end
@doc """
Calculates the bitwise OR of its arguments.
iex> bor(9, 3)
11
Bitwise or.
"""
defmacro bor(left, right) do
quote do: :erlang.bor(unquote(left), unquote(right))
end
@doc """
Infix operator; calculates the bitwise OR of its arguments.
iex> 9 ||| 3
11
Bitwise or as operator.
"""
defmacro left ||| right do
quote do: :erlang.bor(unquote(left), unquote(right))
end
@doc """
Calculates the bitwise XOR of its arguments.
iex> bxor(9, 3)
10
Bitwise xor.
"""
defmacro bxor(left, right) do
quote do: :erlang.bxor(unquote(left), unquote(right))
end
@doc """
Infix operator; calculates the bitwise XOR of its arguments.
iex> 9 ^^^ 3
10
Bitwise xor as operator.
"""
defmacro left ^^^ right do
quote do: :erlang.bxor(unquote(left), unquote(right))
end
@doc """
Calculates the result of an arithmetic left bitshift.
iex> bsl(1, 2)
4
iex> bsl(1, -2)
0
iex> bsl(-1, 2)
-4
iex> bsl(-1, -2)
-1
Arithmetic bitshift left.
"""
defmacro bsl(left, right) do
quote do: :erlang.bsl(unquote(left), unquote(right))
end
@doc """
Infix operator; calculates the result of an arithmetic left bitshift.
iex> 1 <<< 2
4
iex> 1 <<< -2
0
iex> -1 <<< 2
-4
iex> -1 <<< -2
-1
Arithmetic bitshift left as operator.
"""
defmacro left <<< right do
quote do: :erlang.bsl(unquote(left), unquote(right))
end
@doc """
Calculates the result of an arithmetic right bitshift.
iex> bsr(1, 2)
0
iex> bsr(1, -2)
4
iex> bsr(-1, 2)
-1
iex> bsr(-1, -2)
-4
Arithmetic bitshift right.
"""
defmacro bsr(left, right) do
quote do: :erlang.bsr(unquote(left), unquote(right))
end
@doc """
Infix operator; calculates the result of an arithmetic right bitshift.
iex> 1 >>> 2
0
iex> 1 >>> -2
4
iex> -1 >>> 2
-1
iex> -1 >>> -2
-4
Arithmetic bitshift right as operator.
"""
defmacro left >>> right do
quote do: :erlang.bsr(unquote(left), unquote(right))
+32 -145
View File
@@ -2,112 +2,75 @@ defmodule Code do
@moduledoc """
Utilities for managing code compilation, code evaluation and code loading.
This module complements Erlang's [`:code` module](http://www.erlang.org/doc/man/code.html)
to add behaviour which is specific to Elixir. Almost all of the functions in this module
have global side effects on the behaviour of Elixir.
This module complements [Erlang's code module](http://www.erlang.org/doc/man/code.html)
to add behaviour which is specific to Elixir.
"""
@doc """
Lists all loaded files.
## Examples
Code.require_file("../eex/test/eex_test.exs")
List.first(Code.loaded_files) =~ "eex_test.exs" #=> true
List all loaded files.
"""
def loaded_files do
:elixir_code_server.call :loaded
end
@doc """
Removes files from the loaded files list.
Remove files from the loaded files list.
The modules defined in the file are not removed;
calling this function only removes them from the list,
allowing them to be required again.
## Examples
# Load EEx test code, unload file, check for functions still available
Code.load_file("../eex/test/eex_test.exs")
Code.unload_files(Code.loaded_files)
function_exported?(EExTest.Compiled, :before_compile, 0) #=> true
"""
def unload_files(files) do
:elixir_code_server.cast {:unload_files, files}
end
@doc """
Appends a path to the end of the Erlang VM code path list.
This is the list of directories the Erlang VM uses for
finding module code.
Append a path to the Erlang VM code path.
The path is expanded with `Path.expand/1` before being appended.
If this path does not exist, an error is returned.
## Examples
Code.append_path(".") #=> true
Code.append_path("/does_not_exist") #=> {:error, :bad_directory}
"""
def append_path(path) do
:code.add_pathz(to_char_list(Path.expand path))
end
@doc """
Prepends a path to the begining of the Erlang VM code path list.
This is the list of directories the Erlang VM uses for finding
module code.
Prepend a path to the Erlang VM code path.
The path is expanded with `Path.expand/1` before being prepended.
If this path does not exist, an error is returned.
## Examples
Code.prepend_path(".") #=> true
Code.prepend_path("/does_not_exist") #=> {:error, :bad_directory}
"""
def prepend_path(path) do
:code.add_patha(to_char_list(Path.expand path))
end
@doc """
Deletes a path from the Erlang VM code path list. This is the list of
directories the Erlang VM uses for finding module code.
The path is expanded with `Path.expand/1` before being deleted. If the
path does not exist it returns `false`.
## Examples
Code.prepend_path(".")
Code.delete_path(".") #=> true
Code.delete_path("/does_not_exist") #=> false
Delete a path from the Erlang VM code path.
The path is expanded with `Path.expand/1` before being deleted.
"""
def delete_path(path) do
:code.del_path(to_char_list(Path.expand path))
end
@doc false
def readd_paths() do
{pa, pz} = :elixir_code_server.call(:paths)
:code.add_pathsa(pa)
:code.add_pathsz(pz)
:ok
end
@doc """
Evaluates the contents given by `string`.
Evaluate the contents given by `string`.
The `binding` argument is a keyword list of variable bindings.
The `opts` argument is a keyword list of environment options.
Those options can be:
* `:file` - the file to be considered in the evaluation
* `:line` - the line on which the script starts
* `:file` - the file to be considered in the evaluation
* `:line` - the line on which the script starts
* `:delegate_locals_to` - delegate local calls to the given module,
the default is to not delegate
Additionally, the following scope values can be configured:
@@ -170,7 +133,7 @@ defmodule Code do
end
@doc """
Evaluates the quoted contents.
Evaluate the quoted contents.
See `eval_string/3` for a description of arguments and return values.
@@ -239,7 +202,7 @@ defmodule Code do
end
@doc """
Converts the given string to its quoted form.
Convert the given string to its quoted form.
Returns `{:ok, quoted_form}`
if it succeeds, `{:error, {line, error, token}}` otherwise.
@@ -267,7 +230,7 @@ defmodule Code do
end
@doc """
Converts the given string to its quoted form.
Convert the given string to its quoted form.
It returns the ast if it succeeds,
raises an exception otherwise. The exception is a `TokenMissingError`
@@ -297,7 +260,7 @@ defmodule Code do
end
@doc """
Loads the given file.
Load the given file.
Accepts `relative_to` as an argument to tell where the file is located.
If the file was already required/loaded, loads it again.
@@ -308,12 +271,6 @@ defmodule Code do
Notice that if `load_file` is invoked by different processes concurrently,
the target file will be loaded concurrently many times. Check `require_file/2`
if you don't want a file to be loaded concurrently.
## Examples
Code.load_file("eex_test.exs","../eex/test") |> List.first
#=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>}
"""
def load_file(file, relative_to \\ nil) when is_binary(file) do
file = find_file(file, relative_to)
@@ -336,20 +293,7 @@ defmodule Code do
N times with a given file, it will be loaded only once. The first process to
call `require_file` will get the list of loaded modules, others will get `nil`.
Check `load_file/2` if you want a file to be loaded multiple times. See also
`unload_files/1`
## Examples
If the code is already loaded, it returns `nil`:
Code.require_file("eex_test.exs","../eex/test") #=> nil
If the code is not loaded yet, it returns the same as `load_file/2`:
Code.require_file("eex_test.exs","../eex/test") |> List.first
#=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>}
Check `load_file/2` if you want a file to be loaded multiple times.
"""
def require_file(file, relative_to \\ nil) when is_binary(file) do
file = find_file(file, relative_to)
@@ -370,12 +314,6 @@ defmodule Code do
Gets the compilation options from the code server.
Check `compiler_options/1` for more information.
## Examples
Code.compiler_options
#=> [debug_info: true, docs: true, warnings_as_errors: false]
"""
def compiler_options do
:elixir_config.get :compiler_options
@@ -385,12 +323,6 @@ defmodule Code do
Returns a list with the available compiler options.
See `Code.compiler_options/1` for more info.
## Examples
Code.available_compiler_options
#=> [:docs, :debug_info, :ignore_module_conflict, :warnings_as_errors]
"""
def available_compiler_options do
[:docs, :debug_info, :ignore_module_conflict, :warnings_as_errors]
@@ -416,13 +348,6 @@ defmodule Code do
* `:warnings_as_errors` - cause compilation to fail when warnings are
generated
It returns the new list of compiler options.
## Examples
Code.compiler_options(debug_info: true)
#=> [debug_info: true, docs: true, warnings_as_errors: false]
"""
def compiler_options(opts) do
{opts, bad} = Keyword.split(opts, available_compiler_options)
@@ -478,7 +403,7 @@ defmodule Code do
module uses this function to check if a specific parser exists for a given
URI scheme.
## Code.ensure_compiled/1
## `Code.ensure_compiled/1`
Elixir also contains an `ensure_compiled/1` function that is a
superset of `ensure_loaded/1`.
@@ -493,15 +418,6 @@ defmodule Code do
In most cases, `ensure_loaded/1` is enough. `ensure_compiled/1`
must be used in rare cases, usually involving macros that need to
invoke a module for callback information.
## Examples
iex> Code.ensure_loaded(Atom)
{:module, Atom}
iex> Code.ensure_loaded(DoesNotExist)
{:error, :nofile}
"""
def ensure_loaded(module) when is_atom(module) do
:code.ensure_loaded(module)
@@ -513,12 +429,6 @@ defmodule Code do
Similar to `ensure_loaded/1`, but returns `true` if the module
is already loaded or was successfully loaded. Returns `false`
otherwise.
## Examples
iex> Code.ensure_loaded?(Atom)
true
"""
def ensure_loaded?(module) do
match?({:module, ^module}, ensure_loaded(module))
@@ -565,7 +475,7 @@ defmodule Code do
match?({:module, ^module}, ensure_compiled(module))
end
@doc ~S"""
@doc """
Returns the docs for the given module.
When given a module name, it finds its BEAM code and reads the docs from it.
@@ -582,33 +492,10 @@ defmodule Code do
which module definition starts and `doc` is the string
attached to the module using the `@moduledoc` attribute
* `:callback_docs` - list of all docstrings attached to
`@callbacks` using the `@doc` attribute
* `:type_docs` - list of all docstrings attached to
`@type` callbacks using the `@typedoc` attribute
* `:all` - a keyword list with `:docs` and `:moduledoc`, `:callback_docs`,
and `:type_docs`.
If the module cannot be found, it returns `nil`.
## Examples
# Get the documentation for the first function listed
iex> [fun|_] = Code.get_docs(Atom, :docs) |> Enum.sort()
iex> {{_function, _arity}, _line, _kind, _signature, text} = fun
iex> String.split(text, "\n") |> Enum.at(0)
"Converts an atom to a char list."
# Module doesn't exist
iex> Code.get_docs(ModuleNotGood, :all)
nil
* `:all` - a keyword list with both `:docs` and `:moduledoc`
"""
@doc_kinds [:docs, :moduledoc, :callback_docs, :type_docs, :all]
def get_docs(module, kind) when is_atom(module) and kind in @doc_kinds do
def get_docs(module, kind) when is_atom(module) do
case :code.get_object_code(module) do
{_module, bin, _beam_path} ->
do_get_docs(bin, kind)
@@ -617,7 +504,7 @@ defmodule Code do
end
end
def get_docs(binpath, kind) when is_binary(binpath) and kind in @doc_kinds do
def get_docs(binpath, kind) when is_binary(binpath) do
do_get_docs(String.to_char_list(binpath), kind)
end
@@ -639,7 +526,7 @@ defmodule Code do
defp lookup_docs(_, _), do: nil
defp do_lookup_docs(docs, :all), do: docs
defp do_lookup_docs(docs, kind),
defp do_lookup_docs(docs, kind) when kind in [:docs, :moduledoc],
do: Keyword.get(docs, kind)
## Helpers
+52 -250
View File
@@ -1,11 +1,10 @@
defmodule Dict do
@moduledoc ~S"""
This module specifies the Dict API expected to be
implemented by different dictionaries.
It also provides functions that redirect to the underlying
Dict, allowing a developer to work with different Dict
implementations using one API.
implemented by different dictionaries. It also provides
functions that redirect to the underlying Dict, allowing
a developer to work with different Dict implementations
using one API.
To create a new dict, use the `new` functions defined
by each dict type:
@@ -15,13 +14,6 @@ defmodule Dict do
In the examples below, `dict_impl` means a specific
`Dict` implementation, for example `HashDict` or `Map`.
## Warning
Do not use this module if you expect a certain `Dict`
implementation. For example, if you are working with
maps and you don't need polymorphism, it is preferrable
to use the `Map` module instead of the `Dict` one.
## Protocols
Besides implementing the functions in this module, all
@@ -64,7 +56,7 @@ defmodule Dict do
* `size/1`
All functions, except `reduce/3`, are required by the Dict behaviour.
`reduce/3` must be implemented as per the Enumerable protocol.
`reduce/3` must be implemtented as per the Enumerable protocol.
Based on these functions, `Dict` generates default implementations
for the following functions:
@@ -74,17 +66,13 @@ defmodule Dict do
* `fetch!/2`
* `get/2`
* `get/3`
* `get_lazy/3`
* `get_and_update/3`
* `has_key?/2`
* `keys/1`
* `merge/2`
* `merge/3`
* `pop/2`
* `pop/3`
* `pop_lazy/3`
* `put_new/3`
* `put_new_lazy/3`
* `split/2`
* `take/2`
* `to_list/1`
@@ -109,37 +97,35 @@ defmodule Dict do
"""
use Behaviour
@type key :: any
@type value :: any
@type t :: list | map
@callback new :: t
@callback delete(t, key) :: t
@callback drop(t, Enum.t) :: t
@callback equal?(t, t) :: boolean
@callback get(t, key) :: value
@callback get(t, key, value) :: value
@callback get_lazy(t, key, (() -> value)) :: value
@callback get_and_update(t, key, (value -> {value, value})) :: {value, t}
@callback fetch(t, key) :: {:ok, value} | :error
@callback fetch!(t, key) :: value | no_return
@callback has_key?(t, key) :: boolean
@callback keys(t) :: [key]
@callback merge(t, t) :: t
@callback merge(t, t, (key, value, value -> value)) :: t
@callback pop(t, key) :: {value, t}
@callback pop(t, key, value) :: {value, t}
@callback pop_lazy(t, key, (() -> value)) :: {value, t}
@callback put(t, key, value) :: t
@callback put_new(t, key, value) :: t
@callback put_new_lazy(t, key, (() -> value)) :: t
@callback size(t) :: non_neg_integer()
@callback split(t, Enum.t) :: {t, t}
@callback take(t, Enum.t) :: t
@callback to_list(t) :: list()
@callback update(t, key, value, (value -> value)) :: t
@callback update!(t, key, (value -> value)) :: t | no_return
@callback values(t) :: list(value)
defcallback new :: t
defcallback delete(t, key) :: t
defcallback drop(t, Enum.t) :: t
defcallback equal?(t, t) :: boolean
defcallback get(t, key) :: value
defcallback get(t, key, value) :: value
defcallback fetch(t, key) :: {:ok, value} | :error
defcallback fetch!(t, key) :: value | no_return
defcallback has_key?(t, key) :: boolean
defcallback keys(t) :: [key]
defcallback merge(t, t) :: t
defcallback merge(t, t, (key, value, value -> value)) :: t
defcallback pop(t, key) :: {value, t}
defcallback pop(t, key, value) :: {value, t}
defcallback put(t, key, value) :: t
defcallback put_new(t, key, value) :: t
defcallback size(t) :: non_neg_integer()
defcallback split(t, Enum.t) :: {t, t}
defcallback take(t, Enum.t) :: t
defcallback to_list(t) :: list()
defcallback update(t, key, value, (value -> value)) :: t
defcallback update!(t, key, (value -> value)) :: t | no_return
defcallback values(t) :: list(value)
defmacro __using__(_) do
# Use this import to guarantee proper code expansion
@@ -155,19 +141,6 @@ defmodule Dict do
end
end
def get_lazy(dict, key, fun) when is_function(fun, 0) do
case fetch(dict, key) do
{:ok, value} -> value
:error -> fun.()
end
end
def get_and_update(dict, key, fun) do
current_value = get(dict, key)
{get, new_value} = fun.(current_value)
{get, put(dict, key, new_value)}
end
def fetch!(dict, key) do
case fetch(dict, key) do
{:ok, value} -> value
@@ -186,13 +159,6 @@ defmodule Dict do
end
end
def put_new_lazy(dict, key, fun) when is_function(fun, 0) do
case has_key?(dict, key) do
true -> dict
false -> put(dict, key, fun.())
end
end
def drop(dict, keys) do
Enum.reduce(keys, dict, &delete(&2, &1))
end
@@ -282,15 +248,6 @@ defmodule Dict do
end
end
def pop_lazy(dict, key, fun) when is_function(fun, 0) do
case fetch(dict, key) do
{:ok, value} ->
{value, delete(dict, key)}
:error ->
{fun.(), dict}
end
end
def split(dict, keys) do
Enum.reduce(keys, {new, dict}, fn key, {inc, exc} = acc ->
case fetch(exc, key) do
@@ -305,11 +262,11 @@ defmodule Dict do
defoverridable merge: 2, merge: 3, equal?: 2, to_list: 1, keys: 1,
values: 1, take: 2, drop: 2, get: 2, get: 3, fetch!: 2,
has_key?: 2, put_new: 3, pop: 2, pop: 3, split: 2,
update: 4, update!: 3, get_and_update: 3, get_lazy: 3,
pop_lazy: 3, put_new_lazy: 3
update: 4, update!: 3
end
end
defmacrop target(dict) do
quote do
case unquote(dict) do
@@ -333,7 +290,7 @@ defmodule Dict do
iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)
iex> Enum.sort(Dict.keys(dict))
[:a, :b]
[:a,:b]
"""
@spec keys(t) :: [key]
@@ -349,7 +306,7 @@ defmodule Dict do
iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)
iex> Enum.sort(Dict.values(dict))
[1, 2]
[1,2]
"""
@spec values(t) :: [value]
@@ -408,59 +365,6 @@ defmodule Dict do
target(dict).get(dict, key, default)
end
@doc """
Returns the value associated with `key` in `dict`. If `dict` does not
contain `key`, it lazily evaluates `fun` and returns its result.
This is useful if the default value is very expensive to calculate or
generally difficult to set-up and tear-down again.
## Examples
iex> dict = Enum.into([a: 1], dict_impl.new)
iex> fun = fn ->
...> # some expensive operation here
...> :result
...> end
iex> Dict.get_lazy(dict, :a, fun)
1
iex> Dict.get_lazy(dict, :b, fun)
:result
"""
@spec get_lazy(t, key, (() -> value)) :: value
def get_lazy(dict, key, fun) do
target(dict).get_lazy(dict, key, fun)
end
@doc """
Gets a value from `dict` and updates the value at `key` in one pass.
This `fun` argument receives the value of `key` in `dict` (or `nil` if `key`
is not present) and must return a two-elements tuple: the "get" value (the
value retrieved from the dict which can be operated on before being returned)
and the new value to be stored under `key` in `dict`.
The returned value is a tuple with the "get" value returned by `fun` and a new
dict with the updated value under `key`.
## Examples
iex> dict = Enum.into([a: 1], dict_impl.new)
iex> {get, new_dict} = Dict.get_and_update dict, :a, fn(current_value) ->
...> {current_value + 1, "foo"}
...> end
iex> get
2
iex> Dict.get(new_dict, :a)
"foo"
"""
@spec get_and_update(t, key, (value -> {value, value})) :: {value, t}
def get_and_update(dict, key, fun) do
target(dict).get_and_update(dict, key, fun)
end
@doc """
Returns `{:ok, value}` associated with `key` in `dict`.
If `dict` does not contain `key`, returns `:error`.
@@ -513,7 +417,7 @@ defmodule Dict do
end
@doc """
Puts the given `value` under `key` in `dict` unless `key` is already present.
Puts the given `value` under `key` in `dict` unless `key` already exists.
## Examples
@@ -528,33 +432,6 @@ defmodule Dict do
target(dict).put_new(dict, key, val)
end
@doc """
Evaluates `fun` and puts the result under `key` in `dict` unless `key`
is already present.
This is useful if the value is very expensive to calculate or generally
difficult to set-up and tear-down again.
## Examples
iex> dict = Enum.into([a: 1, b: 2], dict_impl.new)
iex> fun = fn ->
...> # some expensive operation here
...> 3
...> end
iex> dict = Dict.put_new_lazy(dict, :a, fun)
iex> Dict.get(dict, :a)
1
iex> dict = Dict.put_new_lazy(dict, :c, fun)
iex> Dict.get(dict, :c)
3
"""
@spec put_new_lazy(t, key, (() -> value)) :: t
def put_new_lazy(dict, key, fun) do
target(dict).put_new_lazy(dict, key, fun)
end
@doc """
Removes the entry stored under the given `key` from `dict`.
If `dict` does not contain `key`, returns the dictionary unchanged.
@@ -579,8 +456,9 @@ defmodule Dict do
@doc """
Merges the dict `dict2` into dict `dict1`.
If one of the `dict2` entries is found in `dict1`, the
conflicting entries in `dict2` have higher precedence.
If one of the `dict2` entries already exists in `dict1`, the
functions in entries in `dict2` have higher precedence unless a
function is given to resolve conflicts.
Notice this function is polymorphic as it merges dicts of any
type. Each dict implementation also provides a `merge` function,
@@ -594,31 +472,6 @@ defmodule Dict do
iex> [a: Dict.get(dict, :a), b: Dict.get(dict, :b), d: Dict.get(dict, :d)]
[a: 3, b: 2, d: 4]
"""
@spec merge(t, t) :: t
def merge(dict1, dict2) do
target1 = target(dict1)
target2 = target(dict2)
if target1 == target2 do
target1.merge(dict1, dict2)
else
do_merge(target1, dict1, dict2, fn(_k, _v1, v2) -> v2 end)
end
end
@doc """
Merges the dict `dict2` into dict `dict1`.
If one of the `dict2` entries is found in `dict1`, the function
will be invoked to resolve the conflict.
Notice this function is polymorphic as it merges dicts of any
type. Each dict implementation also provides a `merge` function,
but they can only merge dicts of the same type.
## Examples
iex> dict1 = Enum.into([a: 1, b: 2], dict_impl.new)
iex> dict2 = Enum.into([a: 3, d: 4], dict_impl.new)
iex> dict = Dict.merge(dict1, dict2, fn(_k, v1, v2) ->
@@ -629,46 +482,39 @@ defmodule Dict do
"""
@spec merge(t, t, (key, value, value -> value)) :: t
def merge(dict1, dict2, fun) do
def merge(dict1, dict2, fun \\ fn(_k, _v1, v2) -> v2 end) do
target1 = target(dict1)
target2 = target(dict2)
if target1 == target2 do
target1.merge(dict1, dict2, fun)
else
do_merge(target1, dict1, dict2, fun)
Enumerable.reduce(dict2, {:cont, dict1}, fn({k, v}, acc) ->
{:cont, target1.update(acc, k, v, fn(other) -> fun.(k, other, v) end)}
end) |> elem(1)
end
end
defp do_merge(target1, dict1, dict2, fun) do
Enumerable.reduce(dict2, {:cont, dict1}, fn({k, v}, acc) ->
{:cont, target1.update(acc, k, v, fn(other) -> fun.(k, other, v) end)}
end) |> elem(1)
end
@doc """
Returns the value associated with `key` in `dict` as
well as the `dict` without `key`.
If `key` is not present in `dict`, then the `dict` will
be returned unmodified.
## Examples
iex> dict = Enum.into([a: 1], dict_impl.new)
iex> {v, dict} = Dict.pop dict, :a
iex> {v, Enum.sort(dict)}
{1, []}
{1,[]}
iex> dict = Enum.into([a: 1], dict_impl.new)
iex> {v, dict} = Dict.pop dict, :b
iex> {v, Enum.sort(dict)}
{nil, [a: 1]}
{nil,[a: 1]}
iex> dict = Enum.into([a: 1], dict_impl.new)
iex> {v, dict} = Dict.pop dict, :b, 3
iex> {v, Enum.sort(dict)}
{3, [a: 1]}
{3,[a: 1]}
"""
@spec pop(t, key, value) :: {value, t}
@@ -677,44 +523,7 @@ defmodule Dict do
end
@doc """
Returns the value associated with `key` in `dict` as
well as the `dict` without `key`.
If `key` is not present in `dict`, then the `dict` will
be returned unmodified, and it will lazily evaluate `fun`
and return its result instead of the missing value.
This is useful if the default value is very expensive to calculate or
generally difficult to set-up and tear-down again.
## Examples
iex> dict = Enum.into([a: 1], dict_impl.new)
iex> fun = fn ->
...> # some expensive operation here
...> :result
...> end
iex> {v, dict} = Dict.pop_lazy dict, :a, fun
iex> {v, Enum.sort(dict)}
{1, []}
iex> dict = Enum.into([a: 1], dict_impl.new)
iex> fun = fn ->
...> # some expensive operation here
...> :result
...> end
iex> {v, dict} = Dict.pop_lazy dict, :b, fun
iex> {v, Enum.sort(dict)}
{:result, [a: 1]}
"""
@spec pop_lazy(t, key, (() -> value)) :: {value, t}
def pop_lazy(dict, key, fun) do
target(dict).pop_lazy(dict, key, fun)
end
@doc """
Updates a value in `dict` by calling `fun` on the value to get a new
Update a value in `dict` by calling `fun` on the value to get a new
value. An exception is generated if `key` is not present in the dict.
## Examples
@@ -731,7 +540,7 @@ defmodule Dict do
end
@doc """
Updates a value in `dict` by calling `fun` on the value to get a new value. If
Update a value in `dict` by calling `fun` on the value to get a new value. If
`key` is not present in `dict` then `initial` will be stored as the first
value.
@@ -751,9 +560,9 @@ defmodule Dict do
@doc """
Returns a tuple of two dicts, where the first dict contains only
entries from `dict` with keys in `keys`, and the second dict
contains only entries from `dict` with keys not in `keys`.
contains only entries from `dict` with keys not in `keys`
All non-member keys are ignored.
Any non-member keys are ignored.
## Examples
@@ -780,7 +589,7 @@ defmodule Dict do
@doc """
Returns a new dict where the given `keys` are removed from `dict`.
All non-member keys are ignored.
Any non-member keys are ignored.
## Examples
@@ -803,7 +612,7 @@ defmodule Dict do
@doc """
Returns a new dict where only the keys in `keys` from `dict` are included.
All non-member keys are ignored.
Any non-member keys are ignored.
## Examples
@@ -828,7 +637,7 @@ defmodule Dict do
end
@doc """
Checks if two dicts are equal using `===`.
Check if two dicts are equal using `===`.
Notice this function is polymorphic as it compares dicts of any
type. Each dict implementation also provides an `equal?` function,
@@ -872,13 +681,6 @@ defmodule Dict do
@doc """
Returns a list of key-value pairs stored in `dict`.
No particular order is enforced.
## Examples
iex> dict = dict_impl.new
iex> dict = Dict.put(dict, :a, 1)
iex> Dict.to_list(dict)
[a: 1]
"""
@spec to_list(t) :: list
def to_list(dict) do
+152 -545
View File
File diff suppressed because it is too large Load Diff
+46 -46
View File
@@ -4,7 +4,7 @@ defmodule Exception do
Note that stacktraces in Elixir are updated on throw,
errors and exits. For example, at any given moment,
`System.stacktrace/0` will return the stacktrace for the
`System.stacktrace` will return the stacktrace for the
last throw/error/exit that occurred in the current process.
Do not rely on the particular format returned by the `format`
@@ -22,8 +22,8 @@ defmodule Exception do
@type stacktrace :: [stacktrace_entry]
@type stacktrace_entry ::
{module, atom, arity_or_args, location} |
{(... -> any), arity_or_args, location}
{module, function, arity_or_args, location} |
{function, arity_or_args, location}
@typep arity_or_args :: non_neg_integer | list
@typep location :: Keyword.t
@@ -32,13 +32,9 @@ defmodule Exception do
@callback message(t) :: String.t
@doc """
Returns `true` if the given `term` is an exception.
Returns true if the given argument is an exception.
"""
def exception?(term)
def exception?(%{__struct__: struct, __exception__: true}) when is_atom(struct),
do: true
def exception?(%{__struct__: struct, __exception__: true}) when is_atom(struct), do: true
def exception?(_), do: false
@doc """
@@ -49,14 +45,9 @@ defmodule Exception do
module.message(exception)
rescue
e ->
"got #{inspect e.__struct__} with message #{inspect message(e)} " <>
"while retrieving Exception.message/1 for #{inspect(exception)}"
else
x when is_binary(x) -> x
x ->
"got #{inspect(x)} " <>
"while retrieving Exception.message/1 for #{inspect(exception)} " <>
"(expected a string)"
raise ArgumentError,
"Got #{inspect e.__struct__} with message " <>
"\"#{message(e)}\" while retrieving message for #{inspect(exception)}"
end
end
@@ -262,7 +253,7 @@ defmodule Exception do
# :supervisor.start_link error reasons
# If value is a list will be formatted by mfa exit in format_exit/1
# If value is a list will be be formatted by mfa exit in format_exit/1
defp format_exit_reason({:bad_return, {mod, :init, value}})
when is_atom(mod) do
format_mfa(mod, :init, 1) <> " returned a bad value: " <> inspect(value)
@@ -448,7 +439,7 @@ defmodule Exception do
@doc """
Formats the given file and line as shown in stacktraces.
If any of the values are `nil`, they are omitted.
If any of the values are nil, they are omitted.
## Examples
@@ -483,17 +474,35 @@ defmodule Exception do
end
end
# Some exceptions implement "message/1" instead of "exception/1" mostly
# Some exceptions implement `message/1` instead of `exception/1` mostly
# for bootstrap reasons. It is recommended for applications to implement
# "exception/1" instead of "message/1" as described in "defexception/1"
# `exception/1` instead of `message/1` as described in `defexception/1`
# docs.
defmodule RuntimeError do
defexception message: "runtime error"
@spec exception(String.t) :: Exception.t
def exception(msg) when is_binary(msg) do
%RuntimeError{message: msg}
end
def exception(arg) do
super(arg)
end
end
defmodule ArgumentError do
defexception message: "argument error"
@spec exception(String.t) :: Exception.t
def exception(msg) when is_binary(msg) do
%ArgumentError{message: msg}
end
def exception(arg) do
super(arg)
end
end
defmodule ArithmeticError do
@@ -612,33 +621,21 @@ defmodule BadArityError do
end
defmodule UndefinedFunctionError do
defexception [module: nil, function: nil, arity: nil, reason: nil]
defexception [module: nil, function: nil, arity: nil, self: false]
def message(%{reason: nil, module: module, function: function, arity: arity} = e) do
cond do
is_nil(function) or is_nil(arity) ->
"undefined function"
not is_nil(module) and :code.is_loaded(module) === false ->
message(%{e | reason: :"module could not be loaded"})
true ->
message(%{e | reason: :"function not exported"})
def message(%{function: function, module: module, arity: arity, self: self}) do
if function do
formatted = Exception.format_mfa module, function, arity
suffix = if self or is_nil(module) or :code.is_loaded(module) do
""
else
" (module #{inspect module} is not available)"
end
"undefined function: #{formatted}" <> suffix
else
"undefined function"
end
end
def message(%{reason: :"module could not be loaded", module: module, function: function, arity: arity}) do
"undefined function: " <> Exception.format_mfa(module, function, arity) <>
" (module #{inspect module} is not available)"
end
def message(%{reason: :"function not exported", module: module, function: function, arity: arity}) do
"undefined function: " <> Exception.format_mfa(module, function, arity)
end
def message(%{reason: :"function not available", module: module, function: function, arity: arity}) do
"nil." <> fa = Exception.format_mfa(nil, function, arity)
"undefined function: " <> Exception.format_mfa(module, function, arity) <>
" (function #{fa} is not available)"
end
end
defmodule FunctionClauseError do
@@ -809,7 +806,7 @@ defmodule ErlangError do
def normalize(:undef, stacktrace) do
stacktrace = stacktrace || :erlang.get_stacktrace
{mod, fun, arity} = from_stacktrace(stacktrace)
%UndefinedFunctionError{module: mod, function: fun, arity: arity}
%UndefinedFunctionError{module: mod, function: fun, arity: arity, self: from_self(stacktrace)}
end
def normalize(:function_clause, stacktrace) do
@@ -836,4 +833,7 @@ defmodule ErlangError do
defp from_stacktrace(_) do
{nil, nil, nil}
end
defp from_self([{module, _, _, _}, {module, _, _, _}|_]), do: true
defp from_self(_), do: false
end
+89 -197
View File
@@ -47,9 +47,9 @@ defmodule File do
File.read!("invalid.txt")
#=> raises File.Error
In general, a developer should use the former in case they want
In general, a developer should use the former in case he wants
to react if the file does not exist. The latter should be used
when the developer expects their software to fail in case the
when the developer expects his software to fail in case the
file cannot be read (i.e. it is literally an exception).
## Processes and raw files
@@ -66,7 +66,7 @@ defmodule File do
and `:delayed_write` are also useful when operating large files or
working with files in tight loops.
Check [`:file.open/2`](http://www.erlang.org/doc/man/file.html#open-2) for more information
Check http://www.erlang.org/doc/man/file.html#open-2 for more information
about such options and other performance considerations.
"""
@@ -77,7 +77,7 @@ defmodule File do
@type stat_options :: [time: :local | :universal | :posix]
@type mode :: :append | :binary | :compressed | :delayed_write | :exclusive |
:raw | :read | :read_ahead | :sync | :write |
{:encoding, :latin1 | :unicode | :utf16 | :utf32 | :utf8 |
{:encoding , :latin1 | :unicode | :utf16 | :utf32 | :utf8 |
{:utf16, :big | :little} | {:utf32, :big | :little}} |
{:read_ahead, pos_integer} |
{:delayed_write, non_neg_integer, non_neg_integer}
@@ -132,12 +132,12 @@ defmodule File do
Typical error reasons are:
* `:eacces` - missing search or write permissions for the parent
directories of `path`
directories of `path`
* `:eexist` - there is already a file or directory named `path`
* `:enoent` - a component of `path` does not exist
* `:enospc` - there is a no space left on the device
* `:enotdir` - a component of `path` is not a directory;
on some platforms, `:enoent` is returned instead
on some platforms, `:enoent` is returned instead
"""
@spec mkdir(Path.t) :: :ok | {:error, posix}
def mkdir(path) do
@@ -149,11 +149,11 @@ defmodule File do
"""
@spec mkdir!(Path.t) :: :ok | no_return
def mkdir!(path) do
path = IO.chardata_to_string(path)
case mkdir(path) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "make directory",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "make directory", path: path
end
end
@@ -164,7 +164,7 @@ defmodule File do
Typical error reasons are:
* `:eacces` - missing search or write permissions for the parent
directories of `path`
directories of `path`
* `:enospc` - there is a no space left on the device
* `:enotdir` - a component of `path` is not a directory
"""
@@ -187,7 +187,7 @@ defmodule File do
{:error, :einval}
else
_ = do_mkdir_p(parent)
case F.make_dir(path) do
case :file.make_dir(path) do
{:error, :eexist} = error ->
if dir?(path), do: :ok, else: error
other ->
@@ -202,11 +202,11 @@ defmodule File do
"""
@spec mkdir_p!(Path.t) :: :ok | no_return
def mkdir_p!(path) do
path = IO.chardata_to_string(path)
case mkdir_p(path) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "make directory (with -p)",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "make directory (with -p)", path: path
end
end
@@ -218,10 +218,10 @@ defmodule File do
* `:enoent` - the file does not exist
* `:eacces` - missing permission for reading the file,
or for searching one of the parent directories
or for searching one of the parent directories
* `:eisdir` - the named file is a directory
* `:enotdir` - a component of the file name is not a directory;
on some platforms, `:enoent` is returned instead
on some platforms, `:enoent` is returned instead
* `:enomem` - there is not enough memory for the contents of the file
You can use `:file.format_error/1` to get a descriptive string of the error.
@@ -237,12 +237,12 @@ defmodule File do
"""
@spec read!(Path.t) :: binary | no_return
def read!(path) do
path = IO.chardata_to_string(path)
case read(path) do
{:ok, binary} ->
binary
{:error, reason} ->
raise File.Error, reason: reason, action: "read file",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "read file", path: path
end
end
@@ -256,18 +256,11 @@ defmodule File do
The accepted options are:
* `:time` - configures how the file timestamps are returned
The values for `:time` can be:
* `:universal` - returns a `{date, time}` tuple in UTC (default)
* `:local` - returns a `{date, time}` tuple using the machine time
* `:posix` - returns the time as integer seconds since epoch
* `:time` - `:local | :universal | :posix`; default: `:local`
"""
@spec stat(Path.t, stat_options) :: {:ok, File.Stat.t} | {:error, posix}
def stat(path, opts \\ []) do
opts = Keyword.put_new(opts, :time, :universal)
case F.read_file_info(IO.chardata_to_string(path), opts) do
{:ok, fileinfo} ->
{:ok, File.Stat.from_record(fileinfo)}
@@ -282,56 +275,11 @@ defmodule File do
"""
@spec stat!(Path.t, stat_options) :: File.Stat.t | no_return
def stat!(path, opts \\ []) do
path = IO.chardata_to_string(path)
case stat(path, opts) do
{:ok, info} -> info
{:error, reason} ->
raise File.Error, reason: reason, action: "read file stats",
path: IO.chardata_to_string(path)
end
end
@doc """
Returns information about the `path`. If the file is a symlink sets
the `type` to `:symlink` and returns `File.Stat` for the link. For any
other file, returns exactly the same values as `stat/2`.
For more details, see [`:file.read_link_info/2`](http://www.erlang.org/doc/man/file.html#read_link_info-2).
## Options
The accepted options are:
* `:time` - configures how the file timestamps are returned
The values for `:time` can be:
* `:universal` - returns a `{date, time}` tuple in UTC (default)
* `:local` - returns a `{date, time}` tuple using the machine time
* `:posix` - returns the time as integer seconds since epoch
"""
@spec lstat(Path.t, stat_options) :: {:ok, File.Stat.t} | {:error, posix}
def lstat(path, opts \\ []) do
opts = Keyword.put_new(opts, :time, :universal)
case F.read_link_info(IO.chardata_to_string(path), opts) do
{:ok, fileinfo} ->
{:ok, File.Stat.from_record(fileinfo)}
error ->
error
end
end
@doc """
Same as `lstat/2` but returns the `File.Stat` directly and
throws `File.Error` if an error is returned.
"""
@spec lstat!(Path.t, stat_options) :: File.Stat.t | no_return
def lstat!(path, opts \\ []) do
case lstat(path, opts) do
{:ok, info} -> info
{:error, reason} ->
raise File.Error, reason: reason, action: "read file stats",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "read file stats", path: path
end
end
@@ -341,7 +289,6 @@ defmodule File do
"""
@spec write_stat(Path.t, File.Stat.t, stat_options) :: :ok | {:error, posix}
def write_stat(path, stat, opts \\ []) do
opts = Keyword.put_new(opts, :time, :universal)
F.write_file_info(IO.chardata_to_string(path), File.Stat.to_record(stat), opts)
end
@@ -351,24 +298,22 @@ defmodule File do
"""
@spec write_stat!(Path.t, File.Stat.t, stat_options) :: :ok | no_return
def write_stat!(path, stat, opts \\ []) do
path = IO.chardata_to_string(path)
case write_stat(path, stat, opts) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "write file stats",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "write file stats", path: path
end
end
@doc """
Updates modification time (mtime) and access time (atime) of
the given file.
File is created if it doesn’t exist. Requires datetime in UTC.
the given file. File is created if it doesn’t exist.
"""
@spec touch(Path.t, :calendar.datetime) :: :ok | {:error, posix}
def touch(path, time \\ :calendar.universal_time) do
def touch(path, time \\ :calendar.local_time) do
path = IO.chardata_to_string(path)
case :elixir_utils.change_universal_time(path, time) do
case F.change_time(path, time) do
{:error, :enoent} -> touch_new(path, time)
other -> other
end
@@ -376,23 +321,22 @@ defmodule File do
defp touch_new(path, time) do
case write(path, "", [:append]) do
:ok -> :elixir_utils.change_universal_time(path, time)
:ok -> F.change_time(path, time)
{:error, _reason} = error -> error
end
end
@doc """
Same as `touch/2` but raises an exception if it fails.
Returns `:ok` otherwise. Requires datetime in UTC.
Returns `:ok` otherwise.
"""
@spec touch!(Path.t, :calendar.datetime) :: :ok | no_return
def touch!(path, time \\ :calendar.universal_time) do
def touch!(path, time \\ :calendar.local_time) do
path = IO.chardata_to_string(path)
case touch(path, time) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "touch",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "touch", path: path
end
end
@@ -440,39 +384,16 @@ defmodule File do
"""
@spec copy!(Path.t, Path.t, pos_integer | :infinity) :: non_neg_integer | no_return
def copy!(source, destination, bytes_count \\ :infinity) do
source = IO.chardata_to_string(source)
destination = IO.chardata_to_string(destination)
case copy(source, destination, bytes_count) do
{:ok, bytes_count} -> bytes_count
{:error, reason} ->
raise File.CopyError, reason: reason, action: "copy",
source: IO.chardata_to_string(source), destination: IO.chardata_to_string(destination)
source: source, destination: destination
end
end
@doc """
Renames the `source` file to `destination` file. If can be used to move files
(and directories) between directories. If moving a file, you must fully
specify the `destination` filename, it is not sufficient to simply specify
it's directory.
It returns `:ok` in case of success, returns `{:error, reason}` otherwise
Note: The command `mv` in Unix systems behaves differently depending
if `source` is a file and the `destination` is an existing directory.
We have chosen to explicitly disallow this behaviour.
## Examples
# Rename file "a.txt" to "b.txt"
File.rename "a.txt", "b.txt"
# Rename directory "samples" to "tmp"
File.rename "samples", "tmp"
"""
@spec rename(Path.t, Path.t) :: :ok | {:error, posix}
def rename(source, destination) do
F.rename(source, destination)
end
@doc """
Copies the contents in `source` to `destination` preserving its mode.
@@ -503,24 +424,20 @@ defmodule File do
end
end
defp path_differs?(path, path),
do: false
defp path_differs?(p1, p2) do
Path.expand(p1) !== Path.expand(p2)
end
@doc """
The same as `cp/3`, but raises `File.CopyError` if it fails.
Returns `:ok` otherwise.
Returns the list of copied files otherwise.
"""
@spec cp!(Path.t, Path.t, (Path.t, Path.t -> boolean)) :: :ok | no_return
def cp!(source, destination, callback \\ fn(_, _) -> true end) do
source = IO.chardata_to_string(source)
destination = IO.chardata_to_string(destination)
case cp(source, destination, callback) do
:ok -> :ok
{:error, reason} ->
raise File.CopyError, reason: reason, action: "copy",
source: IO.chardata_to_string(source), destination: IO.chardata_to_string(destination)
raise File.CopyError, reason: reason, action: "copy recursively",
source: source, destination: destination
end
end
@@ -555,15 +472,15 @@ defmodule File do
## Examples
# Copies file "a.txt" to "b.txt"
File.cp_r "a.txt", "b.txt"
# Copies "a.txt" to "tmp"
File.cp_r "a.txt", "tmp.txt"
# Copies all files in "samples" to "tmp"
File.cp_r "samples", "tmp"
# Same as before, but asks the user how to proceed in case of conflicts
File.cp_r "samples", "tmp", fn(source, destination) ->
IO.gets("Overwriting #{destination} by #{source}. Type y to confirm. ") == "y\n"
IO.gets("Overwriting #{destination} by #{source}. Type y to confirm.") == "y"
end
"""
@@ -584,11 +501,14 @@ defmodule File do
"""
@spec cp_r!(Path.t, Path.t, (Path.t, Path.t -> boolean)) :: [binary] | no_return
def cp_r!(source, destination, callback \\ fn(_, _) -> true end) do
source = IO.chardata_to_string(source)
destination = IO.chardata_to_string(destination)
case cp_r(source, destination, callback) do
{:ok, files} -> files
{:error, reason, file} ->
raise File.CopyError, reason: reason, action: "copy recursively", on: file,
source: IO.chardata_to_string(source), destination: IO.chardata_to_string(destination)
raise File.CopyError, reason: reason, action: "copy recursively",
source: source, destination: destination, on: file
end
end
@@ -637,7 +557,9 @@ defmodule File do
copy_file_mode!(src, dest)
[dest|acc]
{:error, :eexist} ->
if path_differs?(src, dest) and callback.(src, dest) do
if callback.(src, dest) do
# If rm/1 fails, copy/2 will fail
_ = rm(dest)
case copy(src, dest) do
{:ok, _} ->
copy_file_mode!(src, dest)
@@ -657,8 +579,8 @@ defmodule File do
:ok ->
[dest|acc]
{:error, :eexist} ->
if path_differs?(src, dest) and callback.(src, dest) do
# If rm/1 fails, F.make_symlink/2 will fail
if callback.(src, dest) do
# If rm/1 fails, iF.make_symlink/2 will fail
_ = rm(dest)
case F.make_symlink(link, dest) do
:ok -> [dest|acc]
@@ -688,10 +610,10 @@ defmodule File do
* `:enoent` - a component of the file name does not exist
* `:enotdir` - a component of the file name is not a directory;
on some platforms, enoent is returned instead
on some platforms, enoent is returned instead
* `:enospc` - there is a no space left on the device
* `:eacces` - missing permission for writing the file or searching one of
the parent directories
the parent directories
* `:eisdir` - the named file is a directory
Check `File.open/2` for other available options.
@@ -706,11 +628,11 @@ defmodule File do
"""
@spec write!(Path.t, iodata, [mode]) :: :ok | no_return
def write!(path, content, modes \\ []) do
path = IO.chardata_to_string(path)
case F.write_file(path, content, modes) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "write to file",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "write to file", path: path
end
end
@@ -718,7 +640,6 @@ defmodule File do
Tries to delete the file `path`.
Returns `:ok` if successful, or `{:error, reason}` if an error occurs.
Note the file is deleted even if in read-only mode.
Typical error reasons are:
@@ -727,15 +648,15 @@ defmodule File do
* `:eacces` - missing permission for the file or one of its parents
* `:eperm` - the file is a directory and user is not super-user
* `:enotdir` - a component of the file name is not a directory;
on some platforms, enoent is returned instead
on some platforms, enoent is returned instead
* `:einval` - filename had an improper type, such as tuple
## Examples
File.rm("file.txt")
File.rm('file.txt')
#=> :ok
File.rm("tmp_dir/")
File.rm('tmp_dir/')
#=> {:error, :eperm}
"""
@@ -754,7 +675,7 @@ defmodule File do
defp change_mode_windows(path) do
if match? {:win32, _}, :os.type do
case F.read_file_info(path) do
case F.read_file_info(IO.chardata_to_string(path)) do
{:ok, file_info} when elem(file_info, 3) in [:read, :none] ->
change_mode_windows(path, file_info)
_ ->
@@ -764,7 +685,7 @@ defmodule File do
end
defp change_mode_windows(path, file_info) do
case chmod(path, (elem(file_info, 7) + 0o200)) do
case File.chmod(path, (elem(file_info, 7) + 0o200)) do
:ok -> F.delete(path)
{:error, _reason} = error -> error
end
@@ -775,11 +696,11 @@ defmodule File do
"""
@spec rm!(Path.t) :: :ok | no_return
def rm!(path) do
path = IO.chardata_to_string(path)
case rm(path) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "remove file",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "remove file", path: path
end
end
@@ -806,16 +727,16 @@ defmodule File do
"""
@spec rmdir!(Path.t) :: :ok | {:error, posix}
def rmdir!(path) do
path = IO.chardata_to_string(path)
case rmdir(path) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "remove directory",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "remove directory", path: path
end
end
@doc """
Removes files and directories recursively at the given `path`.
Remove files and directories recursively at the given `path`.
Symlinks are not followed but simply removed, non-existing
files are simply ignored (i.e. doesn't make this function fail).
@@ -909,10 +830,11 @@ defmodule File do
"""
@spec rm_rf!(Path.t) :: [binary] | no_return
def rm_rf!(path) do
path = IO.chardata_to_string(path)
case rm_rf(path) do
{:ok, files} -> files
{:error, reason, _} ->
raise File.Error, reason: reason, path: IO.chardata_to_string(path),
raise File.Error, reason: reason, path: path,
action: "remove files and directories recursively from"
end
end
@@ -962,8 +884,8 @@ defmodule File do
cannot cope with the character range of the data, an error occurs and the
file will be closed.
For more information about other options like `:read_ahead` and `:delayed_write`,
see [`:file.open/2`](http://www.erlang.org/doc/man/file.html#open-2).
Check http://www.erlang.org/doc/man/file.html#open-2 for more information about
other options like `:read_ahead` and `:delayed_write`.
This function returns:
@@ -1040,10 +962,11 @@ defmodule File do
"""
@spec open!(Path.t, [mode]) :: io_device | no_return
def open!(path, modes \\ []) do
path = IO.chardata_to_string(path)
case open(path, modes) do
{:ok, device} -> device
{:error, reason} ->
raise File.Error, reason: reason, action: "open", path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "open", path: path
end
end
@@ -1054,10 +977,11 @@ defmodule File do
"""
@spec open!(Path.t, [mode | :ram], (io_device -> res)) :: res | no_return when res: var
def open!(path, modes, function) do
path = IO.chardata_to_string(path)
case open(path, modes, function) do
{:ok, device} -> device
{:error, reason} ->
raise File.Error, reason: reason, action: "open", path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "open", path: path
end
end
@@ -1094,7 +1018,7 @@ defmodule File do
case cwd() do
{:ok, cwd} -> cwd
{:error, reason} ->
raise File.Error, reason: reason, action: "get current working directory"
raise File.Error, reason: reason, action: "get current working directory"
end
end
@@ -1113,11 +1037,11 @@ defmodule File do
"""
@spec cd!(Path.t) :: :ok | no_return
def cd!(path) do
case cd(path) do
path = IO.chardata_to_string(path)
case F.set_cwd(path) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "set current working directory to",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "set current working directory to", path: path
end
end
@@ -1160,11 +1084,11 @@ defmodule File do
"""
@spec ls!(Path.t) :: [binary] | no_return
def ls!(path \\ ".") do
path = IO.chardata_to_string(path)
case ls(path) do
{:ok, value} -> value
{:error, reason} ->
raise File.Error, reason: reason, action: "list directory",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "list directory", path: path
end
end
@@ -1201,23 +1125,10 @@ defmodule File do
device cannot be shared and as such it is convenient to open the file
in raw mode for performance reasons. Therefore, Elixir **will** open
streams in `:raw` mode with the `:read_ahead` option unless an encoding
is specified. This means any data streamed into the file must be
converted to `iodata` type. If you pass `[:utf8]` in the modes parameter,
the underlying stream will use `IO.write/2` and the `String.Chars` protocol
to convert the data. See `IO.binwrite/2` and `IO.write/2` .
is specified.
One may also consider passing the `:delayed_write` option if the stream
is meant to be written to under a tight loop.
## Examples
# Read in 2048 byte chunks rather than lines
File.stream!("./test/test.data", [], 2048)
#=> %File.Stream{line_or_bytes: 2048, modes: [:raw, :read_ahead, :binary],
#=> path: "./test/test.data", raw: true}
See `Stream.run/1` for an example of streaming into a file.
"""
def stream!(path, modes \\ [], line_or_bytes \\ :line) do
modes = open_defaults(modes, true)
@@ -1225,28 +1136,9 @@ defmodule File do
end
@doc """
Changes the `mode` for a given `file`.
Returns `:ok` on success, or `{:error, reason}` on failure.
## Permissions
* 0o400 - read permission: owner
* 0o200 - write permission: owner
* 0o100 - execute permission: owner
* 0o040 - read permission: group
* 0o020 - write permission: group
* 0o010 - execute permission: group
* 0o004 - read permission: other
* 0o002 - write permission: other
* 0o001 - execute permission: other
For example, setting the mode 0o755 gives it
write, read and execute permission to the owner
and both read and execute permission to group
and others.
Changes the unix file `mode` for a given `file`.
Returns `:ok` on success, or `{:error, reason}`
on failure.
"""
@spec chmod(Path.t, non_neg_integer) :: :ok | {:error, posix}
def chmod(path, mode) do
@@ -1258,11 +1150,11 @@ defmodule File do
"""
@spec chmod!(Path.t, non_neg_integer) :: :ok | no_return
def chmod!(path, mode) do
path = IO.chardata_to_string(path)
case chmod(path, mode) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "change mode for",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "change mode for", path: path
end
end
@@ -1281,11 +1173,11 @@ defmodule File do
"""
@spec chgrp!(Path.t, non_neg_integer) :: :ok | no_return
def chgrp!(path, gid) do
path = IO.chardata_to_string(path)
case chgrp(path, gid) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "change group for",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "change group for", path: path
end
end
@@ -1304,11 +1196,11 @@ defmodule File do
"""
@spec chown!(Path.t, non_neg_integer) :: :ok | no_return
def chown!(path, uid) do
path = IO.chardata_to_string(path)
case chown(path, uid) do
:ok -> :ok
{:error, reason} ->
raise File.Error, reason: reason, action: "change owner for",
path: IO.chardata_to_string(path)
raise File.Error, reason: reason, action: "change owner for", path: path
end
end
+2 -3
View File
@@ -6,7 +6,7 @@ defmodule File.Stat do
In Erlang, this struct is represented by a `:file_info` record.
Therefore this module also provides functions for converting
between the Erlang record and the Elixir struct.
in between the Erlang record and the Elixir struct.
Its fields are:
@@ -48,7 +48,7 @@ defmodule File.Stat do
The time type returned in `atime`, `mtime`, and `ctime` is dependent on the
time type set in options. `{:time, type}` where type can be `:local`,
`:universal`, or `:posix`. Default is `:universal`.
`:universal`, or `:posix`. Default is `:local`.
"""
record = Record.extract(:file_info, from_lib: "kernel/include/file.hrl")
@@ -69,7 +69,6 @@ defmodule File.Stat do
@doc """
Converts a `:file_info` record into a `File.Stat`.
"""
def from_record(file_info)
def from_record({:file_info, unquote_splicing(vals)}) do
%File.Stat{unquote_splicing(pairs)}
end
+4
View File
@@ -34,6 +34,10 @@ defmodule File.Stream do
end
defimpl Collectable do
def empty(stream) do
stream
end
def into(%{path: path, modes: modes, raw: raw} = stream) do
modes = for mode <- modes, not mode in [:read], do: mode
+37 -44
View File
@@ -8,22 +8,19 @@ defmodule Float do
@doc """
Parses a binary into a float.
If successful, returns a tuple of the form `{float, remainder_of_binary}`;
otherwise, `:error`.
If a float formatted string wants to be directly converted to a float,
`String.to_float/1` can be used instead.
If successful, returns a tuple of the form `{float, remainder_of_binary}`.
Otherwise `:error`.
## Examples
iex> Float.parse("34")
{34.0, ""}
{34.0,""}
iex> Float.parse("34.25")
{34.25, ""}
{34.25,""}
iex> Float.parse("56.5xyz")
{56.5, "xyz"}
{56.5,"xyz"}
iex> Float.parse("pi")
:error
@@ -37,31 +34,27 @@ defmodule Float do
end
end
def parse("+" <> binary) do
parse_unsigned(binary)
end
def parse(binary) do
parse_unsigned(binary)
end
defp parse_unsigned(<<digit, rest::binary>>) when digit in ?0..?9, do:
parse_unsigned(rest, false, false, <<digit>>)
defp parse_unsigned(<<char, rest::binary>>) when char in ?0..?9, do:
parse_unsigned(rest, false, false, <<char>>)
defp parse_unsigned(binary) when is_binary(binary), do:
:error
defp parse_unsigned(<<digit, rest :: binary>>, dot?, e?, acc) when digit in ?0..?9, do:
parse_unsigned(rest, dot?, e?, <<acc::binary, digit>>)
defp parse_unsigned(<<char, rest :: binary>>, dot?, e?, acc) when char in ?0..?9, do:
parse_unsigned(rest, dot?, e?, <<acc::binary, char>>)
defp parse_unsigned(<<?., digit, rest :: binary>>, false, false, acc) when digit in ?0..?9, do:
parse_unsigned(rest, true, false, <<acc::binary, ?., digit>>)
defp parse_unsigned(<<?., char, rest :: binary>>, false, false, acc) when char in ?0..?9, do:
parse_unsigned(rest, true, false, <<acc::binary, ?., char>>)
defp parse_unsigned(<<exp_marker, digit, rest :: binary>>, dot?, false, acc) when exp_marker in 'eE' and digit in ?0..?9, do:
parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, digit>>)
defp parse_unsigned(<<?e, char, rest :: binary>>, dot?, false, acc) when char in ?0..?9, do:
parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, char>>)
defp parse_unsigned(<<exp_marker, sign, digit, rest :: binary>>, dot?, false, acc) when exp_marker in 'eE' and sign in '-+' and digit in ?0..?9, do:
parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, sign, digit>>)
defp parse_unsigned(<<?e, ?-, char, rest :: binary>>, dot?, false, acc) when char in ?0..?9, do:
parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, ?-, char>>)
defp parse_unsigned(rest, dot?, _e?, acc), do:
{:erlang.binary_to_float(add_dot(acc, dot?)), rest}
@@ -72,10 +65,10 @@ defmodule Float do
@doc """
Rounds a float to the largest integer less than or equal to `num`.
`floor/2` also accepts a precision to round a floating point value down
Floor also accepts a precision to round a floating point value down
to an arbitrary number of fractional digits (between 0 and 15).
This function always returns a float. `Kernel.trunc/1` may be used instead to
This function always returns floats. One may use `Kernel.trunc/1` to
truncate the result to an integer afterwards.
## Examples
@@ -102,10 +95,10 @@ defmodule Float do
@doc """
Rounds a float to the largest integer greater than or equal to `num`.
`ceil/2` also accepts a precision to round a floating point value down
to an arbitrary number of fractional digits (between 0 and 15).
Ceil also accepts a precision to round a floating point value down to
an arbitrary number of fractional digits (between 0 and 15).
This function always returns floats. `Kernel.trunc/1` may be used instead to
This function always returns floats. One may use `Kernel.trunc/1` to
truncate the result to an integer afterwards.
## Examples
@@ -133,9 +126,9 @@ defmodule Float do
Rounds a floating point value to an arbitrary number of fractional digits
(between 0 and 15).
This function only accepts floats and always returns a float. Use
`Kernel.round/1` if you want a function that accepts both floats and integers
and always returns an integer.
This function only accepts floats and returns floats. Use `Kernel.round/1`
if you want a function that accepts both floats and integers and always
returns an integer.
## Examples
@@ -175,20 +168,20 @@ defmodule Float do
"""
@spec to_char_list(float) :: char_list
def to_char_list(float) do
:erlang.float_to_list(float)
def to_char_list(number) do
:erlang.float_to_list(number)
end
@doc """
Returns a list which corresponds to the text representation
of the given float.
of `float`.
## Options
* `:decimals` - number of decimal points to show
* `:scientific` - number of decimal points to show, in scientific format
* `:compact` - when `true`, use the most compact representation (ignored
with the `scientific` option)
* `:decimals` — number of decimal points to show
* `:scientific` — number of decimal points to show, in scientific format
* `:compact` — when true, use the most compact representation (ignored
with the `scientific` option)
## Examples
@@ -203,7 +196,7 @@ defmodule Float do
@doc """
Returns a binary which corresponds to the text representation
of the given float.
of `some_float`.
Inlined by the compiler.
@@ -214,8 +207,8 @@ defmodule Float do
"""
@spec to_string(float) :: String.t
def to_string(float) do
:erlang.float_to_binary(float)
def to_string(some_float) do
:erlang.float_to_binary(some_float)
end
@doc """
@@ -224,10 +217,10 @@ defmodule Float do
## Options
* `:decimals` - number of decimal points to show
* `:scientific` - number of decimal points to show, in scientific format
* `:compact` - when `true`, use the most compact representation (ignored
with the `scientific` option)
* `:decimals` — number of decimal points to show
* `:scientific` — number of decimal points to show, in scientific format
* `:compact` — when true, use the most compact representation (ignored
with the `scientific` option)
## Examples
+80 -183
View File
@@ -8,7 +8,7 @@ defmodule GenEvent do
An event manager implemented using this module will have a standard
set of interface functions and include functionality for tracing and
error reporting. It will also fit into a supervision tree.
error reporting. It will also fit into an supervision tree.
## Example
@@ -36,7 +36,7 @@ defmodule GenEvent do
end
end
{:ok, pid} = GenEvent.start_link([])
{:ok, pid} = GenEvent.start_link()
GenEvent.add_handler(pid, LoggerHandler, [])
#=> :ok
@@ -53,19 +53,67 @@ defmodule GenEvent do
GenEvent.call(pid, LoggerHandler, :messages)
#=> []
We start a new event manager by calling `GenEvent.start_link/1`.
We start a new event manager by calling `GenEvent.start_link/0`.
Notifications can be sent to the event manager which will then
invoke `handle_event/2` for each registered handler.
We can add new handlers with `add_handler/3` and `add_mon_handler/3`.
Calls can also be made to specific handlers by using `call/3`.
We can add new handlers with `add_handler/3`. Calls can also
be made to specific handlers by using `call/3`.
## Callbacks
There are 6 callbacks required to be implemented in a `GenEvent`. By
adding `use GenEvent` to your module, Elixir will automatically define
all 6 callbacks for you, leaving it up to you to implement the ones
you want to customize.
you want to customize. The callbacks are:
* `init(args)` - invoked when the event handler is added.
It must return:
- `{:ok, state}`
- `{:ok, state, :hibernate}`
- `{:error, reason}`
* `handle_event(msg, state)` - invoked whenever an event is sent via
`notify/2`, `ack_notify/2` or `sync_notify/2`.
It must return:
- `{:ok, new_state}`
- `{:ok, new_state, :hibernate}`
- `:remove_handler`
* `handle_call(msg, state)` - invoked when a `call/3` is done to a specific
handler.
It must return:
- `{:ok, reply, new_state}`
- `{:ok, reply, new_state, :hibernate}`
- `{:remove_handler, reply}`
* `handle_info(msg, state)` - invoked to handle all other messages which
are received by the process. Must return the same values as
`handle_event/2`.
* `terminate(reason, state)` - called when the event handler is removed or
the event manager is terminating. It can return any term.
The reason is one of:
- `:stop` - manager is terminating
- `{:stop, reason}` - monitored process terminated (for monitored handlers)
- `:remove_handler` - handler is being removed
- `{:error, term}` - handler crashed or returned a bad value
- `term` - any term passed to functions like `GenEvent.remove_handler/2`
* `code_change(old_vsn, state, extra)` - called when the application
code is being upgraded live (hot code swapping).
It must return:
- `{:ok, new_state}`
## Name Registration
@@ -77,7 +125,7 @@ defmodule GenEvent do
GenEvent stream supports three different notifications.
On `GenEvent.ack_notify/2`, the manager acknowledges each event,
providing backpressure, but processing of the message happens
providing back pressure, but processing of the message happens
asynchronously.
On `GenEvent.sync_notify/2`, the manager acknowledges an event
@@ -88,24 +136,21 @@ defmodule GenEvent do
## Streaming
`GenEvent` messages can be streamed with the help of `stream/2`.
You will need to start another process to consume the stream:
`GenEvent`s can be streamed from and streamed with the help of `stream/2`.
Here are some examples:
Task.start_link fn ->
stream = GenEvent.stream(pid)
stream = GenEvent.stream(pid)
# Discard the next 3 events
_ = Enum.drop(stream, 3)
# Take the next 10 events
Enum.take(stream, 10)
# Print all remaining events
for event <- stream do
IO.inspect event
end
# Print all remaining events
for event <- stream do
IO.inspect event
end
Now call `GenEvent.notify/2` multiple times. You will see the
first three events will be skipped while the rest will be
continuously printed.
A stream may also be given an id, which allows all streams with the given
id to be cancelled at any moment via `cancel_streams/1`.
## Learn more and compatibility
@@ -113,9 +158,9 @@ defmodule GenEvent do
guides provide a tutorial-like introduction. The documentation and links
in Erlang can also provide extra insight.
* [Introduction to Mix – Elixir's Getting Started Guide](http://elixir-lang.org/getting-started/mix-otp/introduction-to-mix.html)
* [`:gen_event` module documentation](http://www.erlang.org/doc/man/gen_event.html)
* [Event Handlers – Learn You Some Erlang for Great Good!](http://learnyousomeerlang.com/event-handlers)
* http://elixir-lang.org/getting_started/mix/1.html
* http://www.erlang.org/doc/man/gen_event.html
* http://learnyousomeerlang.com/event-handlers
Keep in mind though Elixir and Erlang gen events are not 100% compatible.
The `:gen_event.add_sup_handler/3` is not supported by Elixir's GenEvent,
@@ -125,158 +170,11 @@ defmodule GenEvent do
too much kool aid" section of the "Learn you some Erlang" link above. Due
to those changes, Elixir's GenEvent does not trap exits by default.
Furthermore, Elixir's also normalizes the `{:error, _}` tuples returned
Futhermore, Elixir's also normalizes the `{:error, _}` tuples returned
by many functions, in order to be more consistent with themselves and
the `GenServer` module.
"""
@doc """
Invoked when the handler is added to the `GenEvent` process. `add_handler/3`,
(and `add_mon_handler/3`) will block until it returns.
`args` is the argument term (third argument) passed to `add_handler/3`.
Returning `{:ok, state}` will cause `add_handler/3` to return `:ok` and the
handler to become part of the `GenEvent` loop with state `state`.
Returning `{:ok, state, :hibernate}` is similar to
`{:ok, state}` except the `GenEvent` process is hibernated before continuing
its loop. See `handle_event/2` for more information on hibernation.
Returning `{:error, reason}` will cause `add_handler/3` to return
`{:error, reason}` and the handler is not added to `GenEvent` loop.
"""
@callback init(args :: term) ::
{:ok, state} |
{:ok, state, :hibernate} |
{:error, reason :: any} when state: any
@doc """
Invoked to handle `notify/2`, `ack_notify/2` or `sync_notify/2` messages.
`event` is the event message and `state` is the current state of the handler.
Returning `{:ok, new_state}` sets the handler's state to `new_state` and the
`GenEvent` loop continues.
Returning `{:ok, new_state, :hibernate}` is similar to
`{:ok, new_state}` except the process is hibernated once all handlers have
handled the events. The `GenEvent` process will continue the loop once a
message is its message queue. If a message is already in the message queue
this will be immediately. Hibernating a `GenEvent` causes garbage collection
and leaves a continuous heap that minimises the memory used by the process.
Hibernating should not be used aggressively as too much time could be spent
garbage collecting. Normally it should only be used when a message is not
expected soon and minimising the memory of the process is shown to be
beneficial.
Returning `:remove_handler` removes the handler from the `GenEvent` loop and
calls `terminate/2` with reason `:remove_handler` and state `state`.
"""
@callback handle_event(event :: term, state :: term) ::
{:ok, new_state} |
{:ok, new_state, :hibernate} |
:remove_handler when new_state: term
@doc """
Invoked to handle synchronous `call/4` messages to a specific handler.
`request` is the request message sent by a `call/4` and `state` is the current
state of the handler.
Returning `{:ok, reply, new_state}` sends `reply` as a response to the call
and sets the handler's state to `new_state`.
Returning `{:ok, reply, new_state, :hibernate}` is similar to
`{:ok, reply, new_state}` except the process is hibernated. See
`handle_event/2` for more information on hibernation.
Returning `{:remove_handler, reply}` sends `reply` as a reponse to the call,
removes the handler from the `GenEvent` loop and calls `terminate/2` with
reason `:remove_handler` and state `state`.
"""
@callback handle_call(request :: term, state :: term) ::
{:ok, reply, new_state} |
{:ok, reply, new_state, :hibernate} |
{:remove_handler, reply} when reply: term, new_state: term
@doc """
Invoked to handle all other messages. All handlers are run in the `GenEvent`
process so messages intended for other handlers should be ignored with a catch
all clause.
`msg` is the message and `state` is the current state of the handler.
Return values are the same as `handle_event/2`.
"""
@callback handle_info(msg :: term, state :: term) ::
{:ok, new_state} |
{:ok, new_state, :hibernate} |
:remove_handler when new_state: term
@doc """
Invoked when the server is about to exit. It should do any cleanup required.
`reason` is removal reason and `state` is the current state of the handler.
The return value is returned to `GenEvent.remove_handler/3` or ignored if
removing for another reason.
`reason` is one of:
- `:stop` - manager is terminating
- `{:stop, term}` - monitored process terminated (for monitored handlers)
- `:remove_handler` - handler is being removed
- `{:error, term}` - handler crashed or returned a bad value and an error is
logged
- `term` - any term passed to functions like `GenEvent.remove_handler/3`
If part of a supervision tree, a `GenEvent`'s `Supervisor` will send an exit
signal when shutting it down. The exit signal is based on the shutdown
strategy in the child's specification. If it is `:brutal_kill` the `GenEvent`
is killed and so `terminate/2` is not called for its handlers. However if it is
a timeout the `Supervisor` will send the exit signal `:shutdown` and the
`GenEvent` will have the duration of the timeout to call `terminate/2` on all
of its handlers - if the process is still alive after the timeout it is
killed.
If the `GenEvent` receives an exit signal (that is not `:normal`) from any
process when it is not trapping exits it will exit abruptly with the same
reason and so not call the handlers' `terminate/2`. Note that a process does
*NOT* trap exits by default and an exit signal is sent when a linked process
exits or its node is disconnected. Therefore it is not guaranteed that
`terminate/2` is called when a `GenEvent` exits.
Care should be taken to cleanup because the `GenEvent` can continue is loop
after removing the handler. This is different to most other OTP behaviours.
For example if the handler controls a `port` (e.g. `:gen_tcp.socket`) or
`File.io_device`, it will be need to be closed in `terminate/2` as the
process is not exiting so will not be automatically cleaned up.
"""
@callback terminate(reason, state :: term) ::
term when reason: :stop | {:stop, term} | :remove_handler | {:error, term} | term
@doc """
Invoked to change the state of the handler when a different version of the
handler's module module is loaded (hot code swapping) and the state's term
structure should be changed.
`old_vsn` is the previous version of the module (defined by the `@vsn`
attribute) when upgrading. When downgrading the previous version is wrapped in
a 2-tuple with first element `:down`. `state` is the current state of the
handker and `extra` is any extra data required to change the state.
Returning `{:ok, new_state}` changes the state to `new_state` and the code
change is successful.
If `code_change/3` raises, the code change fails and the handler will continue
with its previous state. Therefore this callback does not usually contain side
effects.
"""
@callback code_change(old_vsn, state :: term, extra :: term) ::
{:ok, new_state :: term} when old_vsn: term | {:down, term}
@typedoc "Return values of `start*` functions"
@type on_start :: {:ok, pid} | {:error, {:already_started, pid}}
@@ -290,7 +188,7 @@ defmodule GenEvent do
@type manager :: pid | name | {atom, node}
@typedoc "Supported values for new handlers"
@type handler :: atom | {atom, term}
@type handler :: atom | {atom, term} | {pid, reference}
@doc false
defmacro __using__(_) do
@@ -310,10 +208,9 @@ defmodule GenEvent do
@doc false
def handle_call(msg, state) do
# We do this to trick dialyzer to not complain about non-local returns.
reason = {:bad_call, msg}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:remove_handler, reason}
case :random.uniform(1) do
1 -> exit({:bad_call, msg})
2 -> {:remove_handler, :ok}
end
end
@@ -346,8 +243,8 @@ defmodule GenEvent do
section in the `GenServer` module docs.
If the event manager is successfully created and initialized, the function
returns `{:ok, pid}`, where pid is the pid of the server. If a process with
the specified server name already exists, the function returns
returns `{:ok, pid}`, where pid is the pid of the server. If there already
exists a process with the specified server name, the function returns
`{:error, {:already_started, pid}}` with the pid of that process.
Note that a `GenEvent` started with `start_link/1` is linked to the
@@ -508,7 +405,7 @@ defmodule GenEvent do
Sends a sync event notification to the event `manager`.
In other words, this function only returns `:ok` after the event manager
invokes the `handle_event/2` callback on each installed event handler.
invokes the `handle_event/2` on each installed event handler.
See `notify/2` for more info.
"""
@@ -572,7 +469,7 @@ defmodule GenEvent do
First, the old event handler is deleted by calling `terminate/2` with
the given `args1` and collects the return value. Then the new event handler
is added and initiated by calling `init({args2, term})`, where `term` is the
is added and initiated by calling `init({args2, state}), where term is the
return value of calling `terminate/2` in the old handler. This makes it
possible to transfer information from one handler to another.
@@ -618,7 +515,7 @@ defmodule GenEvent do
end
defp rpc(module, cmd) do
# TODO: Change the tag on OTP 18
# TODO: Change the tag once patch is accepted by OTP
{:ok, reply} = :gen.call(module, self(), cmd, :infinity)
reply
end
@@ -759,7 +656,7 @@ defmodule GenEvent do
end
@doc false
def system_code_change([name, handlers, hib], module, old_vsn, extra) do
def system_code_change([name, handlers, hib], module , old_vsn, extra) do
handlers =
for handler <- handlers do
if handler(handler, :module) == module do
@@ -1116,7 +1013,7 @@ defmodule GenEvent do
defp report_error(handler, reason, state, last_in, name) do
reason =
case reason do
{:undef, [{m, f, a, _}|_]=mfas} ->
{:undef, [{m,f,a,_}|_]=mfas} ->
cond do
:code.is_loaded(m) === false ->
{:"module could not be loaded", mfas}
+10 -13
View File
@@ -6,7 +6,7 @@ defmodule GenEvent.Stream do
contains the following fields:
* `:manager` - the manager reference given to `GenEvent.stream/2`
* `:timeout` - the timeout between events, defaults to `:infinity`
* `:timeout` - the timeout in between events, defaults to `:infinity`
"""
defstruct manager: nil, timeout: :infinity
@@ -22,21 +22,12 @@ defmodule GenEvent.Stream do
@doc false
def handle_event(event, _state) do
# We do this to trick dialyzer to not complain about non-local returns.
case :erlang.phash2(1, 1) do
0 -> exit({:bad_event, event})
1 -> :remove_handler
end
exit({:bad_event, event})
end
@doc false
def handle_call(msg, _state) do
# We do this to trick dialyzer to not complain about non-local returns.
reason = {:bad_call, msg}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:remove_handler, reason}
end
exit({:bad_call, msg})
end
@doc false
@@ -152,9 +143,15 @@ defimpl Enumerable, for: GenEvent.Stream do
defp wait_for_handler_removal(pid, ref, mon_ref) do
receive do
{:gen_event_EXIT, {^pid, ^ref}, _reason} ->
{:gen_event_EXIT, {^pid, ^ref}, reason}
when reason == :normal
when reason == :shutdown
when tuple_size(reason) == 3 and elem(reason, 0) == :swapped ->
Process.demonitor(mon_ref, [:flush])
:ok
{:gen_event_EXIT, {^pid, ^ref}, reason} ->
Process.demonitor(mon_ref, [:flush])
{:error, reason}
{:DOWN, ^mon_ref, _, _, reason} ->
{:error, reason}
end
+67 -297
View File
@@ -61,7 +61,50 @@ defmodule GenServer do
There are 6 callbacks required to be implemented in a `GenServer`. By
adding `use GenServer` to your module, Elixir will automatically define
all 6 callbacks for you, leaving it up to you to implement the ones
you want to customize.
you want to customize. The callbacks are:
* `init(args)` - invoked when the server is started.
It must return:
- `{:ok, state}`
- `{:ok, state, timeout}`
- `:ignore`
- `{:stop, reason}`
* `handle_call(msg, {from, ref}, state)` and `handle_cast(msg, state)` -
invoked to handle call (sync) and cast (async) messages.
It must return:
- `{:reply, reply, new_state}`
- `{:reply, reply, new_state, timeout}`
- `{:reply, reply, new_state, :hibernate}`
- `{:noreply, new_state}`
- `{:noreply, new_state, timeout}`
- `{:noreply, new_state, :hibernate}`
- `{:stop, reason, new_state}`
- `{:stop, reason, reply, new_state}`
* `handle_info(msg, state)` - invoked to handle all other messages which
are received by the process.
It must return:
- `{:noreply, state}`
- `{:noreply, state, timeout}`
- `{:stop, reason, state}`
* `terminate(reason, state)` - called when the server is about to
terminate, useful for cleaning up. It must return `:ok`.
* `code_change(old_vsn, state, extra)` - called when the application
code is being upgraded live (hot code swapping).
It must return:
- `{:ok, new_state}`
- `{:error, reason}`
## Name Registration
@@ -148,228 +191,18 @@ defmodule GenServer do
the same module. If the server and/or client implementations are growing
complex, you may want to have them in different modules.
## Receiving custom messages
The goal of a `GenServer` is to abstract the "receive" loop for developers,
automatically handling system messages, support code change, synchronous
calls and more. Therefore, you should never call your own "receive" inside
the GenServer callbacks as doing so will cause the GenServer to misbehave.
If you want to receive custom messages, always receive them in `handle_info/2`.
## Learn more
If you wish to find out more about gen servers, the Elixir Getting Started
guide provides a tutorial-like introduction. The documentation and links
If you wish to find out more about gen servers, Elixir getting started
guides provide a tutorial-like introduction. The documentation and links
in Erlang can also provide extra insight.
* [GenServer – Elixir's Getting Started Guide](http://elixir-lang.org/getting-started/mix-otp/genserver.html)
* [`:gen_server` module documentation](http://www.erlang.org/doc/man/gen_server.html)
* [gen_server Behaviour – OTP Design Principles](http://www.erlang.org/doc/design_principles/gen_server_concepts.html)
* [Clients and Servers – Learn You Some Erlang for Great Good!](http://learnyousomeerlang.com/clients-and-servers)
* http://elixir-lang.org/getting_started/mix/1.html
* http://www.erlang.org/doc/man/gen_server.html
* http://www.erlang.org/doc/design_principles/gen_server_concepts.html
* http://learnyousomeerlang.com/clients-and-servers
"""
@doc """
Invoked when the server is started. `start_link/3` (or `start/3`) will
block until it returns.
`args` is the argument term (second argument) passed to `start_link/3`.
Returning `{:ok, state}` will cause `start_link/3` to return
`{:ok, pid}` and the process to enter its loop.
Returning `{:ok, state, timeout}` is similar to `{:ok, state}`
except `handle_info(:timeout, state)` will be called after `timeout`
milliseconds if no messages are received within the timeout.
Returning `{:ok, state, :hibernate}` is similar to
`{:ok, state}` except the process is hibernated before entering the loop. See
`handle_call/3` for more information on hibernation.
Returning `:ignore` will cause `start_link/3` to return `:ignore` and the
process will exit normally without entering the loop or calling `terminate/2`.
If used when part of a supervision tree the parent supervisor will not fail
to start nor immediately try to restart the `GenServer`. The remainder of the
supervision tree will be (re)started and so the `GenServer` should not be
required by other processes. It can be started later with
`Supervisor.restart_child/2` as the child specification is saved in the parent
supervisor. The main use cases for this are:
- The `GenServer` is disabled by configuration but might be enabled later.
- An error occured and it will be handled by a different mechanism than the
`Supervisor`. Likely this approach involves calling `Supervisor.restart_child/2`
after a delay to attempt a restart.
Returning `{:stop, reason}` will cause `start_link/3` to return
`{:error, reason}` and the process to exit with reason `reason` without
entering the loop or calling `terminate/2`.
"""
@callback init(args :: term) ::
{:ok, state} |
{:ok, state, timeout | :hibernate} |
:ignore |
{:stop, reason :: any} when state: any
@doc """
Invoked to handle synchronous `call/3` messages. `call/3` will block until a
reply is received (unless the call times out or nodes are disconnected).
`request` is the request message sent by a `call/3`, `from` is a 2-tuple
containing the caller's pid and a term that uniquely identifies the call, and
`state` is the current state of the `GenServer`.
Returning `{:reply, reply, new_state}` sends the response `reply` to the
caller and continues the loop with new state `new_state`.
Returning `{:reply, reply, new_state, timeout}` is similar to
`{:reply, reply, new_state}` except `handle_info(:timeout, new_state)` will be
called after `timeout` milliseconds if no messages are receved.
Returning `{:reply, reply, new_state, :hibernate}` is similar to
`{:reply, reply, new_state}` except the process is hibernated and will
continue the loop once a message is its message queue. If a message is already
in the message queue this will be immediately. Hibernating a `GenServer`
causes garbage collection and leaves a continuous heap that minimises the
memory used by the process.
Hibernating should not be used aggressively as too much time could be spent
garbage collecting. Normally it should only be used when a message is not
expected soon and minimising the memory of the process is shown to be
beneficial.
Returning `{:noreply, new_state}` does not send a response to the caller and
continues the loop with new state `new_state`. The response must be sent with
`reply/2`.
There are three main use cases for not replying using the return value:
- To reply before returning from the callback because the response is known
before calling a slow function.
- To reply after returning from the callback because the response is not yet
available.
- To reply from another process, such as a task.
When replying from another process the `GenServer` should exit if the other
process exits without replying as the caller will be blocking awaiting a
reply.
Returning `{:noreply, new_state, timeout | :hibernate}` is similar to
`{:noreply, new_state}` except a timeout or hibernation occurs as with a
`:reply` tuple.
Returning `{:stop, reason, reply, new_state}` stops the loop and `terminate/2`
is called with reason `reason` and state `new_state`. Then the `reply` is sent
as the response to call and the process exits with reason `reason`.
Returning `{:stop, reason, new_state}` is similar to
`{:stop, reason, reply, new_state}` except a reply is not sent.
"""
@callback handle_call(request :: term, from, state :: term) ::
{:reply, reply, new_state} |
{:reply, reply, new_state, timeout | :hibernate} |
{:noreply, new_state} |
{:noreply, new_state, timeout | :hibernate} |
{:stop, reason, reply, new_state} |
{:stop, reason, new_state} when reply: term, new_state: term, reason: term
@doc """
Invoked to handle asynchronous `cast/2` messages.
`request` is the request message sent by a `cast/2` and `state` is the current
state of the `GenServer`.
Returning `{:noreply, new_state}` continues the loop with new state `new_state`.
Returning `{:noreply, new_state, timeout}` is similar to
`{:noreply, reply, new_state}` except `handle_info(:timeout, new_state)` will
be called after `timeout` milliseconds if no messages are received.
Returning `{:noreply, new_state, :hibernate}` is similar to
`{:noreply, new_state}` except the process is hibernated before continuing the
loop. See `handle_call/3` for more information.
Returning `{:stop, reason, new_state}` stops the loop and `terminate/2` is
called with the reason `reason` and state `new_state`. The process exits with
reason `reason`.
"""
@callback handle_cast(request :: term, state :: term) ::
{:noreply, new_state} |
{:noreply, new_state, timeout | :hibernate} |
{:stop, reason :: term, new_state} when new_state: term
@doc """
Invoked to handle all other messages.
`msg` is the message and `state` is the current state of the `GenServer`. When
a timeout occurs the message is `:timeout`.
Return values are the same as `handle_cast/2`.
"""
@callback handle_info(msg :: :timeout | term, state :: term) ::
{:noreply, new_state} |
{:noreply, new_state, timeout | :hibernate} |
{:stop, reason :: term, new_state} when new_state: term
@doc """
Invoked when the server is about to exit. It should do any cleanup required.
`reason` is exit reason and `state` is the current state of the `GenServer`.
The return value is ignored.
`terminate/2` is called if a callback (except `init/1`) returns a `:stop`
tuple, raises, calls `Kernel.exit/1` or returns an invalid value. It may also
be called if the `GenServer` traps exits using `Process.flag/2` *and* the
parent process sends an exit signal.
If part of a supervision tree a `GenServer`'s `Supervisor` will send an exit
signal when shutting it down. The exit signal is based on the shutdown
strategy in the child's specification. If it is `:brutal_kill` the `GenServer`
is killed and so `terminate/2` is not called. However if it is a timeout the
`Supervisor` will send the exit signal `:shutdown` and the `GenServer` will
have the duration of the timeout to call `terminate/2` - if the process is
still alive after the timeout it is killed.
If the `GenServer` receives an exit signal (that is not `:normal`) from any
process when it is not trapping exits it will exit abruptly with the same
reason and so not call `terminate/2`. Note that a process does *NOT* trap
exits by default and an exit signal is sent when a linked process exits or its
node is disconnected.
Therefore it is not guaranteed that `terminate/2` is called when a `GenServer`
exits. For such reasons, we usually recommend important clean-up rules to
happen in separated processes either by use of monitoring or by links
themselves. For example if the `GenServer` controls a `port` (e.g.
`:gen_tcp.socket`) or `File.io_device`, they will be closed on receiving a
`GenServer`'s exit signal and do not need to be closed in `terminate/2`.
If `reason` is not `:normal`, `:shutdown` nor `{:shutdown, term}` an error is
logged.
"""
@callback terminate(reason, state :: term) ::
term when reason: :normal | :shutdown | {:shutdown, term} | term
@doc """
Invoked to change the state of the `GenServer` when a different version of a
module is loaded (hot code swapping) and the state's term structure should be
changed.
`old_vsn` is the previous version of the module (defined by the `@vsn`
attribute) when upgrading. When downgrading the previous version is wrapped in
a 2-tuple with first element `:down`. `state` is the current state of the
`GenServer` and `extra` is any extra data required to change the state.
Returning `{:ok, new_state}` changes the state to `new_state` and the code
change is successful.
Returning `{:error, reason}` fails the code change with reason `reason` and
the state remains as the previous state.
If `code_change/3` raises the code change fails and the loop will continue
with its previous state. Therefore this callback does not usually contain side effects.
"""
@callback code_change(old_vsn, state :: term, extra :: term) ::
{:ok, new_state :: term} |
{:error, reason :: term} when old_vsn: term | {:down, term}
@typedoc "Return values of `start*` functions"
@type on_start :: {:ok, pid} | :ignore | {:error, {:already_started, pid} | term}
@@ -377,28 +210,17 @@ defmodule GenServer do
@type name :: atom | {:global, term} | {:via, module, term}
@typedoc "Options used by the `start*` functions"
@type options :: [option]
@type options :: [debug: debug,
name: name,
timeout: timeout,
spawn_opt: Process.spawn_opt]
@typedoc "Option values used by the `start*` functions"
@type option :: {:debug, debug} |
{:name, name} |
{:timeout, timeout} |
{:spawn_opt, Process.spawn_opt}
@typedoc "Debug options supported by the `start*` functions"
@typedoc "debug options supported by the `start*` functions"
@type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t}]
@typedoc "The server reference"
@type server :: pid | name | {atom, node}
@typedoc """
Tuple describing the client of a call request.
`pid` is the pid of the caller and `tag` is a unique term used to identify the
call.
"""
@type from :: {pid, tag :: term}
@doc false
defmacro __using__(_) do
quote location: :keep do
@@ -411,12 +233,7 @@ defmodule GenServer do
@doc false
def handle_call(msg, _from, state) do
# We do this to trick Dialyzer to not complain about non-local returns.
reason = {:bad_call, msg}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:stop, reason, state}
end
{:stop, {:bad_call, msg}, state}
end
@doc false
@@ -426,12 +243,7 @@ defmodule GenServer do
@doc false
def handle_cast(msg, state) do
# We do this to trick Dialyzer to not complain about non-local returns.
reason = {:bad_cast, msg}
case :erlang.phash2(1, 1) do
0 -> exit(reason)
1 -> {:stop, reason, state}
end
{:stop, {:bad_cast, msg}, state}
end
@doc false
@@ -479,8 +291,8 @@ defmodule GenServer do
## Return values
If the server is successfully created and initialized, the function returns
`{:ok, pid}`, where pid is the pid of the server. If a process with the
specified server name already exists, the function returns
`{:ok, pid}`, where pid is the pid of the server. If there already exists a
process with the specified server name, the function returns
`{:error, {:already_started, pid}}` with the pid of that process.
If the `init/1` callback fails with `reason`, the function returns
@@ -550,24 +362,17 @@ defmodule GenServer do
@doc """
Sends an asynchronous request to the `server`.
This function returns `:ok` without waiting for the
destination `server` to handle the message. Therefore it
is unknown whether the destination `server` successfully
handled the message. If the `server` is an atom without
an associated process an `ArgumentError` is raised. In
all other cases the function returns `:ok` regardless of
whether the destination `server` (or node) exists. Note
that `{name, node()}` can be used when an exception is
not desired if no process is locally associated with the
atom `name`.
This function returns `:ok` immediately, regardless of
whether the destination node or server does exists, unless
the server is specified as an atom.
`handle_cast/2` will be called on the server to handle
the request. In case the `server` is on a node which is
not yet connected to the caller one, the call is going to
the request. In case the server is a node which is not
yet connected to the caller one, the call is going to
block until a connection happens. This is different than
the behaviour in OTP's `:gen_server` where the message
is sent by another process in this case, which could cause
messages to other nodes to arrive out of order.
would be sent by another process, which could cause
messages to arrive out of order.
"""
@spec cast(server, term) :: :ok
def cast(server, request)
@@ -655,7 +460,7 @@ defmodule GenServer do
This function always returns `:ok`.
"""
@spec reply(from, term) :: :ok
@spec reply({pid, reference}, term) :: :ok
def reply(client, reply)
def reply({to, tag}, reply) do
@@ -667,41 +472,6 @@ defmodule GenServer do
end
end
@doc """
Returns the `pid` or `{name, node}` of a GenServer process.
Returns `nil` if no process is associated with the given name.
For example, to lookup a server process, monitor it and send a cast:
process = GenServer.whereis(server)
monitor = Process.monitor(process)
GenServer.cast(process, :hello)
"""
@spec whereis(server) :: pid | {atom, node} | nil
def whereis(pid) when is_pid(pid), do: pid
def whereis(name) when is_atom(name) do
Process.whereis(name)
end
def whereis({:global, name}) do
case :global.whereis_name(name) do
pid when is_pid(pid) -> pid
:undefined -> nil
end
end
def whereis({:via, mod, name}) do
case apply(mod, :whereis_name, [name]) do
pid when is_pid(pid) -> pid
:undefined -> nil
end
end
def whereis({name, local}) when is_atom(name) and local == node() do
Process.whereis(name)
end
def whereis({name, node} = server) when is_atom(name) and is_atom(node) do
server
end
@compile {:inline, [nodes: 0]}
defp nodes do
+16 -1
View File
@@ -194,7 +194,7 @@ defmodule HashDict do
end
defp do_reduce_each([k|v], {:cont, acc}, fun, next) do
next.(fun.({k, v}, acc))
next.(fun.({k,v}, acc))
end
defp do_reduce_each({k, v, n}, {:cont, acc}, fun, next) do
@@ -233,7 +233,22 @@ defimpl Enumerable, for: HashDict do
def count(dict), do: {:ok, HashDict.size(dict)}
end
defimpl Access, for: HashDict do
def get(dict, key) do
HashDict.get(dict, key, nil)
end
def get_and_update(dict, key, fun) do
{get, update} = fun.(HashDict.get(dict, key, nil))
{get, HashDict.put(dict, key, update)}
end
end
defimpl Collectable, for: HashDict do
def empty(_dict) do
HashDict.new
end
def into(original) do
{original, fn
dict, {:cont, {k, v}} -> Dict.put(dict, k, v)
+4
View File
@@ -253,6 +253,10 @@ defimpl Enumerable, for: HashSet do
end
defimpl Collectable, for: HashSet do
def empty(_dict) do
HashSet.new
end
def into(original) do
{original, fn
set, {:cont, x} -> HashSet.put(set, x)
+2 -3
View File
@@ -41,8 +41,7 @@ defprotocol Inspect do
## Error handling
In case there is an error while your structure is being inspected,
Elixir will raise an `ArgumentError` error and will automatically fall back
to a raw representation for printing the structure.
Elixir will automatically fall back to a raw representation.
You can however access the underlying error by invoking the Inspect
implementation directly. For example, to test Inspect.HashSet above,
@@ -407,7 +406,7 @@ defimpl Inspect, for: Regex do
defp escape(<<term>> <> rest, buf, term),
do: escape(rest, buf <> <<?\\, term>>, term)
# the list of characters is from "String.printable?" impl
# the list of characters is from `String.printable?` impl
# minus characters treated specially by regex: \s, \d, \b, \e
defp escape(<<?\n>> <> rest, buf, term),
+32 -64
View File
@@ -4,8 +4,8 @@ defmodule Inspect.Opts do
The following fields are available:
* `:structs` - when `false`, structs are not formatted by the inspect
protocol, they are instead printed as maps, defaults to `true`.
* `:structs` - when false, structs are not formatted by the inspect
protocol, they are instead printed as maps, defaults to true.
* `:binaries` - when `:as_strings` all binaries will be printed as strings,
non-printable bytes will be escaped.
@@ -27,19 +27,14 @@ defmodule Inspect.Opts do
bitstrings, and lists, does not apply to strings nor char lists, defaults
to 50.
* `:pretty` - if set to `true` enables pretty printing, defaults to `false`.
* `:pretty` - if set to true enables pretty printing, defaults to false.
* `:width` - defaults to the 80 characters, used when pretty is `true` or
* `:width` - defaults to the 80 characters, used when pretty is true or
when printing to IO devices.
* `:base` - print integers as :binary, :octal, :decimal, or :hex, defaults
to :decimal
* `:safe` - when `false`, failures while inspecting structs will be raised
as errors instead of being wrapped in the Inspect.Error exception. This
is useful when debugging failures and crashes for custom inspect
implementations
"""
defstruct structs: true,
@@ -48,36 +43,25 @@ defmodule Inspect.Opts do
limit: 50,
width: 80,
base: :decimal,
pretty: false,
safe: true
pretty: false
@type t :: %__MODULE__{
structs: boolean,
binaries: :infer | :as_binaries | :as_strings,
char_lists: :infer | :as_lists | :as_char_lists,
limit: pos_integer | :infinity,
limit: pos_integer,
width: pos_integer | :infinity,
base: :decimal | :binary | :hex | :octal,
pretty: boolean,
safe: boolean}
end
defmodule Inspect.Error do
@moduledoc """
Raised when a struct cannot be inspected.
"""
defexception [:message]
pretty: boolean}
end
defmodule Inspect.Algebra do
@moduledoc ~S"""
A set of functions for creating and manipulating algebra
documents.
documents, as described in ["Strictly Pretty" (2000) by Christian Lindig][0].
This module implements the functionality described in
["Strictly Pretty" (2000) by Christian Lindig][0] with small
additions, like support for String nodes, and a custom
rendering function that maximises horizontal space use.
An algebra document is represented by an `Inspect.Algebra` node
or a regular string.
iex> Inspect.Algebra.empty
:doc_nil
@@ -145,7 +129,7 @@ defmodule Inspect.Algebra do
@nesting 1
@break " "
# Functional interface to "doc" records
# Functional interface to `doc` records
@type t :: :doc_nil | :doc_line | doc_cons | doc_nest | doc_break | doc_group | binary
@@ -214,20 +198,12 @@ defmodule Inspect.Algebra do
else
try do
Process.put(:inspect_trap, true)
res = Inspect.Map.inspect(map, opts)
res = IO.iodata_to_binary(format(res, :infinity))
exception = Inspect.Error.exception(
message: "got #{inspect e.__struct__} with message " <>
"#{inspect Exception.message(e)} while inspecting #{res}"
)
if opts.safe do
Inspect.inspect(exception, opts)
else
reraise(exception, stacktrace)
end
formatted = IO.iodata_to_binary(format(res, :infinity))
reraise ArgumentError,
"Got #{inspect e.__struct__} with message " <>
"\"#{Exception.message(e)}\" while inspecting #{formatted}",
stacktrace
after
Process.delete(:inspect_trap)
end
@@ -274,7 +250,7 @@ defmodule Inspect.Algebra do
"""
@spec concat([t]) :: doc_cons
def concat(docs) do
fold_doc(docs, &concat(&1, &2))
folddoc(docs, &concat(&1, &2))
end
@doc ~S"""
@@ -405,18 +381,17 @@ defmodule Inspect.Algebra do
## Examples
iex> doc = ["A", "B"]
iex> doc = Inspect.Algebra.fold_doc(doc, fn(x, y) ->
iex> doc = Inspect.Algebra.folddoc(doc, fn(x,y) ->
...> Inspect.Algebra.concat [x, "!", y]
...> end)
iex> Inspect.Algebra.format(doc, 80)
["A", "!", "B"]
"""
@spec fold_doc([t], ((t, t) -> t)) :: t
def fold_doc(list, fun)
def fold_doc([], _), do: empty
def fold_doc([doc], _), do: doc
def fold_doc([d|ds], fun), do: fun.(d, fold_doc(ds, fun))
@spec folddoc([t], ((t, t) -> t)) :: t
def folddoc([], _), do: empty
def folddoc([doc], _), do: doc
def folddoc([d|ds], f), do: f.(d, folddoc(ds, f))
# Elixir conveniences
@@ -472,41 +447,34 @@ defmodule Inspect.Algebra do
concat(left, right)
end
defp do_surround_many(left, docs, right, limit, opts, fun, sep) do
surround(left, do_surround_many(docs, limit, opts, fun, sep), right)
defp do_surround_many(left, docs, right, limit, _opts, fun, sep) do
surround(left, do_surround_many(docs, limit, _opts, fun, sep), right)
end
defp do_surround_many(_, 0, _opts, _fun, _sep) do
"..."
end
defp do_surround_many([], _limit, _opts, _fun, _sep) do
:doc_nil
end
defp do_surround_many([h], limit, opts, fun, _sep) do
fun.(h, %{opts | limit: limit})
end
defp do_surround_many([h|t], limit, opts, fun, sep) when is_list(t) do
limit = decrement(limit)
h = fun.(h, %{opts | limit: limit})
t = do_surround_many(t, limit, opts, fun, sep)
do_join(h, t, sep)
glue(
concat(fun.(h, %{opts | limit: limit}), sep),
do_surround_many(t, limit, opts, fun, sep)
)
end
defp do_surround_many([h|t], limit, opts, fun, _sep) do
limit = decrement(limit)
h = fun.(h, %{opts | limit: limit})
t = fun.(t, %{opts | limit: limit})
do_join(h, t, @tail_separator)
glue(
concat(fun.(h, %{opts | limit: limit}), @tail_separator),
fun.(t, %{opts | limit: limit})
)
end
defp do_join(:doc_nil, :doc_nil, _), do: :doc_nil
defp do_join(h, :doc_nil, _), do: h
defp do_join(:doc_nil, t, _), do: t
defp do_join(h, t, sep), do: glue(concat(h, sep), t)
defp decrement(:infinity), do: :infinity
defp decrement(counter), do: counter - 1
+17 -124
View File
@@ -28,157 +28,50 @@ defmodule Integer do
end
@doc """
Returns the ordered digits for the given non-negative integer.
An optional base value may be provided representing the radix for the returned
digits.
## Examples
iex> Integer.digits(101)
[1, 0, 1]
iex> Integer.digits(58127, 2)
[1, 1, 1, 0, 0, 0, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1]
"""
@spec digits(non_neg_integer, pos_integer) :: [non_neg_integer]
def digits(n, base \\ 10) when is_integer(n) and n >= 0
and is_integer(base) and base >= 2 do
do_digits(n, base, [])
end
defp do_digits(0, _base, []), do: [0]
defp do_digits(0, _base, acc), do: acc
defp do_digits(n, base, acc) do
do_digits div(n, base), base, [rem(n, base) | acc]
end
@doc """
Returns the integer represented by the ordered digits.
An optional base value may be provided representing the radix for the digits.
## Examples
iex> Integer.undigits([1, 0, 1])
101
iex> Integer.undigits([1, 4], 16)
20
"""
@spec undigits([integer], integer) :: integer
def undigits(digits, base \\ 10) when is_integer(base) do
do_undigits(digits, base, 0)
end
defp do_undigits([], _base, acc), do: acc
defp do_undigits([digit | tail], base, acc) do
do_undigits(tail, base, acc * base + digit)
end
@doc """
Converts a binary from a text representation of an integer
in an optional base `base` to the corresponding integer.
If the base `base` is not given, base 10 will be used.
Converts a binary to an integer.
If successful, returns a tuple of the form `{integer, remainder_of_binary}`.
Otherwise `:error`.
Raises an error if `base` is less than 2 or more than 36.
## Examples
iex> Integer.parse("34")
{34, ""}
{34,""}
iex> Integer.parse("34.5")
{34, ".5"}
{34,".5"}
iex> Integer.parse("three")
:error
iex> Integer.parse("34", 10)
{34, ""}
iex> Integer.parse("f4", 16)
{244, ""}
iex> Integer.parse("Awww++", 36)
{509216, "++"}
iex> Integer.parse("fab", 10)
:error
iex> Integer.parse("a2", 38)
** (ArgumentError) invalid base 38
"""
@spec parse(binary, 2..36) :: {integer, binary} | :error | no_return
def parse(binary, base \\ 10)
def parse(binary, base) when is_integer(base) and base in 2..36 do
parse_in_base(binary, base)
end
def parse(_, base) do
raise ArgumentError, "invalid base #{base}"
end
defp parse_in_base(<< ?-, bin :: binary >>, base) do
case do_parse(bin, base) do
@spec parse(binary) :: {integer, binary} | :error
def parse(<< ?-, bin :: binary >>) do
case do_parse(bin) do
:error -> :error
{number, remainder} -> {-number, remainder}
end
end
defp parse_in_base(<< ?+, bin :: binary >>, base) do
do_parse(bin, base)
def parse(<< ?+, bin :: binary >>) do
do_parse(bin)
end
defp parse_in_base(bin, base) when is_binary(bin) do
do_parse(bin, base)
def parse(bin) when is_binary(bin) do
do_parse(bin)
end
defp do_parse(<< char, bin :: binary >>, base) do
if valid_digit_in_base?(char, base) do
do_parse(bin, base, parse_digit(char, base))
else
:error
end
defp do_parse(<< char, bin :: binary >>) when char in ?0..?9, do: do_parse(bin, char - ?0)
defp do_parse(_), do: :error
defp do_parse(<< char, rest :: binary >>, acc) when char in ?0..?9 do
do_parse rest, 10 * acc + (char - ?0)
end
defp do_parse(_, _), do: :error
defp do_parse(<< char, rest :: binary >>, base, acc) do
if valid_digit_in_base?(char, base) do
do_parse(rest, base, base * acc + parse_digit(char, base))
else
{acc, << char, rest :: binary >>}
end
end
defp do_parse(bitstring, _, acc) do
defp do_parse(bitstring, acc) do
{acc, bitstring}
end
defp parse_digit(char, _) do
cond do
char in ?0..?9 -> char - ?0
char in ?A..?Z -> char - ?A + 10
true -> char - ?a + 10
end
end
defp valid_digit_in_base?(char, base) do
if base <= 10 do
char in ?0..(?0 + base - 1)
else
char in ?0..?9 or char in ?A..(?A + base - 11) or char in ?a..(?a + base - 11)
end
end
@doc """
Returns a binary which corresponds to the text representation
of `some_integer`.
@@ -231,7 +124,7 @@ defmodule Integer do
@doc """
Returns a char list which corresponds to the text representation of the
given integer in the given base.
given integer in the given case.
Inlined by the compiler.
+14 -17
View File
@@ -2,7 +2,7 @@ defmodule IO do
@moduledoc """
Functions handling IO.
Many functions in this module expect an IO device as an argument.
Many functions in this module expects an IO device as argument.
An IO device must be a pid or an atom representing a process.
For convenience, Elixir provides `:stdio` and `:stderr` as
shortcuts to Erlang's `:standard_io` and `:standard_error`.
@@ -12,20 +12,21 @@ defmodule IO do
it will do a conversion to string via the `String.Chars` protocol
(as shown in typespecs).
The functions starting with `bin*` expect iodata as an argument,
The functions starting with `bin*` expects iodata as argument,
i.e. binaries or lists of bytes and binaries.
## IO devices
An IO device may be an atom or a pid. In case it is an atom,
the atom must be the name of a registered process. In addition,
Elixir provides two shorcuts:
the atom must be the name of a registered process. However,
there are three exceptions for this rule:
* `:stdio` - a shortcut for `:standard_io`, which maps to
the current `Process.group_leader/0` in Erlang
* `:standard_io` - when the `:standard_io` atom is given,
it is treated as a shortcut for `Process.group_leader`
* `:stderr` - a shortcut for the named process `:standard_error`
provided in Erlang
* `:stdio` - is a shortcut for `:standard_io`
* `:stderr` - is a shortcut for `:standard_error`
"""
@@ -183,24 +184,20 @@ defmodule IO do
80 characters. The width can be changed by explicitly
passing the `:width` option.
See `Inspect.Opts` for a full list of options.
## Examples
IO.inspect Process.list, width: 40
"""
@spec inspect(item, Keyword.t) :: item when item: var
@spec inspect(term, Keyword.t) :: term
def inspect(item, opts \\ []) do
inspect group_leader(), item, opts
end
@doc """
Inspects the item with options using the given device.
See `Inspect.Opts` for a full list of options.
"""
@spec inspect(device, item, Keyword.t) :: item when item: var
@spec inspect(device, term, Keyword.t) :: term
def inspect(device, item, opts) when is_list(opts) do
opts = struct(Inspect.Opts, opts)
iodata = Inspect.Algebra.format(Inspect.Algebra.to_doc(item, opts), opts.width)
@@ -250,7 +247,7 @@ defmodule IO do
Reads a line from the IO device. It returns:
* `data` - the characters in the line terminated
by a line-feed (LF) or end of file (EOF)
by a LF (or end of file)
* `:eof` - end of file was encountered
@@ -366,11 +363,11 @@ defmodule IO do
iex> bin2 = <<4, 5>>
iex> bin3 = <<6>>
iex> IO.iodata_to_binary([bin1, 1, [2, 3, bin2], 4|bin3])
<<1, 2, 3, 1, 2, 3, 4, 5, 4, 6>>
<<1,2,3,1,2,3,4,5,4,6>>
iex> bin = <<1, 2, 3>>
iex> IO.iodata_to_binary(bin)
<<1, 2, 3>>
<<1,2,3>>
"""
@spec iodata_to_binary(iodata) :: binary
+14 -17
View File
@@ -1,7 +1,7 @@
defmodule IO.ANSI.Sequence do
@moduledoc false
defmacro defsequence(name, code, terminator \\ "m") do
defmacro defsequence(name, code \\ "", terminator \\ "m") do
quote bind_quoted: [name: name, code: code, terminator: terminator] do
def unquote(name)() do
"\e[#{unquote(code)}#{unquote(terminator)}"
@@ -16,11 +16,10 @@ end
defmodule IO.ANSI do
@moduledoc """
Functionality to render ANSI escape sequences.
[ANSI escape sequences](https://en.wikipedia.org/wiki/ANSI_escape_code)
are characters embedded in text used to control formatting, color, and
other output options on video text terminals.
Functionality to render ANSI escape sequences
(http://en.wikipedia.org/wiki/ANSI_escape_code) — characters embedded
in text used to control formatting, color, and other output options
on video text terminals.
"""
import IO.ANSI.Sequence
@@ -34,7 +33,7 @@ defmodule IO.ANSI do
This function simply reads the configuration value for
`:ansi_enabled` in the `:elixir` application. The value is by
default `false` unless Elixir can detect during startup that
default false unless Elixir can detect during startup that
both `stdout` and `stderr` are terminals.
"""
@spec enabled? :: boolean
@@ -51,7 +50,7 @@ defmodule IO.ANSI do
@doc "Faint (decreased intensity), not widely supported"
defsequence :faint, 2
@doc "Italic: on. Not widely supported. Sometimes treated as inverse"
@doc "Italic: on. Not widely supported. Sometimes treated as inverse."
defsequence :italic, 3
@doc "Underline: Single"
@@ -72,7 +71,7 @@ defmodule IO.ANSI do
@doc "Conceal. Not widely supported"
defsequence :conceal, 8
@doc "Crossed-out. Characters legible, but marked for deletion. Not widely supported"
@doc "Crossed-out. Characters legible, but marked for deletion. Not widely supported."
defsequence :crossed_out, 9
@doc "Sets primary (default) font"
@@ -96,8 +95,9 @@ defmodule IO.ANSI do
defsequence :blink_off, 25
colors = [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white]
colors = Enum.zip(0..(length(colors)-1), colors)
for {color, code} <- Enum.with_index(colors) do
for {code, color} <- colors do
@doc "Sets foreground color to #{color}"
defsequence color, code + 30
@@ -126,17 +126,14 @@ defmodule IO.ANSI do
@doc "Not overlined"
defsequence :not_overlined, 55
@doc "Sends cursor home"
@doc "Send cursor home"
defsequence :home, "", "H"
@doc "Clears screen"
@doc "Clear screen"
defsequence :clear, "2", "J"
@doc "Clears line"
defsequence :clear_line, "2", "K"
defp format_sequence(other) do
raise ArgumentError, "invalid ANSI sequence specification: #{inspect other}"
raise ArgumentError, "invalid ANSI sequence specification: #{other}"
end
@doc ~S"""
@@ -145,7 +142,7 @@ defmodule IO.ANSI do
The named sequences are represented by atoms.
It will also append an `IO.ANSI.reset/0` to the chardata when a conversion is
It will also append an `IO.ANSI.reset` to the chardata when a conversion is
performed. If you don't want this behaviour, use `format_fragment/2`.
An optional boolean parameter can be passed to enable or disable
+2 -27
View File
@@ -57,7 +57,7 @@ defmodule IO.ANSI.Docs do
def print(doc, options \\ []) do
options = Keyword.merge(default_options, options)
doc
|> String.split(["\r\n", "\n"], trim: false)
|> String.split(["\r\n","\n"], trim: false)
|> Enum.map(&String.rstrip/1)
|> process([], "", options)
end
@@ -94,14 +94,6 @@ defmodule IO.ANSI.Docs do
process_code(rest, [line], indent, options)
end
defp process(["```" <> _line | rest], text, indent, options) do
process_fenced_code_block(rest, text, indent, options, _delimiter = "```")
end
defp process(["~~~" <> _line | rest], text, indent, options) do
process_fenced_code_block(rest, text, indent, options, _delimiter = "~~~")
end
defp process(all=[line | rest], text, indent, options) do
{stripped, count} = strip_spaces(line, 0, :infinity)
if is_table_line?(stripped) and rest != [] and is_table_line?(hd(rest)) do
@@ -229,23 +221,6 @@ defmodule IO.ANSI.Docs do
process(rest, [], indent, options)
end
defp process_fenced_code_block(rest, text, indent, options, delimiter) do
write_text(text, indent, options)
process_fenced_code(rest, [], indent, options, delimiter)
end
defp process_fenced_code([], code, indent, options, _delimiter) do
write_code(code, indent, options)
end
defp process_fenced_code([line | rest], code, indent, options, delimiter) do
if line === delimiter do
process_code(rest, code, indent, options)
else
process_fenced_code(rest, [line|code], indent, options, delimiter)
end
end
defp write_code(code, indent, options) do
write(:doc_code, "#{indent}┃ #{Enum.join(Enum.reverse(code), "\n#{indent}┃ ")}", options)
newline_after_block
@@ -295,7 +270,7 @@ defmodule IO.ANSI.Docs do
do: cols ++ List.duplicate({"", 0}, col_count - length(cols))
defp max_column_widths(cols, widths),
do: Enum.zip(cols, widths) |> Enum.map(fn {a, b} -> max(a, b) end)
do: Enum.zip(cols, widths) |> Enum.map(fn {a,b} -> max(a,b) end)
# If second line is heading separator, use the heading style on the first
defp render_table([first, second | rest], widths, options) do
+4
View File
@@ -30,6 +30,10 @@ defmodule IO.Stream do
end
defimpl Collectable do
def empty(stream) do
stream
end
def into(%{device: device, raw: raw} = stream) do
{:ok, into(stream, device, raw)}
end
+467 -823
View File
File diff suppressed because it is too large Load Diff
+13 -27
View File
@@ -12,6 +12,7 @@ defmodule Kernel.CLI do
argv = for arg <- argv, do: IO.chardata_to_string(arg)
{config, argv} = parse_argv(argv)
:elixir_code_server.cast({:paths, config.pa, config.pz})
System.argv(argv)
run fn _ ->
@@ -33,17 +34,10 @@ defmodule Kernel.CLI do
by escripts generated by Elixir.
"""
def run(fun, halt \\ true) do
{ok_or_shutdown, status} = exec_fun(fun, {:ok, 0})
if ok_or_shutdown == :shutdown or halt do
{_, status} = at_exit({ok_or_shutdown, status})
# Ensure Logger messages are flushed before halting
case :erlang.whereis(Logger) do
pid when is_pid(pid) -> Logger.flush()
_ -> :ok
end
System.halt(status)
res = exec_fun(fun, {:ok, 0})
if elem(res, 0) == :shutdown or halt do
{_, int} = at_exit(res)
System.halt(int)
end
end
@@ -71,7 +65,7 @@ defmodule Kernel.CLI do
parent = self()
{pid, ref} =
spawn_monitor(fn ->
spawn_monitor fn ->
try do
fun.(elem(res, 1))
catch
@@ -88,12 +82,12 @@ defmodule Kernel.CLI do
stack = System.stacktrace
print_error(kind, reason, stack)
send parent, {self, {:shutdown, 1}}
exit(to_exit(kind, reason, stack))
:erlang.raise(kind, reason, stack)
else
_ ->
send parent, {self, res}
end
end)
end
receive do
{^pid, res} ->
@@ -105,10 +99,6 @@ defmodule Kernel.CLI do
end
end
defp to_exit(:throw, reason, stack), do: {{:nocatch, reason}, stack}
defp to_exit(:error, reason, stack), do: {reason, stack}
defp to_exit(:exit, reason, _stack), do: reason
defp shared_option?(list, config, callback) do
case parse_shared(list, config) do
{[h|hs], _} when h == hd(list) ->
@@ -123,9 +113,8 @@ defmodule Kernel.CLI do
IO.puts :stderr, Exception.format(kind, reason, prune_stacktrace(trace))
end
@elixir_internals [:elixir, :elixir_exp, :elixir_compiler, :elixir_module, :elixir_clauses,
:elixir_translator, :elixir_expand, :elixir_lexical, :elixir_exp_clauses,
:elixir_def]
@elixir_internals [:elixir, :elixir_exp, :elixir_compiler, :elixir_module, :elixir_translator,
:elixir_expand, :elixir_lexical]
defp prune_stacktrace([{mod, _, _, _}|t]) when mod in @elixir_internals do
prune_stacktrace(t)
@@ -393,10 +382,7 @@ defmodule Kernel.CLI do
end
defp filter_patterns(pattern) do
pattern
|> Path.wildcard
|> :lists.usort
|> Enum.filter(&File.regular?/1)
Enum.filter(Enum.uniq(Path.wildcard(pattern)), &File.regular?(&1))
end
defp filter_multiple_patterns(patterns) do
@@ -416,9 +402,9 @@ defmodule Kernel.CLI do
&elem(&1, 1)
if missing_patterns == [] do
{:ok, :lists.usort(Enum.concat(files))}
{:ok, Enum.uniq(Enum.concat(files))}
else
{:missing, :lists.usort(missing_patterns)}
{:missing, Enum.uniq(missing_patterns)}
end
end
-54
View File
@@ -1,54 +0,0 @@
defmodule Kernel.Def do
@moduledoc false
@doc """
Callback invoked at compile time for `defdelegate`.
"""
def delegate(fun, opts) do
append_first = Keyword.get(opts, :append_first, false)
{name, args} =
case Macro.decompose_call(fun) do
{_, _} = pair -> pair
_ -> raise ArgumentError, "invalid syntax in defdelegate #{Macro.to_string(fun)}"
end
as_args =
case append_first and args != [] do
true -> tl(args) ++ [hd(args)]
false -> args
end
as = Keyword.get(opts, :as, name)
{name, args, as, as_args}
end
@doc """
Callback invoked at compile time for `defstruct`.
"""
def struct(module, fields) do
case fields do
fs when is_list(fs) -> :ok
other ->
raise ArgumentError, "struct fields definition must be list, got: #{inspect other}"
end
fields = :lists.map(fn
{key, val} when is_atom(key) ->
try do
Macro.escape(val)
rescue
e in [ArgumentError] ->
raise ArgumentError, "invalid value for struct field #{key}, " <> Exception.message(e)
else
_ -> {key, val}
end
key when is_atom(key) ->
{key, nil}
other ->
raise ArgumentError, "struct field names must be atoms, got: #{inspect other}"
end, fields)
:maps.put(:__struct__, module, :maps.from_list(fields))
end
end
+41 -35
View File
@@ -11,22 +11,17 @@ defmodule Kernel.LexicalTracker do
@timeout 30_000
@behaviour :gen_server
@import 2
@alias 3
@doc """
Returns all remotes linked to in this lexical scope.
"""
def remotes(arg) do
:gen_server.call(to_pid(arg), :ets, @timeout)
|> :ets.match({{:mode, :'$1'}, :'$2'})
|> partition([], [])
ets = :gen_server.call(to_pid(arg), :ets, @timeout)
:ets.match(ets, {:"$1", :_, :_}) |> List.flatten
end
defp partition([[remote, :compile]|t], compile, runtime),
do: partition(t, [remote|compile], runtime)
defp partition([[remote, :runtime]|t], compile, runtime),
do: partition(t, compile, [remote|runtime])
defp partition([], compile, runtime),
do: {compile, runtime}
@doc """
Gets the destination the lexical scope is meant to
compile to.
@@ -66,8 +61,8 @@ defmodule Kernel.LexicalTracker do
end
@doc false
def remote_dispatch(pid, module, mode) do
:gen_server.cast(pid, {:remote_dispatch, module, mode})
def remote_dispatch(pid, module) do
:gen_server.cast(pid, {:remote_dispatch, module})
end
@doc false
@@ -82,24 +77,28 @@ defmodule Kernel.LexicalTracker do
@doc false
def collect_unused_imports(pid) do
unused(pid, :import)
unused(pid, @import)
end
@doc false
def collect_unused_aliases(pid) do
unused(pid, :alias)
unused(pid, @alias)
end
defp unused(pid, tag) do
:gen_server.call(pid, :ets, @timeout)
|> :ets.select([{{{tag, :"$1"}, :"$2"}, [is_integer: :"$2"], [{{:"$1", :"$2"}}]}])
|> Enum.sort
defp unused(pid, pos) do
ets = :gen_server.call(pid, :ets, @timeout)
:ets.foldl(fn
{module, _, _} = tuple, acc when is_integer(:erlang.element(pos, tuple)) ->
[{module, :erlang.element(pos, tuple)}|acc]
_, acc ->
acc
end, [], ets) |> Enum.sort
end
# Callbacks
def init(dest) do
{:ok, {:ets.new(__MODULE__, [:protected]), dest}}
{:ok, {:ets.new(:lexical, [:protected]), dest}}
end
@doc false
@@ -111,31 +110,32 @@ defmodule Kernel.LexicalTracker do
{:reply, dest, {d, dest}}
end
def handle_cast({:remote_dispatch, module, mode}, {d, dest}) do
add_compile(d, module, mode)
def handle_call(request, _from, {d, dest}) do
{:stop, {:bad_call, request}, {d, dest}}
end
def handle_cast({:remote_dispatch, module}, {d, dest}) do
add_module(d, module)
{:noreply, {d, dest}}
end
def handle_cast({:import_dispatch, module}, {d, dest}) do
add_dispatch(d, module, :import)
# Always compile time because we depend
# on the module at compile time
add_compile(d, module, :compile)
add_dispatch(d, module, @import)
{:noreply, {d, dest}}
end
def handle_cast({:alias_dispatch, module}, {d, dest}) do
add_dispatch(d, module, :alias)
add_dispatch(d, module, @alias)
{:noreply, {d, dest}}
end
def handle_cast({:add_import, module, line, warn}, {d, dest}) do
add_directive(d, module, line, warn, :import)
add_directive(d, module, line, warn, @import)
{:noreply, {d, dest}}
end
def handle_cast({:add_alias, module, line, warn}, {d, dest}) do
add_directive(d, module, line, warn, :alias)
add_directive(d, module, line, warn, @alias)
{:noreply, {d, dest}}
end
@@ -143,6 +143,10 @@ defmodule Kernel.LexicalTracker do
{:stop, :normal, {d, dest}}
end
def handle_cast(msg, {d, dest}) do
{:stop, {:bad_cast, msg}, {d, dest}}
end
@doc false
def handle_info(_msg, {d, dest}) do
{:noreply, {d, dest}}
@@ -162,17 +166,19 @@ defmodule Kernel.LexicalTracker do
# In the table we keep imports and aliases.
# If the value is false, it was not imported/aliased
# If the value is true, it was imported/aliased
# If the value is a line, it was imported/aliased and has a pending warning
# If the value is true, it was imported/aliased and used
defp add_dispatch(d, module, tag) do
:ets.insert(d, {{tag, module}, true})
defp add_module(d, module) do
:ets.insert_new(d, {module, false, false})
end
defp add_compile(d, module, :runtime), do: :ets.insert_new(d, {{:mode, module}, :runtime})
defp add_compile(d, module, :compile), do: :ets.insert(d, {{:mode, module}, :compile})
defp add_dispatch(d, module, pos) do
:ets.update_element(d, module, {pos, true})
end
defp add_directive(d, module, line, warn, tag) do
defp add_directive(d, module, line, warn, pos) do
add_module(d, module)
marker = if warn, do: line, else: true
:ets.insert(d, {{tag, module}, marker})
:ets.update_element(d, module, {pos, marker})
end
end
+5 -9
View File
@@ -25,7 +25,7 @@ defmodule Kernel.ParallelCompiler do
* `:dest` - the destination directory for the beam files. When using `files/2`,
this information is only used to properly annotate the beam files before
they are loaded into memory. If you want a file to actually be written to
they are loaded into memory. If you want a file to actually be writen to
`dest`, use `files_to_path/3` instead.
Returns the modules generated by each compiled file.
@@ -57,11 +57,8 @@ defmodule Kernel.ParallelCompiler do
# In case --warning-as-errors is enabled and there was a warning,
# compilation status will be set to error and we fail with CompileError
case :elixir_code_server.call({:compilation_status, compiler_pid}) do
:ok ->
result
:error ->
IO.puts :stderr, "Compilation failed due to warnings while using the --warnings-as-errors option"
exit({:shutdown, 1})
:ok -> result
:error -> exit({:shutdown, 1})
end
end
@@ -224,9 +221,8 @@ defmodule Kernel.ParallelCompiler do
IO.puts Exception.format(:exit, reason, [])
end
@elixir_internals [:elixir, :elixir_exp, :elixir_compiler, :elixir_module, :elixir_clauses,
:elixir_translator, :elixir_expand, :elixir_lexical, :elixir_exp_clauses,
:elixir_def]
@elixir_internals [:elixir, :elixir_exp, :elixir_compiler, :elixir_module, :elixir_translator,
:elixir_expand, :elixir_lexical]
defp prune_stacktrace([{mod, _, _, _}|t]) when mod in @elixir_internals do
prune_stacktrace(t)
+41 -76
View File
@@ -37,7 +37,7 @@ defmodule Kernel.SpecialForms do
{1, 2, 3}
iex> quote do: {1, 2, 3}
{:{}, [], [1, 2, 3]}
{:{}, [], [1,2,3]}
"""
defmacro unquote(:{})(args)
@@ -177,15 +177,15 @@ defmodule Kernel.SpecialForms do
A bitstring is made of many segments and each segment has a
type. There are 9 types used in bitstrings:
- `integer`
- `float`
- `bits` (alias for bitstring)
- `bitstring`
- `binary`
- `bytes` (alias for binary)
- `utf8`
- `utf16`
- `utf32`
- `integer`
- `float`
- `bits` (alias for bitstring)
- `bitstring`
- `binary`
- `bytes` (alias for binary)
- `utf8`
- `utf16`
- `utf32`
When no type is specified, the default is `integer`:
@@ -245,7 +245,7 @@ defmodule Kernel.SpecialForms do
Sizes for types are a bit more nuanced. The default size for integers is 8.
For floats, it is 64. For floats, `size * unit` must result in 32 or 64,
corresponding to [IEEE 754](https://en.wikipedia.org/wiki/IEEE_floating_point)
corresponding to [IEEE 754](http://en.wikipedia.org/wiki/IEEE_floating_point)
binary32 and binary64, respectively.
For binaries, the default is the size of the binary. Only the last binary in a
@@ -311,7 +311,7 @@ defmodule Kernel.SpecialForms do
### Endianness
Elixir has three options for endianness: `big`, `little`, and `native`.
The default is `big`:
The default is `big`. `native` is determined by the VM at startup.
iex> <<number::little-integer-size(16)>> = <<0, 1>>
<<0, 1>>
@@ -321,9 +321,10 @@ defmodule Kernel.SpecialForms do
<<0, 1>>
iex> number
1
`native` is determined by the VM at startup and will depend on the
host operating system.
iex> <<number::native-integer-size(16)>> = <<0, 1>>
<<0, 1>>
iex> number
256
## Binary/Bitstring Matching
@@ -391,13 +392,13 @@ defmodule Kernel.SpecialForms do
iex> Kernel.Sample
Kernel.Sample
iex> Kernel.length([1, 2, 3])
iex> Kernel.length([1,2,3])
3
iex> Kernel.+(1, 2)
3
iex> Kernel."length"([1, 2, 3])
iex> Kernel."length"([1,2,3])
3
iex> Kernel.'+'(1, 2)
@@ -508,7 +509,7 @@ defmodule Kernel.SpecialForms do
was not explicitly defined.
Both warning behaviours could be changed by explicitly
setting the `:warn` option to `true` or `false`.
setting the `:warn` option to true or false.
"""
defmacro alias(module, opts)
@@ -554,7 +555,7 @@ defmodule Kernel.SpecialForms do
iex> import List
iex> flatten([1, [2], 3])
[1, 2, 3]
[1,2,3]
## Selector
@@ -580,20 +581,12 @@ defmodule Kernel.SpecialForms do
Notice that calling `except` for a previously declared `import`
simply filters the previously imported elements. For example:
import List, only: [flatten: 1, keyfind: 4]
import List, only: [flatten: 1, keyfind: 3]
import List, except: [flatten: 1]
After the two import calls above, only `List.keyfind/4` will be
After the two import calls above, only `List.keyfind/3` will be
imported.
## Underscore functions
By default functions starting with `_` are not imported. If you really want
to import a function starting with `_` you must explicitly include it in the
`:only` selector.
import File.Stream, only: [__build__: 3]
## Lexical scope
It is important to notice that `import` is lexical. This means you
@@ -601,10 +594,10 @@ defmodule Kernel.SpecialForms do
defmodule Math do
def some_function do
# 1) Disable "if/2" from Kernel
# 1) Disable `if/2` from Kernel
import Kernel, except: [if: 2]
# 2) Require the new "if" macro from MyMacros
# 2) Require the new `if` macro from MyMacros
import MyMacros
# 3) Use the new macro
@@ -628,7 +621,7 @@ defmodule Kernel.SpecialForms do
was not explicitly defined.
Both warning behaviours could be changed by explicitly
setting the `:warn` option to `true` or `false`.
setting the `:warn` option to true or false.
## Ambiguous function/macro names
@@ -672,27 +665,26 @@ defmodule Kernel.SpecialForms do
defmacro __CALLER__
@doc """
Accesses an already bound variable in match clauses. Also known as the pin operator.
Accesses an already bound variable in match clauses.
## Examples
Elixir allows variables to be rebound via static single assignment:
iex> x = 1
iex> x = x + 1
iex> x = 2
iex> x
2
However, in some situations, it is useful to match against an existing
value, instead of rebinding. This can be done with the `^` special form,
colloquially known as the pin operator:
value, instead of rebinding. This can be done with the `^` special form:
iex> x = 1
iex> ^x = List.first([1])
iex> ^x = List.first([2])
** (MatchError) no match of right hand side value: 2
Note that `^x` always refers to the value of `x` prior to the match. The
Note that `^` always refers to the value of x prior to the match. The
following example will match:
iex> x = 0
@@ -703,32 +695,6 @@ defmodule Kernel.SpecialForms do
"""
defmacro ^(var)
@doc """
Matches the value on the right against the pattern on the left.
"""
defmacro left = right
@doc """
Used by types and bitstrings to specify types.
This operator is used in two distinct occasions in Elixir.
It is used in typespecs to specify the type of a variable,
function or of a type itself:
@type number :: integer | float
@spec add(number, number) :: number
It may also be used in bit strings to specify the type
of a given bit segment:
<<int::integer-little, rest::bits>> = bits
Read the documentation for `Kernel.Typespec` and
`<<>>/1` for more information on typespecs and
bitstrings respectively.
"""
defmacro left :: right
@doc ~S"""
Gets the representation of any expression.
@@ -759,7 +725,7 @@ defmodule Kernel.SpecialForms do
## Options
* `:unquote` - when `false`, disables unquoting. Useful when you have a quote
* `:unquote` - when false, disables unquoting. Useful when you have a quote
inside another quote and want to control what quote is able to unquote.
* `:location` - when set to `:keep`, keeps the current line and file from
@@ -905,7 +871,7 @@ defmodule Kernel.SpecialForms do
In the example above, `a` returns 10 even if the macro
is apparently setting it to 1 because variables defined
in the macro do not affect the context the macro is executed in.
in the macro does not affect the context the macro is executed in.
If you want to set or get a variable in the caller's context, you
can do it with the help of the `var!` macro:
@@ -1161,7 +1127,7 @@ defmodule Kernel.SpecialForms do
If you try to run our new macro, you will notice it won't
even compile, complaining that the variables `k` and `v`
do not exist. This is because of the ambiguity: `unquote(k)`
does not exist. This is because of the ambiguity: `unquote(k)`
can either be an unquote fragment, as previously, or a regular
unquote as in `unquote(kv)`.
@@ -1262,7 +1228,7 @@ defmodule Kernel.SpecialForms do
iex> pixels = <<213, 45, 132, 64, 76, 32, 76, 0, 0, 234, 32, 15>>
iex> for <<r::8, g::8, b::8 <- pixels >>, do: {r, g, b}
[{213, 45, 132}, {64, 76, 32}, {76, 0, 0}, {234, 32, 15}]
[{213,45,132},{64,76,32},{76,0,0},{234,32,15}]
Variable assignments inside the comprehension, be it in generators,
filters or inside the block, are not reflected outside of the
@@ -1416,9 +1382,8 @@ defmodule Kernel.SpecialForms do
defmacro __aliases__(args)
@doc """
Calls the overriden function when overriding it with `Kernel.defoverridable/1`.
See `Kernel.defoverridable/1` for more information and documentation.
Calls the overriden function when overriding it with `defoverridable`.
See `Kernel.defoverridable` for more information and documentation.
"""
defmacro super(args)
@@ -1465,15 +1430,15 @@ defmodule Kernel.SpecialForms do
In the example above, value is going to be `7` or `13` depending on
the value of `lucky?`. In case `value` has no previous value before
case, clauses that do not explicitly bind a value have the variable
bound to `nil`.
bound to nil.
"""
defmacro case(condition, clauses)
@doc """
Evaluates the expression corresponding to the first clause that
evaluates to a truthy value.
evaluates to truth value.
Raises an error if all conditions evaluate to `nil` or `false`.
Raises an error if all conditions evaluate to to nil or false.
## Examples
@@ -1490,7 +1455,7 @@ defmodule Kernel.SpecialForms do
defmacro cond(clauses)
@doc ~S"""
Evaluates the given expressions and handle any error, exit
Evaluate the given expressions and handle any error, exit
or throw that may have happened.
## Examples
@@ -1676,7 +1641,7 @@ defmodule Kernel.SpecialForms do
This means the VM no longer needs to keep the stacktrace once inside
an else clause and so tail recursion is possible when using a `try`
with a tail call as the final call inside an else clause. The same
is `true` for `rescue` and `catch` clauses.
is true for rescue and catch clauses.
## Variable handling
@@ -1692,7 +1657,7 @@ defmodule Kernel.SpecialForms do
_, _ -> :failed
end
x #=> unbound variable "x"
x #=> unbound variable `x`
In the example above, `x` cannot be accessed since it was defined
inside the `try` clause. A common practice to address this issue
+167 -242
View File
@@ -8,116 +8,155 @@ defmodule Kernel.Typespec do
tools such as [Dialyzer](http://www.erlang.org/doc/man/dialyzer.html) can
analyze the code with typespecs to find bugs.
The attributes `@type`, `@opaque`, `@typep`, `@spec`, `@callback` and
`@macrocallback` available in modules are handled by the equivalent macros
defined by this module. See sub-sections "Defining a type" and "Defining a
specification" below.
The attributes `@type`, `@opaque`, `@typep`, `@spec` and `@callback` available
in modules are handled by the equivalent macros defined by this module. See
sub-sections "Defining a type" and "Defining a specification" below.
## Types and their syntax
The type syntax provided by Elixir is fairly similar to [the one in
Erlang](http://www.erlang.org/doc/reference_manual/typespec.html).
The type syntax provided by Elixir is fairly similar to the one in
[Erlang](http://www.erlang.org/doc/reference_manual/typespec.html).
Most of the built-in types provided in Erlang (for example, `pid()`) are
expressed the same way: `pid()` or simply `pid`. Parameterized types are also
expressed the same way: `pid()` or simply `pid`. Parametrized types are also
supported (`list(integer)`) and so are remote types (`Enum.t`).
Integers and atom literals are allowed as types (ex. `1`, `:atom` or
`false`). All other types are built of unions of predefined types. Certain
shorthands are allowed, such as `[...]`, `<<>>` and `{...}`.
### Basic types
### Predefined types
type :: any() # the top type, the set of all terms
| none() # the bottom type, contains no terms
| pid()
| port()
| reference()
| tuple()
| atom()
| integer()
| non_neg_integer() # 0, 1, 2, 3, ...
| pos_integer() # 1, 2, 3, ...
| neg_integer() # ..., -3, -2, -1
| float()
| map()
| struct()
| list(type)
| nonempty_list(type)
| improper_list(type1, type2)
| maybe_improper_list(type1, type2)
| Literals # Described in section "Literals"
| Builtin # Described in section "Builtin-types"
| Remotes # Described in section "Remotes"
Type :: any # the top type, the set of all terms
| none # the bottom type, contains no terms
| pid
| port
| reference
| Atom
| Bitstring
| float
| Fun
| Integer
| List
| Map
| Tuple
| Union
| UserDefined # Described in section "Defining a type"
### Literals
Atom :: atom
| ElixirAtom # `:foo`, `:bar`, ...
The following literals are also supported in typespecs:
Bitstring :: <<>>
| << _ :: M >> # M is a positive integer
| << _ :: _ * N >> # N is a positive integer
| << _ :: M, _ :: _ * N >>
type :: :atom ## Atoms
| 1 ## Integers
| 1..10 ## Integers from 1 to 10
| 1.0 ## Floats
Fun :: (... -> any) # any function
| (... -> Type) # any arity, returning Type
| (() -> Type))
| (TList -> Type)
| <<>> ## Bitstrings
| <<_ :: size>> # size is 0 or a positive integer
| <<_ :: _ * unit>> # unit is an integer from 1 to 256
| <<_ :: size * unit>>
Integer :: integer
| ElixirInteger # ..., -1, 0, 1, ... 42 ...
| ElixirInteger..ElixirInteger # an integer range
| [type] ## Lists
| [] # empty list
| [...] # shorthand for nonempty_list(any())
| [type, ...] # shorthand for nonempty_list(type)
| [key: type] # keyword lists
List :: list(Type) # proper list ([]-terminated)
| improper_list(Type1, Type2) # Type1=contents, Type2=termination
| maybe_improper_list(Type1, Type2) # Type1 and Type2 as above
| nonempty_list(Type) # proper non-empty list
| [] # empty list
| [Type] # shorthand for list(Type)
| [...] # shorthand for nonempty_list()
| [Type, ...] # shorthand for nonempty_list(Type)
| [Keyword]
| (... -> type) ## Functions
| (... -> type) # any arity, returns type
| (() -> type) # 0-arity, returns type
| (type1, type2 -> type) # 2-arity, returns type
Map :: map() # map of any size
| %{} # map of any size
| %Struct{} # struct (see defstruct/1)
| %Struct{Keyword}
| %{Keyword}
| %{Pairs}
| %{} ## Maps
| %{key: type} # map with key :key with value of type
| %{type1 => type2} # map with keys of type1 with values of type2
| %SomeStruct{}
| %SomeStruct{key: type}
Tuple :: tuple # a tuple of any size
| {} # empty tuple
| {TList}
| record(Atom) # record (see Record)
| record(Atom, Keyword)
| {} ## Tuples
| {:ok, type} # two element tuple with an atom and any type
Keyword :: ElixirAtom: Type
| ElixirAtom: Type, Keyword
### Built-in types
Pairs :: Type => Type
| Type => Type, Pairs
Those types are also provided by Elixir as shortcuts on top of the
basic and literal types.
TList :: Type
| Type, TList
Built-in type | Defined as
:---------------------- | :---------
`term()` | `any()`
`binary()` | `<< _ :: _ * 8 >>`
`bitstring()` | `<< _ :: _ * 1 >>`
`boolean()` | `false` \| `true`
`byte()` | `0..255`
`char()` | `0..0x10ffff`
`number()` | `integer()` \| `float()`
`char_list()` | `[char()]`
`list()` | `[any()]`
`maybe_improper_list()` | `maybe_improper_list(any(), any())`
`nonempty_list()` | `nonempty_list(any())`
`iodata()` | `iolist()` \| `binary()`
`iolist()` | `maybe_improper_list(byte()` \| `binary()` \| `iolist(), binary()` \| `[])`
`module()` | `atom()` \| `tuple()`
`arity()` | `0..255`
`mfa()` | `{atom(), atom(), arity()}`
`node()` | `atom()`
`timeout()` | `:infinity` \| `non_neg_integer()`
`no_return()` | `none()`
`fun()` | `(... -> any)`
`struct()` | `%{__struct__: atom()}`
Union :: Type | Type
### Remote types
### Bit strings
Any module is also able to define their own type and the modules in
Elixir are no exception. For example, a string is `String.t`, a
range is `Range.t`, any enumerable can be `Enum.t` and so on.
Bit string with a base size of 3:
<< _ :: 3 >>
Bit string with a unit size of 8:
<< _ :: _ * 8 >>
### Anonymous functions
Any anonymous function:
((...) -> any)
(... -> any)
Anonymous function with arity of zero:
(() -> type)
Anonymous function with some arity:
((type, type) -> type)
(type, type -> type)
## Built-in types
Built-in type | Defined as
:-------------------- | :---------
`term` | `any`
`binary` | `<< _ :: _ * 8 >>`
`bitstring` | `<< _ :: _ * 1 >>`
`boolean` | `false` \| `true`
`byte` | `0..255`
`char` | `0..0x10ffff`
`number` | `integer` \| `float`
`char_list` | `[char]`
`list` | `[any]`
`maybe_improper_list` | `maybe_improper_list(any, any)`
`nonempty_list` | `nonempty_list(any)`
`iodata` | `iolist` \| `binary`
`iolist` | `maybe_improper_list(byte` \| `binary` \| `iolist, binary` \| `[])`
`module` | `atom` \| `tuple`
`mfa` | `{atom, atom, arity}`
`arity` | `0..255`
`node` | `atom`
`timeout` | `:infinity` \| `non_neg_integer`
`no_return` | `none`
`fun` | `(... -> any)`
Some built-in types cannot be expressed with valid syntax according to the
language defined above.
Built-in type | Can be interpreted as
:---------------- | :--------------------
`non_neg_integer` | `0..`
`pos_integer` | `1..`
`neg_integer` | `..-1`
Types defined in other modules are referred to as "remote types", they are
referenced as `Module.type_name` (ex. `Enum.t` or `String.t`).
## Defining a type
@@ -129,7 +168,7 @@ defmodule Kernel.Typespec do
`@opaque` is a type where the internal structure of the type will not be
visible, but the type is still public.
Types can be parameterized by defining variables as parameters, these variables
Types can be parametrised by defining variables as parameters, these variables
can then be used to define the type.
@type dict(key, value) :: [{key, value}]
@@ -138,7 +177,6 @@ defmodule Kernel.Typespec do
@spec function_name(type1, type2) :: return_type
@callback function_name(type1, type2) :: return_type
@macrocallback macro_name(type1, type2) :: Macro.t
Callbacks are used to define the callbacks functions of behaviours (see
`Behaviour`).
@@ -244,22 +282,6 @@ defmodule Kernel.Typespec do
end
end
@doc """
Defines a macro callback.
This macro is responsible for handling the attribute `@macrocallback`.
## Examples
@macrocallback add(number, number) :: Macro.t
"""
defmacro defmacrocallback(spec) do
quote do
Kernel.Typespec.defspec(:macrocallback, unquote(Macro.escape(spec, unquote: true)), __ENV__)
end
end
@doc """
Defines a `type`, `typep` or `opaque` by receiving a typespec expression.
"""
@@ -271,7 +293,7 @@ defmodule Kernel.Typespec do
Defines a `spec` by receiving a typespec expression.
"""
def define_spec(kind, expr, env) do
defspec(kind, expr, env)
Module.store_typespec(env.module, kind, {kind, expr, env})
end
@doc """
@@ -280,9 +302,10 @@ defmodule Kernel.Typespec do
for modules being compiled.
"""
def defines_type?(module, name, arity) do
finder = fn {_kind, expr, _caller} ->
finder = fn {_kind, expr, _doc, _caller} ->
type_to_signature(expr) == {name, arity}
end
:lists.any(finder, Module.get_attribute(module, :type)) or
:lists.any(finder, Module.get_attribute(module, :opaque))
end
@@ -312,7 +335,6 @@ defmodule Kernel.Typespec do
@doc """
Converts a spec clause back to Elixir AST.
"""
def spec_to_ast(name, spec)
def spec_to_ast(name, {:type, line, :fun, [{:type, _, :product, args}, result]}) do
meta = [line: line]
body = {name, meta, Enum.map(args, &typespec_to_ast/1)}
@@ -360,7 +382,6 @@ defmodule Kernel.Typespec do
@doc """
Converts a type clause back to Elixir AST.
"""
def type_to_ast(type)
def type_to_ast({{:record, record}, fields, args}) when is_atom(record) do
fields = for field <- fields, do: typespec_to_ast(field)
args = for arg <- args, do: typespec_to_ast(arg)
@@ -373,12 +394,23 @@ defmodule Kernel.Typespec do
quote do: unquote(name)(unquote_splicing(args)) :: unquote(typespec_to_ast(type))
end
# TODO: Deprecate by 1.2
# TODO: Remove by 2.0
@doc false
@doc """
Returns all type docs available from the module's beam code.
The result is returned as a list of tuples where the first element is the pair of type
name and arity and the second element is the documentation.
The module must have a corresponding beam file which can be
located by the runtime system.
"""
@spec beam_typedocs(module | binary) :: [tuple] | nil
def beam_typedocs(module) when is_atom(module) or is_binary(module) do
if docs = Code.get_docs(module, :type_docs) do
for {tuple, _, _, doc} <- docs, do: {tuple, doc}
case abstract_code(module) do
{:ok, abstract_code} ->
type_docs = for {:attribute, _, :typedoc, tup} <- abstract_code, do: tup
:lists.flatten(type_docs)
_ ->
nil
end
end
@@ -480,70 +512,27 @@ defmodule Kernel.Typespec do
do: {name, 0}
def type_to_signature({:::, _, [{name, _, args}, _]}) when is_atom(name),
do: {name, length(args)}
def type_to_signature(_),
do: :error
## Macro callbacks
@doc false
def defspec(kind, expr, caller) when kind in [:callback, :macrocallback] do
case spec_to_signature(expr) do
{name, arity} ->
store_callbackdoc(caller, caller.module, kind, name, arity)
:error ->
:error
end
Module.store_typespec(caller.module, kind, {kind, expr, caller})
end
@doc false
def defspec(kind, expr, caller) do
Module.store_typespec(caller.module, kind, {kind, expr, caller})
end
defp store_callbackdoc(caller, module, kind, name, arity) do
table = :elixir_module.data_table(module)
{line, doc} = get_doc_info(table, :doc, caller)
:ets.insert(table, {{:callbackdoc, {name, arity}}, line, kind, doc})
end
defp get_doc_info(table, attr, caller) do
# TODO: Use :ets.take/2 with Erlang 18
case :ets.lookup(table, attr) do
[{^attr, {line, doc}}] ->
:ets.delete(table, attr)
{line, doc}
[] ->
{caller.line, nil}
end
end
@doc false
def deftype(kind, expr, caller) do
module = caller.module
case type_to_signature(expr) do
{name, arity} -> store_typedoc(caller, caller.module, kind, name, arity)
:error -> :error
end
Module.store_typespec(module, kind, {kind, expr, caller})
end
doc = Module.get_attribute(module, :typedoc)
defp store_typedoc(caller, module, kind, name, arity) do
table = :elixir_module.data_table(module)
{line, doc} = get_doc_info(table, :typedoc, caller)
if kind == :typep && doc do
:elixir_errors.warn(caller.line, caller.file, "type #{name}/#{arity} is private, " <>
"@typedoc's are always discarded for private types")
end
:ets.insert(table, {{:typedoc, {name, arity}}, line, kind, doc})
Module.delete_attribute(module, :typedoc)
Module.store_typespec(module, kind, {kind, expr, doc, caller})
end
## Translation from Elixir AST to typespec AST
@doc false
def translate_type(kind, {:::, _, [{name, _, args}, definition]}, caller) when is_atom(name) and name != ::: do
def translate_type(kind, {:::, _, [{name, _, args}, definition]}, doc, caller) when is_atom(name) and name != ::: do
args =
if is_atom(args) do
[]
@@ -551,11 +540,12 @@ defmodule Kernel.Typespec do
for(arg <- args, do: variable(arg))
end
vars = for {:var, _, var} <- args, do: var
spec = typespec(definition, vars, caller)
vars = for {:var, _, _} = var <- args, do: var
type = {name, spec, vars}
arity = length(vars)
vars = for {:var, _, var} <- args, do: var
spec = typespec(definition, vars, caller)
vars = for {:var, _, _} = var <- args, do: var
type = {name, spec, vars}
arity = length(vars)
{kind, export} =
case kind do
@@ -564,24 +554,19 @@ defmodule Kernel.Typespec do
:opaque -> {:opaque, true}
end
if elixir_builtin_type?(name, arity) do
:elixir_errors.handle_file_error(caller.file,
{caller.line, :erl_lint, {:builtin_type, {name, arity}}})
if not export and doc do
:elixir_errors.warn(caller.line, caller.file, "type #{name}/#{arity} is private, " <>
"@typedoc's are always discarded for private types")
end
{{kind, {name, arity}, type}, caller.line, export}
{{kind, {name, arity}, type}, caller.line, export, doc}
end
def translate_type(_kind, other, caller) do
def translate_type(_kind, other, _doc, caller) do
type_spec = Macro.to_string(other)
compile_error caller, "invalid type specification: #{type_spec}"
end
defp elixir_builtin_type?(:as_boolean, 1), do: true
defp elixir_builtin_type?(:struct, 0), do: true
defp elixir_builtin_type?(:char_list, 0), do: true
defp elixir_builtin_type?(_, _), do: false
@doc false
def translate_spec(kind, {:when, _meta, [spec, guard]}, caller) do
translate_spec(kind, spec, guard, caller)
@@ -594,17 +579,9 @@ defmodule Kernel.Typespec do
defp translate_spec(kind, {:::, meta, [{name, _, args}, return]}, guard, caller) when is_atom(name) and name != ::: do
if is_atom(args), do: args = []
if kind == :macrocallback do
kind = :callback
name = :"MACRO-#{name}"
args = [quote(do: env :: Macro.Env.t)|args]
end
ensure_no_defaults! args
unless Keyword.keyword?(guard) do
guard = Macro.to_string(guard)
compile_error caller, "expected keywords as guard in type specification, got: #{guard}"
compile_error caller, "expected keywords as guard in function type specification, got: #{guard}"
end
vars = Keyword.keys(guard)
@@ -619,34 +596,11 @@ defmodule Kernel.Typespec do
{{kind, {name, arity}, spec}, caller.line}
end
defp translate_spec(_kind, {name, _meta, _args} = spec, _guard, caller) when is_atom(name) and name != ::: do
spec = Macro.to_string(spec)
compile_error caller, "type specification missing return type: #{spec}"
end
defp translate_spec(_kind, spec, _guard, caller) do
spec = Macro.to_string(spec)
compile_error caller, "invalid type specification: #{spec}"
compile_error caller, "invalid function type specification: #{spec}"
end
defp ensure_no_defaults!(args) do
:lists.foreach fn
{:::, _, [left, right]} ->
ensure_not_default(left)
ensure_not_default(right)
left
other ->
ensure_not_default(other)
other
end, args
end
defp ensure_not_default({:\\, _, [_, _]}) do
raise ArgumentError, "default arguments \\\\ not supported in type spec"
end
defp ensure_not_default(_), do: :ok
defp guard_to_constraints(guard, vars, meta, caller) do
line = line(meta)
@@ -726,10 +680,6 @@ defmodule Kernel.Typespec do
[typespec_to_ast(arg), {:..., [line: line], nil}]
end
defp typespec_to_ast({:type, line, :map, :any}) do
{:map, [line: line], []}
end
defp typespec_to_ast({:type, line, :map, fields}) do
fields = Enum.map fields, fn
# OTP 18
@@ -806,10 +756,6 @@ defmodule Kernel.Typespec do
typespec_to_ast({:type, line, :char_list, []})
end
defp typespec_to_ast({:remote_type, line, [{:atom, _, :elixir}, {:atom, _, :struct}, []]}) do
typespec_to_ast({:type, line, :struct, []})
end
defp typespec_to_ast({:remote_type, line, [{:atom, _, :elixir}, {:atom, _, :as_boolean}, [arg]]}) do
typespec_to_ast({:type, line, :as_boolean, [arg]})
end
@@ -874,29 +820,17 @@ defmodule Kernel.Typespec do
{:type, line(meta), :binary, [{:integer, line(meta), 0}, {:integer, line(meta), 0}]}
end
defp typespec({:<<>>, meta, [{:::, unit_meta, [{:_, _, ctx1}, {:*, _, [{:_, _, ctx2}, unit]}]}]}, _, _)
when is_atom(ctx1) and is_atom(ctx2) and is_integer(unit) do
{:type, line(meta), :binary, [{:integer, line(meta), 0}, {:integer, line(unit_meta), unit}]}
defp typespec({:<<>>, meta, [{:::, _, [{:_, meta1, atom}, {:*, _, [{:_, meta2, atom}, unit]}]}]}, _, _) when is_atom(atom) do
{:type, line(meta), :binary, [{:integer, line(meta1), 0}, {:integer, line(meta2), unit}]}
end
defp typespec({:<<>>, meta, [{:::, shared_meta, [{:_, _, ctx}, {:*, _, [size, unit]}]}]}, _, _)
when is_atom(ctx) and is_integer(unit) and is_integer(size) do
{:type, line(meta), :binary, [{:integer, line(shared_meta), size}, {:integer, line(shared_meta), unit}]}
end
defp typespec({:<<>>, meta, [{:::, size_meta, [{:_, _, ctx}, size]}]}, _, _)
when is_atom(ctx) and is_integer(size) do
{:type, line(meta), :binary, [{:integer, line(size_meta), size}, {:integer, line(meta), 0}]}
defp typespec({:<<>>, meta, [{:::, meta1, [{:_, meta2, atom}, base]}]}, _, _) when is_atom(atom) do
{:type, line(meta), :binary, [{:integer, line(meta1), base}, {:integer, line(meta2), 0}]}
end
## Handle maps and structs
defp typespec({:map, meta, args}, _vars, _caller) when args == [] or is_atom(args) do
{:type, line(meta), :map, :any}
end
defp typespec({:%{}, meta, fields}, vars, caller) do
fields =
# TODO: Remove else once we support only OTP >18
if :erlang.system_info(:otp_release) >= '18' do
:lists.map(fn {k, v} ->
{:type, line(meta), :map_field_assoc, [typespec(k, vars, caller), typespec(v, vars, caller)]}
@@ -921,15 +855,12 @@ defmodule Kernel.Typespec do
module.__struct__
end
unless Keyword.keyword?(fields) do
compile_error(caller, "expected key-value pairs in struct #{Macro.to_string(name)}")
end
struct =
:lists.map(fn {field, _} ->
{field, quote do: term()}
end, Map.to_list(struct))
:lists.foreach(fn {field, _} ->
unless Keyword.has_key?(struct, field) do
compile_error(caller, "undefined field #{field} on struct #{Macro.to_string(name)}")
@@ -980,9 +911,7 @@ defmodule Kernel.Typespec do
end
defp typespec({:__aliases__, _, _} = alias, vars, caller) do
# We set a function name to avoid tracking
# aliases in typespecs as compile time dependencies.
atom = Macro.expand(alias, %{caller | function: {:typespec, 0}})
atom = Macro.expand alias, caller
typespec(atom, vars, caller)
end
@@ -1053,10 +982,6 @@ defmodule Kernel.Typespec do
typespec((quote do: :elixir.char_list()), vars, caller)
end
defp typespec({:struct, _meta, []}, vars, caller) do
typespec((quote do: :elixir.struct()), vars, caller)
end
defp typespec({:as_boolean, _meta, [arg]}, vars, caller) do
typespec((quote do: :elixir.as_boolean(unquote(arg))), vars, caller)
end
+59 -202
View File
@@ -20,10 +20,8 @@ defmodule Keyword do
a given key and `delete_first/2` deletes just one of the existing
entries.
The functions in Keyword do not guarantee any property when
it comes to ordering. However, since a keyword list is simply a
list, all the operations defined in `Enum` and `List` can be
applied too, specially when ordering is required.
Since a keyword list is simply a list, all the operations defined
in `Enum` and `List` can be applied.
"""
@compile :inline_list_funcs
@@ -36,13 +34,12 @@ defmodule Keyword do
@type t(value) :: [{key, value}]
@doc """
Returns `true` if `term` is a keyword list; otherwise returns `false`.
Checks if the given argument is a keyword list or not.
"""
@spec keyword?(term) :: boolean
def keyword?(term)
def keyword?([{key, _value} | rest]) when is_atom(key),
do: keyword?(rest)
def keyword?([{key, _value} | rest]) when is_atom(key) do
keyword?(rest)
end
def keyword?([]), do: true
def keyword?(_other), do: false
@@ -51,7 +48,9 @@ defmodule Keyword do
Returns an empty keyword list, i.e. an empty list.
"""
@spec new :: t
def new, do: []
def new do
[]
end
@doc """
Creates a keyword from an enumerable.
@@ -65,13 +64,12 @@ defmodule Keyword do
iex> Keyword.new([{:b, 1}, {:a, 2}])
[a: 2, b: 1]
iex> Keyword.new([{:a, 1}, {:a, 2}, {:a, 3}])
[a: 3]
"""
@spec new(Enum.t) :: t
def new(pairs) do
new(pairs, fn pair -> pair end)
Enum.reduce pairs, [], fn {k, v}, keywords ->
put(keywords, k, v)
end
end
@doc """
@@ -87,14 +85,12 @@ defmodule Keyword do
[a: :a, b: :b]
"""
@spec new(Enum.t, (term -> {key, value})) :: t
@spec new(Enum.t, ({key, value} -> {key, value})) :: t
def new(pairs, transform) do
fun = fn el, acc ->
{k, v} = transform.(el)
put_new(acc, k, v)
Enum.reduce pairs, [], fn i, keywords ->
{k, v} = transform.(i)
put(keywords, k, v)
end
keywords = :lists.foldl(fun, [], Enum.reverse(pairs))
:lists.reverse(keywords)
end
@doc """
@@ -126,76 +122,6 @@ defmodule Keyword do
end
end
@doc """
Gets the value for a specific `key`.
If `key` does not exist, lazily evaluates `fun` and returns its result.
This is useful if the default value is very expensive to calculate or
generally difficult to set-up and tear-down again.
If duplicated entries exist, the first one is returned.
Use `get_values/2` to retrieve all entries.
## Examples
iex> keyword = [a: 1]
iex> fun = fn ->
...> # some expensive operation here
...> :result
...> end
iex> Keyword.get_lazy(keyword, :a, fun)
1
iex> Keyword.get_lazy(keyword, :b, fun)
:result
"""
@spec get_lazy(t, key, (() -> value)) :: value
def get_lazy(keywords, key, fun)
when is_list(keywords) and is_atom(key) and is_function(fun, 0) do
case :lists.keyfind(key, 1, keywords) do
{^key, value} -> value
false -> fun.()
end
end
@doc """
Gets the value from `key` and updates it, all in one pass.
This `fun` argument receives the value of `key` (or `nil` if `key`
is not present) and must return a two-elements tuple: the "get" value (the
retrieved value, which can be operated on before being returned) and the new
value to be stored under `key`.
The returned value is a tuple with the "get" value returned by `fun` and a new
keyword list with the updated value under `key`.
## Examples
iex> Keyword.get_and_update [a: 1], :a, fn(current_value) ->
...> {current_value, "new value!"}
...> end
{1, [a: "new value!"]}
"""
@spec get_and_update(t, key, (value -> {value, value})) :: {value, t}
def get_and_update(keywords, key, fun)
when is_list(keywords) and is_atom(key),
do: get_and_update(keywords, [], key, fun)
defp get_and_update([{key, value}|t], acc, key, fun) do
{get, new_value} = fun.(value)
{get, :lists.reverse(acc, [{key, new_value}|t])}
end
defp get_and_update([h|t], acc, key, fun),
do: get_and_update(t, [h|acc], key, fun)
defp get_and_update([], acc, key, fun) do
{get, update} = fun.(nil)
{get, [{key, update}|:lists.reverse(acc)]}
end
@doc """
Fetches the value for a specific `key` and returns it in a tuple.
@@ -219,8 +145,8 @@ defmodule Keyword do
end
@doc """
Fetches the value for specific `key`.
Fetches the value for specific `key`.
If `key` does not exist, a `KeyError` is raised.
## Examples
@@ -246,7 +172,7 @@ defmodule Keyword do
## Examples
iex> Keyword.get_values([a: 1, a: 2], :a)
[1, 2]
[1,2]
"""
@spec get_values(t, key) :: [value]
@@ -260,17 +186,17 @@ defmodule Keyword do
end
@doc """
Returns all keys from the keyword list.
Returns all keys from the keyword list.
Duplicated keys appear duplicated in the final list of keys.
## Examples
iex> Keyword.keys([a: 1, b: 2])
[:a, :b]
[:a,:b]
iex> Keyword.keys([a: 1, b: 2, a: 3])
[:a, :b, :a]
[:a,:b,:a]
"""
@spec keys(t) :: [key]
@@ -284,7 +210,7 @@ defmodule Keyword do
## Examples
iex> Keyword.values([a: 1, b: 2])
[1, 2]
[1,2]
"""
@spec values(t) :: [value]
@@ -377,35 +303,6 @@ defmodule Keyword do
[{key, value}|delete(keywords, key)]
end
@doc """
Evaluates `fun` and puts the result under `key`
in keyword list unless `key` is already present.
This is useful if the value is very expensive to calculate or generally
difficult to set-up and tear-down again.
## Examples
iex> keyword = [a: 1]
iex> fun = fn ->
...> # some expensive operation here
...> 3
...> end
iex> Keyword.put_new_lazy(keyword, :a, fun)
[a: 1]
iex> Keyword.put_new_lazy(keyword, :b, fun)
[b: 3, a: 1]
"""
@spec put_new_lazy(t, key, (() -> value)) :: t
def put_new_lazy(keywords, key, fun)
when is_list(keywords) and is_atom(key) and is_function(fun, 0) do
case :lists.keyfind(key, 1, keywords) do
{^key, _} -> keywords
false -> [{key, fun.()}|keywords]
end
end
@doc """
Puts the given `value` under `key` unless the entry `key`
already exists.
@@ -428,8 +325,8 @@ defmodule Keyword do
end
@doc """
Checks if two keywords are equal.
Checks if two keywords are equal.
Two keywords are considered to be equal if they contain
the same keys and those keys contain the same values.
@@ -445,25 +342,25 @@ defmodule Keyword do
end
@doc """
Merges two keyword lists into one.
Merges two keyword lists into one.
If they have duplicated keys, the one given in the second argument wins.
## Examples
iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4])
[a: 3, d: 4, b: 2]
iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4]) |> Enum.sort
[a: 3, b: 2, d: 4]
"""
@spec merge(t, t) :: t
def merge(keywords1, keywords2) when is_list(keywords1) and is_list(keywords2) do
fun = fn {k, _v} -> not has_key?(keywords2, k) end
keywords2 ++ :lists.filter(fun, keywords1)
def merge(d1, d2) when is_list(d1) and is_list(d2) do
fun = fn {k, _v} -> not has_key?(d2, k) end
d2 ++ :lists.filter(fun, d1)
end
@doc """
Merges two keyword lists into one.
Merges two keyword lists into one.
If they have duplicated keys, the given function is invoked to solve conflicts.
## Examples
@@ -475,8 +372,8 @@ defmodule Keyword do
"""
@spec merge(t, t, (key, value, value -> value)) :: t
def merge(keywords1, keywords2, fun) when is_list(keywords1) and is_list(keywords2) do
do_merge(keywords2, keywords1, fun)
def merge(d1, d2, fun) when is_list(d1) and is_list(d2) do
do_merge(d2, d1, fun)
end
defp do_merge([{k, v2}|t], acc, fun) do
@@ -505,8 +402,8 @@ defmodule Keyword do
end
@doc """
Updates the `key` with the given function.
Updates the `key` with the given function.
If the `key` does not exist, raises `KeyError`.
If there are duplicated keys, they are all removed and only the first one
@@ -539,8 +436,8 @@ defmodule Keyword do
end
@doc """
Updates the `key` in `keywords` with the given function.
Updates the `key` with the given function.
If the `key` does not exist, inserts the given `initial` value.
If there are duplicated keys, they are all removed and only the first one
@@ -556,8 +453,6 @@ defmodule Keyword do
"""
@spec update(t, key, value, (value -> value)) :: t
def update(keywords, key, initial, fun)
def update([{key, value}|keywords], key, _initial, fun) do
[{key, fun.(value)}|delete(keywords, key)]
end
@@ -572,8 +467,8 @@ defmodule Keyword do
@doc """
Takes all entries corresponding to the given keys and extracts them into a
separate keyword list.
separate keyword list.
Returns a tuple with the new list and the old list with removed keys.
Keys for which there are no entires in the keyword list are ignored.
@@ -655,60 +550,23 @@ defmodule Keyword do
## Examples
iex> Keyword.pop [a: 1], :a
{1, []}
{1,[]}
iex> Keyword.pop [a: 1], :b
{nil, [a: 1]}
{nil,[a: 1]}
iex> Keyword.pop [a: 1], :b, 3
{3, [a: 1]}
{3,[a: 1]}
iex> Keyword.pop [a: 1], :b, 3
{3,[a: 1]}
iex> Keyword.pop [a: 1, a: 2], :a
{1, []}
{1,[]}
"""
@spec pop(t, key, value) :: {value, t}
def pop(keywords, key, default \\ nil) when is_list(keywords) do
case fetch(keywords, key) do
{:ok, value} ->
{value, delete(keywords, key)}
:error ->
{default, keywords}
end
end
@doc """
Returns the first value associated with `key` in the keyword
list as well as the keyword list without `key`.
This is useful if the default value is very expensive to calculate or
generally difficult to set-up and tear-down again.
All duplicated keys are removed. See `pop_first/3` for
removing only the first entry.
## Examples
iex> keyword = [a: 1]
iex> fun = fn ->
...> # some expensive operation here
...> :result
...> end
iex> Keyword.pop_lazy(keyword, :a, fun)
{1, []}
iex> Keyword.pop_lazy(keyword, :b, fun)
{:result, [a: 1]}
"""
@spec pop_lazy(t, key, (() -> value)) :: {value, t}
def pop_lazy(keywords, key, fun)
when is_list(keywords) and is_function(fun, 0) do
case fetch(keywords, key) do
{:ok, value} ->
{value, delete(keywords, key)}
:error ->
{fun.(), keywords}
end
{get(keywords, key, default), delete(keywords, key)}
end
@doc """
@@ -721,24 +579,23 @@ defmodule Keyword do
## Examples
iex> Keyword.pop_first [a: 1], :a
{1, []}
{1,[]}
iex> Keyword.pop_first [a: 1], :b
{nil, [a: 1]}
{nil,[a: 1]}
iex> Keyword.pop_first [a: 1], :b, 3
{3, [a: 1]}
{3,[a: 1]}
iex> Keyword.pop_first [a: 1], :b, 3
{3,[a: 1]}
iex> Keyword.pop_first [a: 1, a: 2], :a
{1, [a: 2]}
{1,[a: 2]}
"""
@spec pop_first(t, key, value) :: {value, t}
def pop_first(keywords, key, default \\ nil) when is_list(keywords) do
case :lists.keytake(key, 1, keywords) do
{:value, {^key, value}, rest} -> {value, rest}
false -> {default, keywords}
end
{get(keywords, key, default), delete_first(keywords, key)}
end
# Dict callbacks
+37 -75
View File
@@ -26,7 +26,7 @@ defmodule List do
## Examples
iex> List.delete([1, 2, 3], 1)
[2, 3]
[2,3]
iex> List.delete([1, 2, 2, 3], 2)
[1, 2, 3]
@@ -43,11 +43,10 @@ defmodule List do
## Examples
iex> List.duplicate("hello", 3)
["hello", "hello", "hello"]
["hello","hello","hello"]
iex> List.duplicate([1, 2], 2)
[[1, 2], [1, 2]]
[[1,2],[1,2]]
"""
@spec duplicate(elem, non_neg_integer) :: [elem] when elem: var
@@ -61,7 +60,7 @@ defmodule List do
## Examples
iex> List.flatten([1, [[2], 3]])
[1, 2, 3]
[1,2,3]
"""
@spec flatten(deep_list) :: list when deep_list: [any | deep_list]
@@ -77,7 +76,7 @@ defmodule List do
## Examples
iex> List.flatten([1, [[2], 3]], [4, 5])
[1, 2, 3, 4, 5]
[1,2,3,4,5]
"""
@spec flatten(deep_list, [elem]) :: [elem] when elem: var, deep_list: [elem | deep_list]
@@ -86,7 +85,7 @@ defmodule List do
end
@doc """
Folds (reduces) the given list from the left with
Folds (reduces) the given list to the left with
a function. Requires an accumulator.
## Examples
@@ -104,7 +103,7 @@ defmodule List do
end
@doc """
Folds (reduces) the given list from the right with
Folds (reduces) the given list to the right with
a function. Requires an accumulator.
## Examples
@@ -160,7 +159,7 @@ defmodule List do
@doc """
Receives a list of tuples and returns the first tuple
where the item at `position` in the tuple matches the
given `key`.
given `item`.
## Examples
@@ -182,7 +181,7 @@ defmodule List do
@doc """
Receives a list of tuples and returns `true` if there is
a tuple where the item at `position` in the tuple matches
the given `key`.
the given `item`.
## Examples
@@ -256,7 +255,7 @@ defmodule List do
@doc """
Receives a list of tuples and deletes the first tuple
where the item at `position` matches the
given `key`. Returns the new list.
given `item`. Returns the new list.
## Examples
@@ -275,33 +274,6 @@ defmodule List do
:lists.keydelete(key, position + 1, list)
end
@doc """
Receives a `list` of tuples and returns the first tuple
where the element at `position` in the tuple matches the
given `key`, as well as the `list` without found tuple.
If such a tuple is not found, `nil` will be returned.
## Examples
iex> List.keytake([a: 1, b: 2], :a, 0)
{{:a, 1}, [b: 2]}
iex> List.keytake([a: 1, b: 2], 2, 1)
{{:b, 2}, [a: 1]}
iex> List.keytake([a: 1, b: 2], :c, 0)
nil
"""
@spec keytake([tuple], any, non_neg_integer) :: {tuple, [tuple]} | nil
def keytake(list, key, position) do
case :lists.keytake(key, position + 1, list) do
{:value, item, list} -> {item, list}
false -> nil
end
end
@doc """
Wraps the argument in a list.
If the argument is already a list, returns the list.
@@ -313,7 +285,7 @@ defmodule List do
["hello"]
iex> List.wrap([1, 2, 3])
[1, 2, 3]
[1,2,3]
iex> List.wrap(nil)
[]
@@ -449,7 +421,7 @@ defmodule List do
iex> List.delete_at([1, 2, 3], 0)
[2, 3]
iex> List.delete_at([1, 2, 3], 10)
iex List.delete_at([1, 2, 3], 10)
[1, 2, 3]
iex> List.delete_at([1, 2, 3], -1)
@@ -485,23 +457,12 @@ defmodule List do
end
@doc """
Converts a char list to an existing atom. Raises an `ArguementError`
if the atom does not exist.
Converts a char list to an existing atom.
Currently Elixir does not support conversions from char lists
which contains Unicode codepoints greater than 0xFF.
Inlined by the compiler.
## Examples
iex> _ = :my_atom
iex> List.to_existing_atom('my_atom')
:my_atom
iex> List.to_existing_atom('this_atom_will_never_exist')
** (ArgumentError) argument error
"""
@spec to_existing_atom(char_list) :: atom
def to_existing_atom(char_list) do
@@ -576,9 +537,9 @@ defmodule List do
Converts a list of integers representing codepoints, lists or
strings into a string.
Notice that this function expects a list of integers representing
Notice that this function expect a list of integer representing
UTF-8 codepoints. If you have a list of bytes, you must instead use
the [`:binary` module](http://www.erlang.org/doc/man/binary.html).
[the `:binary` module](http://erlang.org/doc/man/binary.html).
## Examples
@@ -615,40 +576,40 @@ defmodule List do
list
end
defp do_replace_at([_old | rest], 0, value) do
[value | rest]
defp do_replace_at([_old|rest], 0, value) do
[ value | rest ]
end
defp do_replace_at([h | t], index, value) do
[h | do_replace_at(t, index - 1, value)]
defp do_replace_at([h|t], index, value) do
[ h | do_replace_at(t, index - 1, value) ]
end
# insert_at
defp do_insert_at([], _index, value) do
[value]
[ value ]
end
defp do_insert_at(list, index, value) when index <= 0 do
[value | list]
[ value | list ]
end
defp do_insert_at([h | t], index, value) do
[h | do_insert_at(t, index - 1, value)]
defp do_insert_at([h|t], index, value) do
[ h | do_insert_at(t, index - 1, value) ]
end
# update_at
defp do_update_at([value | list], 0, fun) do
[fun.(value) | list]
defp do_update_at([value|list], 0, fun) do
[ fun.(value) | list ]
end
defp do_update_at(list, index, _fun) when index < 0 do
list
end
defp do_update_at([h | t], index, fun) do
[h | do_update_at(t, index - 1, fun)]
defp do_update_at([h|t], index, fun) do
[ h | do_update_at(t, index - 1, fun) ]
end
defp do_update_at([], _index, _fun) do
@@ -661,7 +622,7 @@ defmodule List do
[]
end
defp do_delete_at([_ | t], 0) do
defp do_delete_at([_|t], 0) do
t
end
@@ -669,18 +630,19 @@ defmodule List do
list
end
defp do_delete_at([h | t], index) do
[h | do_delete_at(t, index - 1)]
defp do_delete_at([h|t], index) do
[h | do_delete_at(t, index-1)]
end
# zip
defp do_zip(list, acc) do
converter = fn x, acc -> do_zip_each(to_list(x), acc) end
case :lists.mapfoldl(converter, [], list) do
{_, nil} -> :lists.reverse(acc)
{mlist, heads} ->
do_zip(mlist, [to_tuple(:lists.reverse(heads)) | acc])
{mlist, heads} = :lists.mapfoldl converter, [], list
case heads do
nil -> :lists.reverse acc
_ -> do_zip mlist, [:erlang.list_to_tuple(:lists.reverse(heads))|acc]
end
end
@@ -688,8 +650,8 @@ defmodule List do
{nil, nil}
end
defp do_zip_each([h | t], acc) do
{t, [h | acc]}
defp do_zip_each([h|t], acc) do
{t, [h|acc]}
end
defp do_zip_each([], _) do
+23 -88
View File
@@ -3,19 +3,6 @@ import Kernel, except: [to_string: 1]
defmodule Macro do
@moduledoc """
Conveniences for working with macros.
## Custom Sigils
To create a custom sigil, define a function with the name
`sigil_{identifier}` that takes two arguments. The first argument will be
the interpolated string, the second will be a char list containing any
modifiers.
Valid modifiers include only lower and upper case letters. Other characters
will cause a syntax error.
The module containing the custom sigil must be imported before the sigil
syntax can be used.
"""
@typedoc "Abstract Syntax Tree (AST)"
@@ -54,11 +41,12 @@ defmodule Macro do
o when o in [:==, :!=, :=~, :===, :!==] -> {:left, 150}
o when o in [:<, :<=, :>=, :>] -> {:left, 160}
o when o in [:|>, :<<<, :>>>, :<~, :~>,
:<<~, :~>>, :<~>, :<|>, :^^^] -> {:left, 170}
:<<~, :~>>, :<~>, :<|>] -> {:left, 170}
:in -> {:left, 180}
o when o in [:++, :--, :.., :<>] -> {:right, 200}
o when o in [:+, :-] -> {:left, 210}
o when o in [:*, :/] -> {:left, 220}
:^^^ -> {:left, 250}
:. -> {:left, 310}
end
end
@@ -91,12 +79,6 @@ defmodule Macro do
bad_pipe(expr, call_args)
end
def pipe(expr, {call, _, [_, _]} = call_args, _integer)
when call in unquote(@binary_ops) do
raise ArgumentError, "cannot pipe #{to_string expr} into #{to_string call_args}, " <>
"the #{to_string call} operator can only take two arguments"
end
def pipe(expr, {call, line, atom}, integer) when is_atom(atom) do
{call, line, List.insert_at([], integer, expr)}
end
@@ -117,7 +99,7 @@ defmodule Macro do
@doc """
Applies the given function to the node metadata if it contains one.
This is often useful when used with `Macro.prewalk/2` to remove
This is often useful when used with `Macro.prewalk/1` to remove
information like lines and hygienic counters from the expression
for either storage or comparison.
@@ -141,7 +123,7 @@ defmodule Macro do
end
@doc """
Generates an AST node representing the variable given
Genrates a AST node representing the variable given
by the atoms `var` and `context`.
## Examples
@@ -287,8 +269,6 @@ defmodule Macro do
"""
@spec decompose_call(Macro.t) :: {atom, [Macro.t]} | {Macro.t, atom, [Macro.t]} | :error
def decompose_call(ast)
def decompose_call({{:., _, [remote, function]}, _, args}) when is_tuple(remote) or is_atom(remote),
do: {remote, function, args}
@@ -362,15 +342,15 @@ defmodule Macro do
defp find_invalid(other), do: {:error, other}
@doc ~S"""
Unescapes the given chars.
Unescape the given chars.
This is the unescaping behaviour used by default in Elixir
single- and double-quoted strings. Check `unescape_string/2`
for information on how to customize the escaping map.
In this setup, Elixir will escape the following: `\0`, `\a`, `\b`,
`\d`, `\e`, `\f`, `\n`, `\r`, `\s`, `\t` and `\v`. Unicode codepoints
can be given as hexadecimals via `\xNN` and `\x{NN...}` escapes.
`\d`, `\e`, `\f`, `\n`, `\r`, `\s`, `\t` and `\v`. Hexadecimals
are also supported via `\xNN` and `\x{NN...}` syntax.
This function is commonly used on sigil implementations
(like `~r`, `~s` and others) which receive a raw, unescaped
@@ -390,7 +370,7 @@ defmodule Macro do
end
@doc ~S"""
Unescapes the given chars according to the map given.
Unescape the given chars according to the map given.
Check `unescape_string/1` if you want to use the same map
as Elixir single- and double-quoted strings.
@@ -434,7 +414,7 @@ defmodule Macro do
end
@doc """
Unescapes the given tokens according to the default map.
Unescape the given tokens according to the default map.
Check `unescape_string/1` and `unescape_string/2` for more
information about unescaping.
@@ -450,7 +430,7 @@ defmodule Macro do
end
@doc """
Unescapes the given tokens according to the given map.
Unescape the given tokens according to the given map.
Check `unescape_tokens/1` and `unescape_string/2` for more information.
"""
@@ -494,14 +474,10 @@ defmodule Macro do
# Bits containers
def to_string({:<<>>, _, args} = ast, fun) do
if interpolated?(ast) do
fun.(ast, interpolate(ast, fun))
else
fun.(ast, case Enum.map_join(args, ", ", &to_string(&1, fun)) do
"<" <> rest -> "<< <" <> rest <> " >>"
rest -> "<<" <> rest <> ">>"
end)
end
fun.(ast, case Enum.map_join(args, ", ", &to_string(&1, fun)) do
"<" <> rest -> "<< <" <> rest <> " >>"
rest -> "<<" <> rest <> ">>"
end)
end
# Tuple containers
@@ -564,17 +540,6 @@ defmodule Macro do
fun.(ast, "(" <> Enum.map_join(left, ", ", &to_string(&1, fun)) <> ") when " <> to_string(right, fun))
end
# Capture
def to_string({:&, _, [{:/, _, [{name, _, ctx}, arity]}]} = ast, fun)
when is_atom(name) and is_atom(ctx) and is_integer(arity) do
fun.(ast, "&" <> Atom.to_string(name) <> "/" <> to_string(arity, fun))
end
def to_string({:&, _, [{:/, _, [{{:., _, [mod, name]}, _, []}, arity]}]} = ast, fun)
when is_atom(name) and is_integer(arity) do
fun.(ast, "&" <> to_string(mod, fun) <> "." <> Atom.to_string(name) <> "/" <> to_string(arity, fun))
end
# Unary ops
def to_string({unary, _, [{binary, _, [_, _]} = arg]} = ast, fun)
when unary in unquote(@unary_ops) and binary in unquote(@binary_ops) do
@@ -637,41 +602,15 @@ defmodule Macro do
end
defp kw_blocks?(_), do: false
# Check if we have an interpolated string.
defp interpolated?({:<<>>, _, [_|_] = parts}) do
Enum.all?(parts, fn
{:::, _, [{{:., _, [Kernel, :to_string]}, _, [_]},
{:binary, _, _}]} -> true
binary when is_binary(binary) -> true
_ -> false
end)
end
defp interpolated?(_) do
false
end
defp interpolate({:<<>>, _, parts}, fun) do
parts = Enum.map_join(parts, "", fn
{:::, _, [{{:., _, [Kernel, :to_string]}, _, [arg]}, {:binary, _, _}]} ->
"\#{" <> to_string(arg, fun) <> "}"
binary when is_binary(binary) ->
binary = inspect(binary, [])
:binary.part(binary, 1, byte_size(binary) - 2)
end)
<<?", parts::binary, ?">>
end
defp module_to_string(atom, _fun) when is_atom(atom), do: inspect(atom, [])
defp module_to_string(other, fun), do: call_to_string(other, fun)
defp sigil_call({func, _, [{:<<>>, _, _} = bin, args]} = ast, fun) when is_list(args) do
defp sigil_call({func, _, [{:<<>>, _, [string]}, args]} = ast, fun) when is_list(args) do
sigil =
case Atom.to_string(func) do
<<"sigil_", name>> ->
"~" <> <<name>> <>
interpolate(bin, fun) <>
fun.(string, inspect(string, [])) <>
sigil_args(args, fun)
_ ->
nil
@@ -686,14 +625,10 @@ defmodule Macro do
defp sigil_args([], _fun), do: ""
defp sigil_args(args, fun), do: fun.(args, List.to_string(args))
defp call_to_string(atom, _fun) when is_atom(atom),
do: Atom.to_string(atom)
defp call_to_string({:., _, [arg]}, fun),
do: module_to_string(arg, fun) <> "."
defp call_to_string({:., _, [left, right]}, fun),
do: module_to_string(left, fun) <> "." <> call_to_string(right, fun)
defp call_to_string(other, fun),
do: to_string(other, fun)
defp call_to_string(atom, _fun) when is_atom(atom), do: Atom.to_string(atom)
defp call_to_string({:., _, [arg]}, fun), do: module_to_string(arg, fun) <> "."
defp call_to_string({:., _, [left, right]}, fun), do: module_to_string(left, fun) <> "." <> call_to_string(right, fun)
defp call_to_string(other, fun), do: to_string(other, fun)
defp call_to_string_with_args(target, args, fun) do
target = call_to_string(target, fun)
@@ -895,7 +830,7 @@ defmodule Macro do
defp do_expand_once({:__aliases__, _, _} = original, env) do
case :elixir_aliases.expand(original, env.aliases, env.macro_aliases, env.lexical_tracker) do
receiver when is_atom(receiver) ->
:elixir_lexical.record_remote(receiver, env.function, env.lexical_tracker)
:elixir_lexical.record_remote(receiver, env.lexical_tracker)
{receiver, true}
aliases ->
aliases = :lists.map(&elem(do_expand_once(&1, env), 0), aliases)
@@ -903,7 +838,7 @@ defmodule Macro do
case :lists.all(&is_atom/1, aliases) do
true ->
receiver = :elixir_aliases.concat(aliases)
:elixir_lexical.record_remote(receiver, env.function, env.lexical_tracker)
:elixir_lexical.record_remote(receiver, env.lexical_tracker)
{receiver, true}
false ->
{original, false}
@@ -1004,7 +939,7 @@ defmodule Macro do
be expanded.
This function uses `expand_once/2` under the hood. Check
it out for more information and examples.
`expand_once/2` for more information and examples.
"""
def expand(tree, env) do
expand_until({tree, true}, env)
+4 -10
View File
@@ -39,8 +39,8 @@ defmodule Macro.Env do
* `vars` - a list keeping all defined variables as `{var, context}`
* `export_vars` - a list keeping all variables to be exported in a
construct (may be `nil`)
* `lexical_tracker` - PID of the lexical tracker which is responsible for
keeping user info
* `lexical_tracker` - PID of the lexical tracker which is responsible to
keep user info
* `local` - the module to expand local functions to
"""
@@ -91,15 +91,14 @@ defmodule Macro.Env do
context_modules: [],
vars: [],
export_vars: nil,
lexical_tracker: nil}
lexical_tracker: nil,
local: nil}
end
@doc """
Returns a keyword list containing the file and line
information as keys.
"""
@spec location(t) :: Keyword.t
def location(env)
def location(%{__struct__: Macro.Env, file: file, line: line}) do
[file: file, line: line]
end
@@ -108,22 +107,17 @@ defmodule Macro.Env do
Returns whether the compilation environment is currently
inside a guard.
"""
@spec in_guard?(t) :: boolean
def in_guard?(env)
def in_guard?(%{__struct__: Macro.Env, context: context}), do: context == :guard
@doc """
Returns whether the compilation environment is currently
inside a match clause.
"""
@spec in_match?(t) :: boolean
def in_match?(env)
def in_match?(%{__struct__: Macro.Env, context: context}), do: context == :match
@doc """
Returns the environment stacktrace.
"""
@spec stacktrace(t) :: list
def stacktrace(%{__struct__: Macro.Env} = env) do
cond do
is_nil(env.module) ->
-45
View File
@@ -38,50 +38,6 @@ defmodule Map do
end, map1, map2
end
@doc """
Updates the value in the map with the given function.
"""
def update!(%{} = map, key, fun) do
case fetch(map, key) do
{:ok, value} ->
put(map, key, fun.(value))
:error ->
:erlang.error({:badkey, key})
end
end
def update!(map, _key, _fun), do: :erlang.error({:badmap, map})
@doc """
Gets a value and updates a map in one operation.
"""
def get_and_update(%{} = map, key, fun) do
current_value = case :maps.find(key, map) do
{:ok, value} -> value
:error -> nil
end
{get, update} = fun.(current_value)
{get, :maps.put(key, update, map)}
end
def get_and_update(map, _key, _fun), do: :erlang.error({:badmap, map})
@doc """
Gets a value and updates a map only if the key exists in one operation.
"""
def get_and_update!(%{} = map, key, fun) do
case :maps.find(key, map) do
{:ok, value} ->
{get, update} = fun.(value)
{get, :maps.put(key, update, map)}
:error ->
:erlang.error({:badkey, key})
end
end
def get_and_update!(map, _key, _fun), do: :erlang.error({:badmap, map})
@doc """
Converts a struct to map.
@@ -109,6 +65,5 @@ defmodule Map do
:maps.remove(:__struct__, struct)
end
def equal?(map1, map2)
def equal?(%{} = map1, %{} = map2), do: map1 === map2
end
-116
View File
@@ -1,116 +0,0 @@
defmodule MapSet do
@moduledoc """
A set store.
The `MapSet` is represented internally as a struct, therefore
`%MapSet{}` can be used whenever there is a need to match
on any `MapSet`. Note though the struct fields are private and
must not be accessed directly. Instead, use the functions on this
or in the `Set` module.
The `MapSet` is implemented using `Map` data type.
For more information about the functions
and their APIs, please consult the `Set` module.
"""
@behaviour Set
defstruct map: %{}
def new(), do: %MapSet{}
def delete(%MapSet{map: map} = set, term) do
%{set | map: Map.delete(map, term)}
end
def difference(%MapSet{} = set1, %MapSet{} = set2) do
reduce(set2, {:cont, set1}, fn value, acc ->
{:cont, delete(acc, value)}
end) |> elem(1)
end
def disjoint?(%MapSet{} = set1, %MapSet{} = set2) do
if size(set1) > size(set2), do: {set1, set2} = {set2, set1}
reduce(set1, {:cont, true}, fn value, _ ->
if member?(set2, value) do
{:halt, false}
else
{:cont, true}
end
end) |> elem(1)
end
def equal?(%MapSet{map: map1}, %MapSet{map: map2}) do
Map.equal?(map1, map2)
end
def intersection(%MapSet{} = set1, %MapSet{} = set2) do
if size(set1) > size(set2), do: {set1, set2} = {set2, set1}
reduce(set1, {:cont, new}, fn value, acc ->
if member?(set2, value) do
{:cont, put(acc, value)}
else
{:cont, acc}
end
end) |> elem(1)
end
def member?(%MapSet{map: map}, value) do
Map.has_key?(map, value)
end
def put(%MapSet{map: map} = set, value) do
%{set | map: Map.put(map, value, nil)}
end
def size(%MapSet{map: map}) do
map_size(map)
end
def subset?(%MapSet{} = set1, %MapSet{} = set2) do
if size(set1) <= size(set2) do
reduce(set1, {:cont, true}, fn value, _ ->
if member?(set2, value), do: {:cont, true}, else: {:halt, false}
end) |> elem(1)
else
false
end
end
@doc false
def reduce(%MapSet{} = set, acc, fun) do
Enumerable.List.reduce(to_list(set), acc, fun)
end
def to_list(%MapSet{map: map}) do
Map.keys(map)
end
def union(%MapSet{map: map1}, %MapSet{map: map2}) do
%MapSet{map: Map.merge(map1, map2)}
end
defimpl Enumerable do
def reduce(set, acc, fun), do: MapSet.reduce(set, acc, fun)
def member?(set, val), do: {:ok, MapSet.member?(set, val)}
def count(set), do: {:ok, MapSet.size(set)}
end
defimpl Collectable do
def into(original) do
{original, fn
set, {:cont, x} -> MapSet.put(set, x)
set, :done -> set
_, :halt -> :ok
end}
end
end
defimpl Inspect do
import Inspect.Algebra
def inspect(set, opts) do
concat ["#MapSet<", Inspect.List.inspect(MapSet.to_list(set), opts), ">"]
end
end
end
+77 -171
View File
@@ -65,7 +65,7 @@ defmodule Module do
* `@behaviour` (notice the British spelling)
Specifies an OTP or user-defined behaviour.
Specify an OTP or user-defined behaviour.
### Example
@@ -77,13 +77,13 @@ defmodule Module do
* `@compile`
Defines options for module compilation that are passed to the Erlang
Define options for module compilation that are passed to the Erlang
compiler.
Accepts an atom, a tuple, or a list of atoms and tuples.
For the list of supported options, see Erlang's
[`:compile` module](http://www.erlang.org/doc/man/compile.html).
See http://www.erlang.org/doc/man/compile.html for the list of supported
options.
Several uses of `@compile` will accumulate instead of overriding
previous ones.
@@ -100,7 +100,7 @@ defmodule Module do
* `@doc`
Provides documentation for the function or macro that follows the
Provide documentation for the function or macro that follows the
attribute.
Accepts a string (often a heredoc) or `false` where `@doc false` will
@@ -118,7 +118,7 @@ defmodule Module do
end
@doc """
Sums `a` to `b`.
Sum.
"""
def sum(a, b) do
a + b
@@ -127,7 +127,7 @@ defmodule Module do
* `@file`
Changes the filename used in stacktraces for the function or macro that
Change the filename used in stacktraces for the function or macro that
follows the attribute.
Accepts a string. Can be used more than once.
@@ -144,7 +144,7 @@ defmodule Module do
* `@moduledoc`
Provides documentation for the current module.
Provide documentation for the current module.
Accepts a string (which is often a heredoc) or `false` where
`@moduledoc false` will make the module invisible to the
@@ -170,13 +170,13 @@ defmodule Module do
- the module environment
- kind: `:def`, `:defp`, `:defmacro`, or `:defmacrop`
- function/macro name
- list of quoted arguments
- list of quoted guards
- quoted function body
- list of expanded arguments
- list of expanded guards
- expanded function body
Note the hook receives the quoted arguments and it is invoked before
Note the hook receives the expanded arguments and it is invoked before
the function is stored in the module. So `Module.defines?/2` will return
`false` for the first clause of every function.
false for the first clause of every function.
If the function/macro being defined has multiple clauses, the hook will
be called for each clause.
@@ -252,7 +252,7 @@ defmodule Module do
* `@external_resource`
Specifies an external resource to the current module.
Specify an external resource to the current module.
Many times a module embeds information from an external file. This
attribute allows the module to annotate which external resources
@@ -261,38 +261,14 @@ defmodule Module do
Tools like Mix may use this information to ensure the module is
recompiled in case any of the external resources change.
* `@dialyzer`
Defines warnings to request or suppress when using a version of
`:dialyzer` that supports module attributes.
Accepts an atom, a tuple, or a list of atoms and tuples.
For the list of supported warnings, see
[`:dialyzer` module](http://www.erlang.org/doc/man/dialyzer.html).
Several uses of `@dialyzer` will accumulate instead of overriding
previous ones.
### Example
defmodule M do
@dialyzer {:nowarn_function, myfun: 1}
def myfun(arg) do
M.not_a_function(arg)
end
end
The following attributes are part of typespecs and are also reserved by
Elixir (see `Kernel.Typespec` for more information about typespecs):
* `@type` - defines a type to be used in `@spec`
* `@typep` - defines a private type to be used in `@spec`
* `@opaque` - defines an opaque type to be used in `@spec`
* `@spec` - provides a specification for a function
* `@callback` - provides a specification for a behaviour callback
* `@macrocallback` - provides a specification for a macro behaviour callback
* `@type` - defines a type to be used in `@spec`
* `@typep` - defines a private type to be used in `@spec`
* `@opaque` - defines an opaque type to be used in `@spec`
* `@spec` - provides a specification for a function
* `@callback` - provides a specification for the behaviour callback
In addition to the built-in attributes outlined above, custom attributes may
also be added. A custom attribute is any valid identifier prefixed with an
@@ -325,14 +301,14 @@ defmodule Module do
* `:module` - module name (`Module == Module.__info__(:module)`)
In addition to the above, you may also pass to `__info__/1` any atom supported
by `:erlang.module_info/0` which also gets defined for each compiled module.
For a list of supported attributes and more information, see [Modules – Erlang Reference Manual](http://www.erlang.org/doc/reference_manual/modules.html#id77056).
by Erlang's `module_info` function which also gets defined for each compiled
module. See http://erlang.org/doc/reference_manual/modules.html#id69430 for
more information.
"""
def __info__(kind)
@doc """
Checks if a module is open, i.e. it is currently being defined
Check if a module is open, i.e. it is currently being defined
and its attributes and functions can be modified.
"""
def open?(module) do
@@ -356,7 +332,7 @@ defmodule Module do
Foo.sum(1, 2) #=> 3
For convenience, you can pass `__ENV__` as an argument and
For convenience, you can my pass `__ENV__` as argument and
all options will be automatically extracted from the environment:
defmodule Foo do
@@ -405,13 +381,13 @@ defmodule Module do
## Differences from `defmodule`
`Module.create/3` works similarly to `defmodule` and
`Module.create` works similarly to `defmodule` and
return the same results. While one could also use
`defmodule` to define modules dynamically, this
function is preferred when the module body is given
by a quoted expression.
Another important distinction is that `Module.create/3`
Another important distinction is that `Module.create`
allows you to control the environment variables used
when defining the module, while `defmodule` automatically
shares the same environment.
@@ -530,7 +506,9 @@ defmodule Module do
assert_not_compiled!(:add_doc, module)
table = data_table_for(module)
signature = simplify_signature(signature)
{signature, _} = :lists.mapfoldl fn(x, acc) ->
{simplify_signature(x, acc), acc + 1}
end, 1, signature
case :ets.lookup(table, {:doc, tuple}) do
[] ->
@@ -550,84 +528,47 @@ defmodule Module do
# Simplify signatures to be stored in docs
defp simplify_signature(signature) do
{signature, acc} = :lists.mapfoldl(&simplify_signature/2, [], signature)
{signature, _} = :lists.mapfoldl(&expand_signature/2, {acc, acc}, signature)
signature
defp simplify_signature({:\\, _, [left, right ]}, i) do
{:\\, [], [simplify_signature(left, i), right]}
end
defp simplify_signature({:\\, _, [left, right ]}, acc) do
{left, acc} = simplify_signature(left, acc)
{{:\\, [], [left, right]}, acc}
defp simplify_signature({:%, _, [left, _]}, _i) when is_atom(left) do
last = List.last(String.split(Atom.to_string(left), "."))
atom = String.to_atom(downcase(last))
{atom, [], nil}
end
defp simplify_signature({:=, _, [_, right]}, acc) do
simplify_signature(right, acc)
defp simplify_signature({:=, _, [_, right]}, i) do
simplify_signature(right, i)
end
defp simplify_signature({var, _, atom}, acc) when is_atom(atom) do
defp simplify_signature({var, _, atom}, _i) when is_atom(atom) do
case Atom.to_string(var) do
"_" <> rest -> {{String.to_atom(rest), [], Elixir}, acc}
_ -> {{var, [], nil}, acc}
"_" <> rest -> {String.to_atom(rest), [], Elixir}
_ -> {var, [], nil}
end
end
defp simplify_signature({:%, _, [left, _]}, acc) when is_atom(left) do
struct_name = String.to_atom(camelcase_to_underscore(List.last(split(left))))
autogenerated(acc, struct_name)
defp simplify_signature(other, i) when is_integer(other), do: {:"int#{i}", [], Elixir}
defp simplify_signature(other, i) when is_boolean(other), do: {:"bool#{i}", [], Elixir}
defp simplify_signature(other, i) when is_atom(other), do: {:"atom#{i}", [], Elixir}
defp simplify_signature(other, i) when is_list(other), do: {:"list#{i}", [], Elixir}
defp simplify_signature(other, i) when is_float(other), do: {:"float#{i}", [], Elixir}
defp simplify_signature(other, i) when is_binary(other), do: {:"binary#{i}", [], Elixir}
defp simplify_signature(_, i), do: {:"arg#{i}", [], Elixir}
defp downcase(<<c :: utf8, rest :: binary>>) when c >= ?A and c <= ?Z do
<<c + 32 :: utf8, downcase(rest) :: binary>>
end
defp simplify_signature({:%{}, _, _}, acc) do
autogenerated(acc, :map)
defp downcase(<<c, rest :: binary>>) do
<<c, downcase(rest) :: binary>>
end
defp simplify_signature(other, acc) when is_integer(other), do: autogenerated(acc, :int)
defp simplify_signature(other, acc) when is_boolean(other), do: autogenerated(acc, :bool)
defp simplify_signature(other, acc) when is_atom(other), do: autogenerated(acc, :atom)
defp simplify_signature(other, acc) when is_list(other), do: autogenerated(acc, :list)
defp simplify_signature(other, acc) when is_float(other), do: autogenerated(acc, :float)
defp simplify_signature(other, acc) when is_binary(other), do: autogenerated(acc, :binary)
defp simplify_signature(_, acc), do: autogenerated(acc, :arg)
defp autogenerated(acc, key) do
{key, [key|acc]}
defp downcase(<<>>) do
<<>>
end
defp expand_signature(key, {all_keys, acc}) when is_atom(key) do
case previous_values(key, all_keys, acc) do
{i, acc} -> {{:"#{key}#{i}", [], Elixir}, {all_keys, acc}}
:none -> {{key, [], Elixir}, {all_keys, acc}}
end
end
defp expand_signature(term, {_, _} = acc) do
{term, acc}
end
defp previous_values(key, all_keys, acc) do
total_occurrences = occurrences(key, all_keys)
if total_occurrences == 1 do
:none
else
index = total_occurrences - occurrences(key, acc) + 1
{index, :lists.delete(key, acc)}
end
end
defp occurrences(key, list) do
length(:lists.filter(fn(el) -> el == key end, list))
end
defp camelcase_to_underscore(<<c :: utf8, rest :: binary>>) when c >= ?A and c <= ?Z,
do: do_camelcase_to_underscore(rest, <<c + 32 :: utf8>>)
defp do_camelcase_to_underscore(<<c :: utf8, rest :: binary>>, acc) when c >= ?A and c <= ?Z,
do: do_camelcase_to_underscore(rest, <<acc :: binary, ?_, c + 32 :: utf8>>)
defp do_camelcase_to_underscore(<<c :: utf8, rest :: binary>>, acc),
do: do_camelcase_to_underscore(rest, <<acc :: binary, c>>)
defp do_camelcase_to_underscore(<<>>, acc),
do: acc
# Merge
defp merge_signatures([h1|t1], [h2|t2], i) do
@@ -699,13 +640,13 @@ defmodule Module do
end
@doc """
Returns all functions defined in `module`.
Return all functions defined in `module`.
## Examples
defmodule Example do
def version, do: 1
Module.definitions_in __MODULE__ #=> [{:version, 0}]
Module.definitions_in __MODULE__ #=> [{:version,0}]
end
"""
@@ -723,7 +664,7 @@ defmodule Module do
defmodule Example do
def version, do: 1
Module.definitions_in __MODULE__, :def #=> [{:version, 0}]
Module.definitions_in __MODULE__, :def #=> [{:version,0}]
Module.definitions_in __MODULE__, :defp #=> []
end
@@ -747,7 +688,7 @@ defmodule Module do
case :elixir_def.lookup_definition(module, tuple) do
false ->
{name, arity} = tuple
raise "cannot make function #{name}/#{arity} overridable because it was not defined"
raise "Cannot make function #{name}/#{arity} overridable because it was not defined"
clause ->
:elixir_def.delete_definition(module, tuple)
@@ -788,7 +729,7 @@ defmodule Module do
def put_attribute(module, key, value) when is_atom(key) do
assert_not_compiled!(:put_attribute, module)
table = data_table_for(module)
value = preprocess_attribute(key, value)
value = normalize_attribute(key, value)
acc = :ets.lookup_element(table, {:elixir, :acc_attributes}, 2)
new =
@@ -901,7 +842,7 @@ defmodule Module do
end
@doc """
Splits the given module name into binary parts.
Split the given module name into binary parts.
## Examples
@@ -909,12 +850,8 @@ defmodule Module do
#=> ["Very", "Long", "Module", "Name", "And", "Even", "Longer"]
"""
def split(module) when is_atom(module) do
split(String.Chars.to_string(module))
end
def split("Elixir." <> name) do
String.split(name, ".")
def split(module) do
tl(String.split(String.Chars.to_string(module), "."))
end
@doc false
@@ -922,22 +859,10 @@ defmodule Module do
# is private and must be used only internally.
def compile_doc(env, kind, name, args, _guards, _body) do
module = env.module
table = data_table_for(module)
line = env.line
arity = length(args)
pair = {name, arity}
{line, doc} = get_doc_info(table, env)
# Arguments are not expanded for the docs, but we make an exception for
# module attributes and for structs (aliases to be precise).
args = Macro.prewalk args, fn
{:@, _, _} = attr ->
Macro.expand_once(attr, env)
{:%, meta, [aliases, fields]} ->
{:%, meta, [Macro.expand_once(aliases, env), fields]}
x ->
x
end
doc = get_attribute(module, :doc)
case add_doc(module, line, kind, pair, args, doc) do
:ok ->
@@ -948,7 +873,7 @@ defmodule Module do
"@doc's are always discarded for private functions"
end
:ok
delete_attribute(module, :doc)
end
@doc false
@@ -973,8 +898,7 @@ defmodule Module do
table = data_table_for(module)
case :ets.lookup(table, key) do
[{^key, val}] ->
postprocess_attribute(key, val)
[{^key, val}] -> val
[] ->
acc = :ets.lookup_element(table, {:elixir, :acc_attributes}, 2)
@@ -983,7 +907,7 @@ defmodule Module do
[]
is_list(warn) ->
:elixir_errors.warn warn_info(warn), "undefined module attribute @#{key}, " <>
"please remove access to @#{key} or explicitly set it before access"
"please remove access to @#{key} or explicitly set it to nil before access"
nil
true ->
nil
@@ -1002,52 +926,34 @@ defmodule Module do
## Helpers
defp preprocess_attribute(:on_load, atom) when is_atom(atom) do
defp normalize_attribute(:on_load, atom) when is_atom(atom) do
{atom, 0}
end
defp preprocess_attribute(:behaviour, atom) when is_atom(atom) do
defp normalize_attribute(:behaviour, atom) when is_atom(atom) do
# Attempt to compile behaviour but ignore failure (will warn later)
_ = Code.ensure_compiled(atom)
atom
end
defp preprocess_attribute(:file, file) when is_binary(file) do
defp normalize_attribute(:file, file) when is_binary(file) do
file
end
defp preprocess_attribute(:before_compile, atom) when is_atom(atom),
do: {atom, :__before_compile__}
defp preprocess_attribute(:after_compile, atom) when is_atom(atom),
do: {atom, :__after_compile__}
defp preprocess_attribute(:on_definition, atom) when is_atom(atom),
do: {atom, :__on_definition__}
defp normalize_attribute(key, atom) when is_atom(atom) and
key in [:before_compile, :after_compile, :on_definition] do
{atom, :"__#{key}__"}
end
defp preprocess_attribute(key, _value) when key in [:type, :typep, :export_type, :opaque, :callback, :macrocallback] do
raise ArgumentError, "attributes type, typep, export_type, opaque, callback and macrocallback " <>
defp normalize_attribute(key, _value) when key in [:type, :typep, :export_type, :opaque, :callback] do
raise ArgumentError, "attributes type, typep, export_type, opaque and callback " <>
"must be set via Kernel.Typespec"
end
defp preprocess_attribute(_key, value) do
defp normalize_attribute(_key, value) do
value
end
defp postprocess_attribute(:doc, {_line, doc}), do: doc
defp postprocess_attribute(:typedoc, {_line, doc}), do: doc
defp postprocess_attribute(:moduledoc, {_line, doc}), do: doc
defp postprocess_attribute(_, value), do: value
defp get_doc_info(table, env) do
# TODO: Use :ets.take/2 with Erlang 18
case :ets.lookup(table, :doc) do
[doc: {_, _} = pair] ->
:ets.delete(table, :doc)
pair
[] ->
{env.line, nil}
end
end
defp data_table_for(module) do
:elixir_module.data_table(module)
end
+11 -3
View File
@@ -30,7 +30,7 @@
# * out neighbours: `Module`
#
# Note that since this is required for bootstrap, we can't use
# any of the `GenServer` conveniences.
# any of the `GenServer.Behaviour` conveniences.
defmodule Module.LocalsTracker do
@moduledoc false
@@ -244,11 +244,11 @@ defmodule Module.LocalsTracker do
@doc false
def handle_call({:cache_env, env}, _from, {d, cache}) do
case cache do
[{i, ^env}|_] ->
[{i,^env}|_] ->
{:reply, i, {d, cache}}
t ->
i = length(t)
{:reply, i, {d, [{i, env}|t]}}
{:reply, i, {d, [{i,env}|t]}}
end
end
@@ -267,6 +267,10 @@ defmodule Module.LocalsTracker do
{:reply, d, state}
end
def handle_call(request, _from, state) do
{:stop, {:bad_call, request}, state}
end
@doc false
def handle_info(_msg, state) do
{:noreply, state}
@@ -313,6 +317,10 @@ defmodule Module.LocalsTracker do
{:stop, :normal, state}
end
def handle_cast(msg, state) do
{:stop, {:bad_cast, msg}, state}
end
@doc false
def terminate(_reason, _state) do
:ok
+17 -25
View File
@@ -72,8 +72,7 @@ defmodule Node do
The result returned when the argument is a list, is the list of nodes
satisfying the disjunction(s) of the list elements.
For more information, see
[`:erlang.nodes/1`](http://www.erlang.org/doc/man/erlang.html#nodes-1).
See http://www.erlang.org/doc/man/erlang.html#nodes-1 for more info.
"""
@typep state :: :visible | :hidden | :connected | :this | :known
@spec list(state | [state]) :: [t]
@@ -87,8 +86,7 @@ defmodule Node do
If `flag` is `true`, monitoring is turned on.
If `flag` is `false`, monitoring is turned off.
For more information, see
[`:erlang.monitor_node/2`](http://www.erlang.org/doc/man/erlang.html#monitor_node-2).
See http://www.erlang.org/doc/man/erlang.html#monitor_node-2 for more info.
"""
@spec monitor(t, boolean) :: true
def monitor(node, flag) do
@@ -99,8 +97,7 @@ defmodule Node do
Behaves as `monitor/2` except that it allows an extra
option to be given, namely `:allow_passive_connect`.
For more information, see
[`:erlang.monitor_node/3`](http://www.erlang.org/doc/man/erlang.html#monitor_node-3).
See http://www.erlang.org/doc/man/erlang.html#monitor_node-3 for more info.
"""
@spec monitor(t, boolean, [:allow_passive_connect]) :: true
def monitor(node, flag, options) do
@@ -131,8 +128,7 @@ defmodule Node do
protocols. Returns `true` if disconnection succeeds, otherwise `false`.
If the local node is not alive, the function returns `:ignored`.
For more information, see
[`:erlang.disconnect_node/1`](http://www.erlang.org/doc/man/erlang.html#disconnect_node-1).
See http://www.erlang.org/doc/man/erlang.html#disconnect_node-1 for more info.
"""
@spec disconnect(t) :: boolean | :ignored
def disconnect(node) do
@@ -145,8 +141,7 @@ defmodule Node do
Returns `true` if successful, `false` if not, and the atom
`:ignored` if the local node is not alive.
For more information, see
[`:erlang.connect_node/1`](http://www.erlang.org/doc/man/net_kernel.html#connect_node-1).
See http://erlang.org/doc/man/net_kernel.html#connect_node-1 for more info.
"""
@spec connect(t) :: boolean | :ignored
def connect(node) do
@@ -157,8 +152,8 @@ defmodule Node do
Returns the pid of a new process started by the application of `fun`
on `node`. If `node` does not exist, a useless pid is returned.
For the list of available options, see
[`:erlang.spawn/2`](http://www.erlang.org/doc/man/erlang.html#spawn-2).
Check http://www.erlang.org/doc/man/erlang.html#spawn-2 for
the list of available options.
Inlined by the compiler.
"""
@@ -171,10 +166,9 @@ defmodule Node do
Returns the pid of a new process started by the application of `fun`
on `node`.
If `node` does not exist, a useless pid is returned.
For the list of available options, see
[`:erlang.spawn_opt/3`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-3).
If `node` does not exist, a useless pid is returned. Check
http://www.erlang.org/doc/man/erlang.html#spawn_opt-3 for the list of
available options.
Inlined by the compiler.
"""
@@ -187,10 +181,9 @@ defmodule Node do
Returns the pid of a new process started by the application of
`module.function(args)` on `node`.
If `node` does not exist, a useless pid is returned.
For the list of available options, see
[`:erlang.spawn/4`](http://www.erlang.org/doc/man/erlang.html#spawn-4).
If `node` does not exist, a useless pid is returned. Check
http://www.erlang.org/doc/man/erlang.html#spawn-4 for the list of
available options.
Inlined by the compiler.
"""
@@ -203,10 +196,9 @@ defmodule Node do
Returns the pid of a new process started by the application of
`module.function(args)` on `node`.
If `node` does not exist, a useless pid is returned.
For the list of available options, see
[`:erlang.spawn/5`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-5).
If `node` does not exist, a useless pid is returned. Check
http://www.erlang.org/doc/man/erlang.html#spawn_opt-5 for the list of
available options.
Inlined by the compiler.
"""
@@ -247,7 +239,7 @@ defmodule Node do
@doc """
Sets the magic cookie of `node` to the atom `cookie`.
The default node is `Node.self/0`, the local node. If `node` is the local node,
The default node is `Node.self`, the local node. If `node` is the local node,
the function also sets the cookie of all other unknown nodes to `cookie`.
This function will raise `FunctionClauseError` if the given `node` is not alive.
+6 -9
View File
@@ -27,7 +27,7 @@ defmodule OptionParser do
By default, Elixir will try to automatically parse switches.
Switches without an argument, like `--debug` will automatically
be set to `true`. Switches followed by a value will be assigned
be set to true. Switches followed by a value will be assigned
to the value, always as strings.
Note Elixir also converts the switches to underscore atoms, as
@@ -53,8 +53,8 @@ defmodule OptionParser do
For each switch, the following types are supported:
* `:boolean` - marks the given switch as a boolean. Boolean switches
never consume the following value unless it is `true` or
`false`.
never consume the following value unless it is `true` or
`false`.
* `:integer` - parses the switch as an integer.
* `:float` - parses the switch as a float.
* `:string` - returns the switch as a string.
@@ -89,13 +89,10 @@ defmodule OptionParser do
...> switches: [limit: :integer])
{[limit: 3, unknown: "xyz"], [], []}
iex> OptionParser.parse(["--unlock", "path/to/file", "--unlock", "path/to/another/file"], strict: [unlock: :keep])
{[unlock: "path/to/file", unlock: "path/to/another/file"], [], []}
## Negation switches
In case a switch is declared as boolean, it may be passed as `--no-SWITCH`
which will set the option to `false`:
which will set the option to false:
iex> OptionParser.parse(["--no-op", "path/to/file"], switches: [op: :boolean])
{[op: false], ["path/to/file"], []}
@@ -280,7 +277,7 @@ defmodule OptionParser do
do_split(strip_leading_spaces(string), "", [], nil)
end
# If we have an escaped quote, simply remove the escape
# If we have a escaped quote, simply remove the escape
defp do_split(<<?\\, quote, t :: binary>>, buffer, acc, quote),
do: do_split(t, <<buffer::binary, quote>>, acc, quote)
@@ -292,7 +289,7 @@ defmodule OptionParser do
defp do_split(<<quote, t :: binary>>, buffer, acc, quote),
do: do_split(t, buffer, acc, nil)
# If we have an escaped quote/space, simply remove the escape as long as we are not inside a quote
# If we have a escaped quote/space, simply remove the escape as long as we are not inside a quote
defp do_split(<<?\\, h, t :: binary>>, buffer, acc, nil) when h in [?\s, ?', ?"],
do: do_split(t, <<buffer::binary, h>>, acc, nil)
+12 -13
View File
@@ -267,7 +267,7 @@ defmodule Path do
In other words, it tries to strip the `from` prefix from `path`.
This function does not query the file system, so it assumes
no symlinks between the paths.
no symlinks in between the paths.
In case a direct relative path cannot be found, it returns
the original path.
@@ -494,14 +494,14 @@ defmodule Path do
## Examples
iex> Path.split("")
[]
iex> Path.split("")
[]
iex> Path.split("foo")
["foo"]
iex> Path.split("foo")
["foo"]
iex> Path.split("/foo/bar")
["/", "foo", "bar"]
iex> Path.split("/foo/bar")
["/", "foo", "bar"]
"""
@spec split(t) :: [binary]
@@ -545,8 +545,7 @@ defmodule Path do
end
@doc """
Traverses paths according to the given `glob` expression, and returns a
list of matches.
Traverses paths according to the given `glob` expression.
The wildcard looks like an ordinary path, except that certain
"wildcard characters" are interpreted in a special way. The
@@ -560,17 +559,17 @@ defmodule Path do
* `**` - two adjacent `*`'s used as a single pattern will match all
files and zero or more directories and subdirectories
* `[char1, char2, ...]` - matches any of the characters listed; two
* `[char1,char2,...]` - matches any of the characters listed; two
characters separated by a hyphen will match a range of characters
* `{item1, item2, ...}` - matches one of the alternatives
* `{item1,item2,...}` - matches one of the alternatives
Other characters represent themselves. Only paths that have
exactly the same character in the same position will match. Note
that matching is case-sensitive; i.e. "a" will not match "A".
By default, the patterns `*` and `?` do not match files starting
with a dot `.` unless `match_dot: true` is given in `opts`.
with a dot `.` unless `match_dot: true` is given.
## Examples
@@ -585,7 +584,7 @@ defmodule Path do
Path.wildcard("projects/*/ebin/**/*.{beam,app}")
"""
@spec wildcard(t, Keyword.t) :: [binary]
@spec wildcard(t) :: [binary]
def wildcard(glob, opts \\ []) do
mod = if Keyword.get(opts, :match_dot), do: :file, else: Path.Wildcard
glob
+14 -30
View File
@@ -4,7 +4,7 @@ defmodule Port do
"""
@doc """
See [`:erlang.open_port/2`](http://www.erlang.org/doc/man/erlang.html#open_port-2)
See http://www.erlang.org/doc/man/erlang.html#open_port-2.
Inlined by the compiler.
"""
@@ -13,7 +13,7 @@ defmodule Port do
end
@doc """
See [`:erlang.port_close/1`](http://www.erlang.org/doc/man/erlang.html#port_close-1)
See http://www.erlang.org/doc/man/erlang.html#port_close-1.
Inlined by the compiler.
"""
@@ -22,7 +22,7 @@ defmodule Port do
end
@doc """
See [`:erlang.port_command/2`](http://www.erlang.org/doc/man/erlang.html#port_command-2)
See http://www.erlang.org/doc/man/erlang.html#port_command-2.
Inlined by the compiler.
"""
@@ -31,7 +31,7 @@ defmodule Port do
end
@doc """
See [`:erlang.port_connect/2`](http://www.erlang.org/doc/man/erlang.html#port_connect-2)
See http://www.erlang.org/doc/man/erlang.html#port_connect-2.
Inlined by the compiler.
"""
@@ -40,7 +40,7 @@ defmodule Port do
end
@doc """
See [`:erlang.port_control/3`](http://www.erlang.org/doc/man/erlang.html#port_control-3)
See http://www.erlang.org/doc/man/erlang.html#port_control-3.
Inlined by the compiler.
"""
@@ -49,7 +49,7 @@ defmodule Port do
end
@doc """
See [`:erlang.port_call/3`](http://www.erlang.org/doc/man/erlang.html#port_call-3)
See http://www.erlang.org/doc/man/erlang.html#port_call-3.
Inlined by the compiler.
"""
@@ -58,45 +58,29 @@ defmodule Port do
end
@doc """
Returns information about the `port`
or `nil` if the port is closed.
See http://www.erlang.org/doc/man/erlang.html#port_info-1.
See [`:erlang.port_info/1`](http://www.erlang.org/doc/man/erlang.html#port_info-1)
Inlined by the compiler.
"""
def info(port) do
nillify :erlang.port_info(port)
:erlang.port_info(port)
end
@doc """
Returns information about the `port`
or `nil` if the port is closed.
See http://www.erlang.org/doc/man/erlang.html#port_info-2.
See [`:erlang.port_info/2`](http://www.erlang.org/doc/man/erlang.html#port_info-2)
Inlined by the compiler.
"""
@spec info(port, atom) :: {atom, term} | nil
def info(port, spec)
def info(port, :registered_name) do
case :erlang.port_info(port, :registered_name) do
[] -> {:registered_name, []}
other -> nillify(other)
end
end
def info(port, item) do
nillify :erlang.port_info(port, item)
:erlang.port_info(port, item)
end
@doc """
See [`:erlang.ports/0`](http://www.erlang.org/doc/man/erlang.html#ports-0)
See http://www.erlang.org/doc/man/erlang.html#ports-0.
Inlined by the compiler.
"""
def list do
:erlang.ports
end
@compile {:inline, nillify: 1}
defp nillify(:undefined), do: nil
defp nillify(other), do: other
end
end
+20 -36
View File
@@ -15,8 +15,8 @@ defmodule Process do
"""
@doc """
Returns `true` if the process exists and is alive (i.e. it is not exiting
and has not exited yet). Otherwise, returns `false`.
Returns true if the process exists and is alive, that is,
is not exiting and has not exited. Otherwise, returns false.
`pid` must refer to a process at the local node.
"""
@@ -81,10 +81,9 @@ defmodule Process do
2. If pid is trapping exits, the exit signal is transformed into a message
`{:EXIT, from, reason}` and delivered to the message queue of pid.
3. If reason is the atom `:normal`, pid will not exit (unless it is the calling
process's pid, in which case it will exit with the reason `:normal`).
If it is trapping exits, the exit signal is transformed into a message
`{:EXIT, from, :normal}` and delivered to its message queue.
3. If reason is the atom `:normal`, pid will not exit. If it is trapping
exits, the exit signal is transformed into a message `{:EXIT, from,
:normal}` and delivered to its message queue.
4. If reason is the atom `:kill`, that is if `exit(pid, :kill)` is called,
an untrappable exit signal is sent to pid which will unconditionally
@@ -167,7 +166,7 @@ defmodule Process do
just the spawned process pid.
It also accepts extra options, for the list of available options
check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4).
check http://www.erlang.org/doc/man/erlang.html#spawn_opt-4
Inlined by the compiler.
"""
@@ -186,7 +185,7 @@ defmodule Process do
just the spawned process pid.
It also accepts extra options, for the list of available options
check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4).
check http://www.erlang.org/doc/man/erlang.html#spawn_opt-4
Inlined by the compiler.
"""
@@ -199,7 +198,7 @@ defmodule Process do
The calling process starts monitoring the item given.
It returns the monitor reference.
See [`:erlang.monitor/2`](http://www.erlang.org/doc/man/erlang.html#monitor-2) for more info.
See http://www.erlang.org/doc/man/erlang.html#monitor-2 for more info.
Inlined by the compiler.
"""
@@ -213,7 +212,7 @@ defmodule Process do
obtained by calling `monitor/1`, this monitoring is turned off.
If the monitoring is already turned off, nothing happens.
See [`:erlang.demonitor/2`](http://www.erlang.org/doc/man/erlang.html#demonitor-2) for more info.
See http://www.erlang.org/doc/man/erlang.html#demonitor-2 for more info.
Inlined by the compiler.
"""
@@ -231,7 +230,7 @@ defmodule Process do
`alive?/1` will return `false` for a process that is exiting,
but its process identifier will be part of the result returned.
See [`:erlang.processes/0`](http://www.erlang.org/doc/man/erlang.html#processes-0) for more info.
See http://www.erlang.org/doc/man/erlang.html#processes-0 for more info.
"""
@spec list :: [pid]
def list do
@@ -242,7 +241,7 @@ defmodule Process do
Creates a link between the calling process and another process
(or port) `pid`, if there is not such a link already.
See [`:erlang.link/1`](http://www.erlang.org/doc/man/erlang.html#link-1) for more info.
See http://www.erlang.org/doc/man/erlang.html#link-1 for more info.
Inlined by the compiler.
"""
@@ -256,7 +255,7 @@ defmodule Process do
the process or port referred to by `pid`. Returns `true` and does not
fail, even if there is no link or `id` does not exist
See [`:erlang.unlink/1`](http://www.erlang.org/doc/man/erlang.html#unlink-1) for more info.
See http://www.erlang.org/doc/man/erlang.html#unlink-1 for more info.
Inlined by the compiler.
"""
@@ -282,7 +281,7 @@ defmodule Process do
@doc """
Removes the registered name, associated with a pid or a port identifier.
See [`:erlang.unregister/1`](http://www.erlang.org/doc/man/erlang.html#unregister-1) for more info.
See http://www.erlang.org/doc/man/erlang.html#unregister-1 for more info.
"""
@spec unregister(atom) :: true
def unregister(name) do
@@ -293,7 +292,7 @@ defmodule Process do
Returns the pid or port identifier with the registered name.
Returns `nil` if the name is not registered.
See [`:erlang.whereis/1`](http://www.erlang.org/doc/man/erlang.html#whereis-1) for more info.
See http://www.erlang.org/doc/man/erlang.html#whereis-1 for more info.
"""
@spec whereis(atom) :: pid | port | nil
def whereis(name) do
@@ -332,7 +331,7 @@ defmodule Process do
Sets certain flags for the process which calls this function.
Returns the old value of the flag.
See [`:erlang.process_flag/2`](http://www.erlang.org/doc/man/erlang.html#process_flag-2) for more info.
See http://www.erlang.org/doc/man/erlang.html#process_flag-2 for more info.
"""
@spec flag(process_flag, term) :: term
def flag(flag, value) do
@@ -344,7 +343,7 @@ defmodule Process do
Returns the old value of the flag. The allowed values for `flag` are
only a subset of those allowed in `flag/2`, namely: `save_calls`.
See [`:erlang.process_flag/3`](http://www.erlang.org/doc/man/erlang.html#process_flag-3) for more info.
See http://www.erlang.org/doc/man/erlang.html#process_flag-3 for more info.
"""
@spec flag(pid, :save_calls, non_neg_integer) :: non_neg_integer
def flag(pid, flag, value) do
@@ -356,7 +355,7 @@ defmodule Process do
is not alive.
Use this only for debugging information.
See [`:erlang.process_info/1`](http://www.erlang.org/doc/man/erlang.html#process_info-1) for more info.
See http://www.erlang.org/doc/man/erlang.html#process_info-1 for more info.
"""
@spec info(pid) :: Keyword.t
def info(pid) do
@@ -367,9 +366,9 @@ defmodule Process do
Returns information about the process identified by `pid`
or `nil` if the process is not alive.
See [`:erlang.process_info/2`](http://www.erlang.org/doc/man/erlang.html#process_info-2) for more info.
See http://www.erlang.org/doc/man/erlang.html#process_info-2 for more info.
"""
@spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil
@spec info(pid, atom) :: {atom, term} | nil
def info(pid, spec)
def info(pid, :registered_name) do
@@ -380,25 +379,10 @@ defmodule Process do
end
end
def info(pid, spec) when is_atom(spec) or is_list(spec) do
def info(pid, spec) when is_atom(spec) do
nillify :erlang.process_info(pid, spec)
end
@doc """
Puts the calling process into a wait state
where its memory allocation has been reduced as much as possible,
which is useful if the process does not expect to receive any messages
in the near future.
See [`:erlang.hibernate/3`](http://www.erlang.org/doc/man/erlang.html#hibernate-3) for more info.
Inlined by the compiler.
"""
@spec hibernate(module, atom, list) :: no_return
def hibernate(mod, fun, args) do
:erlang.hibernate(mod, fun, args)
end
@compile {:inline, nillify: 1}
defp nillify(:undefined), do: nil
defp nillify(other), do: other
+27 -37
View File
@@ -70,7 +70,7 @@ defmodule Protocol do
end
try do
module.__protocol__(:module)
module.__protocol__(:name)
rescue
UndefinedFunctionError ->
raise ArgumentError, "#{inspect module} is not a protocol" <> extra
@@ -115,7 +115,7 @@ defmodule Protocol do
end
@doc """
Derives the `protocol` for `module` with the given options.
Derive the `protocol` for `module` with the given options.
"""
defmacro derive(protocol, module, options \\ []) do
quote do
@@ -127,7 +127,7 @@ defmodule Protocol do
## Consolidation
@doc """
Extracts all protocols from the given paths.
Extract all protocols from the given paths.
The paths can be either a char list or a string. Internally
they are worked on as char lists, so passing them as lists
@@ -149,14 +149,14 @@ defmodule Protocol do
extract_matching_by_attribute paths, 'Elixir.',
fn module, attributes ->
case attributes[:protocol] do
[fallback_to_any: _] -> module
[fallback_to_any: _, consolidated: _] -> module
_ -> nil
end
end
end
@doc """
Extracts all types implemented for the given protocol from
Extract all types implemented for the given protocol from
the given paths.
The paths can be either a char list or a string. Internally
@@ -227,11 +227,11 @@ defmodule Protocol do
end
@doc """
Returns `true` if the protocol was consolidated.
Returns true if the protocol was consolidated.
"""
@spec consolidated?(module) :: boolean
def consolidated?(protocol) do
protocol.__protocol__(:consolidated?)
protocol.__info__(:attributes)[:protocol][:consolidated]
end
@doc """
@@ -250,7 +250,7 @@ defmodule Protocol do
Protocol.consolidated?(Enumerable)
If the first element of the tuple is `true`, it means
If the first element of the tuple is true, it means
the protocol was consolidated.
This function does not load the protocol at any point
@@ -278,7 +278,7 @@ defmodule Protocol do
{:attributes, attributes},
{@docs_chunk, docs}]}} ->
case attributes[:protocol] do
[fallback_to_any: any] ->
[fallback_to_any: any, consolidated: _] ->
{:ok, {protocol, any, abstract_code, docs}}
_ ->
{:error, :not_a_protocol}
@@ -307,16 +307,10 @@ defmodule Protocol do
end
end
defp change_impl_for([{:function, line, :__protocol__, 1, clauses}|t], protocol, types, structs, _, acc) do
clauses = :lists.map(fn
{:clause, l, [{:atom, _, :consolidated?}], [], [{:atom, _, _}]} ->
{:clause, l, [{:atom, 0, :consolidated?}], [], [{:atom, 0, true}]}
{:clause, _, _, _, _} = c ->
c
end, clauses)
defp change_impl_for([{:attribute, line, :protocol, opts}|t], protocol, types, structs, _, acc) do
opts = [fallback_to_any: opts[:fallback_to_any], consolidated: true]
change_impl_for(t, protocol, types, structs, true,
[{:function, line, :__protocol__, 1, clauses}|acc])
[{:attribute, line, :protocol, opts}|acc])
end
defp change_impl_for([{:function, line, :impl_for, 1, _}|t], protocol, types, structs, is_protocol, acc) do
@@ -425,7 +419,7 @@ defmodule Protocol do
@fallback_to_any false
# Invoke the user given block
_ = unquote(block)
unquote(block)
# Finalize expansion
unquote(after_defprotocol)
@@ -465,7 +459,12 @@ defmodule Protocol do
# Internal handler for Any
if @fallback_to_any do
Kernel.defp any_impl_for, do: __MODULE__.Any.__impl__(:target)
Kernel.defp any_impl_for do
case impl_for?(__MODULE__.Any) do
true -> __MODULE__.Any.__impl__(:target)
false -> nil
end
end
else
Kernel.defp any_impl_for, do: nil
end
@@ -495,15 +494,13 @@ defmodule Protocol do
# Store information as an attribute so it
# can be read without loading the module.
Module.register_attribute(__MODULE__, :protocol, persist: true)
@protocol [fallback_to_any: !!@fallback_to_any]
@protocol [fallback_to_any: !!@fallback_to_any, consolidated: false]
@doc false
@spec __protocol__(:module) :: __MODULE__
@spec __protocol__(:name) :: __MODULE__
@spec __protocol__(:functions) :: unquote(Protocol.__functions_spec__(@functions))
@spec __protocol__(:consolidated?) :: boolean
Kernel.def __protocol__(:module), do: __MODULE__
Kernel.def __protocol__(:name), do: __MODULE__
Kernel.def __protocol__(:functions), do: unquote(:lists.sort(@functions))
Kernel.def __protocol__(:consolidated?), do: false
end
end
@@ -526,7 +523,7 @@ defmodule Protocol do
# Unquote the implementation just later
# when all variables will already be injected
# into the module body.
impl =
__impl__ =
quote unquote: false do
@doc false
@spec __impl__(:for) :: unquote(for)
@@ -542,14 +539,7 @@ defmodule Protocol do
for = unquote(for)
name = Module.concat(protocol, for)
# TODO: Remove this by 1.3
if Atom.to_string(protocol) =~ "Elixir.Access" do
:elixir_errors.warn __ENV__.line, __ENV__.file,
"implementation of the Access protocol is deprecated. For customization of " <>
"the dict[key] syntax, please implement the Dict behaviour instead"
else
Protocol.assert_protocol!(protocol)
end
Protocol.assert_protocol!(protocol)
defmodule name do
@behaviour protocol
@@ -561,7 +551,7 @@ defmodule Protocol do
Module.register_attribute(__MODULE__, :impl, persist: true)
@impl [protocol: @protocol, for: @for]
unquote(impl)
unquote(__impl__)
end
end
end
@@ -589,12 +579,12 @@ defmodule Protocol do
defp derive(protocol, for, struct, opts, env) do
extra = ", cannot derive #{inspect protocol} for #{inspect for}"
assert_protocol!(protocol, extra)
assert_impl!(protocol, Any, extra)
assert_impl!(protocol, Map, extra)
# Clean up variables from eval context
env = %{env | vars: [], export_vars: nil}
args = [for, struct, opts]
impl = Module.concat(protocol, Any)
impl = Module.concat(protocol, Map)
:elixir_module.expand_callback(env.line, impl, :__deriving__, args, env, fn
mod, fun, args ->
+42 -32
View File
@@ -2,13 +2,6 @@ defmodule Range do
@moduledoc """
Defines a Range.
A Range represents a discrete number of values where
the first and last values are integers.
Ranges can be either increasing (first <= last) or
decresing (first > last). Ranges are also always
inclusive.
A Range is represented internally as a struct. However,
the most common form of creating and matching on ranges
is via the `../2` macro, auto-imported from Kernel:
@@ -36,7 +29,7 @@ defmodule Range do
end
@doc """
Returns `true` if the given argument is a range.
Returns true if the given argument is a range.
## Examples
@@ -51,34 +44,48 @@ defmodule Range do
def range?(_), do: false
end
defprotocol Range.Iterator do
@moduledoc """
A protocol used for iterating range elements.
"""
@doc """
Returns the function that calculates the next item.
"""
def next(first, range)
@doc """
Count how many items are in the range.
"""
def count(first, range)
end
defimpl Enumerable, for: Range do
def reduce(first .. last, acc, fun) do
validate_range!(first, last)
reduce(first, last, acc, fun, last >= first)
def reduce(first .. last = range, acc, fun) do
reduce(first, last, acc, fun, Range.Iterator.next(first, range), last >= first)
end
defp reduce(_x, _y, {:halt, acc}, _fun, _up) do
defp reduce(_x, _y, {:halt, acc}, _fun, _next, _up) do
{:halted, acc}
end
defp reduce(x, y, {:suspend, acc}, fun, up) do
{:suspended, acc, &reduce(x, y, &1, fun, up)}
defp reduce(x, y, {:suspend, acc}, fun, next, up) do
{:suspended, acc, &reduce(x, y, &1, fun, next, up)}
end
defp reduce(x, y, {:cont, acc}, fun, true) when x <= y do
reduce(x + 1, y, fun.(x, acc), fun, true)
defp reduce(x, y, {:cont, acc}, fun, next, true) when x <= y do
reduce(next.(x), y, fun.(x, acc), fun, next, true)
end
defp reduce(x, y, {:cont, acc}, fun, false) when x >= y do
reduce(x - 1, y, fun.(x, acc), fun, false)
defp reduce(x, y, {:cont, acc}, fun, next, false) when x >= y do
reduce(next.(x), y, fun.(x, acc), fun, next, false)
end
defp reduce(_, _, {:cont, acc}, _fun, _up) do
defp reduce(_, _, {:cont, acc}, _fun, _next, _up) do
{:done, acc}
end
def member?(first .. last, value) when is_integer(value) do
validate_range!(first, last)
def member?(first .. last, value) do
if first <= last do
{:ok, first <= value and value <= last}
else
@@ -86,23 +93,26 @@ defimpl Enumerable, for: Range do
end
end
def member?(_ .. _, _value) do
{:ok, false}
def count(first .. _ = range) do
{:ok, Range.Iterator.count(first, range)}
end
end
def count(first .. last) do
validate_range!(first, last)
if first <= last do
{:ok, last - first + 1}
defimpl Range.Iterator, for: Integer do
def next(first, _ .. last) when is_integer(last) do
if last >= first do
&(&1 + 1)
else
{:ok, first - last + 1}
&(&1 - 1)
end
end
defp validate_range!(first, last) when is_integer(first) and is_integer(last), do: :ok
defp validate_range!(first, last) do
raise ArgumentError,
"ranges (left .. right) expect both sides to be integers, got: #{inspect first..last}"
def count(first, _ .. last) when is_integer(last) do
if last >= first do
last - first + 1
else
first - last + 1
end
end
end
+4 -44
View File
@@ -29,10 +29,10 @@ defmodule Record do
defmodule MyModule do
require Record
Record.defrecord :user, name: "john", age: 25
Record.defrecord :user name: "john", age: 25
@type user :: record(:user, name: String.t, age: integer)
# expands to: "@type user :: {:user, String.t, integer}"
# expands to: `@type user :: {:user, String.t, integer}`
end
"""
@@ -52,21 +52,8 @@ defmodule Record do
uid: :undefined, gid: :undefined]
"""
def extract(name, opts) when is_atom(name) and is_list(opts) do
Record.Extractor.extract(name, opts)
end
@doc """
Extracts all records information from an Erlang file.
Returns a keyword list containing extracted record names as keys, and
lists of tuples describing the fields as values. It expects a named
argument :from or :from_lib, which correspond to *include* or
*include_lib* attribute from Erlang modules, respectively.
"""
def extract_all(opts) when is_list(opts) do
Record.Extractor.extract_all(opts)
defmacro extract(name, opts) when is_atom(name) and is_list(opts) do
Macro.escape Record.Extractor.extract(name, opts)
end
@doc """
@@ -158,14 +145,6 @@ defmodule Record do
# Convert a record to a keyword list
user(record) #=> [name: "meg", age: 26]
The generated macros can also be used in order to pattern match on records and
to bind variables during the match:
record = user() #=> {:user, "meg", 25}
user(name: name) = record
name #=> "meg"
By default, Elixir uses the record name as the first element of
the tuple (the tag). But it can be changed to something else:
@@ -177,25 +156,6 @@ defmodule Record do
require User
User.user() #=> {User, nil}
## Defining extracted records with anonymous functions
If a record defines an anonymous function, an ArgumentError
will occur if you attempt to create a record with it.
This can occur unintentionally when defining a record after extracting
it from an Erlang library that uses anonymous functions for defaults.
Record.defrecord :my_rec, Record.extract(...)
#=> ** (ArgumentError) invalid value for record field fun_field,
cannot escape #Function<12.90072148/2 in :erl_eval.expr/5>.
To work around this error, redefine the field with your own &M.f/a function,
like so:
defmodule MyRec do
require Record
Record.defrecord :my_rec, Record.extract(...) |> Keyword.merge(fun_field: &__MODULE__.foo/2)
def foo(bar, baz), do: IO.inspect({bar, baz})
end
"""
defmacro defrecord(name, tag \\ nil, kv) do
quote bind_quoted: [name: name, tag: tag, kv: kv] do
+12 -36
View File
@@ -4,44 +4,27 @@ defmodule Record.Extractor do
# Retrieve a record definition from an Erlang file using
# the same lookup as the *include* attribute from Erlang modules.
def extract(name, from: file) when is_binary(file) do
extract_record(name, from_file(file))
file = String.to_char_list(file)
realfile =
case :code.where_is_file(file) do
:non_existing -> file
realfile -> realfile
end
extract_record(name, realfile)
end
# Retrieve a record definition from an Erlang file using
# the same lookup as the *include_lib* attribute from Erlang modules.
def extract(name, from_lib: file) when is_binary(file) do
extract_record(name, from_lib_file(file))
end
# Retrieve all records definitions from an Erlang file using
# the same lookup as the *include* attribute from Erlang modules.
def extract_all(from: file) when is_binary(file) do
extract_all_records(from_file(file))
end
# Retrieve all records definitions from an Erlang file using
# the same lookup as the *include_lib* attribute from Erlang modules.
def extract_all(from_lib: file) when is_binary(file) do
extract_all_records(from_lib_file(file))
end
# Find file using the same lookup as the *include* attribute from Erlang modules.
defp from_file(file) do
file = String.to_char_list(file)
case :code.where_is_file(file) do
:non_existing -> file
realfile -> realfile
end
end
# Find file using the same lookup as the *include_lib* attribute from Erlang modules.
defp from_lib_file(file) do
[app|path] = :filename.split(String.to_char_list(file))
case :code.lib_dir(List.to_atom(app)) do
{:error, _} ->
raise ArgumentError, "lib file #{file} could not be found"
libpath ->
:filename.join([libpath|path])
extract_record name, :filename.join([libpath|path])
end
end
@@ -56,13 +39,6 @@ defmodule Record.Extractor do
end
end
# Retrieve all records from the given file
defp extract_all_records(file) do
form = read_file(file)
records = extract_records(form)
for rec = {name, _fields} <- records, do: {name, parse_record(rec, form)}
end
# Parse the given file and extract all existent records.
defp extract_records(form) do
for {:attribute, _, :record, record} <- form, do: record
@@ -70,7 +46,7 @@ defmodule Record.Extractor do
# Read a file and return its abstract syntax form that also
# includes record but with macros and other attributes expanded,
# such as "-include(...)" and "-include_lib(...)". This is done
# such as `-include(...)` and `-include_lib(...)`. This is done
# by using Erlang's epp.
defp read_file(file) do
case :epp.parse_file(file, []) do
+37 -53
View File
@@ -1,13 +1,13 @@
defmodule Regex do
@moduledoc ~S"""
Regular expressions for Elixir built on top of Erlang's `:re` module.
Regular expressions for Elixir built on top of Erlang's `re` module.
As the `:re` module, Regex is based on PCRE
As the `re` module, Regex is based on PCRE
(Perl Compatible Regular Expressions). More information can be
found in the [`:re` module documentation](http://www.erlang.org/doc/man/re.html).
found in the [`re` documentation](http://www.erlang.org/doc/man/re.html).
Regular expressions in Elixir can be created using `Regex.compile!/2`
or using the special form with [`~r`](Kernel.html#sigil_r/2) or [`~R`](Kernel.html#sigil_R/2):
or using the special form with [`~r`](Kernel.html#sigil_r/2):
# A simple regular expressions that matches foo anywhere in the string
~r/foo/
@@ -41,8 +41,7 @@ defmodule Regex do
* `firstline` (f) - forces the unanchored pattern to match before or at the
first newline, though the matched text may continue over the newline
* `ungreedy` (U) - inverts the "greediness" of the regexp
(the previous `r` option is deprecated in favor of `U`)
* `ungreedy` (r) - inverts the "greediness" of the regexp
The options not available are:
@@ -90,7 +89,7 @@ defmodule Regex do
The given options can either be a binary with the characters
representing the same regex options given to the `~r` sigil,
or a list of options, as expected by the Erlang's [`:re` module](http://www.erlang.org/doc/man/re.html).
or a list of options, as expected by the [Erlang `re` docs](http://www.erlang.org/doc/man/re.html).
It returns `{:ok, regex}` in case of success,
`{:error, reason}` otherwise.
@@ -160,8 +159,7 @@ defmodule Regex do
end
@doc """
Returns `true` if the given `term` is a regex.
Otherwise returns `false`.
Returns true if the given argument is a regex.
## Examples
@@ -174,7 +172,6 @@ defmodule Regex do
"""
@spec regex?(t) :: true
@spec regex?(any) :: false
def regex?(term)
def regex?(%Regex{}), do: true
def regex?(_), do: false
@@ -186,7 +183,7 @@ defmodule Regex do
* `:return` - set to `:index` to return indexes. Defaults to `:binary`.
* `:capture` - what to capture in the result. Check the moduledoc for `Regex`
to see the possible capture values.
to see the possible capture values.
## Examples
@@ -197,7 +194,7 @@ defmodule Regex do
nil
iex> Regex.run(~r/c(d)/, "abcd", return: :index)
[{2, 2}, {3, 1}]
[{2,2},{3,1}]
"""
@spec run(t, binary, [term]) :: nil | [binary] | [{integer, integer}]
@@ -292,16 +289,15 @@ defmodule Regex do
@doc """
Same as `run/3`, but scans the target several times collecting all
matches of the regular expression.
A list of lists is returned, where each entry in the primary list represents a
match and each entry in the secondary list represents the captured contents.
matches of the regular expression. A list of lists is returned,
where each entry in the primary list represents a match and each
entry in the secondary list represents the captured contents.
## Options
* `:return` - set to `:index` to return indexes. Defaults to `:binary`.
* `:capture` - what to capture in the result. Check the moduledoc for `Regex`
to see the possible capture values.
to see the possible capture values.
## Examples
@@ -331,8 +327,7 @@ defmodule Regex do
end
@doc """
Splits the given target based on the given pattern and in the given number of
parts.
Splits the given target into the number of parts specified.
## Options
@@ -341,19 +336,20 @@ defmodule Regex do
split the string into the maximum number of parts possible based on the
given pattern.
* `:trim` - when `true`, removes empty strings (`""`) from the result.
* `:trim` - when true, remove blank strings from the result.
* `:on` - specifies which captures to split the string on, and in what
order. Defaults to `:first` which means captures inside the regex do not
affect the splitting process.
* `:on` - specifies which captures and order to split the string
on. Check the moduledoc for `Regex` to see the possible capture
values. Defaults to `:first` which means captures inside the
Regex does not affect the split result.
## Examples
iex> Regex.split(~r/-/, "a-b-c")
["a", "b", "c"]
["a","b","c"]
iex> Regex.split(~r/-/, "a-b-c", [parts: 2])
["a", "b-c"]
["a","b-c"]
iex> Regex.split(~r/-/, "abc")
["abc"]
@@ -371,13 +367,7 @@ defmodule Regex do
@spec split(t, String.t, [term]) :: [String.t]
def split(regex, string, options \\ [])
def split(%Regex{}, "", opts) do
if Keyword.get(opts, :trim, false) do
[]
else
[""]
end
end
def split(%Regex{}, "", _opts), do: [""]
def split(%Regex{re_pattern: compiled}, string, opts) when is_binary(string) do
on = Keyword.get(opts, :on, :first)
@@ -425,12 +415,12 @@ defmodule Regex do
@doc ~S"""
Receives a regex, a binary and a replacement, returns a new
binary where all matches are replaced by the replacement.
binary where the all matches are replaced by replacement.
The replacement can be either a string or a function. The string
is used as a replacement for every match and it allows specific
captures to be accessed via `\\N` or `\g{N}`, where `N` is the
capture. In case `\\0` is used, the whole match is inserted.
captures to be accessed via `\N` or `\g{N}`, where `N` is the
capture. In case `\0` is used, the whole match is inserted.
When the replacement is a function, the function may have arity
N where each argument maps to a capture, with the first argument
@@ -440,7 +430,7 @@ defmodule Regex do
## Options
* `:global` - when `false`, replaces only the first occurrence
(defaults to `true`)
(defaults to true)
## Examples
@@ -456,15 +446,9 @@ defmodule Regex do
iex> Regex.replace(~r/a(b|d)c/, "abcadc", "[\\1]")
"[b][d]"
iex> Regex.replace(~r/\.(\d)$/, "500.5", ".\\g{1}0")
"500.50"
iex> Regex.replace(~r/a(b|d)c/, "abcadc", fn _, x -> "[#{x}]" end)
"[b][d]"
iex> Regex.replace(~r/a/, "abcadc", "A", global: false)
"Abcadc"
"""
@spec replace(t, String.t, String.t | (... -> String.t), [term]) :: String.t
def replace(regex, string, replacement, options \\ [])
@@ -500,13 +484,18 @@ defmodule Regex do
[List.to_integer(ns) | precompile_replacement(rest)]
end
defp precompile_replacement(<<?\\, ?\\, rest :: binary>>) do
[<<?\\>> | precompile_replacement(rest)]
defp precompile_replacement(<<?\\, x, rest :: binary>>) when x < ?0 or x > ?9 do
case precompile_replacement(rest) do
[head | t] when is_binary(head) ->
[<<x, head :: binary>> | t]
other ->
[<<x>> | other]
end
end
defp precompile_replacement(<<?\\, x, rest :: binary>>) when x in ?0..?9 do
defp precompile_replacement(<<?\\, rest :: binary>>) when byte_size(rest) > 0 do
{ns, rest} = pick_int(rest)
[List.to_integer([x|ns]) | precompile_replacement(rest)]
[List.to_integer(ns) | precompile_replacement(rest)]
end
defp precompile_replacement(<<x, rest :: binary>>) do
@@ -545,7 +534,7 @@ defmodule Regex do
[untouched | apply_list(whole, rest, mpos, replacement, list)]
end
defp apply_list(whole, string, pos, replacement, [[{pos, length} | _] = head | tail]) do
defp apply_list(whole, string, pos, replacement, [[{mpos, length} | _] = head | tail]) when mpos == pos do
<<_ :: size(length)-binary, rest :: binary>> = string
new_data = apply_replace(whole, replacement, head)
[new_data | apply_list(whole, rest, pos + length, replacement, tail)]
@@ -633,14 +622,9 @@ defmodule Regex do
defp translate_options(<<?i, t :: binary>>, acc), do: translate_options(t, [:caseless|acc])
defp translate_options(<<?x, t :: binary>>, acc), do: translate_options(t, [:extended|acc])
defp translate_options(<<?f, t :: binary>>, acc), do: translate_options(t, [:firstline|acc])
defp translate_options(<<?U, t :: binary>>, acc), do: translate_options(t, [:ungreedy|acc])
defp translate_options(<<?r, t :: binary>>, acc), do: translate_options(t, [:ungreedy|acc])
defp translate_options(<<?s, t :: binary>>, acc), do: translate_options(t, [:dotall, {:newline, :anycrlf}|acc])
defp translate_options(<<?m, t :: binary>>, acc), do: translate_options(t, [:multiline|acc])
# TODO: Deprecate by 1.2
# TODO: Remove by 2.0
defp translate_options(<<?r, t :: binary>>, acc), do: translate_options(t, [:ungreedy|acc])
defp translate_options(<<>>, acc), do: acc
defp translate_options(rest, _acc), do: {:error, rest}
end
+46 -49
View File
@@ -1,14 +1,14 @@
defmodule Set do
@moduledoc ~S"""
This module specifies the `Set` behaviour expected to be
implemented by different representations of sets.
This module specifies the Set API expected to be
implemented by different representations.
It also provides functions that redirect to the
underlying implementation, allowing a developer to work with
different `Set` implementations using a common API.
underlying Set, allowing a developer to work with
different Set implementations using one API.
To create a new set, use the `new` function which each set implementation
defines:
To create a new set, use the `new` functions defined
by each set type:
HashSet.new #=> creates an empty HashSet
@@ -17,31 +17,33 @@ defmodule Set do
## Protocols
Sets are required to implement both the `Enumerable` and `Collectable`
Sets are required to implement both `Enumerable` and `Collectable`
protocols.
## Matching
## Match
Sets are required to implement all equality checks using the match (`===`)
Sets are required to implement all operations using the match (`===`)
operator.
"""
use Behaviour
@type value :: any
@type values :: [ value ]
@type t :: map
@callback new :: t
@callback delete(t, value) :: t
@callback difference(t, t) :: t
@callback disjoint?(t, t) :: boolean
@callback equal?(t, t) :: boolean
@callback intersection(t, t) :: t
@callback member?(t, value) :: boolean
@callback put(t, value) :: t
@callback size(t) :: non_neg_integer
@callback subset?(t, t) :: boolean
@callback to_list(t) :: list()
@callback union(t, t) :: t
defcallback new :: t
defcallback delete(t, value) :: t
defcallback difference(t, t) :: t
defcallback disjoint?(t, t) :: boolean
defcallback equal?(t, t) :: boolean
defcallback intersection(t, t) :: t
defcallback member?(t, value) :: boolean
defcallback put(t, value) :: t
defcallback size(t) :: non_neg_integer
defcallback subset?(t, t) :: boolean
defcallback to_list(t) :: list()
defcallback union(t, t) :: t
defmacrop target(set) do
quote do
@@ -57,8 +59,6 @@ defmodule Set do
@doc """
Deletes `value` from `set`.
Returns a new set which is a copy of `set` but without `value`.
## Examples
iex> s = Enum.into([1, 2, 3], set_impl.new)
@@ -78,14 +78,13 @@ defmodule Set do
@doc """
Returns a set that is `set1` without the members of `set2`.
Note that this function is polymorphic as it calculates the difference for
sets of the same type as well as of sets of different types. Each set
implementation also provides a `difference` function which only works with
sets of that type.
Notice this function is polymorphic as it calculates the difference
for of any type. Each set implementation also provides a `difference`
function, but they can only work with sets of the same type.
## Examples
iex> Set.difference(Enum.into([1, 2], set_impl.new), Enum.into([2, 3, 4], set_impl.new)) |> Enum.sort
iex> Set.difference(Enum.into([1,2], set_impl.new), Enum.into([2,3,4], set_impl.new)) |> Enum.sort
[1]
"""
@@ -106,9 +105,9 @@ defmodule Set do
@doc """
Checks if `set1` and `set2` have no members in common.
Note that this function is polymorphic as it checks for disjoint sets of
Notice this function is polymorphic as it checks for disjoint sets of
any type. Each set implementation also provides a `disjoint?` function,
but that function can only work with sets of the same type.
but they can only work with sets of the same type.
## Examples
@@ -143,11 +142,11 @@ defmodule Set do
end
@doc """
Checks if two sets are equal using `===`.
Check if two sets are equal using `===`.
Note that this function is polymorphic as it compares sets of
Notice this function is polymorphic as it compares sets of
any type. Each set implementation also provides an `equal?`
function, but that function can only work with sets of the same type.
function, but they can only work with sets of the same type.
## Examples
@@ -176,18 +175,18 @@ defmodule Set do
end
@doc """
Returns a set containing only members that `set1` and `set2` have in common.
Returns a set containing only members in common between `set1` and `set2`.
Note that this function is polymorphic as it calculates the intersection of
any type. Each set implementation also provides an `intersection` function,
but that function can only work with sets of the same type.
Notice this function is polymorphic as it calculates the intersection of
any type. Each set implementation also provides a `intersection` function,
but they can only work with sets of the same type.
## Examples
iex> Set.intersection(Enum.into([1, 2], set_impl.new), Enum.into([2, 3, 4], set_impl.new)) |> Enum.sort
iex> Set.intersection(Enum.into([1,2], set_impl.new), Enum.into([2,3,4], set_impl.new)) |> Enum.sort
[2]
iex> Set.intersection(Enum.into([1, 2], set_impl.new), Enum.into([3, 4], set_impl.new)) |> Enum.sort
iex> Set.intersection(Enum.into([1,2], set_impl.new), Enum.into([3,4], set_impl.new)) |> Enum.sort
[]
"""
@@ -223,7 +222,7 @@ defmodule Set do
end
@doc """
Inserts `value` into `set` if `set` doesn't already contain it.
Inserts `value` into `set` if it does not already contain it.
## Examples
@@ -256,11 +255,9 @@ defmodule Set do
@doc """
Checks if `set1`'s members are all contained in `set2`.
This function checks if `set1` is a subset of `set2`.
Note that this function is polymorphic as it checks the subset for
Notice this function is polymorphic as it checks the subset for
any type. Each set implementation also provides a `subset?` function,
but that function can only work with sets of the same type.
but they can only work with sets of the same type.
## Examples
@@ -289,7 +286,7 @@ defmodule Set do
## Examples
iex> set_impl.to_list(Enum.into([1, 2, 3], set_impl.new)) |> Enum.sort
[1, 2, 3]
[1,2,3]
"""
@spec to_list(t) :: list
@@ -300,14 +297,14 @@ defmodule Set do
@doc """
Returns a set containing all members of `set1` and `set2`.
Note that this function is polymorphic as it calculates the union of sets of
Notice this function is polymorphic as it calculates the union of
any type. Each set implementation also provides a `union` function,
but that function can only work with sets of the same type.
but they can only work with sets of the same type.
## Examples
iex> Set.union(Enum.into([1, 2], set_impl.new), Enum.into([2, 3, 4], set_impl.new)) |> Enum.sort
[1, 2, 3, 4]
iex> Set.union(Enum.into([1,2], set_impl.new), Enum.into([2,3,4], set_impl.new)) |> Enum.sort
[1,2,3,4]
"""
@spec union(t, t) :: t
+101 -164
View File
@@ -9,7 +9,7 @@ defmodule Stream do
iex> range = 1..5
1..5
iex> Enum.map range, &(&1 * 2)
[2, 4, 6, 8, 10]
[2,4,6,8,10]
In the example above, as we mapped over the range, the elements being
enumerated were created one by one, during enumeration. The `Stream`
@@ -18,7 +18,7 @@ defmodule Stream do
iex> range = 1..3
iex> stream = Stream.map(range, &(&1 * 2))
iex> Enum.map(stream, &(&1 + 1))
[3, 5, 7]
[3,5,7]
Notice we started with a range and then we created a stream that is
meant to multiply each item in the range by 2. At this point, no
@@ -43,7 +43,7 @@ defmodule Stream do
2
4
6
#=> [2, 4, 6]
#=> [2,4,6]
Notice that we first printed each item in the list, then multiplied each
element by 2 and finally printed each new value. In this example, the list
@@ -60,7 +60,7 @@ defmodule Stream do
4
3
6
#=> [2, 4, 6]
#=> [2,4,6]
Although the end result is the same, the order in which the items were
printed changed! With streams, we print the first item and then print
@@ -96,27 +96,23 @@ defmodule Stream do
@type element :: any
@type index :: non_neg_integer
@type default :: any
@type t :: %__MODULE__{}
@type t :: %__MODULE__{}
# Require Stream.Reducers and its callbacks
require Stream.Reducers, as: R
defmacrop skip(acc) do
{:cont, acc}
end
defmacrop next(f, entry, acc) do
defmacrop cont(f, entry, acc) do
quote do: unquote(f).(unquote(entry), unquote(acc))
end
defmacrop acc(h, n, t) do
quote do: [unquote(h), unquote(n)|unquote(t)]
quote do: [unquote(h),unquote(n)|unquote(t)]
end
defmacrop next_with_acc(f, entry, h, n, t) do
defmacrop cont_with_acc(f, entry, h, n, t) do
quote do
{reason, [h|t]} = unquote(f).(unquote(entry), [unquote(h)|unquote(t)])
{reason, [h, unquote(n)|t]}
{reason, [h,unquote(n)|t]}
end
end
@@ -156,8 +152,8 @@ defmodule Stream do
[[1, 2, 3], [4, 5, 6]]
"""
@spec chunk(Enumerable.t, pos_integer, pos_integer) :: Enumerable.t
@spec chunk(Enumerable.t, pos_integer, pos_integer, Enumerable.t | nil) :: Enumerable.t
@spec chunk(Enumerable.t, non_neg_integer, non_neg_integer) :: Enumerable.t
@spec chunk(Enumerable.t, non_neg_integer, non_neg_integer, Enumerable.t | nil) :: Enumerable.t
def chunk(enum, n, step, pad \\ nil) when n > 0 and step > 0 do
limit = :erlang.max(n, step)
if is_nil(pad) do
@@ -174,8 +170,8 @@ defmodule Stream do
end
defp do_chunk(acc(h, {buffer, count} = old, t), n, pad, f1) do
buffer = :lists.reverse(buffer, Enum.take(pad, n - count))
next_with_acc(f1, buffer, h, old, t)
buffer = :lists.reverse(buffer) ++ Enum.take(pad, n - count)
cont_with_acc(f1, buffer, h, old, t)
end
@doc """
@@ -202,41 +198,7 @@ defmodule Stream do
end
defp do_chunk_by(acc(h, {buffer, _}, t), f1) do
next_with_acc(f1, :lists.reverse(buffer), h, nil, t)
end
@doc """
Creates a stream that only emits elements if they are different from the last emitted element.
This function only ever needs to store the last emitted element.
Elements are compared using `===`.
## Examples
iex> Stream.dedup([1, 2, 3, 3, 2, 1]) |> Enum.to_list
[1, 2, 3, 2, 1]
"""
@spec dedup(Enumerable.t) :: Enumerable.t
def dedup(enum) do
dedup_by(enum, fn x -> x end)
end
@doc """
Creates a stream that only emits elements if the result of calling `fun` on the element is
different from the (stored) result of calling `fun` on the last emitted element.
## Examples
iex> Stream.dedup_by([{1, :x}, {2, :y}, {2, :z}, {1, :x}], fn {x, _} -> x end) |> Enum.to_list
[{1, :x}, {2, :y}, {1, :x}]
"""
@spec dedup_by(Enumerable.t, (element -> term)) :: Enumerable.t
def dedup_by(enum, fun) when is_function(fun, 1) do
lazy enum, nil, fn f1 -> R.dedup(fun, f1) end
cont_with_acc(f1, :lists.reverse(buffer), h, nil, t)
end
@doc """
@@ -251,11 +213,11 @@ defmodule Stream do
iex> stream = Stream.drop(1..10, 5)
iex> Enum.to_list(stream)
[6, 7, 8, 9, 10]
[6,7,8,9,10]
iex> stream = Stream.drop(1..10, -5)
iex> Enum.to_list(stream)
[1, 2, 3, 4, 5]
[1,2,3,4,5]
"""
@spec drop(Enumerable.t, non_neg_integer) :: Enumerable.t
@@ -295,7 +257,7 @@ defmodule Stream do
iex> stream = Stream.drop_while(1..10, &(&1 <= 5))
iex> Enum.to_list(stream)
[6, 7, 8, 9, 10]
[6,7,8,9,10]
"""
@spec drop_while(Enumerable.t, (element -> as_boolean(term))) :: Enumerable.t
@@ -304,7 +266,7 @@ defmodule Stream do
end
@doc """
Executes the given function for each item.
Execute the given function for each item.
Useful for adding side effects (like printing) to a stream.
@@ -372,7 +334,7 @@ defmodule Stream do
iex> stream = Stream.filter_map(1..6, fn(x) -> rem(x, 2) == 0 end, &(&1 * 2))
iex> Enum.to_list(stream)
[4, 8, 12]
[4,8,12]
"""
@spec filter_map(Enumerable.t, (element -> as_boolean(term)), (element -> any)) :: Enumerable.t
@@ -381,17 +343,16 @@ defmodule Stream do
end
@doc """
Creates a stream that emits a value after the given period `n` in milliseconds.
Creates a stream that emits a value every `n` milliseconds.
The values emitted are an increasing counter starting at `0`.
## Examples
iex> Stream.interval(10) |> Enum.take(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[0,1,2,3,4,5,6,7,8,9]
"""
# TODO: Allow it to handle system messages.
@spec interval(non_neg_integer) :: Enumerable.t
def interval(n) do
unfold 0, fn (count) ->
@@ -446,7 +407,7 @@ defmodule Stream do
iex> stream = Stream.map([1, 2, 3], fn(x) -> x * 2 end)
iex> Enum.to_list(stream)
[2, 4, 6]
[2,4,6]
"""
@spec map(Enumerable.t, (element -> any)) :: Enumerable.t
@@ -462,7 +423,7 @@ defmodule Stream do
iex> stream = Stream.reject([1, 2, 3], fn(x) -> rem(x, 2) == 0 end)
iex> Enum.to_list(stream)
[1, 3]
[1,3]
"""
@spec reject(Enumerable.t, (element -> as_boolean(term))) :: Enumerable.t
@@ -504,7 +465,7 @@ defmodule Stream do
iex> stream = Stream.scan(1..5, &(&1 + &2))
iex> Enum.to_list(stream)
[1, 3, 6, 10, 15]
[1,3,6,10,15]
"""
@spec scan(Enumerable.t, (element, acc -> any)) :: Enumerable.t
@@ -521,7 +482,7 @@ defmodule Stream do
iex> stream = Stream.scan(1..5, 0, &(&1 + &2))
iex> Enum.to_list(stream)
[1, 3, 6, 10, 15]
[1,3,6,10,15]
"""
@spec scan(Enumerable.t, acc, (element, acc -> any)) :: Enumerable.t
@@ -530,72 +491,85 @@ defmodule Stream do
end
@doc """
Lazily takes the next `count` items from the enumerable and stops
Lazily takes the next `n` items from the enumerable and stops
enumeration.
If a negative `count` is given, the last `count` values will be taken.
For such, the collection is fully enumerated keeping up to `2 * count`
If a negative `n` is given, the last `n` values will be taken.
For such, the collection is fully enumerated keeping up to `2 * n`
elements in memory. Once the end of the collection is reached,
the last `count` elements will be executed. Therefore, using
a negative `count` on an infinite collection will never return.
a negative `n` on an infinite collection will never return.
## Examples
iex> stream = Stream.take(1..100, 5)
iex> Enum.to_list(stream)
[1, 2, 3, 4, 5]
[1,2,3,4,5]
iex> stream = Stream.take(1..100, -5)
iex> Enum.to_list(stream)
[96, 97, 98, 99, 100]
[96,97,98,99,100]
iex> stream = Stream.cycle([1, 2, 3]) |> Stream.take(5)
iex> Enum.to_list(stream)
[1, 2, 3, 1, 2]
[1,2,3,1,2]
"""
@spec take(Enumerable.t, integer) :: Enumerable.t
@spec take(Enumerable.t, non_neg_integer) :: Enumerable.t
def take(_enum, 0), do: %Stream{enum: []}
def take([], _count), do: %Stream{enum: []}
def take(enum, count) when is_integer(count) and count > 0 do
lazy enum, count, fn(f1) -> R.take(f1) end
def take(enum, n) when n > 0 and is_integer(n) do
lazy enum, n, fn(f1) -> R.take(f1) end
end
def take(enum, count) when is_integer(count) and count < 0 do
&Enumerable.reduce(Enum.take(enum, count), &1, &2)
def take(enum, n) when n < 0 and is_integer(n) do
&do_take(enum, abs(n), &1, &2)
end
defp do_take(enum, n, acc, f) do
{_, {_count, buf1, buf2}} =
Enumerable.reduce(enum, {:cont, {0, [], []}}, fn
entry, {count, buf1, buf2} ->
buf1 = [entry|buf1]
count = count + 1
if count == n do
{:cont, {0, [], buf1}}
else
{:cont, {count, buf1, buf2}}
end
end)
Enumerable.reduce(do_take_last(buf1, buf2, n, []), acc, f)
end
defp do_take_last(_buf1, _buf2, 0, acc),
do: acc
defp do_take_last([], [], _, acc),
do: acc
defp do_take_last([], [h|t], n, acc),
do: do_take_last([], t, n-1, [h|acc])
defp do_take_last([h|t], buf2, n, acc),
do: do_take_last(t, buf2, n-1, [h|acc])
@doc """
Creates a stream that takes every `nth` item from the enumerable.
Creates a stream that takes every `n` item from the enumerable.
The first item is always included, unless `nth` is 0.
`nth` must be a non-negative integer, or `FunctionClauseError` will be thrown.
The first item is always included, unless `n` is 0.
## Examples
iex> stream = Stream.take_every(1..10, 2)
iex> Enum.to_list(stream)
[1, 3, 5, 7, 9]
iex> stream = Stream.take_every([1, 2, 3, 4, 5], 1)
iex> Enum.to_list(stream)
[1, 2, 3, 4, 5]
iex> stream = Stream.take_every(1..1000, 0)
iex> Enum.to_list(stream)
[]
[1,3,5,7,9]
"""
@spec take_every(Enumerable.t, non_neg_integer) :: Enumerable.t
def take_every(_enum, 0), do: %Stream{enum: []}
def take_every([], _nth), do: %Stream{enum: []}
def take_every(enum, nth) when is_integer(nth) and nth > 0 do
lazy enum, nth, fn(f1) -> R.take_every(nth, f1) end
def take_every(enum, n) when n > 0 do
lazy enum, n, fn(f1) -> R.take_every(n, f1) end
end
def take_every(_enum, 0), do: %Stream{enum: []}
@doc """
Lazily takes elements of the enumerable while the given
function returns `true`.
@@ -604,7 +578,7 @@ defmodule Stream do
iex> stream = Stream.take_while(1..100, &(&1 <= 5))
iex> Enum.to_list(stream)
[1, 2, 3, 4, 5]
[1,2,3,4,5]
"""
@spec take_while(Enumerable.t, (element -> as_boolean(term))) :: Enumerable.t
@@ -652,51 +626,24 @@ defmodule Stream do
...> if acc < n, do: {[i], acc + 1}, else: {:halt, acc}
...> end)
iex> Enum.to_list(stream)
[1, 2, 3]
[1,2,3]
"""
@spec transform(Enumerable.t, acc, fun) :: Enumerable.t when
fun: (element, acc -> {Enumerable.t, acc} | {:halt, acc}),
acc: any
def transform(enum, acc, reducer) when is_function(reducer, 2) do
&do_transform(enum, fn -> acc end, reducer, &1, &2, nil)
def transform(enum, acc, reducer) do
&do_transform(enum, acc, reducer, &1, &2)
end
@doc """
Transforms an existing stream with function-based start and finish.
The accumulator is only calculated when transformation starts. It also
allows an after function to be given which is invoked when the stream
halts or completes.
This function can be seen as a combination of `Stream.resource/3` with
`Stream.transform/3`.
"""
@spec transform(Enumerable.t, (() -> acc), fun, (acc -> term)) :: Enumerable.t when
fun: (element, acc -> {Enumerable.t, acc} | {:halt, acc}),
acc: any
def transform(enum, start_fun, reducer, after_fun)
when is_function(start_fun, 0) and is_function(reducer, 2) and is_function(after_fun, 1) do
&do_transform(enum, start_fun, reducer, &1, &2, after_fun)
end
defp do_transform(enumerables, user_acc, user, inner_acc, fun, after_fun) do
defp do_transform(enumerables, user_acc, user, inner_acc, fun) do
inner = &do_transform_each(&1, &2, fun)
step = &do_transform_step(&1, &2)
next = &Enumerable.reduce(enumerables, &1, step)
do_transform(user_acc.(), user, fun, [], next, inner_acc, inner, after_fun)
do_transform(user_acc, user, fun, [], next, inner_acc, inner)
end
defp do_transform(user_acc, _user, _fun, _next_acc, _next, {:halt, inner_acc}, _inner, after_fun) do
do_after(after_fun, user_acc)
{:halted, inner_acc}
end
defp do_transform(user_acc, user, fun, next_acc, next, {:suspend, inner_acc}, inner, after_fun) do
{:suspended, inner_acc, &do_transform(user_acc, user, fun, next_acc, next, &1, inner, after_fun)}
end
defp do_transform(user_acc, user, fun, next_acc, next, inner_acc, inner, after_fun) do
defp do_transform(user_acc, user, fun, next_acc, next, inner_acc, inner) do
case next.({:cont, next_acc}) do
{:suspended, [val|next_acc], next} ->
try do
@@ -705,77 +652,67 @@ defmodule Stream do
kind, reason ->
stacktrace = System.stacktrace
next.({:halt, next_acc})
do_after(after_fun, user_acc)
:erlang.raise(kind, reason, stacktrace)
else
{[], user_acc} ->
do_transform(user_acc, user, fun, next_acc, next, inner_acc, inner, after_fun)
do_transform(user_acc, user, fun, next_acc, next, inner_acc, inner)
{list, user_acc} when is_list(list) ->
do_list_transform(user_acc, user, fun, next_acc, next, inner_acc, inner,
&Enumerable.List.reduce(list, &1, fun), after_fun)
{:halt, user_acc} ->
&Enumerable.List.reduce(list, &1, fun))
{:halt, _user_acc} ->
next.({:halt, next_acc})
do_after(after_fun, user_acc)
{:halted, elem(inner_acc, 1)}
{other, user_acc} ->
do_enum_transform(user_acc, user, fun, next_acc, next, inner_acc, inner,
&Enumerable.reduce(other, &1, inner), after_fun)
&Enumerable.reduce(other, &1, inner))
end
{reason, _} ->
do_after(after_fun, user_acc)
{reason, elem(inner_acc, 1)}
end
end
defp do_list_transform(user_acc, user, fun, next_acc, next, inner_acc, inner, reduce, after_fun) do
defp do_list_transform(user_acc, user, fun, next_acc, next, inner_acc, inner, reduce) do
try do
reduce.(inner_acc)
catch
kind, reason ->
stacktrace = System.stacktrace
next.({:halt, next_acc})
do_after(after_fun, user_acc)
:erlang.raise(kind, reason, stacktrace)
else
{:done, acc} ->
do_transform(user_acc, user, fun, next_acc, next, {:cont, acc}, inner, after_fun)
do_transform(user_acc, user, fun, next_acc, next, {:cont, acc}, inner)
{:halted, acc} ->
next.({:halt, next_acc})
do_after(after_fun, user_acc)
{:halted, acc}
{:suspended, acc, c} ->
{:suspended, acc, &do_list_transform(user_acc, user, fun, next_acc, next, &1, inner, c, after_fun)}
{:suspended, acc, &do_list_transform(user_acc, user, fun, next_acc, next, &1, inner, c)}
end
end
defp do_enum_transform(user_acc, user, fun, next_acc, next, {op, inner_acc}, inner, reduce, after_fun) do
defp do_enum_transform(user_acc, user, fun, next_acc, next, {op, inner_acc}, inner, reduce) do
try do
reduce.({op, [:outer|inner_acc]})
catch
kind, reason ->
stacktrace = System.stacktrace
next.({:halt, next_acc})
do_after(after_fun, user_acc)
:erlang.raise(kind, reason, stacktrace)
else
# Only take into account outer halts when the op is not halt itself.
# Otherwise, we were the ones wishing to halt, so we should just stop.
{:halted, [:outer|acc]} when op != :halt ->
do_transform(user_acc, user, fun, next_acc, next, {:cont, acc}, inner, after_fun)
do_transform(user_acc, user, fun, next_acc, next, {:cont, acc}, inner)
{:halted, [_|acc]} ->
next.({:halt, next_acc})
do_after(after_fun, user_acc)
{:halted, acc}
{:done, [_|acc]} ->
do_transform(user_acc, user, fun, next_acc, next, {:cont, acc}, inner, after_fun)
do_transform(user_acc, user, fun, next_acc, next, {:cont, acc}, inner)
{:suspended, [_|acc], c} ->
{:suspended, acc, &do_enum_transform(user_acc, user, fun, next_acc, next, &1, inner, c, after_fun)}
{:suspended, acc, &do_enum_transform(user_acc, user, fun, next_acc, next, &1, inner, c)}
end
end
defp do_after(nil, _user_acc), do: :ok
defp do_after(fun, user_acc), do: fun.(user_acc)
defp do_transform_each(x, [:outer|acc], f) do
case f.(x, acc) do
{:halt, res} -> {:halt, [:inner|res]}
@@ -797,17 +734,17 @@ defmodule Stream do
## Examples
iex> Stream.uniq([1, 2, 3, 3, 2, 1]) |> Enum.to_list
iex> Stream.uniq([1, 2, 3, 2, 1]) |> Enum.to_list
[1, 2, 3]
iex> Stream.uniq([{1, :x}, {2, :y}, {2, :z}, {1, :x}], fn {x, _} -> x end) |> Enum.to_list
[{1, :x}, {2, :y}]
iex> Stream.uniq([{1, :x}, {2, :y}, {1, :z}], fn {x, _} -> x end) |> Enum.to_list
[{1,:x}, {2,:y}]
"""
@spec uniq(Enumerable.t) :: Enumerable.t
@spec uniq(Enumerable.t, (element -> term)) :: Enumerable.t
def uniq(enum, fun \\ fn x -> x end) do
lazy enum, HashSet.new, fn f1 -> R.uniq(fun, f1) end
lazy enum, [], fn f1 -> R.uniq(fun, f1) end
end
@doc """
@@ -818,7 +755,7 @@ defmodule Stream do
iex> stream = Stream.with_index([1, 2, 3])
iex> Enum.to_list(stream)
[{1, 0}, {2, 1}, {3, 2}]
[{1,0},{2,1},{3,2}]
"""
@spec with_index(Enumerable.t) :: Enumerable.t
@@ -835,7 +772,7 @@ defmodule Stream do
iex> stream = Stream.concat([1..3, 4..6, 7..9])
iex> Enum.to_list(stream)
[1, 2, 3, 4, 5, 6, 7, 8, 9]
[1,2,3,4,5,6,7,8,9]
"""
@spec concat(Enumerable.t) :: Enumerable.t
@@ -850,13 +787,13 @@ defmodule Stream do
iex> stream = Stream.concat(1..3, 4..6)
iex> Enum.to_list(stream)
[1, 2, 3, 4, 5, 6]
[1,2,3,4,5,6]
iex> stream1 = Stream.cycle([1, 2, 3])
iex> stream2 = Stream.cycle([4, 5, 6])
iex> stream = Stream.concat(stream1, stream2)
iex> Enum.take(stream, 6)
[1, 2, 3, 1, 2, 3]
[1,2,3,1,2,3]
"""
@spec concat(Enumerable.t, Enumerable.t) :: Enumerable.t
@@ -874,7 +811,7 @@ defmodule Stream do
iex> concat = Stream.concat(1..3, 4..6)
iex> cycle = Stream.cycle([:a, :b, :c])
iex> Stream.zip(concat, cycle) |> Enum.to_list
[{1, :a}, {2, :b}, {3, :c}, {4, :a}, {5, :b}, {6, :c}]
[{1,:a},{2,:b},{3,:c},{4,:a},{5,:b},{6,:c}]
"""
@spec zip(Enumerable.t, Enumerable.t) :: Enumerable.t
@@ -917,7 +854,7 @@ defmodule Stream do
{:suspended, [i|fun_acc], fun} ->
do_zip(t, acc, callback, [i|list], [{fun, fun_acc}|buffer])
{_, _} ->
do_zip_close(:lists.reverse(buffer, t))
do_zip_close(:lists.reverse(buffer) ++ t)
{:done, acc}
end
end
@@ -945,9 +882,9 @@ defmodule Stream do
## Examples
iex> stream = Stream.cycle([1, 2, 3])
iex> stream = Stream.cycle([1,2,3])
iex> Enum.take(stream, 5)
[1, 2, 3, 1, 2]
[1,2,3,1,2]
"""
@spec cycle(Enumerable.t) :: Enumerable.t
@@ -998,13 +935,13 @@ defmodule Stream do
end
@doc """
Emits a sequence of values, starting with `start_value`. Successive
Emit a sequence of values, starting with `start_value`. Successive
values are generated by calling `next_fun` on the previous value.
## Examples
iex> Stream.iterate(0, &(&1+1)) |> Enum.take(5)
[0, 1, 2, 3, 4]
[0,1,2,3,4]
"""
@spec iterate(element, (element -> element)) :: Enumerable.t
+28 -40
View File
@@ -17,9 +17,9 @@ defmodule Stream.Reducers do
end
if count == unquote(n) do
next_with_acc(unquote(f), :lists.reverse(buffer), h, new, t)
cont_with_acc(unquote(f), :lists.reverse(buffer), h, new, t)
else
skip(acc(h, new, t))
{:cont, acc(h, new, t)}
end
end
end
@@ -31,24 +31,12 @@ defmodule Stream.Reducers do
entry, acc(h, {buffer, value}, t) ->
new_value = unquote(callback).(entry)
if new_value == value do
skip(acc(h, {[entry|buffer], value}, t))
{:cont, acc(h, {[entry|buffer], value}, t)}
else
next_with_acc(unquote(f), :lists.reverse(buffer), h, {[entry], new_value}, t)
cont_with_acc(unquote(f), :lists.reverse(buffer), h, {[entry], new_value}, t)
end
entry, acc(h, nil, t) ->
skip(acc(h, {[entry], unquote(callback).(entry)}, t))
end
end
end
defmacro dedup(callback, f \\ nil) do
quote do
fn(entry, acc(h, prev, t) = acc) ->
value = unquote(callback).(entry)
case prev do
{:value, ^value} -> skip(acc)
_ -> next_with_acc(unquote(f), entry, h, {:value, value}, t)
end
{:cont, acc(h, {[entry], unquote(callback).(entry)}, t)}
end
end
end
@@ -57,9 +45,9 @@ defmodule Stream.Reducers do
quote do
fn
_entry, acc(h, n, t) when n > 0 ->
skip(acc(h, n-1, t))
{:cont, acc(h, n-1, t)}
entry, acc(h, n, t) ->
next_with_acc(unquote(f), entry, h, n, t)
cont_with_acc(unquote(f), entry, h, n, t)
end
end
end
@@ -68,9 +56,9 @@ defmodule Stream.Reducers do
quote do
fn entry, acc(h, bool, t) = orig ->
if bool and unquote(callback).(entry) do
skip(orig)
{:cont, orig}
else
next_with_acc(unquote(f), entry, h, false, t)
cont_with_acc(unquote(f), entry, h, false, t)
end
end
end
@@ -80,9 +68,9 @@ defmodule Stream.Reducers do
quote do
fn(entry, acc) ->
if unquote(callback).(entry) do
next(unquote(f), entry, acc)
cont(unquote(f), entry, acc)
else
skip(acc)
{:cont, acc}
end
end
end
@@ -92,9 +80,9 @@ defmodule Stream.Reducers do
quote do
fn(entry, acc) ->
if unquote(filter).(entry) do
next(unquote(f), unquote(mapper).(entry), acc)
cont(unquote(f), unquote(mapper).(entry), acc)
else
skip(acc)
{:cont, acc}
end
end
end
@@ -103,7 +91,7 @@ defmodule Stream.Reducers do
defmacro map(callback, f \\ nil) do
quote do
fn(entry, acc) ->
next(unquote(f), unquote(callback).(entry), acc)
cont(unquote(f), unquote(callback).(entry), acc)
end
end
end
@@ -112,9 +100,9 @@ defmodule Stream.Reducers do
quote do
fn(entry, acc) ->
unless unquote(callback).(entry) do
next(unquote(f), entry, acc)
cont(unquote(f), entry, acc)
else
skip(acc)
{:cont, acc}
end
end
end
@@ -124,10 +112,10 @@ defmodule Stream.Reducers do
quote do
fn
entry, acc(h, :first, t) ->
next_with_acc(unquote(f), entry, h, {:ok, entry}, t)
cont_with_acc(unquote(f), entry, h, {:ok, entry}, t)
entry, acc(h, {:ok, acc}, t) ->
value = unquote(callback).(entry, acc)
next_with_acc(unquote(f), value, h, {:ok, value}, t)
cont_with_acc(unquote(f), value, h, {:ok, value}, t)
end
end
end
@@ -136,7 +124,7 @@ defmodule Stream.Reducers do
quote do
fn(entry, acc(h, acc, t)) ->
value = unquote(callback).(entry, acc)
next_with_acc(unquote(f), value, h, value, t)
cont_with_acc(unquote(f), value, h, value, t)
end
end
end
@@ -148,12 +136,12 @@ defmodule Stream.Reducers do
0 ->
{:halt, orig}
1 ->
case next_with_acc(unquote(f), entry, h, n-1, t) do
case cont_with_acc(unquote(f), entry, h, n-1, t) do
{:cont, acc} -> {:halt, acc}
reason -> reason
end
_ ->
next_with_acc(unquote(f), entry, h, n-1, t)
cont_with_acc(unquote(f), entry, h, n-1, t)
end
end
end
@@ -164,9 +152,9 @@ defmodule Stream.Reducers do
fn
entry, acc(h, n, t) when n === :first
when n === unquote(nth) ->
next_with_acc(unquote(f), entry, h, 1, t)
cont_with_acc(unquote(f), entry, h, 1, t)
entry, acc(h, n, t) ->
skip(acc(h, n+1, t))
{:cont, acc(h, n+1, t)}
end
end
end
@@ -175,7 +163,7 @@ defmodule Stream.Reducers do
quote do
fn(entry, acc) ->
if unquote(callback).(entry) do
next(unquote(f), entry, acc)
cont(unquote(f), entry, acc)
else
{:halt, acc}
end
@@ -187,10 +175,10 @@ defmodule Stream.Reducers do
quote do
fn(entry, acc(h, prev, t) = acc) ->
value = unquote(callback).(entry)
if HashSet.member?(prev, value) do
skip(acc)
if :lists.member(value, prev) do
{:cont, acc}
else
next_with_acc(unquote(f), entry, h, HashSet.put(prev, value), t)
cont_with_acc(unquote(f), entry, h, [value|prev], t)
end
end
end
@@ -199,7 +187,7 @@ defmodule Stream.Reducers do
defmacro with_index(f \\ nil) do
quote do
fn(entry, acc(h, counter, t)) ->
next_with_acc(unquote(f), {entry, counter}, h, counter + 1, t)
cont_with_acc(unquote(f), {entry, counter}, h, counter + 1, t)
end
end
end
+238 -407
View File
File diff suppressed because it is too large Load Diff
-22
View File
@@ -55,24 +55,6 @@ defmodule StringIO do
GenServer.call(pid, :contents)
end
@doc """
Flushes output buffer.
## Examples
iex> {:ok, pid} = StringIO.open("in")
iex> IO.write(pid, "out")
iex> StringIO.flush(pid)
"out"
iex> StringIO.contents(pid)
{"in", ""}
"""
@spec flush(pid) :: binary
def flush(pid) when is_pid(pid) do
GenServer.call(pid, :flush)
end
@doc """
Stops the IO device and returns remaining buffers.
@@ -109,10 +91,6 @@ defmodule StringIO do
{:reply, {input, output}, s}
end
def handle_call(:flush, _from, %{output: output} = s) do
{:reply, output, %{s | output: ""}}
end
def handle_call(:close, _from, %{input: input, output: output} = s) do
{:stop, :normal, {:ok, {input, output}}, s}
end
+12 -13
View File
@@ -3,13 +3,13 @@ defmodule Supervisor do
A behaviour module for implementing supervision functionality.
A supervisor is a process which supervises other processes called
child processes. Supervisors are used to build a hierarchical process
child processes. Supervisors are used to build an hierarchical process
structure called a supervision tree, a nice way to structure fault-tolerant
applications.
A supervisor implemented using this module will have a standard set
of interface functions and include functionality for tracing and error
reporting. It will also fit into a supervision tree.
reporting. It will also fit into an supervision tree.
## Example
@@ -20,7 +20,7 @@ defmodule Supervisor do
defmodule Stack do
use GenServer
def start_link(state, opts \\ []) do
def start_link(state, opts) do
GenServer.start_link(__MODULE__, state, opts)
end
@@ -108,10 +108,10 @@ defmodule Supervisor do
You may want to use a module-based supervisor if:
* You need to do some particular action on supervisor
initialization, like setting up an ETS table.
initialization, like setting up a ETS table.
* You want to perform partial hot-code swapping of the
tree. For example, if you add or remove children,
tree. For example, if you add or remove a children,
the module-based supervision will add and remove the
new children directly, while the dynamic supervision
requires the whole tree to be restarted in order to
@@ -245,7 +245,7 @@ defmodule Supervisor do
as described in `Supervisor.Spec.supervise/2` docs.
The options can also be used to register a supervisor name.
The supported values are described under the `Name Registration`
the supported values are described under the `Name Registration`
section in the `GenServer` module docs.
If the supervisor and its child processes are successfully created
@@ -265,7 +265,7 @@ defmodule Supervisor do
and will exit not only on crashes but also if the parent process
exits with `:normal` reason.
"""
@spec start_link([Supervisor.Spec.spec], options) :: on_start
@spec start_link([tuple], options) :: on_start
def start_link(children, options) when is_list(children) do
spec = Supervisor.Spec.supervise(children, options)
start_link(Supervisor.Default, spec, options)
@@ -291,7 +291,6 @@ defmodule Supervisor do
Other failure conditions are specified in `start_link/2` docs.
"""
@spec start_link(module, term) :: on_start
@spec start_link(module, term, options) :: on_start
def start_link(module, arg, options \\ []) when is_list(options) do
case Keyword.get(options, :name) do
@@ -316,19 +315,19 @@ defmodule Supervisor do
of terms is expected. The child process will then be started by appending
the given list to the existing function arguments in the child specification.
If a child specification with the specified id already exists,
If there already exists a child specification with the specified id,
`child_spec` is discarded and the function returns an error with `:already_started`
or `:already_present` if the corresponding child process is running or not.
If the child process starts, function returns `{:ok, child}` or `{:ok, child, info}`,
If the child process start function returns `{:ok, child}` or `{:ok, child, info}`,
the child specification and pid is added to the supervisor and the function returns
the same value.
If the child process starts, function returns `:ignore`, the child specification is
If the child process start function returns `:ignore, the child specification is
added to the supervisor, the pid is set to undefined and the function returns
`{:ok, :undefined}`.
If the child process starts, function returns an error tuple or an erroneous value,
If the child process start function returns an error tuple or an erroneous value,
or if it fails, the child specification is discarded and the function returns
`{:error, error}` where `error` is a term containing information about the error
and child specification.
@@ -428,7 +427,7 @@ defmodule Supervisor do
* `type` - `:worker` or `:supervisor` as defined in the child specification
* `modules` - as defined in the child specification
* `modules` – as defined in the child specification
"""
@spec which_children(supervisor) ::
[{Supervisor.Spec.child_id | :undefined,
+1 -1
View File
@@ -3,7 +3,7 @@ defmodule Supervisor.Default do
@behaviour :supervisor
@doc """
Supervisor callback that simply returns the given args.
Supevisor callback that simply returns the given args.
This is the supervisor used by `Supervisor.start_link/2`.
"""
+4 -4
View File
@@ -40,7 +40,7 @@ defmodule Supervisor.Spec do
Explicit supervisors as above are required when there is a need to:
1. Partially change the supervision tree during hot-code swaps.
1. Partialy change the supervision tree during hot-code swaps.
2. Define supervisors inside other supervisors.
@@ -70,7 +70,7 @@ defmodule Supervisor.Spec do
child process is a `Supervisor` or `GenServer`; if the child
process is a `GenEvent`, modules should be `:dynamic`
### Restart values (:restart)
### Restart values
The following restart values are supported:
@@ -83,7 +83,7 @@ defmodule Supervisor.Spec do
terminates abnormally, i.e. with another exit reason than
`:normal`, `:shutdown` or `{:shutdown, term}`
### Shutdown values (:shutdown)
### Shutdown values
The following shutdown values are supported:
@@ -97,7 +97,7 @@ defmodule Supervisor.Spec do
* Finally, it can also be any integer meaning that the supervisor tells
the child process to terminate by calling `Process.exit(child, :shutdown)`
and then waits for an exit signal back. If no exit signal is received
within the specified time (in milliseconds), the child process is
within the specified time (in miliseconds), the child process is
unconditionally terminated using `Process.exit(child, :kill)`.
"""
+35 -30
View File
@@ -17,7 +17,7 @@ defmodule System do
end
end
# Read and strip the version from the VERSION file.
# Read and strip the version from the `VERSION` file.
defmacrop get_version do
case read_stripped(:filename.join(__DIR__, "../../../VERSION")) do
"" -> raise RuntimeError, message: "could not read the version number from VERSION"
@@ -25,7 +25,7 @@ defmodule System do
end
end
# Tries to run "git describe --always --tags". In the case of success returns
# Tries to run `git describe --always --tags`. In the case of success returns
# the most recent tag. If that is not available, tries to read the commit hash
# from .git/HEAD. If that fails, returns an empty string.
defmacrop get_describe do
@@ -66,7 +66,7 @@ defmodule System do
end
@doc """
Lists command line arguments.
List command line arguments.
Returns the list of command line arguments passed to the program.
"""
@@ -76,7 +76,7 @@ defmodule System do
end
@doc """
Modifies command line arguments.
Modify command line arguments.
Changes the list of command line arguments. Use it with caution,
as it destroys any previous argv information.
@@ -122,9 +122,13 @@ defmodule System do
User home directory.
Returns the user home directory (platform independent).
Returns `nil` if no user home is set.
"""
def user_home do
:elixir_config.get(:home)
case :os.type() do
{:win32, _} -> get_windows_home
_ -> get_unix_home
end
end
@doc """
@@ -138,6 +142,20 @@ defmodule System do
raise RuntimeError, message: "could not find the user home, please set the HOME environment variable"
end
defp get_unix_home do
get_env("HOME")
end
defp get_windows_home do
:filename.absname(
get_env("USERPROFILE") || (
hd = get_env("HOMEDRIVE")
hp = get_env("HOMEPATH")
hd && hp && hd <> hp
)
)
end
@doc ~S"""
Writable temporary directory.
@@ -262,13 +280,13 @@ defmodule System do
Returns the process identifier of the current Erlang emulator
in the format most commonly used by the operating system environment.
For more information, see [`:os.getpid/0`](http://www.erlang.org/doc/man/os.html#getpid-0).
See http://www.erlang.org/doc/man/os.html#getpid-0 for more info.
"""
@spec get_pid() :: binary
def get_pid, do: IO.iodata_to_binary(:os.getpid)
@doc """
Sets an environment variable value.
Set an environment variable value.
Sets a new `value` for the environment variable `varname`.
"""
@@ -279,7 +297,7 @@ defmodule System do
end
@doc """
Sets multiple environment variables.
Set multiple environment variables.
Sets a new value for each environment variable corresponding
to each key in `dict`.
@@ -314,7 +332,7 @@ defmodule System do
end
@doc """
Halts the Erlang runtime system.
Halt the Erlang runtime system.
Halts the Erlang runtime system where the argument `status` must be a
non-negative integer, the atom `:abort` or a binary.
@@ -325,13 +343,13 @@ defmodule System do
* If `:abort`, the runtime system aborts producing a core dump, if that is
enabled in the operating system.
* If a string, an Erlang crash dump is produced with status as slogan,
* If a string, an erlang crash dump is produced with status as slogan,
and then the runtime system exits with status code 1.
Note that on many platforms, only the status codes 0-255 are supported
by the operating system.
For more information, see [`:erlang.halt/1`](http://www.erlang.org/doc/man/erlang.html#halt-1).
For more information, check: http://www.erlang.org/doc/man/erlang.html#halt-1
## Examples
@@ -352,7 +370,7 @@ defmodule System do
:erlang.halt(String.to_char_list(status))
end
@doc ~S"""
@doc """
Executes the given `command` with `args`.
`command` is expected to be an executable available in PATH
@@ -363,20 +381,7 @@ defmodule System do
not happen unless `Path.wildcard/2` is used. On Windows though,
wildcard expansion is up to the program.
This function returns a tuple containing the collected result
and the command exit status.
## Examples
iex> System.cmd "echo", ["hello"]
{"hello\n", 0}
iex> System.cmd "echo", ["hello"], env: [{"MIX_ENV", "test"}]
{"hello\n", 0}
iex> System.cmd "echo", ["hello"], into: IO.stream(:stdio, :line)
hello
{%IO.Stream{}, 0}
A set of options are also supported and described below.
## Options
@@ -384,9 +389,9 @@ defmodule System do
* `:cd` - the directory to run the command in
* `:env` - an enumerable of tuples containing environment key-value as binary
* `:arg0` - set the command arg0
* `:stderr_to_stdout` - redirects stderr to stdout when `true`
* `:parallelism` - when `true`, the VM will schedule port tasks to improve
parallelism in the system. If set to `false`, the VM will try to perform
* `:stderr_to_stdout` - redirects stderr to stdout when true
* `:parallelism` - when true, the VM will schedule port tasks to improve
parallelism in the system. If set to false, the VM will try to perform
commands immediately, improving latency at the expense of parallelism.
The default can be set on system startup by passing the "+spp" argument
to `--erl`.
@@ -421,7 +426,7 @@ defmodule System do
If you desire to execute a trusted command inside a shell, with pipes,
redirecting and so on, please check
[`:os.cmd/1`](http://www.erlang.org/doc/man/os.html#cmd-1).
[Erlang's :os.cmd/1 function](http://www.erlang.org/doc/man/os.html#cmd-1).
"""
@spec cmd(binary, [binary], Keyword.t) ::
{Collectable.t, exit_status :: non_neg_integer}
+43 -269
View File
@@ -27,30 +27,10 @@ defmodule Task do
the task action finishes, a message will be sent to the caller
with the result.
`Task.await/2` is used to read the message sent by the task.
`await` will check the monitor setup by the call to `async/1` to
verify if the process exited for any abnormal reason (or in case
exits are being trapped by the caller).
There are two important things to consider when using async:
1. If you are using async tasks, you must await for a reply
as they are *always* sent. If you are not expecting a reply,
consider using `Task.start_link/1` detailed below
2. async tasks link the caller and the spawned process. This
means that, if the caller crashes, the task will crash
too and vice-versa. This is on purpose, if the process
meant to receive the result no longer exists, there is
no purpose in computing the result until the end. If this
is not desired, consider using `Task.start_link/1` as well
`Task.yield/2` is an alternative to `await/2` where the caller will
temporarily block waiting for a task's result. If the result does not
arrive within the timeout it can be called again at later moment. This
allows checking for the result of a task multiple times or to handle
a timeout. If a reply does not arrive within the desired time, and the
caller is not going exit, `Task.shutdown/2` can be used to stop the task.
`Task.await/2` is used to read the message sent by the task. On
`await`, Elixir will also setup a monitor to verify if the process
exited for any abnormal reason (or in case exits are being
trapped by the caller).
## Supervised tasks
@@ -72,66 +52,40 @@ defmodule Task do
unlike `async/1`, returns `{:ok, pid}` (which is
the result expected by supervision trees).
By default, most supervision strategies will try to restart
a worker after it exits regardless of reason. If you design the
task to terminate normally (as in the example with `IO.puts/2` above),
consider passing `restart: :transient` in the options to `worker/3`.
## Supervision trees
## Dynamically supervised tasks
The `Task.Supervisor` module allows developers to dynamically
create multiple supervised tasks.
A short example is:
The `Task.Supervisor` module allows developers to start supervisors
that dynamically supervise tasks:
{:ok, pid} = Task.Supervisor.start_link()
task = Task.Supervisor.async(pid, fn ->
# Do something
end)
Task.await(task)
Task.Supervisor.async(pid, MyMod, :my_fun, [arg1, arg2, arg3])
However, in the majority of cases, you want to add the task supervisor
to your supervision tree:
`Task.Supervisor` also makes it possible to spawn tasks in remote nodes as
long as the supervisor is registered locally or globally:
# In the remote node
Task.Supervisor.start_link(name: :tasks_sup)
# In the client
Task.Supervisor.async({:tasks_sup, :remote@local}, MyMod, :my_fun, [arg1, arg2, arg3])
`Task.Supervisor` is more often started in your supervision tree as:
import Supervisor.Spec
children = [
supervisor(Task.Supervisor, [[name: MyApp.TaskSupervisor]])
supervisor(Task.Supervisor, [[name: :tasks_sup]])
]
Now you can dynamically start supervised tasks:
Task.Supervisor.start_child(MyApp.TaskSupervisor, fn ->
# Do something
end)
Or even use the async/await pattern:
Task.Supervisor.async(MyApp.TaskSupervisor, fn ->
# Do something
end) |> Task.await()
Finally, check `Task.Supervisor` for other operations supported by the
Task supervisor.
## Distributed tasks
Since Elixir provides a Task supervisor, it is easy to use a task
supervisor to dynamically spawn tasks across nodes:
# In the remote node
Task.Supervisor.start_link(name: MyApp.DistSupervisor)
# In the client
Task.Supervisor.async({MyApp.DistSupervisor, :remote@local},
MyMod, :my_fun, [arg1, arg2, arg3])
Note that, when working with distributed tasks, one should use the `async/4` function
that expects explicit module, function and arguments, instead of `async/2` that
works with anonymous functions. That's because anonymous functions expect
Note that, when working with distributed tasks, one should use the `async/3` API,
that expects explicit module, function and arguments, instead of `async/1` that
works with anonymous functions. That's because the anonymous function API expects
the same module version to exist on all involved nodes. Check the `Agent` module
documentation for more information on distributed processes as the limitations
documentation for more information on distributed processes, as the limitations
described in the agents documentation apply to the whole ecosystem.
Finally, check `Task.Supervisor` for other operations supported by the Task
supervisor.
"""
@doc """
@@ -139,8 +93,8 @@ defmodule Task do
It contains two fields:
* `:pid` - the process reference of the task process; `nil` if the task does
not use a task process.
* `:pid` - the process reference of the task process; it may be a pid
or a tuple containing the process and node names
* `:ref` - the task monitor reference
@@ -196,9 +150,6 @@ defmodule Task do
by the caller process. A `Task` struct is returned containing
the relevant information.
Read the `Task` module documentation for more info on general
usage of `async/1` and `async/3`.
## Task's message format
The reply sent by the task will be in the format `{ref, msg}`,
@@ -212,17 +163,8 @@ defmodule Task do
@doc """
Starts a task that can be awaited on.
This function spawns a process that is linked to and monitored
by the caller process. A `Task` struct is returned containing
the relevant information.
Read the `Task` module documentation for more info on general
usage of `async/1` and `async/3`.
## Task's message format
The reply sent by the task will be in the format `{ref, msg}`,
where `ref` is the monitoring reference held by the task.
Similar to `async/1`, but the task is specified by the given
module, function and arguments.
"""
@spec async(module, atom, [term]) :: t
def async(mod, fun, args) do
@@ -247,18 +189,6 @@ defmodule Task do
A timeout, in milliseconds, can be given with default value
of `5000`. In case the task process dies, this function will
exit with the same reason as the task.
If the timeout is exceeded, `await` will exit, however,
the task will continue to run. When the calling process exits, its
exit signal will close the task if it is not trapping exits.
This function assumes the task's monitor is still active or the monitor's
`:DOWN` message is in the message queue. If it has been demonitored, or the
message already received, this function may wait for the duration of the
timeout awaiting the message.
This function will always demonitor the task and so the task can not be used
again. To await the task's reply multiple times use `yield/2` instead.
"""
@spec await(t, timeout) :: term | no_return
def await(%Task{ref: ref}=task, timeout \\ 5000) do
@@ -266,8 +196,11 @@ defmodule Task do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
reply
{:DOWN, ^ref, _, proc, reason} ->
exit({reason(reason, proc), {__MODULE__, :await, [task, timeout]}})
{:DOWN, ^ref, _, _, :noconnection} ->
mfa = {__MODULE__, :await, [task, timeout]}
exit({{:nodedown, node(task.pid)}, mfa})
{:DOWN, ^ref, _, _, reason} ->
exit({reason, {__MODULE__, :await, [task, timeout]}})
after
timeout ->
Process.demonitor(ref, [:flush])
@@ -279,43 +212,16 @@ defmodule Task do
Receives a group of tasks and a message and finds
a task that matches the given message.
This function returns a tuple with the returned value
in case the message matches a task that exited with
success alongside the matching task. It raises in case
the found task failed or `nil` if no task was found.
This function returns a tuple with the task and the
returned value in case the message matches a task that
exited with success, it raises in case the found task
failed or `nil` if no task was found.
This function is useful in situations where multiple
tasks are spawned and their results are collected
later on. For example, a `GenServer` can spawn tasks,
store the tasks in a list and later use `Task.find/2`
to see if incoming messages are from any of the tasks.
## Examples
defmodule TaskFinder do
def run do
task1 = Task.async fn -> :timer.sleep(1000); 1 end
task2 = Task.async fn -> :timer.sleep(5000); 2 end
await [task1, task2]
end
# Be careful, this will receive all messages sent
# to this process. It will return the first task
# reply and the list of tasks that came second.
def await(tasks) do
receive do
message ->
case Task.find(tasks, message) do
{reply, task} ->
{reply, List.delete(tasks, task)}
nil ->
await(tasks)
end
end
end
end
TaskFinder.run
"""
@spec find([t], any) :: {term, t} | nil | no_return
def find(tasks, msg)
@@ -330,11 +236,13 @@ defmodule Task do
end
end
def find(tasks, {:DOWN, ref, _, proc, reason} = msg) when is_reference(ref) do
def find(tasks, {:DOWN, ref, _, _, reason} = msg) when is_reference(ref) do
find = fn(%Task{ref: task_ref}) -> task_ref == ref end
case Enum.find(tasks, find) do
%Task{pid: pid} when reason == :noconnection ->
exit({{:nodedown, node(pid)}, {__MODULE__, :find, [tasks, msg]}})
%Task{} ->
exit({reason(reason, proc), {__MODULE__, :find, [tasks, msg]}})
exit({reason, {__MODULE__, :find, [tasks, msg]}})
nil ->
nil
end
@@ -343,138 +251,4 @@ defmodule Task do
def find(_tasks, _msg) do
nil
end
@doc """
Yields, temporarily, for a task reply.
Returns `{:ok, reply}` if the reply is received.
A timeout, in milliseconds, can be given with default value
of `5000`. In case of the timeout, this function will return `nil`
and the monitor will remain active. Therefore `yield/2` can be
called multiple times on the same task.
In case the task process dies, this function will exit with the
same reason as the task.
This function assumes the task's monitor is still active or the monitor's
`:DOWN` message is in the message queue. If it has been demonitored, or the
message already received, this function wait for the duration of the timeout
awaiting the message.
"""
@spec yield(t, timeout) :: {:ok, term} | nil
def yield(%Task{ref: ref} = task, timeout \\ 5_000) do
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
{:ok, reply}
{:DOWN, ^ref, _, proc, reason} ->
exit({reason(reason, proc), {__MODULE__, :yield, [task, timeout]}})
after
timeout ->
nil
end
end
@doc """
Unlinks and shutdowns the task, and then checks for a reply.
Returns `{:ok, reply}` if the reply is received while shutting down the task,
otherwise `nil`.
The shutdown method is either a timeout or `:brutal_kill`. In the case
of a `timeout`, a `:shutdown` exit signal is sent to the task process
and if it does not exit within the timeout it is killed. With `:brutal_kill`
the task is killed straight away. In the case that the task exits abnormal,
or a timeout shutdown kills the task, this function will exit with the same
reason.
It is not required to call this function when terminating the caller, unless
exiting with reason `:normal` or the task is trapping exits. If the caller is
exiting with a reason other than `:normal` and the task is not trapping exits the
caller's exit signal will stop the task. The caller can exit with reason
`:shutdown` to shutdown linked processes, such as tasks, that are not trapping
exits without generating any log messages.
This function assumes the task's monitor is still active or the monitor's
`:DOWN` message is in the message queue. If it has been demonitored, or the
message already received, this function will block forever awaiting the message.
"""
@spec shutdown(t, timeout | :brutal_kill) :: {:ok, term} | nil
def shutdown(task, shutdown \\ 5_000)
def shutdown(%Task{pid: nil} = task, _) do
raise ArgumentError, "task #{inspect task} does not have an associated task process."
end
def shutdown(%Task{pid: pid} = task, :brutal_kill) do
exit(pid, :kill)
case shutdown_receive(task, :brutal_kill, :infinity) do
{:error, reason} ->
exit({reason, {__MODULE__, :shutdown, [task, :brutal_kill]}})
result ->
result
end
end
def shutdown(%Task{pid: pid} = task, timeout) do
exit(pid, :shutdown)
case shutdown_receive(task, :shutdown, timeout) do
{:error, reason} ->
exit({reason, {__MODULE__, :shutdown, [task, timeout]}})
result ->
result
end
end
## Helpers
defp reason(:noconnection, proc), do: {:nodedown, monitor_node(proc)}
defp reason(reason, _), do: reason
defp monitor_node(pid) when is_pid(pid), do: node(pid)
defp monitor_node({_, node}), do: node
# spawn a process to ensure task gets exit signal if process dies from exit signal
# between unlink and exit.
defp exit(task, reason) do
caller = self()
ref = make_ref()
enforcer = spawn(fn() -> enforce_exit(task, reason, caller, ref) end)
Process.unlink(task)
Process.exit(task, reason)
send(enforcer, {:done, ref})
:ok
end
defp enforce_exit(pid, reason, caller, ref) do
mon = Process.monitor(caller)
receive do
{:done, ^ref} -> :ok
{:DOWN, ^mon, _, _, _} -> Process.exit(pid, reason)
end
end
defp shutdown_receive(%{ref: ref} = task, type, timeout) do
receive do
{:DOWN, ^ref, _, _, :shutdown} when type in [:shutdown, :timeout_kill] ->
flush_reply(ref)
{:DOWN, ^ref, _, _, :killed} when type == :brutal_kill ->
flush_reply(ref)
{:DOWN, ^ref, _, proc, reason} ->
flush_reply(ref) || {:error, reason(reason, proc)}
after
timeout ->
Process.exit(task.pid, :kill)
shutdown_receive(task, :timeout_kill, :infinity)
end
end
defp flush_reply(ref) do
receive do
{^ref, reply} -> {:ok, reply}
after
0 -> nil
end
end
end
+9 -29
View File
@@ -25,8 +25,8 @@ defmodule Task.Supervised do
:proc_lib.init_ack({:ok, self()})
ref =
# There is a race condition on this operation when working across
# node that manifests if a "Task.Supervisor.async/1" call is made
# There is a race condition on this operation when working accross
# node that manifests if a `Task.Supervisor.async/1` call is made
# while the supervisor is busy spawning previous tasks.
#
# Imagine the following workflow:
@@ -38,7 +38,7 @@ defmodule Task.Supervised do
# 5. The spawned task waits forever for the monitor reference so it can begin
#
# We have solved this by specifying a timeout of 5000 seconds.
# Given no work is done in the client between the task start and
# Given no work is done in the client in between the task start and
# sending the reference, 5000 should be enough to not raise false
# negatives unless the nodes are indeed not available.
receive do
@@ -74,24 +74,22 @@ defmodule Task.Supervised do
apply(module, fun, args)
catch
:error, value ->
reason = {value, System.stacktrace()}
exit(info, mfa, reason, reason)
exit(info, mfa, {value, System.stacktrace()})
:throw, value ->
reason = {{:nocatch, value}, System.stacktrace()}
exit(info, mfa, reason, reason)
exit(info, mfa, {{:nocatch, value}, System.stacktrace()})
:exit, value ->
exit(info, mfa, {value, System.stacktrace()}, value)
exit(info, mfa, value)
end
end
defp exit(_info, _mfa, _log_reason, reason)
defp exit(_info, _mfa, reason)
when reason == :normal
when reason == :shutdown
when tuple_size(reason) == 2 and elem(reason, 0) == :shutdown do
exit(reason)
end
defp exit(info, mfa, log_reason, reason) do
defp exit(info, mfa, reason) do
{fun, args} = get_running(mfa)
:error_logger.format(
@@ -100,7 +98,7 @@ defmodule Task.Supervised do
'** When function == ~p~n' ++
'** arguments == ~p~n' ++
'** Reason for termination == ~n' ++
'** ~p~n', [self, get_from(info), fun, args, get_reason(log_reason)])
'** ~p~n', [self, get_from(info), fun, args, reason])
exit(reason)
end
@@ -110,22 +108,4 @@ defmodule Task.Supervised do
defp get_running({:erlang, :apply, [fun, []]}) when is_function(fun, 0), do: {fun, []}
defp get_running({mod, fun, args}), do: {:erlang.make_fun(mod, fun, length(args)), args}
defp get_reason({:undef, [{mod, fun, args, _info} | _] = stacktrace} = reason)
when is_atom(mod) and is_atom(fun) do
cond do
:code.is_loaded(mod) === false ->
{:"module could not be loaded", stacktrace}
is_list(args) and not function_exported?(mod, fun, length(args)) ->
{:"function not exported", stacktrace}
is_integer(args) and not function_exported?(mod, fun, args) ->
{:"function not exported", stacktrace}
true ->
reason
end
end
defp get_reason(reason) do
reason
end
end
+2 -1
View File
@@ -7,7 +7,8 @@ defmodule Task.Supervisor do
`:simple_one_for_one` supervisor where the workers are temporary
(i.e. they are not restarted after they die).
See the `Task` module for more information.
The functions in this module allow tasks to be spawned and awaited
from a supervisor, similar to the functions defined in the `Task` module.
## Name Registration
+4 -35
View File
@@ -1,9 +1,6 @@
defmodule Tuple do
@moduledoc """
Functions for working with tuples.
See also `Kernel.elem/2`, `Kernel.is_tuple/1`, `Kernel.put_elem/3`, and
`Kernel.tuple_size/1`.
"""
@doc """
@@ -29,7 +26,7 @@ defmodule Tuple do
Inserts an element into a tuple.
Inserts `value` into `tuple` at the given zero-based `index`.
Raises an `ArgumentError` if `index` is negative or greater than the
Raises an `ArgumentError` if `index` is greater than the
length of `tuple`.
Inlined by the compiler.
@@ -39,39 +36,18 @@ defmodule Tuple do
iex> tuple = {:bar, :baz}
iex> Tuple.insert_at(tuple, 0, :foo)
{:foo, :bar, :baz}
iex> Tuple.insert_at(tuple, 2, :bong)
{:bar, :baz, :bong}
"""
@spec insert_at(tuple, non_neg_integer, term) :: tuple
def insert_at(tuple, index, value) do
:erlang.insert_element(index + 1, tuple, value)
end
@doc """
Inserts an element into the end of a tuple.
Returns a new tuple which has one element more than `tuple`, and contains
the elements in `tuple` followed by `value` as the last element.
Inlined by the compiler.
## Examples
iex> tuple = {:foo, :bar}
iex> Tuple.append(tuple, :baz)
{:foo, :bar, :baz}
"""
@spec append(tuple, term) :: tuple
def append(tuple, value) do
:erlang.append_element(tuple, value)
def insert_at(tuple, index, term) do
:erlang.insert_element(index + 1, tuple, term)
end
@doc """
Removes an element from a tuple.
Deletes the element at the zero-based `index` from `tuple`.
Raises an `ArgumentError` if `index` is negative or greater than
Raises an `ArgumentError` if `index` is greater than
or equal to the length of `tuple`.
Inlined by the compiler.
@@ -92,13 +68,6 @@ defmodule Tuple do
Converts a tuple to a list.
Inlined by the compiler.
## Examples
iex> tuple = {:foo, :bar, :baz}
iex> Tuple.to_list(tuple)
[:foo, :bar, :baz]
"""
@spec to_list(tuple) :: list
def to_list(tuple) do
+28 -20
View File
@@ -11,6 +11,25 @@ defmodule URI do
import Bitwise
@schemes [
"ftp",
"http",
"https",
"ldap",
"sftp",
"tftp",
]
Enum.each @schemes, fn scheme ->
def normalize_scheme(unquote(scheme)), do: unquote(scheme)
end
@doc """
Normalizes the scheme according to the spec by downcasing it.
"""
def normalize_scheme(nil), do: nil
def normalize_scheme(scheme), do: String.downcase(scheme)
@doc """
Returns the default port for a given scheme.
@@ -127,14 +146,14 @@ defmodule URI do
end
defp pair({k, v}) do
encode_www_form(Kernel.to_string(k)) <>
"=" <> encode_www_form(Kernel.to_string(v))
encode_www_form(to_string(k)) <>
"=" <> encode_www_form(to_string(v))
end
@doc """
Checks if the character is a "reserved" character in a URI.
Reserved characters are specified in [RFC3986, section 2.2](http://tools.ietf.org/html/rfc3986#section-2.2).
Reserved characters are specified in RFC3986, section 2.2.
"""
def char_reserved?(c) do
c in ':/?#[]@!$&\'()*+,;='
@@ -143,7 +162,7 @@ defmodule URI do
@doc """
Checks if the character is a "unreserved" character in a URI.
Unreserved characters are specified in [RFC3986, section 2.3](http://tools.ietf.org/html/rfc3986#section-2.3).
Unreserved characters are specified in RFC3986, section 2.3.
"""
def char_unreserved?(c) do
c in ?0..?9 or
@@ -163,7 +182,7 @@ defmodule URI do
end
@doc """
Percent-escapes a URI.
Percent-escape a URI.
Accepts `predicate` function as an argument to specify if char can be left as is.
## Example
@@ -177,7 +196,7 @@ defmodule URI do
end
@doc """
Encodes a string as "x-www-urlencoded".
Encode a string as "x-www-urlencoded".
## Example
@@ -206,7 +225,7 @@ defmodule URI do
defp hex(n), do: <<n + ?A - 10>>
@doc """
Percent-unescapes a URI.
Percent-unescape a URI.
## Examples
@@ -222,7 +241,7 @@ defmodule URI do
end
@doc """
Decodes a string as "x-www-urlencoded".
Decode a string as "x-www-urlencoded".
## Examples
@@ -264,7 +283,7 @@ defmodule URI do
can be used to parse a wide range of relative URIs.
This function uses the parsing regular expression as defined
in the [Appendix B of RFC3986](http://tools.ietf.org/html/rfc3986#appendix-B).
in the Appendix B of RFC3986.
When a URI is given without a port, the values registered via
`URI.default_port/1` and `URI.default_port/2` are used.
@@ -332,9 +351,6 @@ defmodule URI do
{userinfo, host, port}
end
defp normalize_scheme(nil), do: nil
defp normalize_scheme(scheme), do: String.downcase(scheme)
# Regex.run returns empty strings sometimes. We want
# to replace those with nil for consistency.
defp nillify(l) do
@@ -342,14 +358,6 @@ defmodule URI do
if byte_size(s) > 0, do: s, else: nil
end
end
@doc """
Converts the URI to string.
iex> URI.to_string(URI.parse("http://google.com"))
"http://google.com"
"""
defdelegate to_string(uri), to: String.Chars.URI
end
defimpl String.Chars, for: URI do
+14 -13
View File
@@ -88,6 +88,7 @@ defmodule Version do
build: build}
defmodule Requirement do
@moduledoc false
defstruct [:source, :matchspec]
@type t :: %__MODULE__{}
end
@@ -101,7 +102,7 @@ defmodule Version do
end
@doc """
Checks if the given version matches the specification.
Check if the given version matches the specification.
Returns `true` if `version` satisfies `requirement`, `false` otherwise.
Raises a `Version.InvalidRequirementError` exception if `requirement` is not
@@ -125,12 +126,12 @@ defmodule Version do
"""
@spec match?(version, requirement) :: boolean
def match?(version, requirement) when is_binary(requirement) do
case parse_requirement(requirement) do
{:ok, requirement} ->
match?(version, requirement)
def match?(vsn, req) when is_binary(req) do
case parse_requirement(req) do
{:ok, req} ->
match?(vsn, req)
:error ->
raise InvalidRequirementError, message: requirement
raise InvalidRequirementError, message: req
end
end
@@ -160,8 +161,8 @@ defmodule Version do
"""
@spec compare(version, version) :: :gt | :eq | :lt
def compare(version1, version2) do
do_compare(to_matchable(version1), to_matchable(version2))
def compare(vsn1, vsn2) do
do_compare(to_matchable(vsn1), to_matchable(vsn2))
end
defp do_compare({major1, minor1, patch1, pre1}, {major2, minor2, patch2, pre2}) do
@@ -177,7 +178,7 @@ defmodule Version do
end
@doc """
Parses a version string into a `Version`.
Parse a version string into a `Version`.
## Examples
@@ -193,16 +194,16 @@ defmodule Version do
def parse(string) when is_binary(string) do
case Version.Parser.parse_version(string) do
{:ok, {major, minor, patch, pre}} ->
version = %Version{major: major, minor: minor, patch: patch,
vsn = %Version{major: major, minor: minor, patch: patch,
pre: pre, build: get_build(string)}
{:ok, version}
{:ok, vsn}
:error ->
:error
end
end
@doc """
Parses a version requirement string into a `Version.Requirement`.
Parse a version requirement string into a `Version.Requirement`.
## Examples
@@ -230,7 +231,7 @@ defmodule Version do
defp to_matchable(string) do
case Version.Parser.parse_version(string) do
{:ok, version} -> version
{:ok, vsn} -> vsn
:error -> raise InvalidVersionError, message: string
end
end
+16 -20
View File
@@ -9,9 +9,8 @@
-include("elixir.hrl").
%% Top level types
-export_type([char_list/0, struct/0, as_boolean/1]).
-export_type([char_list/0, as_boolean/1]).
-type char_list() :: string().
-type struct() :: #{'__struct__' => atom()}.
-type as_boolean(T) :: T.
%% OTP Application API
@@ -25,20 +24,18 @@ start(_Type, _Args) ->
%% has encoding set to latin1.
Opts =
case init:get_argument(noshell) of
{ok, _} -> [binary, {encoding, utf8}];
{ok, _} -> [binary,{encoding,utf8}];
error -> [binary]
end,
ok = io:setopts(standard_io, Opts),
%% TODO: Remove this once we support only OTP >18
ok = case io:setopts(standard_error, [{encoding, utf8}]) of
ok = case io:setopts(standard_error, [{encoding,utf8}]) of
ok -> ok;
{error, _} -> io:setopts(standard_error, [{unicode, true}]) %% OTP 17.3 and earlier
{error, _} -> io:setopts(standard_error, [{unicode,true}]) %% R17.3 and earlier
end,
Encoding = file:native_name_encoding(),
case Encoding of
case file:native_name_encoding() of
latin1 ->
io:format(standard_error,
"warning: the VM is running with native name encoding of latin1 which may cause "
@@ -55,10 +52,8 @@ start(_Type, _Args) ->
{<<"https">>, 443},
{<<"ldap">>, 389}],
URIConfig = [{{uri, Scheme}, Port} || {Scheme, Port} <- URIs],
CompilerOpts = [{docs, true}, {debug_info, true}, {warnings_as_errors, false}],
{ok, [[Home] | _]} = init:get_argument(home),
CompilerOpts = [{docs,true},{debug_info,true},{warnings_as_errors,false}],
Config = [{at_exit, []},
{home, unicode:characters_to_binary(Home, Encoding, Encoding)},
{compiler_options, orddict:from_list(CompilerOpts)}
| URIConfig],
Tab = elixir_config:new(Config),
@@ -98,6 +93,7 @@ start_cli() ->
env_for_eval(Opts) ->
env_for_eval((elixir_env:new())#{
local := nil,
requires := elixir_dispatch:default_requires(),
functions := elixir_dispatch:default_functions(),
macros := elixir_dispatch:default_macros()
@@ -114,6 +110,11 @@ env_for_eval(Env, Opts) ->
false -> ?m(Env, file)
end,
Local = case lists:keyfind(delegate_locals_to, 1, Opts) of
{delegate_locals_to, LocalOpt} when is_atom(LocalOpt) -> LocalOpt;
false -> ?m(Env, local)
end,
Aliases = case lists:keyfind(aliases, 1, Opts) of
{aliases, AliasesOpt} when is_list(AliasesOpt) -> AliasesOpt;
false -> ?m(Env, aliases)
@@ -140,7 +141,7 @@ env_for_eval(Env, Opts) ->
end,
Env#{
file := File, module := Module,
file := File, local := Local, module := Module,
macros := Macros, functions := Functions,
requires := Requires, aliases := Aliases, line := Line
}.
@@ -174,7 +175,7 @@ eval_forms(Tree, Binding, E) ->
eval_forms(Tree, Binding, E, elixir_env:env_to_scope(E)).
eval_forms(Tree, Binding, Env, Scope) ->
{ParsedBinding, ParsedScope} = elixir_scope:load_binding(Binding, Scope),
ParsedEnv = Env#{vars := [K || {K, _} <- ParsedScope#elixir_scope.vars]},
ParsedEnv = Env#{vars := [K || {K,_} <- ParsedScope#elixir_scope.vars]},
{Erl, NewEnv, NewScope} = quoted_to_erl(Tree, ParsedEnv, ParsedScope),
case Erl of
@@ -232,19 +233,14 @@ quoted_to_erl(Quoted, Env, Scope) ->
string_to_quoted(String, StartLine, File, Opts) when is_integer(StartLine), is_binary(File) ->
case elixir_tokenizer:tokenize(String, StartLine, [{file, File}|Opts]) of
{ok, _Line, _Column, Tokens} ->
{ok, _Line, Tokens} ->
try elixir_parser:parse(Tokens) of
{ok, Forms} -> {ok, Forms};
{error, {{Line, _, _}, _, [Error, Token]}} -> {error, {Line, to_binary(Error), to_binary(Token)}};
{error, {Line, _, [Error, Token]}} -> {error, {Line, to_binary(Error), to_binary(Token)}}
catch
{error, {{Line, _, _}, _, [Error, Token]}} -> {error, {Line, to_binary(Error), to_binary(Token)}};
{error, {Line, _, [Error, Token]}} -> {error, {Line, to_binary(Error), to_binary(Token)}}
end;
{error, {Line, {ErrorPrefix, ErrorSuffix}, Token}, _Rest, _SoFar} ->
{error, {Line, {to_binary(ErrorPrefix), to_binary(ErrorSuffix)}, to_binary(Token)}};
{error, {Line, Error, Token}, _Rest, _SoFar} ->
{error, {Line, to_binary(Error), to_binary(Token)}}
{error, {Line, Error, Token}, _Rest, _SoFar} -> {error, {Line, to_binary(Error), to_binary(Token)}}
end.
'string_to_quoted!'(String, StartLine, File, Opts) ->
+3 -2
View File
@@ -7,6 +7,7 @@
noname=false, %% when true, don't add new names (used by try)
super=false, %% when true, it means super was invoked
caller=false, %% when true, it means caller was invoked
return=true, %% when true, the return value is used
module=nil, %% the current module
function=nil, %% the current function
vars=[], %% a dict of defined variables and their alias
@@ -54,8 +55,7 @@
-define(is_atom_start(S), (?is_quote(S) orelse ?is_upcase(S) orelse ?is_downcase(S) orelse (S == $_))).
-define(is_atom(S), (?is_identifier(S) orelse (S == $@))).
-define(is_identifier_start(S), (?is_upcase(S) orelse ?is_downcase(S) orelse (S == $_))).
-define(is_identifier(S), (?is_digit(S) orelse ?is_identifier_start(S))).
-define(is_identifier(S), (?is_digit(S) orelse ?is_upcase(S) orelse ?is_downcase(S) orelse (S == $_))).
-define(is_sigil(S), ((S == $/) orelse (S == $<) orelse (S == $") orelse (S == $') orelse
(S == $[) orelse (S == $() orelse (S == ${) orelse (S == $|))).
@@ -66,3 +66,4 @@
-define(is_horizontal_space(S), ((S == $\s) orelse (S == $\t))).
-define(is_vertical_space(S), ((S == $\r) orelse (S == $\n))).
-define(is_space(S), (?is_horizontal_space(S) orelse ?is_vertical_space(S))).
-define(is_invalid_space(S), (S == 16#A0)).
+5 -5
View File
@@ -16,7 +16,7 @@ expand(Meta, Args, E) ->
expand_bitstr(_Fun, [], Acc, E) ->
{lists:reverse(Acc), E};
expand_bitstr(Fun, [{'::', Meta, [Left, Right]}|T], Acc, E) ->
expand_bitstr(Fun, [{'::',Meta,[Left,Right]}|T], Acc, E) ->
{ELeft, EL} = Fun(Left, E),
%% Variables defined outside the binary can be accounted
@@ -27,7 +27,7 @@ expand_bitstr(Fun, [{'::', Meta, [Left, Right]}|T], Acc, E) ->
end,
ERight = expand_bit_info(Meta, Right, ER),
expand_bitstr(Fun, T, [{'::', Meta, [ELeft, ERight]}|Acc], EL);
expand_bitstr(Fun, T, [{'::',Meta,[ELeft,ERight]}|Acc], EL);
expand_bitstr(Fun, [H|T], Acc, E) ->
{Expr, ES} = Fun(H, E),
@@ -152,7 +152,7 @@ build_bitstr(Fun, Exprs, Meta, S) ->
build_bitstr_each(_Fun, [], _Meta, S, Acc) ->
{Acc, S};
build_bitstr_each(Fun, [{'::', _, [H, V]}|T], Meta, S, Acc) ->
build_bitstr_each(Fun, [{'::',_,[H,V]}|T], Meta, S, Acc) ->
{Size, Types} = extract_bit_info(V, S#elixir_scope{context=nil}),
build_bitstr_each(Fun, T, Meta, S, Acc, H, Size, Types);
@@ -191,7 +191,7 @@ build_bitstr_each(Fun, T, Meta, S, Acc, H, Size, Types) ->
case Expr of
{bin, _, Elements} ->
case (Size == default) andalso types_allow_splice(Types, Elements) of
true -> build_bitstr_each(Fun, T, Meta, NS, lists:reverse(Elements, Acc));
true -> build_bitstr_each(Fun, T, Meta, NS, lists:reverse(Elements) ++ Acc);
false -> build_bitstr_each(Fun, T, Meta, NS, [{bin_element, ?line(Meta), Expr, Size, Types}|Acc])
end;
_ ->
@@ -220,7 +220,7 @@ is_byte_size([], Size) ->
Size rem 8 == 0.
elem_size({bin_element, _, _, default, _}) -> {0, 0};
elem_size({bin_element, _, _, {integer, _, Size}, Types}) -> {Size, unit_size(Types, 1)};
elem_size({bin_element, _, _, {integer,_,Size}, Types}) -> {Size, unit_size(Types, 1)};
elem_size({bin_element, _, _, _Size, Types}) -> {unknown, unit_size(Types, 1)}.
unit_size([binary|T], _) -> unit_size(T, 8);
+9 -9
View File
@@ -18,7 +18,7 @@
'MACRO-defmacro'(Caller, Call, Expr) -> define(Caller, defmacro, Call, Expr).
'MACRO-defmacrop'(Caller, Call, Expr) -> define(Caller, defmacrop, Call, Expr).
'MACRO-defmodule'(_Caller, Alias, [{do, Block}]) ->
'MACRO-defmodule'(_Caller, Alias, [{do,Block}]) ->
{Escaped, _} = elixir_quote:escape(Block, false),
Args = [Alias, Escaped, [], env()],
{{'.', [], [elixir_module, compile]}, [], Args}.
@@ -27,15 +27,15 @@
[];
'__info__'(macros) ->
[{'@', 1},
{def, 1},
{def, 2},
{defmacro, 1},
{defmacro, 2},
{defmacrop, 2},
{defmodule, 2},
{defp, 2}].
{def,1},
{def,2},
{defmacro,1},
{defmacro,2},
{defmacrop,2},
{defmodule,2},
{defp,2}].
define({Line, E}, Kind, Call, Expr) ->
define({Line,E}, Kind, Call, Expr) ->
{EscapedCall, UC} = elixir_quote:escape(Call, true),
{EscapedExpr, UE} = elixir_quote:escape(Expr, true),
Args = [Line, Kind, not(UC or UE), EscapedCall, EscapedExpr, elixir_locals:cache_env(E)],
+19 -19
View File
@@ -1,7 +1,7 @@
%% Handle code related to args, guard and -> matching for case,
%% fn, receive and friends. try is handled in elixir_try.
-module(elixir_clauses).
-export([match/3, clause/6, clauses/3, guards/4, get_pairs/3, get_pairs/4,
-export([match/3, clause/7, clauses/4, guards/4, get_pairs/3, get_pairs/4,
extract_splat_guards/1, extract_guards/1]).
-include("elixir.hrl").
@@ -31,9 +31,9 @@ match(Fun, Args, S) -> Fun(Args, S).
%% Translate clauses with args, guards and expressions
clause(Line, Fun, Args, Expr, Guards, S) when is_integer(Line) ->
clause(Line, Fun, Args, Expr, Guards, Return, S) when is_integer(Line) ->
{TArgs, SA} = match(Fun, Args, S#elixir_scope{extra_guards=[]}),
{TExpr, SE} = elixir_translator:translate(Expr, SA#elixir_scope{extra_guards=nil}),
{TExpr, SE} = elixir_translator:translate_block(Expr, Return, SA#elixir_scope{extra_guards=nil}),
Extra = SA#elixir_scope.extra_guards,
TGuards = guards(Line, Guards, Extra, SA),
@@ -60,7 +60,7 @@ extract_or_guards(Term) -> [Term].
% Extract guards when multiple left side args are allowed.
extract_splat_guards([{'when', _, [_, _|_] = Args}]) ->
extract_splat_guards([{'when', _, [_,_|_] = Args}]) ->
{Left, Right} = elixir_utils:split_last(Args),
{Left, extract_or_guards(Right)};
extract_splat_guards(Else) ->
@@ -68,18 +68,18 @@ extract_splat_guards(Else) ->
% Function for translating macros with match style like case and receive.
clauses(Meta, Clauses, #elixir_scope{export_vars=CV} = S) ->
{TC, TS} = do_clauses(Meta, Clauses, S#elixir_scope{export_vars=[]}),
clauses(Meta, Clauses, Return, #elixir_scope{export_vars=CV} = S) ->
{TC, TS} = do_clauses(Meta, Clauses, Return, S#elixir_scope{export_vars=[]}),
{TC, TS#elixir_scope{export_vars=elixir_scope:merge_opt_vars(CV, TS#elixir_scope.export_vars)}}.
do_clauses(_Meta, [], S) ->
do_clauses(_Meta, [], _Return, S) ->
{[], S};
do_clauses(Meta, DecoupledClauses, S) ->
do_clauses(Meta, DecoupledClauses, Return, S) ->
% Transform tree just passing the variables counter forward
% and storing variables defined inside each clause.
Transformer = fun(X, {SAcc, VAcc}) ->
{TX, TS} = each_clause(Meta, X, SAcc),
{TX, TS} = each_clause(Meta, X, Return, SAcc),
{TX, {elixir_scope:mergec(S, TS), [TS#elixir_scope.export_vars|VAcc]}}
end,
@@ -119,15 +119,15 @@ expand_clauses(Line, [Clause|T], [ClauseVars|V], FinalVars, Acc, S) ->
true ->
case Final of
{match, _, {var, _, UserVarName} = UserVar, _} when UserVarName /= '_' ->
{[UserVar, MatchExpr, Final|RawClauseExprs], S};
{[UserVar,MatchExpr,Final|RawClauseExprs], S};
_ ->
{VarName, _, SS} = elixir_scope:build_var('_', S),
StorageVar = {var, Line, VarName},
StorageExpr = {match, Line, StorageVar, Final},
{[StorageVar, MatchExpr, StorageExpr|RawClauseExprs], SS}
{[StorageVar,MatchExpr,StorageExpr|RawClauseExprs], SS}
end;
false ->
{[Final, MatchExpr|RawClauseExprs], S}
{[Final,MatchExpr|RawClauseExprs], S}
end,
FinalClause = setelement(5, Clause, lists:reverse(FinalClauseExprs)),
@@ -139,14 +139,14 @@ expand_clauses(_Line, [], [], _FinalVars, Acc, S) ->
% Handle each key/value clause pair and translate them accordingly.
each_clause(Export, {match, Meta, [Condition], Expr}, S) ->
each_clause(Export, {match, Meta, [Condition], Expr}, Return, S) ->
Fun = wrap_export_fun(Export, fun elixir_translator:translate_args/2),
{Arg, Guards} = extract_guards(Condition),
clause(?line(Meta), Fun, [Arg], Expr, Guards, S);
clause(?line(Meta), Fun, [Arg], Expr, Guards, Return, S);
each_clause(Export, {expr, Meta, [Condition], Expr}, S) ->
each_clause(Export, {expr, Meta, [Condition], Expr}, Return, S) ->
{TCondition, SC} = (wrap_export_fun(Export, fun elixir_translator:translate/2))(Condition, S),
{TExpr, SB} = elixir_translator:translate(Expr, SC),
{TExpr, SB} = elixir_translator:translate_block(Expr, Return, SC),
{{clause, ?line(Meta), [TCondition], [], unblock(TExpr)}, SB}.
wrap_export_fun(Meta, Fun) ->
@@ -180,11 +180,11 @@ has_match_tuple(H) when is_list(H) ->
lists:any(fun has_match_tuple/1, H);
has_match_tuple(_) -> false.
% Normalize the given var between clauses
% by picking one value as reference and retrieving
% Normalize the given var in between clauses
% by picking one value as reference and retriving
% its previous value.
normalize_vars(Key, Value, #elixir_scope{vars=Vars, export_vars=ClauseVars} = S) ->
normalize_vars(Key, Value, #elixir_scope{vars=Vars,export_vars=ClauseVars} = S) ->
VS = S#elixir_scope{
vars=orddict:store(Key, Value, Vars),
export_vars=orddict:store(Key, Value, ClauseVars)
+12 -5
View File
@@ -7,7 +7,8 @@
-define(timeout, 30000).
-record(elixir_code_server, {
loaded=[],
mod_pool={[], 0},
paths={[],[]},
mod_pool={[],0},
mod_ets=dict:new(),
compilation_status=[]
}).
@@ -66,11 +67,14 @@ handle_call({compilation_status, CompilerPid}, _From, Config) ->
handle_call(retrieve_module_name, _From, Config) ->
case Config#elixir_code_server.mod_pool of
{[H|T], Counter} ->
{reply, module_tuple(H), Config#elixir_code_server{mod_pool={T, Counter}}};
{reply, module_tuple(H), Config#elixir_code_server{mod_pool={T,Counter}}};
{[], Counter} ->
{reply, module_tuple(Counter), Config#elixir_code_server{mod_pool={[], Counter+1}}}
{reply, module_tuple(Counter), Config#elixir_code_server{mod_pool={[],Counter+1}}}
end;
handle_call(paths, _From, Config) ->
{reply, Config#elixir_code_server.paths, Config};
handle_call(Request, _From, Config) ->
{stop, {badcall, Request}, Config}.
@@ -107,8 +111,11 @@ handle_cast({unload_files, Files}, Config) ->
Unloaded = lists:foldl(fun(File, Acc) -> orddict:erase(File, Acc) end, Current, Files),
{noreply, Config#elixir_code_server{loaded=Unloaded}};
handle_cast({return_module_name, H}, #elixir_code_server{mod_pool={T, Counter}} = Config) ->
{noreply, Config#elixir_code_server{mod_pool={[H|T], Counter}}};
handle_cast({return_module_name, H}, #elixir_code_server{mod_pool={T,Counter}} = Config) ->
{noreply, Config#elixir_code_server{mod_pool={[H|T],Counter}}};
handle_cast({paths, PA, PZ}, #elixir_code_server{} = Config) ->
{noreply, Config#elixir_code_server{paths={PA,PZ}}};
handle_cast(Request, Config) ->
{stop, {badcast, Request}, Config}.
+11 -15
View File
@@ -29,7 +29,7 @@ quoted(Forms, File, Dest) ->
put(elixir_compiled, []),
elixir_lexical:run(File, Dest, fun
(Pid) ->
Env = elixir:env_for_eval([{line, 1}, {file, File}]),
Env = elixir:env_for_eval([{line,1},{file,File}]),
eval_forms(Forms, [], Env#{lexical_tracker := Pid})
end),
lists:reverse(get(elixir_compiled))
@@ -106,15 +106,15 @@ options(nil) ->
false -> [];
Str when is_list(Str) ->
case erl_scan:string(Str) of
{ok, Tokens, _} ->
{ok,Tokens,_} ->
case erl_parse:parse_term(Tokens ++ [{dot, 1}]) of
{ok, List} when is_list(List) -> List;
{ok, Term} -> [Term];
{error, _Reason} ->
{ok,List} when is_list(List) -> List;
{ok,Term} -> [Term];
{error,_Reason} ->
io:format("Ignoring bad term in ~ts\n", [Key]),
[]
end;
{error, {_, _, _Reason}, _} ->
{error, {_,_,_Reason}, _} ->
io:format("Ignoring bad term in ~ts\n", [Key]),
[]
end
@@ -160,7 +160,7 @@ return_module_name(I) ->
allows_fast_compilation({'__block__', _, Exprs}) ->
lists:all(fun allows_fast_compilation/1, Exprs);
allows_fast_compilation({defmodule, _, _}) -> true;
allows_fast_compilation({defmodule,_,_}) -> true;
allows_fast_compilation(_) -> false.
%% INTERNAL API
@@ -181,7 +181,7 @@ inner_module(Forms, Options, Bootstrap, #{file := File} = E, Callback) when
is_list(Forms), is_list(Options), is_boolean(Bootstrap), is_function(Callback) ->
Source = elixir_utils:characters_to_list(File),
case compile:noenv_forms([no_auto_import()|Forms], [return, {source, Source}|Options]) of
case compile:noenv_forms([no_auto_import()|Forms], [return,{source,Source}|Options]) of
{ok, Module, Binary, Warnings} ->
format_warnings(Bootstrap, Warnings),
{module, Module} = code:load_binary(Module, beam_location(E), Binary),
@@ -207,7 +207,7 @@ no_auto_import() ->
core() ->
{ok, _} = application:ensure_all_started(elixir),
New = orddict:from_list([{docs, false}, {internal, true}]),
New = orddict:from_list([{docs,false},{internal,true}]),
Merge = fun(_, _, Value) -> Value end,
Update = fun(Old) -> orddict:merge(Merge, Old, New) end,
_ = elixir_config:update(compiler_options, Update),
@@ -233,9 +233,7 @@ core_main() ->
<<"lib/elixir/lib/macro.ex">>,
<<"lib/elixir/lib/code.ex">>,
<<"lib/elixir/lib/module/locals_tracker.ex">>,
<<"lib/elixir/lib/kernel/def.ex">>,
<<"lib/elixir/lib/kernel/typespec.ex">>,
<<"lib/elixir/lib/behaviour.ex">>,
<<"lib/elixir/lib/exception.ex">>,
<<"lib/elixir/lib/protocol.ex">>,
<<"lib/elixir/lib/stream/reducers.ex">>,
@@ -257,10 +255,8 @@ core_main() ->
binary_to_path({ModuleName, Binary}, CompilePath) ->
Path = filename:join(CompilePath, atom_to_list(ModuleName) ++ ".beam"),
case file:write_file(Path, Binary) of
ok -> Path;
{error, Reason} -> error('Elixir.File.Error':exception([{action, "write to"}, {path, Path}, {reason, Reason}]))
end.
ok = file:write_file(Path, Binary),
Path.
%% ERROR HANDLING
+36 -32
View File
@@ -52,11 +52,16 @@ store_definition(Line, Kind, CheckClauses, Call, Body, Pos) ->
%% Check if there is a file information in the definition.
%% If so, we assume this come from another source and
%% we need to linify taking into account keep line numbers.
{Location, Key} =
case elixir_utils:meta_location(Meta) of
{_, _} = KeepLocation -> {KeepLocation, keep};
nil -> {nil, line}
end,
{Location, Key} = case lists:keyfind(file, 1, Meta) of
{file, KeepFile} when is_binary(KeepFile) ->
case lists:keyfind(keep, 1, Meta) of
{keep, KeepLine} when is_integer(KeepLine) -> KeepLine;
_ -> KeepLine = 0
end,
{{KeepFile, KeepLine}, keep};
_ ->
{nil, line}
end,
LinifyArgs = elixir_quote:linify(Line, Key, Args),
LinifyGuards = elixir_quote:linify(Line, Key, Guards),
@@ -74,8 +79,7 @@ store_definition(Line, Kind, CheckClauses, Name, Args, Guards, Body, KeepLocatio
elixir_locals:record_definition(Tuple, Kind, Module),
Location = retrieve_location(KeepLocation, Module),
{Function, Defaults, Super} = translate_definition(Kind, Line, Name, Args, Guards, Body, E),
run_on_definition_callbacks(Kind, Line, Module, Name, Args, Guards, expr_from_body(Line, Body), E),
{Function, Defaults, Super} = translate_definition(Kind, Line, Module, Name, Args, Guards, Body, E),
DefaultsLength = length(Defaults),
elixir_locals:record_defaults(Tuple, Kind, Module, DefaultsLength),
@@ -150,7 +154,7 @@ compile_super(_Module, _, _E) -> ok.
%% Translate the given call and expression given
%% and then store it in memory.
translate_definition(Kind, Line, Name, Args, Guards, Body, E) when is_integer(Line) ->
translate_definition(Kind, Line, Module, Name, Args, Guards, Body, E) when is_integer(Line) ->
Arity = length(Args),
{EArgs, EGuards, EBody, _} = elixir_exp_clauses:def(fun elixir_def_defaults:expand/2,
@@ -162,6 +166,7 @@ translate_definition(Kind, Line, Name, Args, Guards, Body, E) when is_integer(Li
{Unpacked, Defaults} = elixir_def_defaults:unpack(Kind, Name, EArgs, S),
{Clauses, Super} = translate_clause(Body, Line, Kind, Unpacked, EGuards, EBody, S),
run_on_definition_callbacks(Kind, Line, Module, Name, EArgs, EGuards, EBody, E),
Function = {function, Line, Name, Arity, Clauses},
{Function, Defaults, Super}.
@@ -171,7 +176,7 @@ translate_clause(nil, Line, Kind, _Args, _Guards, _Body, #elixir_scope{file=File
elixir_errors:form_error([{line, Line}], File, ?MODULE, {missing_do, Kind});
translate_clause(_, Line, Kind, Args, Guards, Body, S) ->
{TClause, TS} = elixir_clauses:clause(Line,
fun elixir_translator:translate_args/2, Args, Body, Guards, S),
fun elixir_translator:translate_args/2, Args, Body, Guards, true, S),
FClause = case is_macro(Kind) of
true ->
@@ -196,7 +201,7 @@ translate_clause(_, Line, Kind, Args, Guards, Body, S) ->
expr_from_body(_Line, nil) -> nil;
expr_from_body(_Line, [{do, Expr}]) -> Expr;
expr_from_body(Line, Else) -> {'try', [{line, Line}], [Else]}.
expr_from_body(Line, Else) -> {'try', [{line,Line}], [Else]}.
is_macro(defmacro) -> true;
is_macro(defmacrop) -> true;
@@ -267,8 +272,8 @@ split_definition([{Tuple, defmacrop, _Line, _Location, _Body}|T], Unreachable,
split_definition(T, Unreachable, Def, Defp, Defmacro, [Tuple|Defmacrop],
Exports, Functions);
split_definition([], Unreachable, Def, Defp, Defmacro, Defmacrop, Exports, {Head, Tail}) ->
{Def, Defp, Defmacro, Defmacrop, Exports, Head ++ Tail, Unreachable}.
split_definition([], _Unreachable, Def, Defp, Defmacro, Defmacrop, Exports, {Head, Tail}) ->
{Def, Defp, Defmacro, Defmacrop, Exports, Head ++ Tail}.
%% Helpers
@@ -277,7 +282,7 @@ export(Kind, {Name, Arity}) when Kind == defmacro; Kind == defmacrop ->
export(Kind, {Name, Arity}) when Kind == def; Kind == defp ->
{Name, Arity}.
function_for_stored_definition(Line, {Name, Arity}, Clauses) ->
function_for_stored_definition(Line, {Name,Arity}, Clauses) ->
{function, Line, Name, Arity, Clauses}.
add_definition(_Line, nil, Body, {Head, Tail}) ->
@@ -320,7 +325,7 @@ store_each(Check, Kind, File, Location, Module, Defaults, {function, Line, Name,
check_valid_kind(Line, File, Name, Arity, Kind, StoredKind),
(Check and StoredCheck) andalso
check_valid_clause(Line, File, Name, Arity, Kind, Data, StoredLine, StoredFile),
check_valid_defaults(Line, File, Name, Arity, Kind, Defaults, StoredDefaults, LastDefaults, LastHasBody);
check_valid_defaults(Line, File, Name, Arity, Kind, Defaults, LastDefaults, LastHasBody);
[] ->
FinalLine = Line,
FinalLocation = Location,
@@ -340,7 +345,7 @@ check_valid_kind(Line, File, Name, Arity, Kind, StoredKind) ->
check_valid_clause(Line, File, Name, Arity, Kind, Data, StoredLine, StoredFile) ->
case ets:lookup_element(Data, ?last_def, 2) of
{Name, Arity} -> [];
{Name,Arity} -> [];
[] -> [];
_ ->
Relative = elixir_utils:relative_to_cwd(elixir_utils:relative_to_cwd(StoredFile)),
@@ -348,19 +353,19 @@ check_valid_clause(Line, File, Name, Arity, Kind, Data, StoredLine, StoredFile)
{ungrouped_clause, {Kind, Name, Arity, StoredLine, Relative}})
end.
% Clause with defaults after clause with defaults
check_valid_defaults(Line, File, Name, Arity, Kind, Defaults, StoredDefaults, _, _) when Defaults > 0, StoredDefaults > 0 ->
% Any clause after clause with defaults (body less does not count)
check_valid_defaults(Line, File, Name, Arity, Kind, _, StoredDefaults, true) when StoredDefaults > 0 ->
elixir_errors:form_error([{line, Line}], File, ?MODULE,
{clauses_with_defaults, {Kind, Name, Arity}});
% Clause with defaults after clause(s) without defaults
check_valid_defaults(Line, File, Name, Arity, Kind, Defaults, 0, 0, _) when Defaults > 0 ->
elixir_errors:form_warn([{line, Line}], File, ?MODULE, {out_of_order_defaults, {Kind, Name, Arity}});
% Clause without defaults directly after clause with defaults (body less does not count)
check_valid_defaults(Line, File, Name, Arity, Kind, 0, _, LastDefaults, true) when LastDefaults > 0 ->
elixir_errors:form_warn([{line, Line}], File, ?MODULE,
{out_of_order_defaults, {Kind, Name, Arity}});
% Clause without defaults
check_valid_defaults(_Line, _File, _Name, _Arity, _Kind, 0, _, _, _) -> [].
check_valid_defaults(_Line, _File, _Name, _Arity, _Kind, 0, _, _) -> [];
% Clause with defaults after clause without defaults
check_valid_defaults(Line, File, Name, Arity, Kind, _, 0, _) ->
elixir_errors:form_warn([{line, Line}], File, ?MODULE, {out_of_order_defaults, {Kind, Name, Arity}});
% Clause with defaults after clause with defaults
check_valid_defaults(Line, File, Name, Arity, Kind, _, _, _) ->
elixir_errors:form_error([{line, Line}], File, ?MODULE,
{clauses_with_defaults, {Kind, Name, Arity}}).
check_previous_defaults(Line, Module, Name, Arity, Kind, Defaults, E) ->
Matches = ets:match(elixir_module:defs_table(Module), {{Name, '$2'}, '$1', '_', '_', '_', '_', {'$3', '_', '_'}}),
@@ -401,7 +406,7 @@ assert_valid_name(_Line, _Kind, _Name, _Args, _S) ->
format_error({bodyless_fun, Kind, {Name, Arity}}) ->
io_lib:format("bodyless clause provided for nonexistent ~ts ~ts/~B", [Kind, Name, Arity]);
format_error({no_module, {Kind, Name, Arity}}) ->
format_error({no_module,{Kind,Name,Arity}}) ->
io_lib:format("cannot define function outside module, invalid scope for ~ts ~ts/~B", [Kind, Name, Arity]);
format_error({defs_with_defaults, Name, {Kind, Arity}, {K, A}}) when Arity > A ->
@@ -412,19 +417,18 @@ format_error({defs_with_defaults, Name, {Kind, Arity}, {K, A}}) when Arity < A -
io_lib:format("~ts ~ts/~B conflicts with defaults from ~ts ~ts/~B",
[Kind, Name, Arity, K, Name, A]);
format_error({clauses_with_defaults, {Kind, Name, Arity}}) ->
format_error({clauses_with_defaults,{Kind,Name,Arity}}) ->
io_lib:format("~ts ~ts/~B has default values and multiple clauses, "
"define a function head with the defaults", [Kind, Name, Arity]);
format_error({out_of_order_defaults, {Kind, Name, Arity}}) ->
io_lib:format("multiple clauses with default values should define a function head with the defaults, "
"~ts ~ts/~B has multiple clauses and defines defaults in a clause with a body", [Kind, Name, Arity]);
format_error({out_of_order_defaults,{Kind,Name,Arity}}) ->
io_lib:format("clause with defaults should be the first clause in ~ts ~ts/~B", [Kind, Name, Arity]);
format_error({ungrouped_clause, {Kind, Name, Arity, OrigLine, OrigFile}}) ->
format_error({ungrouped_clause,{Kind,Name,Arity,OrigLine,OrigFile}}) ->
io_lib:format("clauses for the same ~ts should be grouped together, ~ts ~ts/~B was previously defined (~ts:~B)",
[Kind, Kind, Name, Arity, OrigFile, OrigLine]);
format_error({changed_kind, {Name, Arity, Previous, Current}}) ->
format_error({changed_kind,{Name,Arity,Previous,Current}}) ->
io_lib:format("~ts ~ts/~B already defined as ~ts", [Current, Name, Arity, Previous]);
format_error({no_alias, Atom}) ->
+8 -7
View File
@@ -62,14 +62,13 @@ import_function(Meta, Name, Arity, E) ->
require_function(Meta, Receiver, Name, Arity, E) ->
case is_element({Name, Arity}, get_optional_macros(Receiver)) of
true -> false;
false ->
elixir_lexical:record_remote(Receiver, ?m(E, function), ?m(E, lexical_tracker)),
remote_function(Meta, Receiver, Name, Arity, E)
false -> remote_function(Meta, Receiver, Name, Arity, E)
end.
remote_function(Meta, Receiver, Name, Arity, E) ->
check_deprecation(Meta, Receiver, Name, Arity, E),
elixir_lexical:record_remote(Receiver, ?m(E, lexical_tracker)),
case elixir_rewrite:inline(Receiver, Name, Arity) of
{AR, AN} -> {remote, AR, AN, Arity};
false -> {remote, Receiver, Name, Arity}
@@ -146,7 +145,7 @@ do_expand_import(Meta, {Name, Arity} = Tuple, Args, Module, E, Result) ->
elixir_locals:record_import(Tuple, Receiver, Module, ?m(E, function)),
{ok, Receiver, expand_macro_named(Meta, Receiver, Name, Arity, Args, E)};
{import, Receiver} ->
case expand_require([{require, false}|Meta], Receiver, Tuple, Args, E) of
case expand_require([{require,false}|Meta], Receiver, Tuple, Args, E) of
{ok, _, _} = Response -> Response;
error -> {ok, Receiver, Name, Args}
end;
@@ -168,7 +167,7 @@ expand_require(Meta, Receiver, {Name, Arity} = Tuple, Args, E) ->
Requires = ?m(E, requires),
case (Receiver == Module) orelse is_element(Receiver, Requires) orelse skip_require(Meta) of
true ->
elixir_lexical:record_remote(Receiver, ?m(E, function), ?m(E, lexical_tracker)),
elixir_lexical:record_remote(Receiver, ?m(E, lexical_tracker)),
{ok, Receiver, expand_macro_named(Meta, Receiver, Name, Arity, Args, E)};
false ->
Info = {unrequired_module, {Receiver, Name, length(Args), Requires}},
@@ -261,9 +260,11 @@ is_import(Meta) ->
{import, _} = Import ->
case lists:keyfind(context, 1, Meta) of
{context, _} -> Import;
false -> false
false ->
false
end;
false -> false
false ->
false
end.
% %% We've reached the macro wrapper fun, skip it with the rest
+3 -2
View File
@@ -18,7 +18,8 @@ new() ->
context_modules => [], %% modules defined in the current context
vars => [], %% a set of defined variables
export_vars => nil, %% a set of variables to be exported in some constructs
lexical_tracker => nil}. %% holds the lexical tracker pid
lexical_tracker => nil, %% holds the lexical tracker pid
local => nil}. %% the module to delegate local functions to
linify({Line, Env}) ->
Env#{line := Line}.
@@ -29,7 +30,7 @@ env_to_scope(#{module := Module, file := File, function := Function, context :=
env_to_scope_with_vars(Env, Vars) ->
(env_to_scope(Env))#elixir_scope{
vars=orddict:from_list(Vars),
counter=[{'_', length(Vars)}]
counter=[{'_',length(Vars)}]
}.
%% SCOPE MERGING

Some files were not shown because too many files have changed in this diff Show More