Compare commits

..
84 Commits
Author SHA1 Message Date
Schnittchen a1fb6c0d0e Use System.os_time as reference in Mix.Utils.last_modified_and_size/1 (#8502) 2018-12-11 12:51:54 +01:00
Ivan Mironov 4f4aad2cd4 Fix direct Logger.log call in case of compile_time_purge_matching logger option (#8391) 2018-11-20 17:43:27 +01:00
Alan Walton d0f5236c8e Fix misleading doc string (#8355)
naive_datetime_to_iso_days takes a datetime without time zone
2018-11-02 16:57:05 +01:00
Alan Walton 2b95813d98 Fix copy/paste error in doc string (#8356)
Doc string for split/3 seems to have been copied from contains?/1, with references left behind to true and false return values.
2018-11-02 14:16:21 +01:00
José Valim eb5679bfcc Release v1.7.4 2018-10-24 20:11:49 +02:00
Fernando Tapia Rico e38ae98c3a Allow typespec attrs to be used as module attrs (#8327)
Port of: https://github.com/elixir-lang/elixir/commit/c190f09d5cbb1e79b510ea4332c65a7717aa9eb8
2018-10-24 13:05:53 +02:00
Eric Meadows-Jönsson 71a537b950 Add --no-load-deps flag to deps.loadpaths task (#8256) 2018-10-09 22:44:58 +02:00
José Valim 7087149bfa Run the formatter 2018-10-09 20:56:25 +02:00
José Valim b4b1947a22 Ensure eval_quoted properly resets last definition, closes #8261
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-10-09 20:49:41 +02:00
Po Chen a33d9116ab Expand paths so mix format path\for\windows.ex works (#8147) 2018-10-09 13:32:43 +02:00
Gabe Jackson 7d744ebc84 Ensure that mix --cover displays correct coverage in an umbrella app (#8176)
`:cover.start/0` initializes the internal database where coverage data
on all compiled modules is stored. Prior to this change, the database
wasn't cleared out between sub-apps in an umbrella app. When
`:cover.analyse/2` is called, it runs against the entire contents of the
internal database. In an umbrella app, the coverage report for App1
would show App1, the report for App2 would show App1 and App2, App3
would have App1, App2, and App3, and so on.

Closes #8086
2018-10-09 13:32:23 +02:00
Paul Wilson 3e6c6986f2 Fix for converting from negative iso days on New Year in a leap year (#8145) 2018-10-09 13:31:49 +02:00
Eric Meadows-Jönsson f167716f53 Unload previous archive versions before building (#8253)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-10-07 17:03:58 +02:00
José Valim 0cdf6d28b1 Consider that Macro may have not been bootstrapped 2018-09-27 14:50:59 +02:00
José Valim e4c1e3d262 Format kernel accordingly 2018-09-27 14:18:51 +02:00
José Valim 3f6313906d Avoid range creation in Calendar.ISO.valid_date?/3 2018-09-27 13:08:52 +02:00
Saša Jurić 0089a40a33 Fix typespec (#8207) 2018-09-20 11:58:46 +02:00
Tobiasz Małecki 549745fa5e Inspect.Algebra typespecs improvement (#8047)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-09-20 11:07:15 +02:00
Mike Schutte ac41358b5a Fix small curly typo in tuple docs (#8162) 2018-09-03 16:54:56 +02:00
As-har Dweedar 0db2ad6953 Fix warning for unused variable (#8158) 2018-09-01 20:42:48 +02:00
José Valim 8ca85ed2a8 Release v1.7.3 2018-08-24 20:46:27 +02:00
José Valim af64fe7e98 Consider :runtime and :app from mix.exs (#8109)
Since those values are not stored on Hex, we should not
expect them to be available on Mix.Dep.cached. Instead
we traverse the deps in `mix.exs` to lift this information.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-08-24 20:13:26 +02:00
Fernando Tapia Rico 28cf40fe03 Fix arity of try/1 in :elixir_import.special_form (#8079)
Fixes #8078

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-08-14 12:57:12 +02:00
José Valim d38a189907 Do not use protocols while consolidating
This avoids a race condition in tests.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-08-06 07:47:22 +02:00
José Valim 2b338092b6 Release v1.7.2 2018-08-05 09:01:26 +02:00
Scott Riley 557b779bd4 Move parentheses in System.cmd() docs (#8046) 2018-08-04 18:44:11 +02:00
José Valim ece40480f6 Update CHANGELOG 2018-08-04 16:12:28 +02:00
José Valim a77445c46b Revert "Fix errors with ref/4 IEx helper (#8016)"
This reverts commit b9d6f4f9c1.
2018-08-04 15:37:15 +02:00
José Valim 4d55fa6814 Accordingly mark top level optional dependencies from child deps (#8035)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-08-04 14:08:33 +02:00
Fernando Tapia Rico b9d6f4f9c1 Fix errors with ref/4 IEx helper (#8016)
* Fix errors with ref/4 IEx helper

In addition, include documentation for that function.

* Update helpers.ex

* Add IEx.Helpers.ref/* tests

* Use examples that do not return ArgumentError

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-08-04 14:07:37 +02:00
Fernando Tapia Rico b0cf76c74c Fix year in negative datetimes with offset (#8038) 2018-08-04 13:18:41 +02:00
José Valim 7841fbb8e0 Do not fail suite if there are no tests to run
This matters in umbrella apps where some apps may not
have Elixir tests.

Closes #8040

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-08-04 00:46:04 +02:00
José Valim f5773fed42 Take negative years into account in DateTime (#8033)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-08-03 11:39:30 +02:00
José Valim e2b8ab9a0d Unify alias doc handling
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-31 23:20:35 +02:00
Dave Lucia 1dc6d10f30 mix help when theres a task and alias (#8020)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-31 23:20:30 +02:00
José Valim e7138fb2c6 Avoid Mix.ProjectStack deadlock, closes #8024
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-31 21:29:45 +02:00
José Valim 04ecc05adc Remove warnings for docs in the same clause
Unfortunately this leads to false positives when trying
to override the docs of an overridable definition.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-28 21:33:46 +02:00
José Valim 8aab53b941 Release v1.7.1 2018-07-26 21:33:18 +02:00
Michał Muskała 07c276ab5c Fix issues with dialyzer infinite loop (#7993)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-26 21:30:35 +02:00
David Cuddeback 89e3a81adc Skip intermediate parts when creating NaiveDateTime 2018-07-26 11:37:43 +02:00
David Cuddeback 9752f1ce05 Optimize ISO-8601 parsing for UTC 2018-07-26 11:37:43 +02:00
José Valim 06e5ec2d4c Release v1.7.0 2018-07-25 22:36:59 +02:00
José Valim b6d3f29b69 Allow to prune metadata while escaping (#7949)
We use this option in ExUnit as we are escaping
the code to eventually convert it to a string
representation and therefore the metadata is not
relevant.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-25 00:56:53 +02:00
Boyd Multerer bfdaf3f8d1 Update Process.info spec to reflect the possible nil return value (#7977)
The @spec for it did not reflect that possible return value - which causes dialyzer to throw errors if you check for that condition. Now the spec allows for a return value of nil.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-25 00:56:28 +02:00
José Valim bc26f10040 Mark contextual_vars as private
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-25 00:56:07 +02:00
Tobiasz Małecki 52868e556d Added missing info about new StringIO.open/3 function (#7970) 2018-07-22 19:56:17 +02:00
José Valim 04c45b031a Use quote fragments to remove duplication and optimize calendar parsing (#7951)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-21 10:48:38 +02:00
José Valim d410466ce4 Format lib/elixir/lib/code.ex 2018-07-20 16:36:11 +02:00
José Valim fe3c263599 Remove other hard deprecations 2018-07-20 16:26:14 +02:00
José Valim 7558c9a023 Remove warning on since module attribute 2018-07-20 09:50:31 +02:00
José Valim 0d30dbfd24 Properly annotate key errors for structs, closes #7935 2018-07-19 22:41:45 +02:00
José Valim 793bbe6e3c Move some runtime deprecations to compile time 2018-07-19 22:36:21 +02:00
Jean-Philippe Cugnet 3318d33d2e Fix a typo in the unnecessary quotes warning (#7934)
[ci skip]

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-19 20:12:30 +02:00
José Valim b6d7769674 Release v1.7.0-rc.1 2018-07-19 12:09:05 +02:00
José Valim dc3a56c44f Remove leftover spaces
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:40:45 +02:00
Callum Dempsey Leach ea9cb84eb1 Clarify Application.get_env by illustrating a use case (#7929)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:40:41 +02:00
José Valim b7b7282a22 Optimize metadata merging and ensure no nil leakage (#7927)
Closes #7926

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:40:32 +02:00
José Valim d3d1833d47 Properly populate top_level field of deps (#7931)
Closes #7930

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:40:26 +02:00
Gary Rennie 7d427719fe Fix nested use of Mix.Config.eval!/2 (#7925)
Previously, if a config file uses Mix.Config.eval!/2 then it would fail with the
following error:

 > ** (RuntimeError) could not set configuration via Mix.Config. This usually
 >  means you are trying to execute a configuration file directly instead of
 > using the proper command, such as mix loadconfig
 > code: assert Mix.Config.eval!(fixture_path("configs/nested_import.exs")) ==
 > stacktrace:
 >   (mix) lib/mix/config.ex:71: Mix.Config.raise_improper_use!/0
 >   (mix) lib/mix/config.ex:222: Mix.Config.eval!/2
 >   lib/mix/test/mix/config_test.exs:110: (test)

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:40:17 +02:00
Tobiasz Małecki 9812b74a2c Added missing @doc :since metadata (#7922)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:40:01 +02:00
Tobiasz Małecki aebc7e2fe1 Fixed indentation in StringIO.open/3 examples (#7920)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:39:57 +02:00
Fernando Tapia Rico f0aeb7136f Use "time zone" instead of "timezone" everywhere (#7917)
There is a mix of "timezone" and "time zone" in the codebase. For what I read, "time zone" is usually more correct.

In addition, there are some variables and types named `time_zone`, so I think the best option is to go with "time zone".

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:39:50 +02:00
Tobiasz Małecki d92a450637 fixed typo in float moduledoc (#7915)
[ci skip]

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:39:44 +02:00
Andrea Leopardi afb4667cd0 Add an additional example to the docs for String.jaro_distance/1
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:39:39 +02:00
Fernando Tapia Rico eb50a09679 Clarify documentation of @compile :inline flag (#7909)
[ci skip]

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:39:30 +02:00
Henrik Larsson 2f8ecec32c Clarify how to assert on exits from linked processes (#7904)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:39:17 +02:00
Fernando Tapia Rico 4354938168 Remove duplicated sentence from Map's doc (#7907)
[ci skip]

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 19:39:13 +02:00
José Valim b06d82c93e Allow all args on Mix.Dep.loaded
Even though the API was private, developers were abusing it.
So we allow it to work for now until we remove it in future
versions.

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-18 10:36:59 +02:00
Myron Marston 3dbe8a6661 Changelog: explain mix test --failed more accurately. (#7911)
`mix test --failed` runs all tests that failed the last time they ran,
even if they were not included in the last run of the test suite. This
is important, because it means that you can run individual failed tests
to focus on fixing them without worrying about mix losing track of the
other failed tests.
2018-07-16 09:21:54 +02:00
José Valim 6932e25159 Doc fixes 2018-07-15 22:24:56 +02:00
José Valim 22abd6a48e Fix CHANGELOG typo 2018-07-14 14:21:39 +02:00
José Valim 05f5073cd1 Clarify that any metadata is accepted, only some are shown 2018-07-14 11:51:39 +02:00
Tobiasz Małecki 18d96c2fd5 Add Function docs to "Basic Types" group (#7900)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-13 23:45:26 +02:00
Wojtek Mach ea04ec8f81 Clarify how to configure :test_coverage (#7896)
[ci skip]

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-13 23:45:18 +02:00
Wojtek Mach 0a5d633a5e Update --cover docs (#7897)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-13 23:45:05 +02:00
José Valim 7392d736c4 Print checksums headings 2018-07-13 15:17:14 +02:00
José Valim 1164784b8e Release v1.7.0-rc.0 2018-07-13 14:43:27 +02:00
José Valim 6694ddbd2f Properly add parens around when with keywords as argument 2018-07-13 00:07:26 +02:00
José Valim 85a4d55efb Update CHANGELOG 2018-07-12 20:28:19 +02:00
Arkadiusz Gil 9b238e0316 Ignore unknown child info in Logger.Translator (#7892)
This prevents Logger application from crashing when supervisors report
children progress with fields unknown to Logger.Translator.

Closes #7889

Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-12 20:15:08 +02:00
László Bácsi ca82388792 Show documentation metadata in IEx (only since and deprecated for now) (#7886) 2018-07-12 20:07:45 +02:00
Lukasz Samson b33dd12d86 Fix error when :trim_bom is used with :encoding
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-12 14:37:14 +02:00
Dimitrios Zorbas c36b2c9070 Fix syntax highlighting of Calendar.ISO docs (#7880)
Signed-off-by: José Valim <jose.valim@plataformatec.com.br>
2018-07-12 12:44:41 +02:00
José Valim ac75cdbe05 Prepare for v1.7 release 2018-07-12 11:57:29 +02:00
338 changed files with 7442 additions and 13709 deletions
+4 -1
View File
@@ -5,12 +5,15 @@ env:
global:
- ELIXIR_ASSERT_TIMEOUT=2000
matrix:
- OTP_RELEASE=OTP-19.0
- OTP_RELEASE=OTP-19.1
- OTP_RELEASE=OTP-19.2
- OTP_RELEASE=OTP-19.3
- OTP_RELEASE=OTP-20.0
- OTP_RELEASE=OTP-20.1
- OTP_RELEASE=OTP-20.2
- OTP_RELEASE=OTP-20.3
- OTP_RELEASE=OTP-21.0
- OTP_RELEASE=OTP-21.1
- OTP_RELEASE=maint
- OTP_RELEASE=master
+249 -153
View File
@@ -1,214 +1,310 @@
# Changelog for Elixir v1.8
# Changelog for Elixir v1.7
Elixir v1.8 comes with many improvements at the infrastructure level, improving compilation time, speeding up common patterns, and adding features around introspection of the system.
Elixir v1.7 is the last release to support Erlang/OTP 19. We recommend everyone to migrate to Erlang/OTP 20+.
## Custom struct inspections
## Documentation metadata
Elixir now provides a derivable implementation of the `Inspect` protocol. In a nutshell, this means it is really easy to filter data from your data structures whenever they are inspected. For example, imagine you have a user struct with security and privacy sensitive information:
Elixir v1.7 implements [EEP 48](http://erlang.org/eep/eeps/eep-0048.html). EEP 48 aims to bring documentation interoperability across all languages running on the Erlang VM. The documentation format proposed by EEP 48 also supports metadata, which is now fully exposed to Elixir developers:
```elixir
defmodule User do
defstruct [:id, :name, :age, :email, :encrypted_password]
@moduledoc "A brand new module"
@moduledoc authors: ["Jane", "Mary"], since: "1.4.0"
```
Passing metadata is supported on `@doc`, `@moduledoc` and `@typedoc`.
To access the new documentation format, developers should use `Code.fetch_docs/1`. The old documentation format is no longer available and the old `Code.get_docs/2` function will return `nil` accordingly.
Tools like IEx and ExDoc have been updated to leverage the new format and show relevant metadata to users. While Elixir allows any metadata to be given, those tools currently exhibit only `:deprecated` and `:since`. Other keys may be shown in the future.
## The `__STACKTRACE__` construct
Erlang/OTP 21.0 introduces a new way to retrieve the stacktrace that is lexically scoped and no longer relies on side-effects like `System.stacktrace/0` does. Before one would write:
```elixir
try do
... something that may fail ...
rescue
e ->
log(e, System.stacktrace())
reraise(e, System.stacktrace())
end
```
By default, if you inspect a user via `inspect(user)`, it will include all fields. This can cause fields such as `:email` and `:encrypted_password` to appear in logs, error reports, etc. You could always define a custom implementation of the `Inspect` protocol for such cases but Elixir v1.8 makes it simpler by allowing you to derive the `Inspect` protocol:
In Elixir v1.7, this can be written as:
```elixir
defmodule User do
@derive {Inspect, only: [:id, :name, :age]}
defstruct [:id, :name, :age, :email, :encrypted_password]
try do
... something that may fail ...
rescue
e ->
log(e, __STACKTRACE__)
reraise(e, __STACKTRACE__)
end
```
Now all user structs will be printed with all remaining fields collapsed:
This change may also yield performance improvements in the future, since the lexical scope allows us to track precisely when a stacktrace is used and we no longer need to keep references to stacktrace entries after the `try` construct finishes.
#User<id: 1, name: "Jane", age: 33, ...>
Other parts of the exception system have been improved. For example, more information is provided in certain occurrences of `ArgumentError`, `ArithmeticError` and `KeyError` messages.
You can also pass `@derive {Inspect, except: [...]}` in case you want to keep all fields by default and exclude only some.
## Erlang/OTP logger integration
## Time zone database support
Erlang/OTP 21 includes a new `:logger` module. Elixir v1.7 fully integrates with the new `:logger` and leverages its metadata system. The `Logger.Translator` mechanism has also been improved to export metadata, allowing custom Logger backends to leverage information such as:
In Elixir v1.3, Elixir added four types, known as Calendar types, to work with dates and times: `Time`, `Date`, `NaiveDateTime` (without time zone) and `DateTime` (with time zone). Over the last releases we have added many enhancements to the Calendar types but the `DateTime` module always evolved at a slower pace since Elixir did not provide support for a time zone database.
* `:crash_reason` - a two-element tuple with the throw/error/exit reason as first argument and the stacktrace as second
Elixir v1.8 now defines a `Calendar.TimeZoneDatabase` behaviour, allowing developers to bring in their own time zone databases. By defining an explicit contract for time zone behaviours, Elixir can now extend the `DateTime` API, adding functions such as `DateTime.shift_zone/3`. By default, Elixir ships with a time zone database called `Calendar.UTCOnlyTimeZoneDatabase` that only handles UTC.
* `:initial_call` - the initial call that started the process
Other Calendar related improvements include the addition of `Date.day_of_year/1`, `Date.quarter_of_year/1`, `Date.year_of_era/1`, and `Date.day_of_era/1`.
* `:registered_name` - the process registered name as an atom
## Faster compilation and other performance improvements
We recommend Elixir libraries that previously hooked into Erlang's `:error_logger` to hook into `Logger` instead, in order to support all current and future Erlang/OTP versions.
Due to improvements to the compiler made over the last year, Elixir v1.8 should compile code about 5% faster on average. This is yet another release where we have been able to reduce compilation times and provide a more joyful development experience to everyone.
## Other Logger improvements
The compiler also emits more efficient code for range checks in guards (such as `x in y..z`), for charlists with interpolation (such as `'foo #{bar} baz'`), and when working with records via the `Record` module.
Previously, Logger macros such as `debug`, `info`, and so on would always evaluate their arguments, even when nothing would be logged. From Elixir v1.7, the arguments are only evaluated when the message is logged.
Finally, EEx templates got their own share of optimizations, emitting more compact code that runs faster.
The Logger configuration system also accepts a new option called `:compile_time_purge_matching` that allows you to remove log calls with specific compile-time metadata. For example, to remove all logger calls from application `:foo` with level lower than `:info`, as well as remove all logger calls from `Bar.foo/3`, you can use the following configuration:
## Improved instrumentation and ownership with `$callers`
```elixir
config :logger,
compile_time_purge_matching: [
[application: :foo, level_lower_than: :info],
[module: Bar, function: "foo/3"]
]
```
The `Task` module is one of the most common ways to spawn light-weight processes to perform work concurrently. Whenever you spawn a new process, Elixir annotates the parent of that process through the `$ancestors` key. This information can be used by instrumentation tools to track the relationship between events occurring within multiple processes. However, many times, tracking only the `$ancestors` is not enough.
## ExUnit improvements
For example, we recommend developers to always start tasks under a supervisor. This provides more visibility and allows us to control how those tasks are terminated when a node shuts down. In your code, this can be done by invoking something like: `Task.Supervisor.start_child(MySupervisor, task_specification)`. This means that, although your code is the one who invokes the task, the actual parent of the task would be the supervisor, as the supervisor is the one spawning it. We would list the supervisor as one of the `$ancestors` for the task, but the relationship between your code and the task is lost.
ExUnit has also seen its own share of improvements. Assertions such as `assert some_fun(arg1, arg2, arg3)` will now include the value of each argument in the failure report:
In Elixir v1.8, we now track the relationship between your code and the task via the `$callers` key in the process dictionary, which aligns well with the existing `$ancestors` key. Therefore, assuming the `Task.Supervisor` call above, we have:
```
1) test function call arguments (TestOneOfEach)
lib/ex_unit/examples/one_of_each.exs:157
Expected truthy, got false
code: assert some_vars(1 + 2, 3 + 4)
arguments:
[your code] -- calls --> [supervisor] ---- spawns --> [task]
# 1
3
which means we store the following relationships:
# 2
7
[your code] [supervisor] <-- ancestor -- [task]
^ |
|--------------------- caller ---------------------|
stacktrace:
lib/ex_unit/examples/one_of_each.exs:158: (test)
```
When a task is spawned directly from your code, without a supervisor, then the process running your code will be listed under both `$ancestors` and `$callers`.
Furthermore, failures in doctests are now colored and diffed.
This small feature is very powerful. It allows instrumentation and monitoring tools to better track and relate the events happening in your system. This feature can also be used by tools like the "Ecto Sandbox". The "Ecto Sandbox" allows developers to run tests concurrently against the database, by using transactions and an ownership mechanism where each process explicitly gets a connection assigned to it. Without `$callers`, every time you spawned a task that queries the database, the task would not know its caller, and therefore it would be unable to know which connection was assigned to it. This often meant features that relies on tasks could not be tested concurrently. With `$callers`, figuring out this relationship is trivial and you have more tests using the full power of your machine.
On the `mix test` side of things, there is a new `--failed` flag that runs all tests that failed the last time they ran. Finally, coverage reports generated with `mix test --cover` include a summary out of the box:
## v1.8.2 (2019-05-11)
```
Generating cover results ...
### 1. Bug fixes
Percentage | Module
-----------|--------------------------
100.00% | Plug.Exception.Any
100.00% | Plug.Adapters.Cowboy2.Stream
100.00% | Collectable.Plug.Conn
100.00% | Plug.Crypto.KeyGenerator
100.00% | Plug.Parsers
100.00% | Plug.Head
100.00% | Plug.Router.Utils
100.00% | Plug.RequestId
... | ...
-----------|--------------------------
77.19% | Total
```
#### EEx
* [EEx] Raise readable error message on bad EEx state
#### Elixir
* [Protocol] Ensure `:debug_info` is kept in protocols
#### Logger
* [Logger] Make sure Logger v1.8 does not get stuck in discard mode
* [Logger.Translator] Translate remote process crash in Logger
## v1.8.1 (2019-01-30)
### 1. Bug fixes
#### Elixir
* [Float] Fix rounding for subnormal floats
#### IEx
* [IEx] Fix `IEx.pry` crash when IEx isn't running
* [IEx.CLI] Add IEx warning when using `--remsh` with dumb terminal
* [IEx.Helpers] Sort results by arity on `h` helper
#### Mix
* [mix compile] Do not include optional dependencies in extra applications as it is incompatible with shared deps in umbrellas
## v1.8.0 (2019-01-14)
## v1.7.4 (2018-10-24)
### 1. Enhancements
#### EEx
* [EEx] Optimize the default template engine to compile and execute more efficiently
#### Elixir
* [Calendar] Add `Calendar.TimeZoneDatabase` and a `Calendar.UTCOnlyTimeZoneDatabase` implementation
* [Calendar] Add callbacks `day_of_year/3`, `quarter_of_year/3`, `year_of_era/1`, and `day_of_era/3`
* [Code.Formatter] Preserve user's choice of new line after most operators
* [Date] Add `Date.day_of_year/1`, `Date.quarter_of_year/1`, `Date.year_of_era/1`, and `Date.day_of_era/1`
* [DateTime] Add `DateTime.from_naive/3`, `DateTime.now/1`, and `DateTime.shift_zone/3`
* [File] Allow `:raw` option in `File.exists?/2`, `File.regular?/2`, and `File.dir?/2`
* [File] Allow POSIX time as an integer in `File.touch/2` and `File.touch!/2`
* [Inspect] Allow `Inspect` protocol to be derivable with the `:only`/`:except` options
* [Kernel] Do not propagate counters to variables in quote inside another quote
* [Kernel] Warn on ambiguous use of `::` and `|` in typespecs
* [Kernel] Add `:delegate_to` `@doc` metadata tag when using `defdelegate`
* [Kernel] Improve compile-time building of ranges via the `..` operator
* [Kernel] Compile charlist interpolation more efficiently
* [Kernel] Add `floor/1` and `ceil/1` guards
* [Kernel.SpecialForms] Add `:reduce` option to `for` comprehensions
* [List] Add `List.myers_difference/3` and `List.improper?/1`
* [Macro] Add `Macro.struct!/2` for proper struct resolution during compile time
* [Map] Optimize and merge nested maps `put` and `merge` operations
* [Range] Add `Range.disjoint?/2`
* [Record] Reduce memory allocation when updating multiple fields in a record
* [Registry] Allow associating a value on `:via` tuple
* [String] Add `String.bag_distance/2`
* [Task] Add `$callers` tracking to `Task` - this makes it easier to find which process spawned a task and use it for tracking ownership and monitoring
#### ExUnit
* [ExUnit] Add `ExUnit.after_suite/1` callback
* [ExUnit.Assertions] Show last N messages (instead of first N) from mailbox on `assert_receive` fail
#### IEx
* [IEx.Helpers] Add `port/1` and `port/2`
* [IEx.Server] Expose `IEx.Server.run/1` for custom IEx sessions with the ability to broker pry sessions
* [Kernel] Expand `left..right` at compile time in more cases, which leads to improved performance under different scenarios, especially on `x in left..right` expressions
#### Mix
* [Mix] Add `Mix.target/0` and `Mix.target/1` to control dependency management per target
* [Mix.Project] Add `:depth` and `:parents` options to `deps_paths/1`
* [mix archive.install] Add a timeout when installing archives
* [mix compile] Include optional dependencies in `:extra_applications`
* [mix escript.install] Add a timeout when installing escripts
* [mix format] Warn when the same file may be formatted by multiple `.formatter.exs`
* [mix test] Allow setting the maximum number of failures via `--max-failures`
* [mix test] Print a message instead of raising on unmatched tests inside umbrella projects
* [mix deps.loadpaths] Add `--no-load-deps` flag. This is useful for Rebar 3 compatibility
### 2. Bug fixes
#### Elixir
* [Calendar] Allow printing dates with more than 9999 years
* [Exception] Exclude deprecated functions in "did you mean?" hints
* [Float] Handle subnormal floats in `Float.ratio/1`
* [Kernel] Remove `Guard test tuple_size(...) can never succeed` Dialyzer warning on `try`
* [Kernel] Expand operands in `size*unit` bitstring modifier instead of expecting `size` and `unit` to be literal integers
* [Kernel] Do not deadlock on circular struct dependencies in typespecs
* [Kernel] Raise proper error message when passing flags to the Erlang compiler that Elixir cannot handle
* [Kernel] Do not leak variables in `cond` clauses with a single matching at compile-time clause
* [NaiveDateTime] Do not accept leap seconds in builder and parsing functions
* [String] Fix ZWJ handling in Unicode grapheme clusters
* [StringIO] Handle non-printable args in StringIO gracefully
#### IEx
* [IEx.Helpers] Use typespec info (instead of docs chunk) and properly format callbacks in `b/1`
#### Logger
* [Logger] Allow Logger backends to be dynamically removed when an application is shutting down
* [Calendar] Fix for converting from negative iso days on New Year in a leap year
* [Kernel] Ensure `@spec`, `@callback`, `@type` and friends can be read accordingly
* [Module] Avoid warnings when using Module.eval_quoted in the middle of existing definitions
#### Mix
* [mix compile] Ensure changes in deps propagate to all umbrella children - this fix a long standing issue where updating a dependency would not recompile all projects accordingly, requiring a complete removal of `_build`
* [mix compile] Avoid time drift when checking and updating compiler manifest files
* [mix compile.app] Respect the `:only` option between umbrella siblings
* [mix compile.protocols] Reconsolidate protocols if local dependencies are stale
* [mix deps] Properly mark dependencies with different `:system_env` as diverged
* [mix new] Use `--module` value when setting up filenames
* [mix archive.build] Unload previous archive versions before building
* [mix format] Expand paths so mix format `path\for\windows.ex` works
* [mix test] Ensure that `--cover` displays correct coverage in an umbrella app
## v1.7.3 (2018-08-24)
### 1. Bug fixes
#### ExUnit
* [ExUnit.Assertions] Do not attempt to expand `try/1` as it is a special form
#### Mix
* [mix compile.app] Do not include applications with `runtime: false` as a runtime dependency for applications coming from Hex
## v1.7.2 (2018-08-05)
### 1. Bug fixes
#### Elixir
* [DateTime] Take negative years into account in `DateTime.from_iso8601/1`
* [Kernel] Do not emit warnings for repeated docs over different clauses due to false positives
#### Mix
* [mix compile] Properly mark top-level dependencies as optional and as runtime. This fixes a bug where Mix attempted to start optional dependencies of a package when those optional dependencies were not available
* [mix compile] Avoid deadlock when a config has a timestamp later than current time
* [mix help] Show task and alias help when both are available
* [mix test] Do not fail suite if there are no test files
## v1.7.1 (2018-07-26)
### 1. Bug fixes
#### Elixir
* [Calendar] Work-around a Dialyzer bug that causes it to loop for a long time, potentially indefinitely
## v1.7.0 (2018-07-25)
### 1. Enhancements
#### Elixir
* [Calendar.ISO] Support negative dates in `Calendar.ISO`
* [Calendar] Add `Calendar.months_in_year/1` callback
* [Code] Add `Code.compile_file/2` that compiles files without leaving footprints on the system
* [Code] Add `Code.purge_compiler_modules/0` that purges any compiler module left behind. This is useful for live systems dynamically compiling code
* [Code] Add `Code.fetch_docs/1` that returns docs in the [EEP 48](http://erlang.org/eep/eeps/eep-0048.html) format
* [Date] Add `Date.months_in_year/1` function
* [DynamicSupervisor] Use the name of the `DynamicSupervisor` as the ID whenever possible
* [Exception] Provide "did you mean" suggestions on KeyError
* [Exception] Provide more information on ArithmeticError on Erlang/OTP 21+
* [Function] Add `Function` module with `capture/3`, `info/1` and `info/2` functions
* [GenServer] Support the new `handle_continue/2` callback on Erlang/OTP 21+
* [IO.ANSI] Add cursor movement to `IO.ANSI`
* [Kernel] Support adding arbitrary documentation metadata by passing a keyword list to `@doc`, `@moduledoc` and `@typedoc`
* [Kernel] Introduce `__STACKTRACE__` to retrieve the current stacktrace inside `catch`/`rescue` (this will be a requirement for Erlang/OTP 21+)
* [Kernel] Raise on unsafe variables in order to allow us to better track unused variables
* [Kernel] Warn when using `length` to check if a list is not empty on guards
* [Kernel] Add hints on mismatched `do`/`end` and others pairs
* [Kernel] Warn when comparing structs using the `>`, `<`, `>=` and `<=` operators
* [Kernel] Warn on unsupported nested comparisons such as `x < y < z`
* [Kernel] Warn if redefining documentation across clauses of the same definition
* [Kernel] Warn on unnecessary quotes around atoms, keywords and calls
* [Macro] Add `Macro.special_form?/2` and `Macro.operator?/2` that returns `true` if the given name/arity is a special form or operator respectively
* [Macro.Env] Add `Macro.Env.vars/1` and `Macro.Env.has_var?/2` that gives access to environment data without accessing private fields
* [Regex] Include endianness in the regex version. This allows regexes to be recompiled when an archive is installed in a system with a different endianness
* [Registry] Add `Registry.count/1` and `Registry.count_match/4`
* [String] Update to Unicode 11
* [StringIO] Add `StringIO.open/3`
* [System] Use ISO 8601 in `System.build_info/0`
#### ExUnit
* [ExUnit.Assertion] Print the arguments in error reports when asserting on a function call. For example, if `assert is_list(arg)` fails, the argument will be shown in the report
* [ExUnit.Diff] Improve diffing of lists when one list is a subset of the other
* [ExUnit.DocTest] Show colored diffs on failed doctests
* [ExUnit.Formatter] Excluded tests, via the `--exclude` and `--only` flags, are now shown as "Excluded" in reports. Tests skipped via `@tag :skip` are now exclusively shown as "Skipped" and in yellow
#### IEx
* [IEx.Helpers] Add `use_if_available/2`
* [IEx.Helpers] Allow `force: true` option in `recompile/1`
* [IEx.Helpers] Add `:allocators` pane to `runtime_info/1`
* [IEx.Helpers] Show documentation metadata in `h/1` helpers
#### Logger
* [Logger] Ensure nil metadata is always pruned
* [Logger] Only evaluate Logger macro arguments when the message will be logged
* [Logger] Add `:compile_time_purge_matching` to purge logger calls that match certain compile time metadata, such as module names and application names
* [Logger] Log to `:stderr` if a backend fails and there are no other backends
* [Logger] Allow translators to return custom metadata
* [Logger] Return `:crash_reason`, `:initial_call` and `:registered_name` as metadata in crash reports coming from Erlang/OTP
#### Mix
* [mix archive.install] Add support for the Hex organization via `--organization`
* [mix archive.uninstall] Support `--force` flag
* [mix compile] Improve support for external build tools such as `rebar`
* [mix deps] Include `override: true` in rebar dependencies to make the behaviour closer to how rebar3 works (although diverged deps are still marked as diverged)
* [mix escript.install] Add support for the Hex organization via `--organization`
* [mix escript.uninstall] Support `--force` flag
* [mix help] Also list aliases
* [mix local] Use ipv6 with auto fallback to ipv4 when downloading data
* [mix profile] Allow all profiling tasks to run programatically
* [mix test] Add `--failed` option that only runs previously failed tests
* [mix test] Print coverage summary by default when the `--cover` flag is given
* [Mix.Project] Add `Mix.Project.clear_deps_cache/0`
* [Mix.Project] Add `Mix.Project.config_mtime/0` that caches the config mtime values to avoid filesystem access
### 2. Bug fixes
#### Elixir
* [IO.ANSI.Docs] Fix table column alignment when converting docs to ANSI escapes
* [Code] Ensure `string_to_quoted` returns error tuples instead of raising in certain constructs
* [Code.Formatter] Consistently format keyword lists in function calls with and without parens
* [Code.Formatter] Do not break after `->` when there are only comments and one-line clauses
* [File] Allow the `:trim_bom` option to be used with `:encoding`
* [Kernel] Raise on unsafe variables as some of the code emitted with unsafe variables would not correctly propagate variables or would disable tail call optimization semantics
* [Kernel] Do not crash on dynamic sizes in binary generators with collectable into in comprehensions
* [Kernel] Do not crash on literals with non-unary size in binary generators with collectable into in comprehensions
* [Task] Improve error reports and exit reasons for failed tasks on Erlang/OTP 20+
#### ExUnit
* [ExUnit.Case] Raise proper error if `@tag` and `@moduletag` are used before `use ExUnit.Case`
* [ExUnit.Case] Raise proper error if `@describetag` is used outside of `describe/2` blocks
* [ExUnit.DocTest] Emit proper assertion error on doctests with invalid UTF-8
#### Mix
* [mix archive.install] Fetch optional dependencies when installing an archive from Git/Hex
* [mix compile] Properly track config files in umbrella projects and recompile when any relevant umbrella configuration changes
* [mix deps] Ensure the same dependency from different SCMs are tagged as diverged when those SCMs are remote and non-remote
* [mix deps] Ensure we re-run dependency resolution when overriding a skipped dep in umbrella
* [mix deps.compile] Perform clean builds for dependencies on outdated locks to avoid old modules from affecting future compilation
* [mix escript.install] Fetch optional dependencies when installing an escript from Git/Hex
### 3. Soft-deprecations (no warnings emitted)
None.
#### Elixir
* [Code] Deprecate `Code.load_file/2` in favor of `Code.compile_file/2`
* [Code] Deprecate `Code.loaded_files/0` in favor of `Code.required_files/0`
* [Code] Deprecate `Code.unload_files/1` in favor of `Code.unrequire_files/1`
#### Logger
* [Logger] `compile_time_purge_level` is deprecated in favor of `compile_time_purge_matching`
### 4. Hard-deprecations
#### Elixir
* [Enum] Passing a non-empty list to `Enum.into/2` was inconsistent with maps and is deprecated in favor of `Kernel.++/2` or `Keyword.merge/2`
* [Inspect.Algebra] `surround/3` is deprecated in favor of `Inspect.Algebra.concat/2` and `Inspect.Algebra.nest/2`
* [Inspect.Algebra] `surround_many/6` is deprecated in favor of `container_doc/6`
* [Kernel] Using `@since` will now emit a unused attribute warning. Use `@doc since: "1.7.2"` instead
* [Kernel] Passing a non-empty list as `:into` in `for` comprehensions was inconsistent with maps and is deprecated in favor of `Kernel.++/2` or `Keyword.merge/2`
* [Kernel.ParallelCompiler] `files/2` is deprecated in favor of `compile/2`
* [Kernel.ParallelCompiler] `files_to_path/2` is deprecated in favor of `compile_to_path/2`
* [Kernel.ParallelRequire] `files/2` is deprecated in favor of `Kernel.ParallelCompiler.require/2`
* [System] `:seconds`, `:milliseconds`, etc. as time units is deprecated in favor of `:second`, `:millisecond`, etc.
* [System] `System.cwd/0` and `System.cwd!/0` are deprecated in favor of `File.cwd/0` and `File.cwd!/0`
* [Code] `Code.get_docs/2` is deprecated in favor of `Code.fetch_docs/1`
* [Enum] `Enum.chunk/2/3/4` is deprecated in favor of `Enum.chunk_every/2/3/4` - notice `chunk_every` does not discard incomplete chunks by default
* [GenServer] Warn if `super` is used in any of the GenServer callbacks
* [Kernel] `not left in right` is ambiguous and is deprecated in favor of `left not in right`
* [Kernel] Warn on confusing operator sequences, such as `1+++1` meaning `1 ++ +1` or `........` meaning `... .. ...`
* [OptionParser] Deprecate dynamic option parser mode that depended on atoms to be previously loaded and therefore behaved inconsistently
* [Stream] `Stream.chunk/2/3/4` is deprecated in favor of `Stream.chunk_every/2/3/4` - notice `chunk_every` does not discard incomplete chunks by default
#### Mix
## v1.6
* [mix compile.erlang] Returning `{:ok, contents}` or `:error` as the callback in `Mix.Compilers.Erlang.compile/6` is deprecated in favor of returning `{:ok, contents, warnings}` or `{:error, errors, warnings}`
## v1.7
The CHANGELOG for v1.7 releases can be found [in the v1.7 branch](https://github.com/elixir-lang/elixir/blob/v1.7/CHANGELOG.md).
The CHANGELOG for v1.6 releases can be found [in the v1.6 branch](https://github.com/elixir-lang/elixir/blob/v1.6/CHANGELOG.md).
+1 -3
View File
@@ -1,9 +1,8 @@
### Precheck
* Do not use the issues tracker for help or support (try Elixir Forum, Stack Overflow, IRC, etc.)
* For proposing a new feature, please start a discussion on the Elixir Core mailing list: https://groups.google.com/group/elixir-lang-core
* For proposing a new feature, please start a discussion on the Elixir Core mailing list
* For bugs, do a quick search and make sure the bug has not yet been reported
* Please disclose security vulnerabilities privately at elixir-security@googlegroups.com
* Finally, be nice and have fun!
### Environment
@@ -17,4 +16,3 @@ Include code samples, errors and stacktraces if appropriate.
### Expected behavior
A short description on how you expect the code to behave.
+25
View File
@@ -174,3 +174,28 @@
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "{}"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2012 Plataformatec
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+19 -16
View File
@@ -1,9 +1,8 @@
PREFIX ?= /usr/local
SHARE_PREFIX ?= $(PREFIX)/share
MAN_PREFIX ?= $(SHARE_PREFIX)/man
CANONICAL := v1.8/ # master/ or vMAJOR.MINOR/
ELIXIRC := bin/elixirc --verbose --ignore-module-conflict --warnings-as-errors
ERLC := erlc -I lib/elixir/include +warnings_as_errors
CANONICAL := v1.7/
ELIXIRC := bin/elixirc --verbose --ignore-module-conflict
ERLC := erlc -I lib/elixir/include
ERL := erl -I lib/elixir/include -noshell -pa lib/elixir/ebin
GENERATE_APP := $(CURDIR)/lib/elixir/generate_app.escript
VERSION := $(strip $(shell cat VERSION))
@@ -23,9 +22,9 @@ GIT_TAG = $(strip $(shell head="$(call GIT_REVISION)"; git tag --points-at $$hea
#==> Functions
define CHECK_ERLANG_RELEASE
erl -noshell -eval '{V,_} = string:to_integer(erlang:system_info(otp_release)), io:fwrite("~s", [is_integer(V) and (V >= 20)])' -s erlang halt | grep -q '^true'; \
erl -noshell -eval '{V,_} = string:to_integer(erlang:system_info(otp_release)), io:fwrite("~s", [is_integer(V) and (V >= 19)])' -s erlang halt | grep -q '^true'; \
if [ $$? != 0 ]; then \
echo "At least Erlang/OTP 20.0 is required to build Elixir"; \
echo "At least Erlang/OTP 19.0 is required to build Elixir"; \
exit 1; \
fi
endef
@@ -34,7 +33,11 @@ define APP_TEMPLATE
$(1): lib/$(1)/ebin/Elixir.$(2).beam lib/$(1)/ebin/$(1).app
lib/$(1)/ebin/$(1).app: lib/$(1)/mix.exs
$(Q) cd lib/$(1) && ../../bin/elixir -e 'Mix.start(:permanent, [])' -r mix.exs -e 'Mix.Task.run("compile.app", ~w[--compile-path ebin])'
$(Q) mkdir -p lib/$(1)/_build/shared/lib/$(1)
$(Q) cp -R lib/$(1)/ebin lib/$(1)/_build/shared/lib/$(1)/
$(Q) cd lib/$(1) && ../../bin/elixir -e 'Mix.start(:permanent, [])' -r mix.exs -e 'Mix.Task.run("compile.app")'
$(Q) cp lib/$(1)/_build/shared/lib/$(1)/ebin/$(1).app lib/$(1)/ebin/$(1).app
$(Q) rm -rf lib/$(1)/_build
lib/$(1)/ebin/Elixir.$(2).beam: $(wildcard lib/$(1)/lib/*.ex) $(wildcard lib/$(1)/lib/*/*.ex) $(wildcard lib/$(1)/lib/*/*/*.ex)
@ echo "==> $(1) (compile)"
@@ -42,7 +45,7 @@ lib/$(1)/ebin/Elixir.$(2).beam: $(wildcard lib/$(1)/lib/*.ex) $(wildcard lib/$(1
$(Q) cd lib/$(1) && ../../$$(ELIXIRC) "lib/**/*.ex" -o ebin
test_$(1): compile $(1)
@ echo "==> $(1) (ex_unit)"
@ echo "==> $(1) (exunit)"
$(Q) cd lib/$(1) && ../../bin/elixir -r "test/test_helper.exs" -pr "test/**/*_test.exs";
endef
@@ -138,7 +141,7 @@ clean_residual_files:
LOGO_PATH = $(shell test -f ../docs/logo.png && echo "--logo ../docs/logo.png")
SOURCE_REF = $(shell tag="$(call GIT_TAG)" revision="$(call GIT_REVISION)"; echo "$${tag:-$$revision}\c")
DOCS_FORMAT = html
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 "$(call SOURCE_REF)" $(call LOGO_PATH) -o doc/$(2) -n https://hexdocs.pm/$(2)/$(CANONICAL) -p https://elixir-lang.org/docs.html -f "$(DOCS_FORMAT)" $(4)
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 "$(call SOURCE_REF)" $(call LOGO_PATH) -o doc/$(2) -n https://hexdocs.pm/$(2)/$(CANONICAL) -p http://elixir-lang.org/docs.html -f "$(DOCS_FORMAT)" $(4)
docs: compile ../ex_doc/bin/ex_doc docs_elixir docs_eex docs_mix docs_iex docs_ex_unit docs_logger
@@ -227,7 +230,7 @@ $(TEST_EBIN)/%.beam: $(TEST_ERL)/%.erl
test_elixir: test_stdlib test_ex_unit test_logger test_mix test_eex test_iex
test_stdlib: compile
@ echo "==> elixir (ex_unit)"
@ echo "==> elixir (exunit)"
$(Q) exec epmd & exit
$(Q) if [ "$(OS)" = "Windows_NT" ]; then \
cd lib/elixir && cmd //C call ../../bin/elixir.bat -r "test/elixir/test_helper.exs" -pr "test/elixir/**/*_test.exs"; \
@@ -251,7 +254,7 @@ build_plt: clean_plt $(PLT)
dialyze: compile $(PLT)
@ echo "==> Dialyzing Elixir..."
$(Q) dialyzer -pa lib/elixir/ebin --plt $(PLT) $(DIALYZER_OPTS) lib/*/ebin
$(Q) dialyzer --plt $(PLT) $(DIALYZER_OPTS) lib/*/ebin
#==> Man page tasks
@@ -276,9 +279,9 @@ clean_man:
rm -f man/iex.1.bak
install_man: build_man
$(Q) mkdir -p $(DESTDIR)$(MAN_PREFIX)/man1
$(Q) $(INSTALL_DATA) man/elixir.1 $(DESTDIR)$(MAN_PREFIX)/man1
$(Q) $(INSTALL_DATA) man/elixirc.1 $(DESTDIR)$(MAN_PREFIX)/man1
$(Q) $(INSTALL_DATA) man/iex.1 $(DESTDIR)$(MAN_PREFIX)/man1
$(Q) $(INSTALL_DATA) man/mix.1 $(DESTDIR)$(MAN_PREFIX)/man1
$(Q) mkdir -p $(DESTDIR)$(SHARE_PREFIX)/man/man1
$(Q) $(INSTALL_DATA) man/elixir.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
$(Q) $(INSTALL_DATA) man/elixirc.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
$(Q) $(INSTALL_DATA) man/iex.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
$(Q) $(INSTALL_DATA) man/mix.1 $(DESTDIR)$(SHARE_PREFIX)/man/man1
$(MAKE) clean_man
+3 -17
View File
@@ -1,7 +1,9 @@
LEGAL NOTICE INFORMATION
------------------------
All the files in this distribution are copyright to the terms below.
All the files in this distribution are copyright (c) 2012 Plataformatec
covered under Elixir's license (see the file LICENSE) except the cases
below.
== lib/elixir/src/elixir_parser.erl (generated by build scripts)
@@ -18,19 +20,3 @@ distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
== All other files
Copyright 2012 Plataformatec
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+15 -19
View File
@@ -3,15 +3,10 @@
[![Travis build](https://secure.travis-ci.org/elixir-lang/elixir.svg?branch=master
"Build Status")](https://travis-ci.org/elixir-lang/elixir)
Elixir is a dynamic, functional language designed for building scalable
and maintainable applications.
Elixir is a dynamic, functional language designed for building scalable and maintainable applications.
For more about Elixir, installation and documentation,
[check Elixir's website](https://elixir-lang.org/).
## Announcements
New releases are announced in the [announcements mailing list](https://groups.google.com/group/elixir-lang-ann). All security releases [will be tagged with `[security]`](https://groups.google.com/forum/#!searchin/elixir-lang-ann/%5Bsecurity%5D%7Csort:date).
[check Elixir's website](http://elixir-lang.org/).
## Compiling from source
@@ -35,10 +30,10 @@ 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/OTP version
(Elixir requires Erlang/OTP 20.0 or later). You can check your Erlang/OTP version
(Elixir requires Erlang/OTP 19.0 or later). You can check your Erlang/OTP version
by calling `erl` in the command line. You will see some information as follows:
Erlang/OTP 20 [erts-9.0] [smp:2:2] [async-threads:10] [kernel-poll:false]
Erlang/OTP 19 [erts-8.0] [smp:2:2] [async-threads:10] [kernel-poll:false]
If you have properly set up your dependencies and tests still fail,
you may want to open up a bug report, as explained next.
@@ -46,8 +41,8 @@ you may want to open up a bug report, as explained next.
## Bug reports
For reporting bugs, [visit our issues tracker][2] and follow the steps
for reporting a new issue. **Please disclose security vulnerabilities
privately at elixir-security@googlegroups.com**.
for reporting a new issue. Please disclose security vulnerabilities
privately at elixir-security@googlegroups.com.
## Proposing new features
@@ -106,9 +101,9 @@ To recompile (including Erlang modules):
make compile
```
After your changes are done, please remember to run `mix format` to guarantee
all files are properly formatted and then run the full suite with
`make test`.
After your changes are done, please remember to run the full suite with
`make test` and then `mix format` to guarantee all files are properly
formatted.
If your contribution fails during the bootstrapping of the language,
you can rebuild the language from scratch with:
@@ -127,9 +122,9 @@ With tests running and passing, you are ready to contribute to Elixir and
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)
* [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)
### Reviewing changes
@@ -184,7 +179,7 @@ the `doc` directory. If you are planning to contribute documentation,
[3]: https://groups.google.com/group/elixir-lang-core
[4]: https://webchat.freenode.net/?channels=#elixir-lang
[5]: http://www.freenode.net
[6]: https://elixir-lang.org/docs.html
[6]: http://elixir-lang.org/docs.html
[7]: CODE_OF_CONDUCT.md
## License
@@ -193,4 +188,5 @@ the `doc` directory. If you are planning to contribute documentation,
Elixir source code is released under Apache 2 License.
Check [NOTICE](NOTICE) and [LICENSE](LICENSE) files for more information.
Check [NOTICE](NOTICE) and [LICENSE](LICENSE) files for more
information.
+3 -7
View File
@@ -20,9 +20,7 @@
9. Publish new zips with `make zips`, upload `Precompiled.zip` and `Docs.zip` to GitHub Releases, and include SHAs+CHANGELOG
10. Add the release to `elixir.csv` (all releases) and `_data/elixir-versions.yml` (except for RCs) files in `elixir-lang/elixir-lang.github.com`
11. Send an e-mail to elixir-lang-ann@googlegroups.com with title "Elixir vVERSION released". The body should be a link to the Release page on GitHub and the checksums. If it is a security release, prefix the title with the `[security]` tag
10. Add the release to `elixir.csv` and `_data/elixir-versions.yml` files in `elixir-lang/elixir-lang.github.com`
## Creating a new vMAJOR.MINOR branch
@@ -30,7 +28,7 @@
1. Set `CANONICAL=` in /Makefile
2. Update tables in "Compatibility and Deprecations"
2. Update **all** tables in "Compatibility and Deprecations"
3. Commit "Prepare vMAJOR.MINOR for release"
@@ -40,6 +38,4 @@
2. Start new /CHANGELOG.md
3. Update tables in "Compatibility and Deprecations"
4. Commit "Start vMAJOR.MINOR+1"
3. Commit "Start vMAJOR.MINOR+1"
+1 -1
View File
@@ -1 +1 @@
1.8.2
1.7.4
+1 -1
View File
@@ -50,7 +50,7 @@ set originPath=%~dp0
rem Optional parameters before the "-extra" parameter
set beforeExtra=
rem Option which determines whether or not to use werl vs erl
rem Flag which determines whether or not to use werl vs erl
set useWerl=0
rem Designates which mode / Elixir component to run as
+2 -2
View File
@@ -167,7 +167,7 @@ defmodule EEx do
Gets a string `source` and generate a quoted expression
that can be evaluated by Elixir or compiled to a function.
"""
@spec compile_string(String.t(), keyword) :: Macro.t()
@spec compile_string(String.t(), keyword) :: Macro.t() | no_return
def compile_string(source, options \\ []) when is_binary(source) and is_list(options) do
EEx.Compiler.compile(source, options)
end
@@ -176,7 +176,7 @@ defmodule EEx do
Gets a `filename` and generate a quoted expression
that can be evaluated by Elixir or compiled to a function.
"""
@spec compile_file(String.t(), keyword) :: Macro.t()
@spec compile_file(String.t(), keyword) :: Macro.t() | no_return
def compile_file(filename, options \\ []) when is_binary(filename) and is_list(options) do
options = Keyword.merge(options, file: filename, line: 1)
compile_string(File.read!(filename), options)
+1 -1
View File
@@ -9,7 +9,7 @@ defmodule EEx.Compiler do
and the engine together by handling the tokens and invoking
the engine every time a full expression or text is received.
"""
@spec compile(String.t(), keyword) :: Macro.t()
@spec compile(String.t(), keyword) :: Macro.t() | no_return
def compile(source, opts) when is_binary(source) and is_list(opts) do
file = opts[:file] || "nofile"
line = opts[:line] || 1
+97 -114
View File
@@ -2,70 +2,58 @@ defmodule EEx.Engine do
@moduledoc ~S"""
Basic EEx engine that ships with Elixir.
An engine needs to implement all callbacks below.
An engine needs to implement six functions:
An engine may also `use EEx.Engine` to get the default behaviour
but this is not advised. In such cases, if any of the callbacks
are overridden, they must call `super()` to delegate to the
underlying `EEx.Engine`.
* `init(opts)` - called at the beginning of every text
and it must return the initial state.
* `handle_body(state)` - receives the state of the document
and it must return a quoted expression.
* `handle_text(state, text)` - it receives the state,
the text and must return a new quoted expression.
* `handle_expr(state, marker, expr)` - it receives the state,
the marker, the expr and must return a new state.
* `handle_begin(state)` - called every time there a new state
is needed with an empty buffer. Typically called for do/end
blocks, case expressions, anonymous functions, etc
* `handle_end(state)` - opposite of `handle_begin(state)` and
it must return quoted expression
The marker is what follows exactly after `<%`. For example,
`<% foo %>` has an empty marker, but `<%= foo %>` has `"="`
as marker. The allowed markers so far are:
* `""`
* `"="`
* `"/"`
* `"|"`
Markers `"/"` and `"|"` are only for use in custom EEx engines
and are not implemented by default. Using them without the
implementation raises `EEx.SyntaxError`.
If your engine does not implement all markers, please ensure that
`handle_expr/3` falls back to `EEx.Engine.handle_expr/3`
to raise the proper error message.
Read `handle_expr/3` below for more information about the markers
implemented by default by this engine.
`EEx.Engine` can be used directly if one desires to use the
default implementations for the functions above.
"""
@type state :: term
@doc """
Called at the beginning of every template.
It must return the initial state.
"""
@callback init(opts :: keyword) :: state
@doc """
Called at the end of every template.
It must return Elixir's quoted expressions for the template.
"""
@callback handle_body(state) :: Macro.t()
@doc """
Called for the text/static parts of a template.
It must return the updated state.
"""
@callback handle_text(state, text :: String.t()) :: state
@doc """
Called for the dynamic/code parts of a template.
The marker is what follows exactly after `<%`. For example,
`<% foo %>` has an empty marker, but `<%= foo %>` has `"="`
as marker. The allowed markers so far are:
* `""`
* `"="`
* `"/"`
* `"|"`
Markers `"/"` and `"|"` are only for use in custom EEx engines
and are not implemented by default. Using them without an
appropriate implementation raises `EEx.SyntaxError`.
It must return the updated state.
"""
@callback handle_expr(state, marker :: String.t(), expr :: Macro.t()) :: state
@doc """
Invoked at the beginning of every nesting.
It must return a new state that is used only inside the nesting.
Once the nesting terminates, the current `state` is resumed.
"""
@callback handle_begin(state) :: state
@doc """
Invokes at the end of a nesting.
It must return Elixir's quoted expressions for the nesting.
"""
@callback handle_end(state) :: Macro.t()
@doc false
@@ -77,24 +65,24 @@ defmodule EEx.Engine do
EEx.Engine.init(opts)
end
def handle_body(state) do
EEx.Engine.handle_body(state)
def handle_body(quoted) do
EEx.Engine.handle_body(quoted)
end
def handle_begin(state) do
EEx.Engine.handle_begin(state)
def handle_begin(quoted) do
EEx.Engine.handle_begin(quoted)
end
def handle_end(state) do
EEx.Engine.handle_end(state)
def handle_end(quoted) do
EEx.Engine.handle_end(quoted)
end
def handle_text(state, text) do
EEx.Engine.handle_text(state, text)
def handle_text(buffer, text) do
EEx.Engine.handle_text(buffer, text)
end
def handle_expr(state, marker, expr) do
EEx.Engine.handle_expr(state, marker, expr)
def handle_expr(buffer, marker, expr) do
EEx.Engine.handle_expr(buffer, marker, expr)
end
defoverridable EEx.Engine
@@ -110,9 +98,9 @@ defmodule EEx.Engine do
This can be added to any custom engine by invoking
`handle_assign/1` with `Macro.prewalk/2`:
def handle_expr(state, token, expr) do
def handle_expr(buffer, token, expr) do
expr = Macro.prewalk(expr, &EEx.Engine.handle_assign/1)
super(state, token, expr)
EEx.Engine.handle_expr(buffer, token, expr)
end
"""
@@ -147,73 +135,68 @@ defmodule EEx.Engine do
end
end
@doc false
@doc """
Returns an empty string as initial buffer.
"""
def init(_opts) do
%{
binary: [],
dynamic: [],
vars_count: 0
}
""
end
@doc false
def handle_begin(state) do
check_state!(state)
%{state | binary: [], dynamic: []}
@doc """
Returns an empty string as the new buffer.
"""
def handle_begin(_previous) do
""
end
@doc false
@doc """
End of the new buffer.
"""
def handle_end(quoted) do
handle_body(quoted)
quoted
end
@doc false
def handle_body(state) do
check_state!(state)
%{binary: binary, dynamic: dynamic} = state
binary = {:<<>>, [], Enum.reverse(binary)}
dynamic = [binary | dynamic]
{:__block__, [], Enum.reverse(dynamic)}
@doc """
The default implementation simply returns the given expression.
"""
def handle_body(quoted) do
quoted
end
@doc false
def handle_text(state, text) do
%{binary: binary} = state
%{state | binary: [text | binary]}
@doc """
The default implementation simply concatenates text to the buffer.
"""
def handle_text(buffer, text) do
quote(do: unquote(buffer) <> unquote(text))
end
@doc false
def handle_expr(state, "=", ast) do
%{binary: binary, dynamic: dynamic, vars_count: vars_count} = state
var = Macro.var(:"arg#{vars_count}", __MODULE__)
@doc """
Implements expressions according to the markers.
ast =
quote do
unquote(var) = String.Chars.to_string(unquote(ast))
end
<% Elixir expression - inline with output %>
<%= Elixir expression - replace with result %>
<%/ Elixir expression - raise EEx.SyntaxError, to be implemented by custom engines %>
<%| Elixir expression - raise EEx.SyntaxError, to be implemented by custom engines %>
segment =
quote do
unquote(var) :: binary
end
%{state | dynamic: [ast | dynamic], binary: [segment | binary], vars_count: vars_count + 1}
All other markers are not implemented by this engine.
"""
def handle_expr(buffer, "=", expr) do
quote do
tmp1 = unquote(buffer)
tmp1 <> String.Chars.to_string(unquote(expr))
end
end
def handle_expr(state, "", ast) do
%{dynamic: dynamic} = state
%{state | dynamic: [ast | dynamic]}
def handle_expr(buffer, "", expr) do
quote do
tmp2 = unquote(buffer)
unquote(expr)
tmp2
end
end
def handle_expr(_state, marker, _ast) when marker in ["/", "|"] do
def handle_expr(_buffer, marker, _expr) when marker in ["/", "|"] do
raise EEx.SyntaxError,
"unsupported EEx syntax <%#{marker} %> (the syntax is valid but not supported by the current EEx engine)"
end
defp check_state!(%{binary: _, dynamic: _, vars_count: _}), do: :ok
defp check_state!(state) do
raise "unexpected EEx.Engine state: #{inspect(state)}. " <>
"This typically means a bug or an outdated EEx.Engine or tool"
end
end
+2 -2
View File
@@ -501,7 +501,7 @@ defmodule EExTest do
test "begin/end" do
assert_eval(
~s[BODY(INIT:TEXT(foo):EQUAL(if do\n "BEGIN:TEXT(this):END"\nelse\n "BEGIN:TEXT(that):END"\nend))],
~s[BODY(INIT:TEXT(foo):EQUAL(if() do\n "BEGIN:TEXT(this):END"\nelse\n "BEGIN:TEXT(that):END"\nend))],
"foo <%= if do %>this<% else %>that<% end %>",
[],
engine: TestEngine
@@ -519,7 +519,7 @@ defmodule EExTest do
end
defp assert_eval(expected, actual, binding \\ [], opts \\ []) do
opts = Keyword.merge([file: __ENV__.file, engine: opts[:engine] || EEx.Engine], opts)
opts = Enum.into([file: __ENV__.file, engine: opts[:engine] || EEx.Engine], opts)
result = EEx.eval_string(actual, binding, opts)
assert result == expected
end
+3 -1
View File
@@ -8,10 +8,12 @@
warn_unused_record,
warn_deprecated_function,
warn_obsolete_guard,
strict_validation,
warn_exported_vars,
%% warn_export_vars,
%% warn_missing_spec,
%% warn_untyped_record,
warnings_as_errors,
%% warnings_as_errors,
debug_info,
{outdir, "ebin/"}
]}.
+2 -10
View File
@@ -1,10 +1,6 @@
# Returns config for Elixir docs
[
extras: Path.wildcard("lib/elixir/pages/*.md"),
groups_for_functions: [
Guards: & &1[:guard] == true
],
skip_undefined_reference_warnings_on: ["compatibility-and-deprecations"],
groups_for_modules: [
# [Kernel, Kernel.SpecialForms],
@@ -12,6 +8,8 @@
Atom,
Base,
Bitwise,
Calendar,
Calendar.ISO,
Date,
DateTime,
Exception,
@@ -51,12 +49,6 @@
StringIO,
System
],
"Calendar": [
Calendar,
Calendar.ISO,
Calendar.TimeZoneDatabase,
Calendar.UTCOnlyTimeZoneDatabase
],
"Modules & Code": [
Code,
Kernel.ParallelCompiler,
+9 -13
View File
@@ -105,7 +105,7 @@ defmodule Access do
### Summing up
The bracket-based syntax, `user[:name]`, is used by dynamic structures,
is extensible and returns nil on missing keys.
is extensible and returns nil on misisng keys.
The dot-based syntax, `user.name`, is used exclusively to access atom
keys in maps and structs, and it raises on missing keys.
@@ -118,9 +118,9 @@ defmodule Access do
For example, to update a map inside another map:
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"].age, 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
iex> users = %{"john" => %{age: 27}, "meg" => %{age: 23}}
iex> put_in(users["john"].age, 28)
%{"john" => %{age: 28}, "meg" => %{age: 23}}
This module provides convenience functions for traversing other
structures, like tuples and lists. These functions can be used
@@ -132,17 +132,13 @@ defmodule Access do
iex> languages = [
...> %{name: "elixir", type: :functional},
...> %{name: "c", type: :procedural}
...> %{name: "c", type: :procedural},
...> ]
iex> user = %{name: "john", languages: languages}
iex> update_in(user, [:languages, Access.all(), :name], &String.upcase/1)
%{
name: "john",
languages: [
%{name: "ELIXIR", type: :functional},
%{name: "C", type: :procedural}
]
}
%{name: "john",
languages: [%{name: "ELIXIR", type: :functional},
%{name: "C", type: :procedural}]}
See the functions `key/1`, `key!/1`, `elem/1`, and `all/0` for some of the
available accessors.
@@ -615,7 +611,7 @@ defmodule Access do
numbers and multiplying odd numbers by 2:
iex> require Integer
iex> get_and_update_in([1, 2, 3, 4, 5], [Access.all()], fn num ->
iex> get_and_update_in([1, 2, 3, 4, 5], [Access.all], fn num ->
...> if Integer.is_even(num), do: :pop, else: {num, num * 2}
...> end)
{[1, 2, 3, 4, 5], [2, 6, 10]}
+42 -84
View File
@@ -11,42 +11,44 @@ defmodule Agent do
## Examples
For example, the following agent implements a counter:
For example, in the Mix tool that ships with Elixir, we need
to keep a set of all tasks executed by a given project. Since
this set is shared, we can implement it with an agent:
defmodule Counter do
defmodule Mix.TasksServer do
use Agent
def start_link(initial_value) do
Agent.start_link(fn -> initial_value end, name: __MODULE__)
def start_link(_) do
Agent.start_link(fn -> MapSet.new end, name: __MODULE__)
end
def value do
Agent.get(__MODULE__, & &1)
@doc "Checks if the task has already executed"
def executed?(task, project) do
item = {task, project}
Agent.get(__MODULE__, fn set ->
item in set
end)
end
def increment do
Agent.update(__MODULE__, &(&1 + 1))
@doc "Marks a task as executed"
def put_task(task, project) do
item = {task, project}
Agent.update(__MODULE__, &MapSet.put(&1, item))
end
@doc "Resets the executed tasks and returns the previous list of tasks"
def take_all() do
Agent.get_and_update(__MODULE__, fn set ->
{Enum.into(set, []), MapSet.new}
end)
end
end
Usage would be:
Counter.start_link(0)
Counter.value #=> 0
Counter.increment #=> :ok
Counter.increment #=> :ok
Counter.value #=> 2
Thanks to the agent server process, the counter can be safely incremented
concurrently.
Agents provide a segregation between the client and server APIs (similar to
`GenServer`s). In particular, the functions passed as arguments to the calls to
`Agent` functions are invoked inside the agent (the server). This distinction
is important because you may want to avoid expensive operations inside the
agent, as they will effectively block the agent until the request is
fulfilled.
Agents provide a segregation between the client and server APIs (similar
to GenServers). In particular, the anonymous functions given to the `Agent`
are executed inside the agent (the server). This distinction is important
because you may want to avoid expensive operations inside the agent,
as they will effectively block the agent until the request is fulfilled.
Consider these two examples:
@@ -57,7 +59,7 @@ defmodule Agent do
# Compute in the agent/client
def get_something(agent) do
Agent.get(agent, & &1) |> do_something_expensive()
Agent.get(agent, &(&1)) |> do_something_expensive()
end
The first function blocks the agent. The second function copies all the state
@@ -71,61 +73,20 @@ defmodule Agent do
than in the server can lead to race conditions if multiple clients are trying
to update the same state to different values.
## How to supervise
An `Agent` is most commonly started under a supervision tree.
When we invoke `use Agent`, it automatically defines a `child_spec/1`
function that allows us to start the agent directly under a supervisor.
To start an agent under a supervisor with an initial counter of 0,
one may do:
children = [
{Counter, 0}
]
Supervisor.start_link(children, strategy: :one_for_all)
While one could also simply pass the `Counter` as a child to the supervisor,
such as:
children = [
Counter # Same as {Counter, []}
]
Supervisor.start_link(children, strategy: :one_for_all)
The definition above wouldn't work for this particular example,
as it would attempt to start the counter with an initial value
of an empty list. However, this may be a viable option in your
own agents. A common approach is to use a keyword list, as that
would allow setting the initial value and giving a name to the
counter process, for example:
def start_link(opts) do
{initial_value, opts} = Keyword.pop(opts, :initial_value, 0)
Agent.start_link(fn -> initial_value end, opts)
end
and then you can use `Counter`, `{Counter, name: :my_counter}` or
even `{Counter, initial_value: 0, name: :my_counter}` as a child
specification.
`use Agent` also accepts a list of options which configures the
child specification and therefore how it runs under a supervisor.
The generated `child_spec/1` can be customized with the following options:
Finally note `use Agent` defines a `child_spec/1` function, allowing the
defined module to be put under a supervision tree. The generated
`child_spec/1` can be customized with the following options:
* `:id` - the child specification identifier, defaults to the current module
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
* `:restart` - when the child should be restarted, defaults to `:permanent`
* `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down
* `:shutdown` - how to shut down the child
For example:
use Agent, restart: :transient, shutdown: 10_000
See the "Child specification" section in the `Supervisor` module for more
detailed information. The `@doc` annotation immediately preceding
`use Agent` will be attached to the generated `child_spec/1` function.
See the `Supervisor` docs for more information.
## Name registration
@@ -181,7 +142,7 @@ defmodule Agent do
@doc """
Returns a specification to start an agent under a supervisor.
See the "Child specification" section in the `Supervisor` module for more detailed information.
See `Supervisor`.
"""
@doc since: "1.5.0"
def child_spec(arg) do
@@ -194,14 +155,11 @@ defmodule Agent do
@doc false
defmacro __using__(opts) do
quote location: :keep, bind_quoted: [opts: opts] do
if Module.get_attribute(__MODULE__, :doc) == nil do
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
end
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
def child_spec(arg) do
default = %{
id: __MODULE__,
@@ -220,9 +178,9 @@ defmodule Agent do
This is often used to start the agent as part of a supervision tree.
Once the agent is spawned, the given function `fun` is invoked in the server
process, and should return the initial agent state. Note that `start_link/2`
does not return until the given function has returned.
Once the agent is spawned, the given function `fun` is invoked and its return
value is used as the agent state. Note that `start_link/2` does not return
until the given function has returned.
## Options
+26 -37
View File
@@ -23,8 +23,8 @@ defmodule Application do
`mix.exs`, and others are generated by Mix itself.
You can learn more about the generation of application resource files in the
documentation of `Mix.Tasks.Compile.App`, available as well by running
`mix help compile.app`.
documentation of `Mix.Tasks.Compile.App`, available as well by running `mix
help compile.app`.
## The application environment
@@ -66,8 +66,8 @@ defmodule Application do
own environment. Please do not use the functions in this module for directly
accessing or modifying the environment of other applications.
The application environment can be overridden via the `-config` option of
`erl`, as well as command-line options, as we are going to see below.
The application environment can be overriden via the `-config` option of
`erl`, as well as command-line flags, as we are going to see below.
## The application callback module
@@ -135,7 +135,7 @@ defmodule Application do
is merged with any overrides from config files passed to `erl` via the
`-config` option. It is worth highlighting that releases pass `sys.config`
this way. The resulting environment can still be overridden again via specific
`-Application` options passed to `erl`.
`-Application` flags passed to `erl`.
Loading an application *does not* load its modules.
@@ -197,9 +197,9 @@ defmodule Application do
Shutting down a live system cleanly can be done by calling `System.stop/1`. It
will shut down every application in the opposite order they had been started.
By default, a SIGTERM from the operating system will automatically translate to
`System.stop/0`. You can also have more explicit control over OS signals via the
`:os.set_signal/2` function.
From Erlang/OTP 19.1, a SIGTERM from the operating system will automatically
translate to `System.stop/0`. Erlang/OTP 20 gives user more explicit control
over OS signals via the `:os.set_signal/2` function.
## Tooling
@@ -296,7 +296,7 @@ defmodule Application do
@callback stop(state) :: term
@doc """
Starts an application in synchronous phases.
Start an application in synchronous phases.
This function is called after `start/2` finishes but before
`Application.start/2` returns. It will be called once for every start phase
@@ -306,18 +306,7 @@ defmodule Application do
@callback start_phase(phase :: term, start_type, phase_args :: term) ::
:ok | {:error, reason :: term}
@doc """
Callback invoked after code upgrade, if the application environment
has changed.
`changed` is a keyword list of keys and their changed values in the
application environment. `new` is a keyword list with all new keys
and their values. `removed` is a list with all removed keys.
"""
@callback config_change(changed, new, removed) :: :ok
when changed: keyword, new: keyword, removed: [atom]
@optional_callbacks start_phase: 3, prep_stop: 1, config_change: 3
@optional_callbacks start_phase: 3, prep_stop: 1
@doc false
defmacro __using__(_) do
@@ -365,7 +354,7 @@ defmodule Application do
`fetch_env/2`. Returns `nil` if the application is not loaded.
"""
@spec spec(app) :: [{key, value}] | nil
def spec(app) when is_atom(app) do
def spec(app) do
case :application.get_all_key(app) do
{:ok, info} -> :lists.keydelete(:env, 1, info)
:undefined -> nil
@@ -380,7 +369,7 @@ defmodule Application do
will raise. Returns `nil` if the application is not loaded.
"""
@spec spec(app, key) :: value | nil
def spec(app, key) when is_atom(app) and key in @application_keys do
def spec(app, key) when key in @application_keys do
case :application.get_key(app, key) do
{:ok, value} -> value
:undefined -> nil
@@ -406,7 +395,7 @@ defmodule Application do
Returns all key-value pairs for `app`.
"""
@spec get_all_env(app) :: [{key, value}]
def get_all_env(app) when is_atom(app) do
def get_all_env(app) do
:application.get_all_env(app)
end
@@ -429,12 +418,12 @@ defmodule Application do
config :my_app, Databases.RepoOne,
# A database configuration
ip: "localhost",
ip: "localhost"
port: 5433
config :my_app, Databases.RepoTwo,
# Another database configuration (for the same OTP app)
ip: "localhost",
ip: "localhost"
port: 20717
config :my_app, my_app_databases: [Databases.RepoOne, Databases.RepoTwo]
@@ -449,10 +438,10 @@ defmodule Application do
**Important:** if you are writing a library to be used by other developers,
it is generally recommended to avoid the application environment, as the
application environment is effectively a global storage. For more information,
read our [library guidelines](library-guidelines.html).
read our [library guidelines](/library-guidelines.html).
"""
@spec get_env(app, key, value) :: value
def get_env(app, key, default \\ nil) when is_atom(app) do
def get_env(app, key, default \\ nil) do
:application.get_env(app, key, default)
end
@@ -462,7 +451,7 @@ defmodule Application do
If the configuration parameter does not exist, the function returns `:error`.
"""
@spec fetch_env(app, key) :: {:ok, value} | :error
def fetch_env(app, key) when is_atom(app) do
def fetch_env(app, key) do
case :application.get_env(app, key) do
{:ok, value} -> {:ok, value}
:undefined -> :error
@@ -474,8 +463,8 @@ defmodule Application do
If the configuration parameter does not exist, raises `ArgumentError`.
"""
@spec fetch_env!(app, key) :: value
def fetch_env!(app, key) when is_atom(app) do
@spec fetch_env!(app, key) :: value | no_return
def fetch_env!(app, key) do
case fetch_env(app, key) do
{:ok, value} ->
value
@@ -513,13 +502,13 @@ 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.
"""
@spec put_env(app, key, value, timeout: timeout, persistent: boolean) :: :ok
def put_env(app, key, value, opts \\ []) when is_atom(app) do
def put_env(app, key, value, opts \\ []) do
:application.set_env(app, key, value, opts)
end
@@ -529,7 +518,7 @@ defmodule Application do
See `put_env/4` for a description of the options.
"""
@spec delete_env(app, key, timeout: timeout, persistent: boolean) :: :ok
def delete_env(app, key, opts \\ []) when is_atom(app) do
def delete_env(app, key, opts \\ []) do
:application.unset_env(app, key, opts)
end
@@ -605,7 +594,7 @@ defmodule Application do
When stopped, the application is still loaded.
"""
@spec stop(app) :: :ok | {:error, term}
def stop(app) when is_atom(app) do
def stop(app) do
:application.stop(app)
end
@@ -688,11 +677,11 @@ defmodule Application do
@spec app_dir(app, String.t() | [String.t()]) :: String.t()
def app_dir(app, path)
def app_dir(app, path) when is_atom(app) and is_binary(path) do
def app_dir(app, path) when is_binary(path) do
Path.join(app_dir(app), path)
end
def app_dir(app, path) when is_atom(app) and is_list(path) do
def app_dir(app, path) when is_list(path) do
Path.join([app_dir(app) | path])
end
-12
View File
@@ -66,7 +66,6 @@ defmodule Bitwise do
1
"""
@doc guard: true
defmacro bnot(expr) do
quote(do: :erlang.bnot(unquote(expr)))
end
@@ -80,7 +79,6 @@ defmodule Bitwise do
1
"""
@doc guard: true
defmacro ~~~expr do
quote(do: :erlang.bnot(unquote(expr)))
end
@@ -92,7 +90,6 @@ defmodule Bitwise do
1
"""
@doc guard: true
defmacro band(left, right) do
quote(do: :erlang.band(unquote(left), unquote(right)))
end
@@ -104,7 +101,6 @@ defmodule Bitwise do
1
"""
@doc guard: true
defmacro left &&& right do
quote(do: :erlang.band(unquote(left), unquote(right)))
end
@@ -116,7 +112,6 @@ defmodule Bitwise do
11
"""
@doc guard: true
defmacro bor(left, right) do
quote(do: :erlang.bor(unquote(left), unquote(right)))
end
@@ -128,7 +123,6 @@ defmodule Bitwise do
11
"""
@doc guard: true
defmacro left ||| right do
quote(do: :erlang.bor(unquote(left), unquote(right)))
end
@@ -140,7 +134,6 @@ defmodule Bitwise do
10
"""
@doc guard: true
defmacro bxor(left, right) do
quote(do: :erlang.bxor(unquote(left), unquote(right)))
end
@@ -152,7 +145,6 @@ defmodule Bitwise do
10
"""
@doc guard: true
defmacro left ^^^ right do
quote(do: :erlang.bxor(unquote(left), unquote(right)))
end
@@ -170,7 +162,6 @@ defmodule Bitwise do
-1
"""
@doc guard: true
defmacro bsl(left, right) do
quote(do: :erlang.bsl(unquote(left), unquote(right)))
end
@@ -188,7 +179,6 @@ defmodule Bitwise do
-1
"""
@doc guard: true
defmacro left <<< right do
quote(do: :erlang.bsl(unquote(left), unquote(right)))
end
@@ -206,7 +196,6 @@ defmodule Bitwise do
-4
"""
@doc guard: true
defmacro bsr(left, right) do
quote(do: :erlang.bsr(unquote(left), unquote(right)))
end
@@ -224,7 +213,6 @@ defmodule Bitwise do
-4
"""
@doc guard: true
defmacro left >>> right do
quote(do: :erlang.bsr(unquote(left), unquote(right)))
end
+12 -71
View File
@@ -17,15 +17,11 @@ defmodule Calendar do
"""
@type year :: integer
@type month :: pos_integer
@type day :: pos_integer
@type week :: pos_integer
@type day_of_week :: non_neg_integer
@type era :: non_neg_integer
@type hour :: non_neg_integer
@type minute :: non_neg_integer
@type second :: non_neg_integer
@type month :: integer
@type day :: integer
@type hour :: integer
@type minute :: integer
@type second :: integer
@typedoc """
The internal time format is used when converting between calendars.
@@ -40,8 +36,13 @@ defmodule Calendar do
The internal date format that is used when converting between calendars.
This is the number of days including the fractional part that has passed of
the last day since 0000-01-01+00:00T00:00.000000 in ISO 8601 notation (also
the last day since 0000-01-01+00:00T00:00.00000 in ISO 8601 notation (also
known as midnight 1 January BC 1 of the proleptic Gregorian calendar).
The `parts_per_day` represent how many subparts the current day is subdivided in
(for different calendars, picking a different `parts_per_day` might make sense).
The `parts_in_day` represents how many of these `parts_per_day` have passed in the
last day.
"""
@type iso_days :: {days :: integer, day_fraction}
@@ -111,28 +112,6 @@ defmodule Calendar do
std_offset: std_offset
}
@typedoc """
Specifies the time zone database for calendar operations.
Many functions in the `DateTime` module require a time zone database.
By default, it uses the default time zone database returned by
`Calendar.get_time_zone_database/0`, which defaults to
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC"
datetimes and returns `{:error, :utc_only_time_zone_database}`
for any other time zone.
Other time zone databases (including ones provided by packages)
can be configure as default either via configuration:
config :elixir, :time_zone_database, CustomTimeZoneDatabase
or by calling `Calendar.put_time_zone_database/1`.
See `Calendar.TimeZoneDatabase` for more information on custom
time zone databases.
"""
@type time_zone_database :: module()
@doc """
Returns how many days there are in the given year-month.
"""
@@ -155,27 +134,7 @@ defmodule Calendar do
@doc """
Calculates the day of the week from the given `year`, `month`, and `day`.
"""
@callback day_of_week(year, month, day) :: day_of_week()
@doc """
Calculates the day of the year from the given `year`, `month`, and `day`.
"""
@callback day_of_year(year, month, day) :: non_neg_integer()
@doc """
Calculates the quarter of the year from the given `year`, `month`, and `day`.
"""
@callback quarter_of_year(year, month, day) :: non_neg_integer()
@doc """
Calculates the year and era from the given `year`.
"""
@callback year_of_era(year) :: {year, era}
@doc """
Calculates the day and era from the given `year`, `month`, and `day`.
"""
@callback day_of_era(year, month, day) :: {non_neg_integer(), era}
@callback day_of_week(year, month, day) :: non_neg_integer()
@doc """
Converts the date into a string according to the calendar.
@@ -299,22 +258,4 @@ defmodule Calendar do
end
def truncate(_, :second), do: {0, 0}
@doc """
Sets the current time zone database.
"""
@doc since: "1.8.0"
@spec put_time_zone_database(time_zone_database()) :: :ok
def put_time_zone_database(database) do
Application.put_env(:elixir, :time_zone_database, database)
end
@doc """
Gets the current time zone database.
"""
@doc since: "1.8.0"
@spec get_time_zone_database() :: time_zone_database()
def get_time_zone_database() do
Application.get_env(:elixir, :time_zone_database, Calendar.UTCOnlyTimeZoneDatabase)
end
end
+7 -120
View File
@@ -4,7 +4,7 @@ defmodule Date do
The Date struct contains the fields year, month, day and calendar.
New dates can be built with the `new/3` function or using the
`~D` (see `Kernel.sigil_D/2`) sigil:
[`~D`](`Kernel.sigil_D/2`) sigil:
iex> ~D[2000-01-01]
~D[2000-01-01]
@@ -25,7 +25,7 @@ defmodule Date do
Developers should avoid creating the Date structs directly
and instead rely on the functions provided by this module as well
as the ones in third-party calendar libraries.
as the ones in 3rd party calendar libraries.
## Comparing dates
@@ -53,7 +53,7 @@ defmodule Date do
@enforce_keys [:year, :month, :day]
defstruct [:year, :month, :day, calendar: Calendar.ISO]
@type t :: %__MODULE__{
@type t :: %Date{
year: Calendar.year(),
month: Calendar.month(),
day: Calendar.day(),
@@ -248,8 +248,6 @@ defmodule Date do
Parses the extended "Dates" format described by
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
The year parsed by this function is limited to four digits.
## Examples
iex> Date.from_iso8601("2015-01-23")
@@ -467,7 +465,7 @@ defmodule Date do
cannot compare #{inspect(date1)} with #{inspect(date2)}.
This comparison would be ambiguous as their calendars have incompatible day rollover moments.
Specify an exact time of day (using DateTime) to resolve this ambiguity
Specify an exact time of day (using `DateTime`s) to resolve this ambiguity
"""
end
end
@@ -558,20 +556,9 @@ defmodule Date do
"""
@doc since: "1.5.0"
@spec add(Calendar.date(), integer()) :: t
def add(%{calendar: Calendar.ISO} = date, days) do
%{year: year, month: month, day: day} = date
{year, month, day} =
Calendar.ISO.date_to_iso_days(year, month, day)
|> Kernel.+(days)
|> Calendar.ISO.date_from_iso_days()
%Date{calendar: Calendar.ISO, year: year, month: month, day: day}
end
def add(%{calendar: calendar} = date, days) do
{base_days, fraction} = to_iso_days(date)
from_iso_days({base_days + days, fraction}, calendar)
{iso_days, fraction} = to_iso_days(date)
from_iso_days({iso_days + days, fraction}, calendar)
end
@doc """
@@ -652,113 +639,13 @@ defmodule Date do
"""
@doc since: "1.4.0"
@spec day_of_week(Calendar.date()) :: Calendar.day()
@spec day_of_week(Calendar.date()) :: non_neg_integer()
def day_of_week(date)
def day_of_week(%{calendar: calendar, year: year, month: month, day: day}) do
calendar.day_of_week(year, month, day)
end
@doc """
Calculates the day of the year of a given `date`.
Returns the day of the year as an integer. For the ISO 8601
calendar (the default), it is an integer from 1 to 366.
## Examples
iex> Date.day_of_year(~D[2016-01-01])
1
iex> Date.day_of_year(~D[2016-11-01])
306
iex> Date.day_of_year(~D[-0015-10-30])
303
iex> Date.day_of_year(~D[2004-12-31])
366
"""
@doc since: "1.8.0"
@spec day_of_year(Calendar.date()) :: Calendar.day()
def day_of_year(date)
def day_of_year(%{calendar: calendar, year: year, month: month, day: day}) do
calendar.day_of_year(year, month, day)
end
@doc """
Calculates the quarter of the year of a given `date`.
Returns the day of the year as an integer. For the ISO 8601
calendar (the default), it is an integer from 1 to 4.
## Examples
iex> Date.quarter_of_year(~D[2016-10-31])
4
iex> Date.quarter_of_year(~D[2016-01-01])
1
iex> Date.quarter_of_year(~N[2016-04-01 01:23:45])
2
iex> Date.quarter_of_year(~D[-0015-09-30])
3
"""
@doc since: "1.8.0"
@spec quarter_of_year(Calendar.date()) :: non_neg_integer()
def quarter_of_year(date)
def quarter_of_year(%{calendar: calendar, year: year, month: month, day: day}) do
calendar.quarter_of_year(year, month, day)
end
@doc """
Calculates the year-of-era and era for a given
calendar year.
Returns a tuple `{year, era}` representing the
year within the era and the era number.
## Examples
iex> Date.year_of_era(~D[0001-01-01])
{1, 1}
iex> Date.year_of_era(~D[0000-12-31])
{1, 0}
iex> Date.year_of_era(~D[-0001-01-01])
{2, 0}
"""
@doc since: "1.8.0"
@spec year_of_era(Calendar.date()) :: {Calendar.year(), non_neg_integer()}
def year_of_era(date)
def year_of_era(%{calendar: calendar, year: year}) do
calendar.year_of_era(year)
end
@doc """
Calculates the day-of-era and era for a given
calendar `date`.
Returns a tuple `{day, era}` representing the
day within the era and the era number.
## Examples
iex> Date.day_of_era(~D[0001-01-01])
{1, 1}
iex> Date.day_of_era(~D[0000-12-31])
{1, 0}
"""
@doc since: "1.8.0"
@spec day_of_era(Calendar.date()) :: {Calendar.day(), non_neg_integer()}
def day_of_era(date)
def day_of_era(%{calendar: calendar, year: year, month: month, day: day}) do
calendar.day_of_era(year, month, day)
end
## Helpers
defimpl String.Chars do
+112 -441
View File
@@ -12,25 +12,26 @@ defmodule DateTime do
are structural and based on the DateTime struct fields. For proper
comparison between datetimes, use the `compare/2` function.
The functions on this module work with the `DateTime` struct as well
as any struct that contains the same fields as the `DateTime` struct.
Such functions expect `t:Calendar.datetime/0` in their typespecs
(instead of `t:t/0`).
Developers should avoid creating the `DateTime` struct directly
and instead rely on the functions provided by this module as
well as the ones in third-party calendar libraries.
well as the ones in 3rd party calendar libraries.
## Time zone database
## Where are my functions?
Many functions in this module require a time zone database.
By default, it uses the default time zone database returned by
`Calendar.get_time_zone_database/0`, which defaults to
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC"
datetimes and returns `{:error, :utc_only_time_zone_database}`
for any other time zone.
You will notice this module only contains conversion
functions as well as functions that work on UTC. This
is because a proper `DateTime` implementation requires a
time zone database which currently is not provided as part
of Elixir.
Other time zone databases (including ones provided by packages)
can be configure as default either via configuration:
config :elixir, :time_zone_database, CustomTimeZoneDatabase
or by calling `Calendar.put_time_zone_database/1`.
Such may be addressed in upcoming versions, meanwhile,
use 3rd party packages to provide `DateTime` building and
similar functionality with time zone backing.
"""
@enforce_keys [:year, :month, :day, :hour, :minute, :second] ++
@@ -175,11 +176,8 @@ defmodule DateTime do
@doc """
Converts the given `NaiveDateTime` to `DateTime`.
It expects a time zone to put the `NaiveDateTime` in.
If the time zone is "Etc/UTC", it always succeeds. Otherwise,
the NaiveDateTime is checked against the time zone database
given as `time_zone_database`. See the "Time zone database"
section in the module documentation.
It expects a time zone to put the NaiveDateTime in.
Currently it only supports "Etc/UTC" as time zone.
## Examples
@@ -187,136 +185,12 @@ defmodule DateTime do
iex> datetime
#DateTime<2016-05-24 13:26:08.003Z>
When the datetime is ambiguous - for instance during changing from summer
to winter time - the two possible valid datetimes are returned. First the one
that happens first, then the one that happens after.
iex> {:ambiguous, first_dt, second_dt} = DateTime.from_naive(~N[2018-10-28 02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
iex> first_dt
#DateTime<2018-10-28 02:30:00+02:00 CEST Europe/Copenhagen>
iex> second_dt
#DateTime<2018-10-28 02:30:00+01:00 CET Europe/Copenhagen>
When there is a gap in wall time - for instance in spring when the clocks are
turned forward - the latest valid datetime just before the gap and the first
valid datetime just after the gap.
iex> {:gap, just_before, just_after} = DateTime.from_naive(~N[2019-03-31 02:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
iex> just_before
#DateTime<2019-03-31 01:59:59.999999+01:00 CET Europe/Copenhagen>
iex> just_after
#DateTime<2019-03-31 03:00:00+02:00 CEST Europe/Copenhagen>
Most of the time there is one, and just one, valid datetime for a certain
date and time in a certain time zone.
iex> {:ok, datetime} = DateTime.from_naive(~N[2018-07-28 12:30:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
iex> datetime
#DateTime<2018-07-28 12:30:00+02:00 CEST Europe/Copenhagen>
This function accepts any map or struct that contains at least the same fields as a `NaiveDateTime`
struct. The most common example of that is a `DateTime`. In this case the information about the time
zone of that `DateTime` is completely ignored. This is the same principle as passing a `DateTime` to
`Date.to_iso8601/2`. `Date.to_iso8601/2` extracts only the date-specific fields (calendar, year,
month and day) of the given structure and ignores all others.
This way if you have a `DateTime` in one time zone, you can get the same wall time in another time zone.
For instance if you have 2018-08-24 10:00:00 in Copenhagen and want a `DateTime` for 2018-08-24 10:00:00
in UTC you can do:
iex> cph_datetime = DateTime.from_naive!(~N[2018-08-24 10:00:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
iex> {:ok, utc_datetime} = DateTime.from_naive(cph_datetime, "Etc/UTC", FakeTimeZoneDatabase)
iex> utc_datetime
#DateTime<2018-08-24 10:00:00Z>
If instead you want a `DateTime` for the same point time in a different time zone see the
`DateTime.shift_zone/3` function which would convert 2018-08-24 10:00:00 in Copenhagen
to 2018-08-24 08:00:00 in UTC.
"""
@doc since: "1.4.0"
@spec from_naive(
Calendar.naive_datetime(),
Calendar.time_zone(),
Calendar.time_zone_database()
) ::
{:ok, t}
| {:ambiguous, t, t}
| {:gap, t, t}
| {:error,
:incompatible_calendars | :time_zone_not_found | :utc_only_time_zone_database}
def from_naive(
naive_datetime,
time_zone,
time_zone_database \\ Calendar.get_time_zone_database()
)
def from_naive(naive_datetime, "Etc/UTC", _) do
utc_period = %{std_offset: 0, utc_offset: 0, zone_abbr: "UTC"}
{:ok, from_naive_with_period(naive_datetime, "Etc/UTC", utc_period)}
end
def from_naive(%{calendar: Calendar.ISO} = naive_datetime, time_zone, time_zone_database) do
case time_zone_database.time_zone_periods_from_wall_datetime(naive_datetime, time_zone) do
{:ok, period} ->
{:ok, from_naive_with_period(naive_datetime, time_zone, period)}
{:ambiguous, first_period, second_period} ->
first_datetime = from_naive_with_period(naive_datetime, time_zone, first_period)
second_datetime = from_naive_with_period(naive_datetime, time_zone, second_period)
{:ambiguous, first_datetime, second_datetime}
{:gap, {first_period, first_period_until_wall}, {second_period, second_period_from_wall}} ->
# `until_wall` is not valid, but any time just before is.
# So by subtracting a second and adding .999999 seconds
# we get the last microsecond just before.
before_naive =
first_period_until_wall
|> Map.put(:microsecond, {999_999, 6})
|> NaiveDateTime.add(-1)
after_naive = second_period_from_wall
latest_datetime_before = from_naive_with_period(before_naive, time_zone, first_period)
first_datetime_after = from_naive_with_period(after_naive, time_zone, second_period)
{:gap, latest_datetime_before, first_datetime_after}
{:error, _} = error ->
error
end
end
def from_naive(%{calendar: calendar} = naive_datetime, time_zone, time_zone_database)
when calendar != Calendar.ISO do
# For non-ISO calendars, convert to ISO, create ISO DateTime, and then
# convert to original calendar
iso_result =
with {:ok, in_iso} <- NaiveDateTime.convert(naive_datetime, Calendar.ISO) do
from_naive(in_iso, time_zone, time_zone_database)
end
case iso_result do
{:ok, dt} ->
convert(dt, calendar)
{:ambiguous, dt1, dt2} ->
with {:ok, dt1converted} <- convert(dt1, calendar),
{:ok, dt2converted} <- convert(dt2, calendar),
do: {:ambiguous, dt1converted, dt2converted}
{:gap, dt1, dt2} ->
with {:ok, dt1converted} <- convert(dt1, calendar),
{:ok, dt2converted} <- convert(dt2, calendar),
do: {:gap, dt1converted, dt2converted}
{:error, _} = error ->
error
end
end
defp from_naive_with_period(naive_datetime, time_zone, period) do
%{std_offset: std_offset, utc_offset: utc_offset, zone_abbr: zone_abbr} = period
@spec from_naive(NaiveDateTime.t(), Calendar.time_zone()) :: {:ok, t}
def from_naive(naive_datetime, time_zone)
def from_naive(%NaiveDateTime{} = naive_datetime, "Etc/UTC") do
%{
calendar: calendar,
hour: hour,
@@ -328,7 +202,7 @@ defmodule DateTime do
day: day
} = naive_datetime
%DateTime{
datetime = %DateTime{
calendar: calendar,
year: year,
month: month,
@@ -337,171 +211,40 @@ defmodule DateTime do
minute: minute,
second: second,
microsecond: microsecond,
std_offset: std_offset,
utc_offset: utc_offset,
zone_abbr: zone_abbr,
time_zone: time_zone
std_offset: 0,
utc_offset: 0,
zone_abbr: "UTC",
time_zone: "Etc/UTC"
}
{:ok, datetime}
end
@doc """
Converts the given `NaiveDateTime` to `DateTime`.
It expects a time zone to put the NaiveDateTime in.
If the time zone is "Etc/UTC", it always succeeds. Otherwise,
the NaiveDateTime is checked against the time zone database
given as `time_zone_database`. See the "Time zone database"
section in the module documentation.
Currently it only supports "Etc/UTC" as time zone.
## Examples
iex> DateTime.from_naive!(~N[2016-05-24 13:26:08.003], "Etc/UTC")
#DateTime<2016-05-24 13:26:08.003Z>
iex> DateTime.from_naive!(~N[2018-05-24 13:26:08.003], "Europe/Copenhagen", FakeTimeZoneDatabase)
#DateTime<2018-05-24 13:26:08.003+02:00 CEST Europe/Copenhagen>
"""
@doc since: "1.4.0"
@spec from_naive!(
NaiveDateTime.t(),
Calendar.time_zone(),
Calendar.time_zone_database()
) :: t
def from_naive!(
naive_datetime,
time_zone,
time_zone_database \\ Calendar.get_time_zone_database()
) do
case from_naive(naive_datetime, time_zone, time_zone_database) do
@spec from_naive!(NaiveDateTime.t(), Calendar.time_zone()) :: t
def from_naive!(naive_datetime, time_zone) do
case from_naive(naive_datetime, time_zone) do
{:ok, datetime} ->
datetime
{:ambiguous, dt1, dt2} ->
raise ArgumentError,
"cannot convert #{inspect(naive_datetime)} to datetime because such " <>
"instant is ambiguous in time zone #{time_zone} as there is an overlap " <>
"between #{inspect(dt1)} and #{inspect(dt2)}"
{:gap, dt1, dt2} ->
raise ArgumentError,
"cannot convert #{inspect(naive_datetime)} to datetime because such " <>
"instant does not exist in time zone #{time_zone} as there is a gap " <>
"between #{inspect(dt1)} and #{inspect(dt2)}"
{:error, reason} ->
raise ArgumentError,
"cannot convert #{inspect(naive_datetime)} to datetime, reason: #{inspect(reason)}"
"cannot parse #{inspect(naive_datetime)} to datetime, reason: #{inspect(reason)}"
end
end
@doc """
Changes the time zone of a `DateTime`.
Returns a `DateTime` for the same point in time, but instead at
the time zone provided. It assumes that `DateTime` is valid and
exists in the given time zone and calendar.
By default, it uses the default time zone database returned by
`Calendar.get_time_zone_database/0`, which defaults to
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC" datetimes.
Other time zone databases can be passed as argument or set globally.
See the "Time zone database" section in the module docs.
## Examples
iex> cph_datetime = DateTime.from_naive!(~N[2018-07-16 12:00:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
iex> {:ok, pacific_datetime} = DateTime.shift_zone(cph_datetime, "America/Los_Angeles", FakeTimeZoneDatabase)
iex> pacific_datetime
#DateTime<2018-07-16 03:00:00-07:00 PDT America/Los_Angeles>
"""
@doc since: "1.8.0"
@spec shift_zone(t, Calendar.time_zone(), Calendar.time_zone_database()) ::
{:ok, t} | {:error, :time_zone_not_found | :utc_only_time_zone_database}
def shift_zone(datetime, time_zone, time_zone_database \\ Calendar.get_time_zone_database())
def shift_zone(%{time_zone: time_zone} = datetime, time_zone, _) do
{:ok, datetime}
end
def shift_zone(datetime, time_zone, time_zone_database) do
%{
std_offset: std_offset,
utc_offset: utc_offset,
calendar: calendar,
microsecond: {_, precision}
} = datetime
datetime
|> to_iso_days()
|> apply_tz_offset(utc_offset + std_offset)
|> shift_zone_for_iso_days_utc(calendar, precision, time_zone, time_zone_database)
end
defp shift_zone_for_iso_days_utc(iso_days_utc, calendar, precision, time_zone, time_zone_db) do
case time_zone_db.time_zone_period_from_utc_iso_days(iso_days_utc, time_zone) do
{:ok, %{std_offset: std_offset, utc_offset: utc_offset, zone_abbr: zone_abbr}} ->
{year, month, day, hour, minute, second, {microsecond_without_precision, _}} =
iso_days_utc
|> apply_tz_offset(-(utc_offset + std_offset))
|> calendar.naive_datetime_from_iso_days()
datetime = %DateTime{
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: {microsecond_without_precision, precision},
std_offset: std_offset,
utc_offset: utc_offset,
zone_abbr: zone_abbr,
time_zone: time_zone
}
{:ok, datetime}
{:error, _} = error ->
error
end
end
@doc """
Returns the current datetime in the provided time zone.
By default, it uses the default time_zone returned by
`Calendar.get_time_zone_database/0`, which defaults to
`Calendar.UTCOnlyTimeZoneDatabase` which only handles "Etc/UTC" datetimes.
Other time zone databases can be passed as argument or set globally.
See the "Time zone database" section in the module docs.
## Examples
iex> {:ok, datetime} = DateTime.now("Etc/UTC")
iex> datetime.time_zone
"Etc/UTC"
iex> DateTime.now("Europe/Copenhagen")
{:error, :utc_only_time_zone_database}
iex> DateTime.now("not a real time zone name", FakeTimeZoneDatabase)
{:error, :time_zone_not_found}
"""
@doc since: "1.8.0"
@spec now(Calendar.time_zone(), Calendar.time_zone_database()) ::
{:ok, t} | {:error, :time_zone_not_found | :utc_only_time_zone_database}
def now(time_zone, time_zone_database \\ Calendar.get_time_zone_database())
def now("Etc/UTC", _) do
{:ok, utc_now()}
end
def now(time_zone, time_zone_database) do
shift_zone(utc_now(), time_zone, time_zone_database)
end
@doc """
Converts the given `datetime` to Unix time.
@@ -554,9 +297,9 @@ defmodule DateTime do
~N[2000-02-29 23:00:07.0]
"""
@spec to_naive(Calendar.datetime()) :: NaiveDateTime.t()
def to_naive(datetime) do
%{
@spec to_naive(t) :: NaiveDateTime.t()
def to_naive(%DateTime{} = datetime) do
%DateTime{
calendar: calendar,
year: year,
month: month,
@@ -594,8 +337,8 @@ defmodule DateTime do
~D[2000-02-29]
"""
@spec to_date(Calendar.datetime()) :: Date.t()
def to_date(datetime) do
@spec to_date(t) :: Date.t()
def to_date(%DateTime{} = datetime) do
%{year: year, month: month, day: day, calendar: calendar} = datetime
%Date{year: year, month: month, day: day, calendar: calendar}
end
@@ -615,8 +358,8 @@ defmodule DateTime do
~T[23:00:07.0]
"""
@spec to_time(Calendar.datetime()) :: Time.t()
def to_time(datetime) do
@spec to_time(t) :: Time.t()
def to_time(%DateTime{} = datetime) do
%{hour: hour, minute: minute, second: second, microsecond: microsecond, calendar: calendar} =
datetime
@@ -723,10 +466,10 @@ defmodule DateTime do
As specified in the standard, the separator "T" may be omitted if
desired as there is no ambiguity within this function.
The year parsed by this function is limited to four digits and,
while ISO 8601 allows datetimes to specify 24:00:00 as the zero
hour of the next day, this notation is not supported by Elixir.
Note leap seconds are not supported by the built-in Calendar.ISO.
Time representations with reduced accuracy are not supported.
Note that while ISO 8601 allows datetimes to specify 24:00:00 as the
zero hour of the next day, this notation is not supported by Elixir.
## Examples
@@ -752,14 +495,19 @@ defmodule DateTime do
iex> DateTime.from_iso8601("2015-01-23P23:50:07")
{:error, :invalid_format}
iex> DateTime.from_iso8601("2015-01-23 23:50:07A")
{:error, :invalid_format}
iex> DateTime.from_iso8601("2015-01-23T23:50:07")
{:error, :missing_offset}
iex> DateTime.from_iso8601("2015-01-23 23:50:61")
{:error, :invalid_time}
iex> DateTime.from_iso8601("2015-01-32 23:50:07")
{:error, :invalid_date}
iex> DateTime.from_iso8601("2015-01-23T23:50:07.123-00:00")
{:error, :invalid_format}
iex> DateTime.from_iso8601("2015-01-23T23:50:07.123-00:60")
{:error, :invalid_format}
"""
@doc since: "1.4.0"
@@ -779,14 +527,14 @@ defmodule DateTime do
[match_date, guard_date, read_date] = Calendar.ISO.__match_date__()
[match_time, guard_time, read_time] = Calendar.ISO.__match_time__()
defp raw_from_iso8601(string, calendar, is_year_negative) do
defp raw_from_iso8601(string, calendar, is_negative_datetime) do
with <<unquote(match_date), sep, unquote(match_time), rest::binary>> <- string,
true <- unquote(guard_date) and sep in @sep and unquote(guard_time),
{microsecond, rest} <- Calendar.ISO.parse_microsecond(rest),
{offset, ""} <- Calendar.ISO.parse_offset(rest) do
{year, month, day} = unquote(read_date)
{hour, minute, second} = unquote(read_time)
year = if is_year_negative, do: -year, else: year
year = if is_negative_datetime, do: -year, else: year
cond do
not calendar.valid_date?(year, month, day) ->
@@ -817,36 +565,22 @@ defmodule DateTime do
{:error, :missing_offset}
true ->
day_fraction = Calendar.ISO.time_to_day_fraction(hour, minute, second, {0, 0})
{_, precision} = microsecond
{{year, month, day}, {hour, minute, second, _}} =
case apply_tz_offset({0, day_fraction}, offset) do
{0, day_fraction} ->
{{year, month, day}, Calendar.ISO.time_from_day_fraction(day_fraction)}
datetime =
Calendar.ISO.naive_datetime_to_iso_days(
year,
month,
day,
hour,
minute,
second,
microsecond
)
|> apply_tz_offset(offset)
|> from_iso_days("Etc/UTC", "UTC", 0, 0, calendar, precision)
{extra_days, day_fraction} ->
base_days = Calendar.ISO.date_to_iso_days(year, month, day)
{Calendar.ISO.date_from_iso_days(base_days + extra_days),
Calendar.ISO.time_from_day_fraction(day_fraction)}
end
datetime = %DateTime{
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond,
std_offset: 0,
utc_offset: 0,
zone_abbr: "UTC",
time_zone: "Etc/UTC"
}
{:ok, datetime, offset}
{:ok, %{datetime | microsecond: microsecond}, offset}
end
else
_ -> {:error, :invalid_format}
@@ -939,8 +673,8 @@ defmodule DateTime do
@doc since: "1.4.0"
@spec compare(Calendar.datetime(), Calendar.datetime()) :: :lt | :eq | :gt
def compare(
%{utc_offset: utc_offset1, std_offset: std_offset1} = datetime1,
%{utc_offset: utc_offset2, std_offset: std_offset2} = datetime2
%{calendar: _, utc_offset: utc_offset1, std_offset: std_offset1} = datetime1,
%{calendar: _, utc_offset: utc_offset2, std_offset: std_offset2} = datetime2
) do
{days1, {parts1, ppd1}} =
datetime1
@@ -953,13 +687,13 @@ defmodule DateTime do
|> apply_tz_offset(utc_offset2 + std_offset2)
# Ensure fraction tuples have same denominator.
first = {days1, parts1 * ppd2}
second = {days2, parts2 * ppd1}
iso_days1 = {days1, parts1 * ppd2}
iso_days2 = {days2, parts2 * ppd1}
cond do
first > second -> :gt
first < second -> :lt
true -> :eq
case {iso_days1, iso_days2} do
{first, second} when first > second -> :gt
{first, second} when first < second -> :lt
_ -> :eq
end
end
@@ -988,7 +722,7 @@ defmodule DateTime do
"""
@doc since: "1.5.0"
@spec diff(Calendar.datetime(), Calendar.datetime(), System.time_unit()) :: integer()
@spec diff(Calendar.datetime(), Calendar.datetime()) :: integer()
def diff(
%{utc_offset: utc_offset1, std_offset: std_offset1} = datetime1,
%{utc_offset: utc_offset2, std_offset: std_offset2} = datetime2,
@@ -1002,81 +736,10 @@ defmodule DateTime do
naive_diff + System.convert_time_unit(offset_diff, :second, unit)
end
@doc """
Adds a specified amount of time to a `DateTime`.
Accepts an `amount_to_add` in any `unit` available from `t:System.time_unit/0`.
Negative values will move backwards in time.
Takes changes such as summer time/DST into account. This means that adding time
can cause the wall time to "go backwards" during "fall back" during autumn.
Adding just a few seconds to a datetime just before "spring forward" can cause wall
time to increase by more than an hour.
Fractional second precision stays the same in a similar way to `NaiveDateTime.add/2`.
### Examples
iex> dt = DateTime.from_naive!(~N[2018-11-15 10:00:00], "Europe/Copenhagen", FakeTimeZoneDatabase)
iex> dt |> DateTime.add(3600, :second, FakeTimeZoneDatabase)
#DateTime<2018-11-15 11:00:00+01:00 CET Europe/Copenhagen>
iex> dt = DateTime.from_naive!(~N[2018-11-15 10:00:00], "Etc/UTC")
iex> dt |> DateTime.add(3600, :second)
#DateTime<2018-11-15 11:00:00Z>
When adding 3 seconds just before "spring forward" we go from 1:59:59 to 3:00:02
iex> dt = DateTime.from_naive!(~N[2019-03-31 01:59:59.123], "Europe/Copenhagen", FakeTimeZoneDatabase)
iex> dt |> DateTime.add(3, :second, FakeTimeZoneDatabase)
#DateTime<2019-03-31 03:00:02.123+02:00 CEST Europe/Copenhagen>
"""
@doc since: "1.8.0"
@spec add(Calendar.datetime(), integer, System.time_unit(), Calendar.time_zone_database()) ::
t()
def add(
datetime,
amount_to_add,
unit \\ :second,
time_zone_database \\ Calendar.get_time_zone_database()
)
when is_integer(amount_to_add) do
%{
utc_offset: utc_offset,
std_offset: std_offset,
calendar: calendar,
microsecond: {_, precision}
} = datetime
ppd = System.convert_time_unit(86400, :second, unit)
total_offset = System.convert_time_unit(utc_offset + std_offset, :second, unit)
result =
datetime
|> to_iso_days()
# Subtract total offset in order to get UTC and add the integer for the addition
|> Calendar.ISO.add_day_fraction_to_iso_days(amount_to_add - total_offset, ppd)
|> shift_zone_for_iso_days_utc(calendar, precision, datetime.time_zone, time_zone_database)
case result do
{:ok, result_datetime} ->
result_datetime
{:error, error} ->
raise ArgumentError,
"cannot add #{amount_to_add} #{unit} to #{inspect(datetime)} (with time zone " <>
"database #{inspect(time_zone_database)}), reason: #{inspect(error)}"
end
end
@doc """
Returns the given datetime with the microsecond field truncated to the given
precision (`:microsecond`, `millisecond` or `:second`).
The given datetime is returned unchanged if it already has lower precision than
the given precision.
## Examples
iex> dt1 = %DateTime{year: 2017, month: 11, day: 7, zone_abbr: "CET",
@@ -1099,15 +762,11 @@ defmodule DateTime do
"""
@doc since: "1.6.0"
@spec truncate(Calendar.datetime(), :microsecond | :millisecond | :second) :: t()
@spec truncate(t(), :microsecond | :millisecond | :second) :: t()
def truncate(%DateTime{microsecond: microsecond} = datetime, precision) do
%{datetime | microsecond: Calendar.truncate(microsecond, precision)}
end
def truncate(%{} = datetime_map, precision) do
truncate(from_map(datetime_map), precision)
end
@doc """
Converts a given `datetime` from one calendar to another.
@@ -1135,12 +794,40 @@ defmodule DateTime do
@spec convert(Calendar.datetime(), Calendar.calendar()) ::
{:ok, t} | {:error, :incompatible_calendars}
def convert(%DateTime{calendar: calendar} = datetime, calendar) do
{:ok, datetime}
end
# Keep it multiline for proper function clause errors.
def convert(
%{
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond,
time_zone: time_zone,
zone_abbr: zone_abbr,
utc_offset: utc_offset,
std_offset: std_offset
},
calendar
) do
datetime = %DateTime{
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond,
time_zone: time_zone,
zone_abbr: zone_abbr,
utc_offset: utc_offset,
std_offset: std_offset
}
def convert(%{calendar: calendar} = datetime, calendar) do
{:ok, from_map(datetime)}
{:ok, datetime}
end
def convert(%{calendar: dt_calendar, microsecond: {_, precision}} = datetime, calendar) do
@@ -1179,7 +866,7 @@ defmodule DateTime do
"""
@doc since: "1.5.0"
@spec convert!(Calendar.datetime(), Calendar.calendar()) :: t
@spec convert!(Calendar.datetime(), Calendar.calendar()) :: t | no_return
def convert!(datetime, calendar) do
case convert(datetime, calendar) do
{:ok, value} ->
@@ -1211,6 +898,10 @@ defmodule DateTime do
%{time_zone: time_zone, zone_abbr: zone_abbr, utc_offset: utc_offset, std_offset: std_offset} =
datetime
from_iso_days(iso_days, time_zone, zone_abbr, utc_offset, std_offset, calendar, precision)
end
defp from_iso_days(iso_days, time_zone, zone_abbr, utc_offset, std_offset, calendar, precision) do
{year, month, day, hour, minute, second, {microsecond, _}} =
calendar.naive_datetime_from_iso_days(iso_days)
@@ -1230,30 +921,10 @@ defmodule DateTime do
}
end
defp apply_tz_offset(iso_days, 0) do
iso_days
end
defp apply_tz_offset(iso_days, offset) do
Calendar.ISO.add_day_fraction_to_iso_days(iso_days, -offset, 86400)
end
defp from_map(%{} = datetime_map) do
%DateTime{
year: datetime_map.year,
month: datetime_map.month,
day: datetime_map.day,
hour: datetime_map.hour,
minute: datetime_map.minute,
second: datetime_map.second,
microsecond: datetime_map.microsecond,
time_zone: datetime_map.time_zone,
zone_abbr: datetime_map.zone_abbr,
utc_offset: datetime_map.utc_offset,
std_offset: datetime_map.std_offset
}
end
defimpl String.Chars do
def to_string(datetime) do
%{
+19 -150
View File
@@ -26,7 +26,7 @@ defmodule Calendar.ISO do
@seconds_per_minute 60
@seconds_per_hour 60 * 60
# Note that this does *not* handle leap seconds.
# Note that this does _not_ handle leap seconds.
@seconds_per_day 24 * 60 * 60
@last_second_of_the_day @seconds_per_day - 1
@microseconds_per_second 1_000_000
@@ -37,11 +37,6 @@ defmodule Calendar.ISO do
@months_in_year 12
# The ISO epoch starts, in this implementation,
# with ~D[0000-01-01]. Era "1" starts
# on ~D[0001-01-01] which is 366 days later.
@iso_epoch 366
@doc false
def __match_date__ do
quote do
@@ -180,12 +175,8 @@ defmodule Calendar.ISO do
@impl true
@spec time_from_day_fraction(Calendar.day_fraction()) ::
{Calendar.hour(), Calendar.minute(), Calendar.second(), Calendar.microsecond()}
def time_from_day_fraction({0, _}) do
{0, 0, 0, {0, 6}}
end
def time_from_day_fraction({parts_in_day, parts_per_day}) do
total_microseconds = divide_by_parts_per_day(parts_in_day, parts_per_day)
total_microseconds = div(parts_in_day * @parts_per_day, parts_per_day)
{hours, rest_microseconds1} =
div_mod(total_microseconds, @seconds_per_hour * @microseconds_per_second)
@@ -197,13 +188,9 @@ defmodule Calendar.ISO do
{hours, minutes, seconds, {microseconds, 6}}
end
defp divide_by_parts_per_day(parts_in_day, @parts_per_day), do: parts_in_day
defp divide_by_parts_per_day(parts_in_day, parts_per_day),
do: div(parts_in_day * @parts_per_day, parts_per_day)
# Converts year, month, day to count of days since 0000-01-01.
@doc false
@doc since: "1.5.0"
def date_to_iso_days(0, 1, 1) do
0
end
@@ -339,123 +326,7 @@ defmodule Calendar.ISO do
@impl true
def day_of_week(year, month, day)
when is_integer(year) and is_integer(month) and is_integer(day) do
iso_days_to_day_of_week(date_to_iso_days(year, month, day))
end
defp iso_days_to_day_of_week(iso_days) do
Integer.mod(iso_days + 5, 7) + 1
end
@doc """
Calculates the day of the year from the given `year`, `month`, and `day`.
It is an integer from 1 to 366.
## Examples
iex> Calendar.ISO.day_of_year(2016, 1, 31)
31
iex> Calendar.ISO.day_of_year(-99, 2, 1)
32
iex> Calendar.ISO.day_of_year(2018, 2, 28)
59
"""
@doc since: "1.8.0"
@spec day_of_year(year, month, day) :: 1..366
@impl true
def day_of_year(year, month, day)
when is_integer(year) and is_integer(month) and is_integer(day) do
true = day <= days_in_month(year, month)
days_before_month(month) + leap_day_offset(year, month) + day
end
@doc """
Calculates the quarter of the year from the given `year`, `month`, and `day`.
It is an integer from 1 to 4.
## Examples
iex> Calendar.ISO.quarter_of_year(2016, 1, 31)
1
iex> Calendar.ISO.quarter_of_year(2016, 4, 3)
2
iex> Calendar.ISO.quarter_of_year(-99, 9, 31)
3
iex> Calendar.ISO.quarter_of_year(2018, 12, 28)
4
"""
@doc since: "1.8.0"
@spec quarter_of_year(year, month, day) :: 1..4
@impl true
def quarter_of_year(year, month, day)
when is_integer(year) and is_integer(month) and is_integer(day) do
div(month - 1, 3) + 1
end
@doc """
Calculates the year and era from the given `year`.
The ISO calendar has two eras: the current era which
starts in year 1 and is defined as era "1". And a
second era for those years less than 1 defined as
era "0".
## Examples
iex> Calendar.ISO.year_of_era(1)
{1, 1}
iex> Calendar.ISO.year_of_era(2018)
{2018, 1}
iex> Calendar.ISO.year_of_era(0)
{1, 0}
iex> Calendar.ISO.year_of_era(-1)
{2, 0}
"""
@doc since: "1.8.0"
@spec year_of_era(year) :: {year, era :: 0..1}
@impl true
def year_of_era(year) when is_integer(year) and year > 0 do
{year, 1}
end
def year_of_era(year) when is_integer(year) and year < 1 do
{abs(year) + 1, 0}
end
@doc """
Calculates the day and era from the given `year`, `month`, and `day`.
## Examples
iex> Calendar.ISO.day_of_era(0, 1, 1)
{366, 0}
iex> Calendar.ISO.day_of_era(1, 1, 1)
{1, 1}
iex> Calendar.ISO.day_of_era(0, 12, 31)
{1, 0}
iex> Calendar.ISO.day_of_era(0, 12, 30)
{2, 0}
iex> Calendar.ISO.day_of_era(-1, 12, 31)
{367, 0}
"""
@doc since: "1.8.0"
@spec day_of_era(year, month, day) :: {day :: pos_integer(), era :: 0..1}
@impl true
def day_of_era(year, month, day)
when is_integer(year) and is_integer(month) and is_integer(day) and year > 0 do
day = date_to_iso_days(year, month, day) - @iso_epoch + 1
{day, 1}
end
def day_of_era(year, month, day)
when is_integer(year) and is_integer(month) and is_integer(day) and year < 1 do
day = abs(date_to_iso_days(year, month, day) - @iso_epoch)
{day, 0}
Integer.mod(date_to_iso_days(year, month, day) + 5, 7) + 1
end
@doc """
@@ -556,16 +427,13 @@ defmodule Calendar.ISO do
## Examples
iex> time_zone = "Europe/Berlin"
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "CET", 3600, 0)
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, "Europe/Berlin", "CET", 3600, 0)
"2017-08-01 01:02:03.00000+01:00 CET Europe/Berlin"
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, time_zone, "CDT", 3600, 3600)
iex> Calendar.ISO.datetime_to_string(2017, 8, 1, 1, 2, 3, {4, 5}, "Europe/Berlin", "CDT", 3600, 3600)
"2017-08-01 01:02:03.00000+02:00 CDT Europe/Berlin"
iex> time_zone = "America/Los_Angeles"
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, time_zone, "PST", -28800, 0)
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, "America/Los_Angeles", "PST", -28800, 0)
"2015-02-28 01:02:03.00000-08:00 PST America/Los_Angeles"
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, time_zone, "PDT", -28800, 3600)
iex> Calendar.ISO.datetime_to_string(2015, 2, 28, 1, 2, 3, {4, 5}, "America/Los_Angeles", "PDT", -28800, 3600)
"2015-02-28 01:02:03.00000-07:00 PDT America/Los_Angeles"
"""
@@ -628,32 +496,30 @@ defmodule Calendar.ISO do
@doc """
Determines if the date given is valid according to the proleptic Gregorian calendar.
Note that while ISO 8601 allows times to specify 24:00:00 as the
zero hour of the next day, this notation is not supported by Elixir.
Leap seconds are not supported as well by the built-in Calendar.ISO.
Note that leap seconds are considered valid, but the use of 24:00:00 as the
zero hour of the day is considered invalid.
## Examples
iex> Calendar.ISO.valid_time?(10, 50, 25, {3006, 6})
true
iex> Calendar.ISO.valid_time?(23, 59, 60, {0, 0})
false
true
iex> Calendar.ISO.valid_time?(24, 0, 0, {0, 0})
false
"""
@doc since: "1.5.0"
@impl true
@spec valid_time?(Calendar.hour(), Calendar.minute(), Calendar.second(), Calendar.microsecond()) ::
@spec valid_time?(Calendar.hour(), Calendar.minute(), Calendar.secon(), Calendar.microsecond()) ::
boolean
def valid_time?(hour, minute, second, {microsecond, precision}) do
hour in 0..23 and minute in 0..59 and second in 0..59 and microsecond in 0..999_999 and
hour in 0..23 and minute in 0..59 and second in 0..60 and microsecond in 0..999_999 and
precision in 0..6
end
@doc """
See `c:Calendar.day_rollover_relative_to_midnight_utc/0` for documentation.
See `c:Calendar.day_rollover_relative_to_midlight_utc/0` for documentation.
"""
@doc since: "1.5.0"
@impl true
@@ -689,7 +555,7 @@ defmodule Calendar.ISO do
defp zero_pad(val, count) when val >= 0 do
num = Integer.to_string(val)
:binary.copy("0", max(count - byte_size(num), 0)) <> num
:binary.copy("0", count - byte_size(num)) <> num
end
defp zero_pad(val, count) do
@@ -725,6 +591,7 @@ defmodule Calendar.ISO do
do: precision_for_unit(div(number, 10), precision + 1)
@doc false
@doc since: "1.5.0"
def date_to_iso8601(year, month, day, format \\ :extended) do
date_to_string(year, month, day, format)
end
@@ -829,13 +696,15 @@ defmodule Calendar.ISO do
end
@doc false
@doc since: "1.5.0"
def iso_days_to_unit({days, {parts, ppd}}, unit) do
day_microseconds = days * @parts_per_day
microseconds = divide_by_parts_per_day(parts, ppd)
microseconds = div(parts * @parts_per_day, ppd)
System.convert_time_unit(day_microseconds + microseconds, :microsecond, unit)
end
@doc false
@doc since: "1.5.0"
def add_day_fraction_to_iso_days({days, {parts, ppd}}, add, ppd) do
normalize_iso_days(days, parts + add, ppd)
end
+36 -98
View File
@@ -5,7 +5,7 @@ defmodule NaiveDateTime do
The NaiveDateTime struct contains the fields year, month, day, hour,
minute, second, microsecond and calendar. New naive datetimes can be
built with the `new/2` and `new/8` functions or using the
`~N` (see `Kernel.sigil_N/2`) sigil:
[`~N`](`Kernel.sigil_N/2`) sigil:
iex> ~N[2000-01-01 23:00:07]
~N[2000-01-01 23:00:07]
@@ -28,9 +28,14 @@ defmodule NaiveDateTime do
`NaiveDateTime` is not validated against a time zone, such errors
would go unnoticed.
The functions of this module work with the `NaiveDateTime` struct as well
as any struct that contains the same fields as the `NaiveDateTime` struct,
such as `DateTime`. Such functions expect
`t:Calendar.naive_datetime/0` in their typespecs (instead of `t:t/0`).
Developers should avoid creating the NaiveDateTime structs directly
and instead, rely on the functions provided by this module as well
as the ones in third-party calendar libraries.
as the ones in 3rd party calendar libraries.
## Comparing naive date times
@@ -67,7 +72,7 @@ defmodule NaiveDateTime do
calendar: Calendar.ISO
]
@type t :: %__MODULE__{
@type t :: %NaiveDateTime{
year: Calendar.year(),
month: Calendar.month(),
day: Calendar.day(),
@@ -141,11 +146,13 @@ defmodule NaiveDateTime do
{:ok, ~N[2000-01-01 23:59:59.0]}
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 59, 999_999)
{:ok, ~N[2000-01-01 23:59:59.999999]}
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 60, 999_999)
{:ok, ~N[2000-01-01 23:59:60.999999]}
iex> NaiveDateTime.new(2000, 1, 1, 24, 59, 59, 999_999)
{:error, :invalid_time}
iex> NaiveDateTime.new(2000, 1, 1, 23, 60, 59, 999_999)
{:error, :invalid_time}
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 60, 999_999)
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 61, 999_999)
{:error, :invalid_time}
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 59, 1_000_000)
{:error, :invalid_time}
@@ -228,9 +235,11 @@ defmodule NaiveDateTime do
@doc """
Adds a specified amount of time to a `NaiveDateTime`.
Accepts an `amount_to_add` in any `unit` available from `t:System.time_unit/0`.
Accepts an `integer` in any `unit` available from `t:System.time_unit/0`.
Negative values will move backwards in time.
This operation is only possible if both calendars are convertible to `Calendar.ISO`.
## Examples
# adds seconds by default
@@ -258,29 +267,17 @@ defmodule NaiveDateTime do
iex> NaiveDateTime.add(~N[0000-01-01 00:00:00], 63_579_428_950)
~N[2014-10-02 00:29:10]
Passing a `Datetime` automatically converts it to `NaiveDateTime`,
discarding the time zone information:
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "CET",
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Warsaw"}
iex> NaiveDateTime.add(dt, 21, :second)
~N[2000-02-29 23:00:28]
"""
@doc since: "1.4.0"
@spec add(Calendar.naive_datetime(), integer, System.time_unit()) :: t
def add(
%{microsecond: {_, precision}, calendar: calendar} = naive_datetime,
amount_to_add,
unit \\ :second
)
when is_integer(amount_to_add) do
@spec add(t, integer, System.time_unit()) :: t
def add(%NaiveDateTime{} = naive_datetime, integer, unit \\ :second)
when is_integer(integer) do
%{microsecond: {_, precision}, calendar: calendar} = naive_datetime
ppd = System.convert_time_unit(86400, :second, unit)
naive_datetime
|> to_iso_days()
|> Calendar.ISO.add_day_fraction_to_iso_days(amount_to_add, ppd)
|> Calendar.ISO.add_day_fraction_to_iso_days(integer, ppd)
|> from_iso_days(calendar, precision)
end
@@ -311,13 +308,13 @@ defmodule NaiveDateTime do
"""
@doc since: "1.4.0"
@spec diff(Calendar.naive_datetime(), Calendar.naive_datetime(), System.time_unit()) :: integer
@spec diff(t, t, System.time_unit()) :: integer
def diff(
%{calendar: calendar1} = naive_datetime1,
%{calendar: calendar2} = naive_datetime2,
%NaiveDateTime{} = naive_datetime1,
%NaiveDateTime{} = naive_datetime2,
unit \\ :second
) do
if not Calendar.compatible_calendars?(calendar1, calendar2) do
if not Calendar.compatible_calendars?(naive_datetime1.calendar, naive_datetime2.calendar) do
raise ArgumentError,
"cannot calculate the difference between #{inspect(naive_datetime1)} and " <>
"#{inspect(naive_datetime2)} because their calendars are not compatible " <>
@@ -333,9 +330,6 @@ defmodule NaiveDateTime do
Returns the given naive datetime with the microsecond field truncated to the
given precision (`:microsecond`, `:millisecond` or `:second`).
The given naive datetime is returned unchanged if it already has lower precision
than the given precision.
## Examples
iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :microsecond)
@@ -354,31 +348,6 @@ defmodule NaiveDateTime do
%{naive_datetime | microsecond: Calendar.truncate(microsecond, precision)}
end
def truncate(
%{
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond
},
precision
) do
%NaiveDateTime{
calendar: calendar,
year: year,
month: month,
day: day,
hour: hour,
minute: minute,
second: second,
microsecond: Calendar.truncate(microsecond, precision)
}
end
@doc """
Converts a `NaiveDateTime` into a `Date`.
@@ -391,24 +360,11 @@ defmodule NaiveDateTime do
~D[2002-01-13]
"""
@spec to_date(Calendar.naive_datetime()) :: Date.t()
@spec to_date(t) :: Date.t()
def to_date(%NaiveDateTime{year: year, month: month, day: day, calendar: calendar}) do
%Date{year: year, month: month, day: day, calendar: calendar}
end
def to_date(%{
year: year,
month: month,
day: day,
calendar: calendar,
hour: _,
minute: _,
second: _,
microsecond: _
}) do
%Date{year: year, month: month, day: day, calendar: calendar}
end
@doc """
Converts a `NaiveDateTime` into `Time`.
@@ -421,7 +377,7 @@ defmodule NaiveDateTime do
~T[23:00:07]
"""
@spec to_time(Calendar.naive_datetime()) :: Time.t()
@spec to_time(t) :: Time.t()
def to_time(%NaiveDateTime{} = naive_datetime) do
%{
hour: hour,
@@ -440,25 +396,6 @@ defmodule NaiveDateTime do
}
end
def to_time(%{
year: _,
month: _,
day: _,
calendar: calendar,
hour: hour,
minute: minute,
second: second,
microsecond: microsecond
}) do
%Time{
hour: hour,
minute: minute,
second: second,
microsecond: microsecond,
calendar: calendar
}
end
@doc """
Converts the given naive datetime to a string according to its calendar.
@@ -507,10 +444,10 @@ defmodule NaiveDateTime do
As specified in the standard, the separator "T" may be omitted if
desired as there is no ambiguity within this function.
The year parsed by this function is limited to four digits and,
while ISO 8601 allows datetimes to specify 24:00:00 as the zero
hour of the next day, this notation is not supported by Elixir.
Note leap seconds are not supported by the built-in Calendar.ISO.
Time representations with reduced accuracy are not supported.
Note that while ISO 8601 allows datetimes to specify 24:00:00 as the
zero hour of the next day, this notation is not supported by Elixir.
## Examples
@@ -580,8 +517,8 @@ defmodule NaiveDateTime do
{year, month, day} = unquote(read_date)
{hour, min, sec} = unquote(read_time)
with {:ok, iso_naive_dt} <- new(year, month, day, hour, min, sec, microsec, Calendar.ISO) do
convert(iso_naive_dt, calendar)
with {:ok, utc_date} <- new(year, month, day, hour, min, sec, microsec, Calendar.ISO) do
convert(utc_date, calendar)
end
else
_ -> {:error, :invalid_format}
@@ -604,7 +541,7 @@ defmodule NaiveDateTime do
** (ArgumentError) cannot parse "2015-01-23P23:50:07" as naive datetime, reason: :invalid_format
"""
@spec from_iso8601!(String.t(), Calendar.calendar()) :: t
@spec from_iso8601!(String.t(), Calendar.calendar()) :: t | no_return
def from_iso8601!(string, calendar \\ Calendar.ISO) do
case from_iso8601(string, calendar) do
{:ok, value} ->
@@ -734,8 +671,8 @@ defmodule NaiveDateTime do
def from_erl(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
def from_erl({{year, month, day}, {hour, minute, second}}, microsecond, calendar) do
with {:ok, iso_naive_dt} <- new(year, month, day, hour, minute, second, microsecond),
do: convert(iso_naive_dt, calendar)
with {:ok, utc_date} <- new(year, month, day, hour, minute, second, microsecond),
do: convert(utc_date, calendar)
end
@doc """
@@ -754,7 +691,8 @@ defmodule NaiveDateTime do
** (ArgumentError) cannot convert {{2000, 13, 1}, {13, 30, 15}} to naive datetime, reason: :invalid_date
"""
@spec from_erl!(:calendar.datetime(), Calendar.microsecond(), Calendar.calendar()) :: t
@spec from_erl!(:calendar.datetime(), Calendar.microsecond(), Calendar.calendar()) ::
t | no_return
def from_erl!(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO) do
case from_erl(tuple, microsecond, calendar) do
{:ok, value} ->
+20 -59
View File
@@ -4,7 +4,7 @@ defmodule Time do
The Time struct contains the fields hour, minute, second and microseconds.
New times can be built with the `new/4` function or using the
`~T` (see `Kernel.sigil_T/2`) sigil:
[`~T`](`Kernel.sigil_T/2`) sigil:
iex> ~T[23:00:07.001]
~T[23:00:07.001]
@@ -25,7 +25,7 @@ defmodule Time do
Developers should avoid creating the Time structs directly
and instead rely on the functions provided by this module as well
as the ones in third-party calendar libraries.
as the ones in 3rd party calendar libraries.
## Comparing times
@@ -37,7 +37,7 @@ defmodule Time do
@enforce_keys [:hour, :minute, :second]
defstruct [:hour, :minute, :second, microsecond: {0, 0}, calendar: Calendar.ISO]
@type t :: %__MODULE__{
@type t :: %Time{
hour: Calendar.hour(),
minute: Calendar.minute(),
second: Calendar.second(),
@@ -45,8 +45,6 @@ defmodule Time do
calendar: Calendar.calendar()
}
@parts_per_day 86_400_000_000
@doc """
Returns the current time in UTC.
@@ -80,10 +78,9 @@ defmodule Time do
Expects all values to be integers. Returns `{:ok, time}` if each
entry fits its appropriate range, returns `{:error, reason}` otherwise.
Microseconds can also be given with a precision, which must be an
integer between 0 and 6.
The built-in calendar does not support leap seconds.
Note a time may have 60 seconds in case of leap seconds. Microseconds
can also be given with a precision, which must be an integer between
0 and 6.
## Examples
@@ -91,12 +88,18 @@ defmodule Time do
{:ok, ~T[00:00:00.000000]}
iex> Time.new(23, 59, 59, 999_999)
{:ok, ~T[23:59:59.999999]}
iex> Time.new(23, 59, 60, 999_999)
{:ok, ~T[23:59:60.999999]}
# Time with microseconds and their precision
iex> Time.new(23, 59, 60, {10_000, 2})
{:ok, ~T[23:59:60.01]}
iex> Time.new(24, 59, 59, 999_999)
{:error, :invalid_time}
iex> Time.new(23, 60, 59, 999_999)
{:error, :invalid_time}
iex> Time.new(23, 59, 60, 999_999)
iex> Time.new(23, 59, 61, 999_999)
{:error, :invalid_time}
iex> Time.new(23, 59, 59, 1_000_000)
{:error, :invalid_time}
@@ -184,7 +187,6 @@ defmodule Time do
Note that while ISO 8601 allows times to specify 24:00:00 as the
zero hour of the next day, this notation is not supported by Elixir.
Leap seconds are not supported as well by the built-in Calendar.ISO.
## Examples
@@ -403,9 +405,12 @@ defmodule Time do
@spec add(Calendar.time(), integer, System.time_unit()) :: t
def add(%{calendar: calendar} = time, number, unit \\ :second) when is_integer(number) do
number = System.convert_time_unit(number, unit, :microsecond)
total = time_to_microseconds(time) + number
parts = Integer.mod(total, @parts_per_day)
{hour, minute, second, microsecond} = calendar.time_from_day_fraction({parts, @parts_per_day})
iso_days = {0, to_day_fraction(time)}
total = Calendar.ISO.iso_days_to_unit(iso_days, :microsecond) + number
iso_ppd = 86_400_000_000
parts = Integer.mod(total, iso_ppd)
{hour, minute, second, microsecond} = calendar.time_from_day_fraction({parts, iso_ppd})
%Time{
hour: hour,
@@ -416,21 +421,6 @@ defmodule Time do
}
end
defp time_to_microseconds(%{
calendar: Calendar.ISO,
hour: 0,
minute: 0,
second: 0,
microsecond: {0, _}
}) do
0
end
defp time_to_microseconds(time) do
iso_days = {0, to_day_fraction(time)}
Calendar.ISO.iso_days_to_unit(iso_days, :microsecond)
end
@doc """
Compares two time structs.
@@ -607,33 +597,7 @@ defmodule Time do
"""
@doc since: "1.5.0"
@spec diff(Calendar.time(), Calendar.time(), System.time_unit()) :: integer
def diff(time1, time2, unit \\ :second)
def diff(
%{
calendar: Calendar.ISO,
hour: hour1,
minute: minute1,
second: second1,
microsecond: {microsecond1, @parts_per_day}
},
%{
calendar: Calendar.ISO,
hour: hour2,
minute: minute2,
second: second2,
microsecond: {microsecond2, @parts_per_day}
},
unit
) do
total =
(hour1 - hour2) * 3_600_000_000 + (minute1 - minute2) * 60_000_000 +
(second1 - second2) * 1_000_000 + (microsecond1 - microsecond2)
System.convert_time_unit(total, :microsecond, unit)
end
def diff(time1, time2, unit) do
def diff(time1, time2, unit \\ :second) do
fraction1 = to_day_fraction(time1)
fraction2 = to_day_fraction(time2)
@@ -645,9 +609,6 @@ defmodule Time do
Returns the given time with the microsecond field truncated to the given
precision (`:microsecond`, `millisecond` or `:second`).
The given time is returned unchanged if it already has lower precision than
the given precision.
## Examples
iex> Time.truncate(~T[01:01:01.123456], :microsecond)
@@ -1,96 +0,0 @@
defmodule Calendar.TimeZoneDatabase do
@moduledoc """
This module defines a behaviour for providing time zone data.
IANA provides time zone data that includes data about different
UTC offsets and standard offsets for time zones.
"""
@typedoc """
A period where a certain combination of UTC offset, standard offset and zone
abbreviation is in effect.
For instance one period could be the summer of 2018 in "Europe/London" where summer time /
daylight saving time is in effect and lasts from spring to autumn. At autumn the `std_offset`
changes along with the `zone_abbr` so a different period is needed during winter.
"""
@type time_zone_period :: %{
optional(any) => any,
utc_offset: Calendar.utc_offset(),
std_offset: Calendar.std_offset(),
zone_abbr: Calendar.zone_abbr()
}
@typedoc """
Limit for when a certain time zone period begins or ends.
A beginning is inclusive. An ending is exclusive. Eg. if a period is from
2015-03-29 01:00:00 and until 2015-10-25 01:00:00, the period includes and
begins from the begining of 2015-03-29 01:00:00 and lasts until just before
2015-10-25 01:00:00.
A beginning or end for certain periods are infinite. For instance the latest
period for time zones without DST or plans to change. However for the purpose
of this behaviour they are only used for gaps in wall time where the needed
period limits are at a certain time.
"""
@type time_zone_period_limit :: Calendar.naive_datetime()
@doc """
Time zone period for a point in time in UTC for a specific time zone.
Takes a time zone name and a point in time for UTC and returns a
`time_zone_period` for that point in time.
"""
@doc since: "1.8.0"
@callback time_zone_period_from_utc_iso_days(Calendar.iso_days(), Calendar.time_zone()) ::
{:ok, time_zone_period}
| {:error, :time_zone_not_found | :utc_only_time_zone_database}
@doc """
Possible time zone periods for a certain time zone and wall clock date and time.
When the provided `datetime` is ambiguous a tuple with `:ambiguous` and two possible
periods. The periods in the list are sorted with the first element being the one that begins first.
When the provided `datetime` is in a gap - for instance during the "spring forward" when going
from winter time to summer time, a tuple with `:gap` and two periods with limits are returned
in a nested tuple. The first nested two-tuple is the period before the gap and a naive datetime
with a limit for when the period ends (wall time). The second nested two-tuple is the period
just after the gap and a datetime (wall time) for when the period begins just after the gap.
If there is only a single possible period for the provided `datetime`, the a tuple with `:single`
and the `time_zone_period` is returned.
"""
@doc since: "1.8.0"
@callback time_zone_periods_from_wall_datetime(Calendar.naive_datetime(), Calendar.time_zone()) ::
{:ok, time_zone_period}
| {:ambiguous, time_zone_period, time_zone_period}
| {:gap, {time_zone_period, time_zone_period_limit},
{time_zone_period, time_zone_period_limit}}
| {:error, :time_zone_not_found | :utc_only_time_zone_database}
end
defmodule Calendar.UTCOnlyTimeZoneDatabase do
@moduledoc """
Built-in time zone database that works only in Etc/UTC.
For all other time zones, it returns `{:error, :utc_only_time_zone_database}`.
"""
@behaviour Calendar.TimeZoneDatabase
@impl true
def time_zone_period_from_utc_iso_days(_, "Etc/UTC"),
do: {:ok, %{std_offset: 0, utc_offset: 0, zone_abbr: "UTC"}}
def time_zone_period_from_utc_iso_days(_, _),
do: {:error, :utc_only_time_zone_database}
@impl true
def time_zone_periods_from_wall_datetime(_, "Etc/UTC"),
do: {:ok, %{std_offset: 0, utc_offset: 0, zone_abbr: "UTC"}}
def time_zone_periods_from_wall_datetime(_, _),
do: {:error, :utc_only_time_zone_database}
end
+23 -23
View File
@@ -26,7 +26,7 @@ defmodule Code do
times. This is common in scripts.
`compile_file/2` must be used when you are interested in the modules defined in a
file, without tracking. `eval_file/2` should be used when you are interested in
file, without tracking. `eval_file/2` should be used when you are intested on
the result of evaluating the file rather than the modules it defines.
"""
@@ -416,7 +416,7 @@ defmodule Code do
rules in the future. The goal of documenting them is to provide better
understanding on what to expect from the formatter.
### Multi-line lists, maps, tuples, etc.
### Multi-line lists, maps, tuples, etc
You can force lists, tuples, bitstrings, maps, structs and function
calls to have one entry per line by adding a newline after the opening
@@ -697,7 +697,7 @@ defmodule Code do
Accepts `relative_to` as an argument to tell where the file is located.
While `require_file/2` and `compile_file/2` return the loaded modules and their
While `require_file/2` and `compile_file/2` returns the loaded modules and their
bytecode, `eval_file/2` simply evaluates the file contents and returns the
evaluation result and its bindings (exactly the same return value as `eval_string/3`).
"""
@@ -732,7 +732,7 @@ defmodule Code do
others will get `nil`.
See `compile_file/2` if you would like to compile a file without tracking its
filenames. Finally, if you would like to get the result of evaluating a file rather
filenames. Finally, if you would like to get the result of evaluating file rather
than the modules defined in it, see `eval_file/2`.
## Examples
@@ -743,7 +743,7 @@ defmodule Code do
List.first(modules)
#=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>}
If the file has been required, it returns `nil`:
If the code has been required, it returns `nil`:
Code.require_file("eex_test.exs", "../eex/test")
#=> nil
@@ -790,7 +790,7 @@ defmodule Code do
@doc """
Returns a list with the available compiler options.
See `compiler_options/1` for more information.
See `compiler_options/1` for more info.
## Examples
@@ -809,11 +809,11 @@ defmodule Code do
The compiler utilizes temporary modules to compile code. For example,
`elixir_compiler_1`, `elixir_compiler_2`, etc. In case the compiled code
stores references to anonymous functions or similar, the Elixir compiler
may be unable to reclaim those modules, keeping an unnecessary amount of
may be unable to reclaim those modules, keeping an unecessary amount of
code in memory and eventually leading to modules such as `elixir_compiler_12345`.
This function purges all modules currently kept by the compiler, allowing
old compiler module names to be reused. If there are any processes running
old compiler module names to be resued. If there are any processes running
any code from such modules, they will be terminated too.
It returns `{:ok, number_of_modules_purged}`.
@@ -1047,7 +1047,7 @@ defmodule Code do
end
@doc ~S"""
Returns the docs for the given module or path to `.beam` file.
Returns the docs for the given module.
When given a module name, it finds its BEAM code and reads the docs from it.
@@ -1072,20 +1072,19 @@ defmodule Code do
"""
@doc since: "1.7.0"
@spec fetch_docs(module | String.t()) ::
{:docs_v1, annotation, beam_language, format, module_doc :: doc_content, metadata,
docs :: [doc_element]}
{:docs_v1, anno, beam_language, format, module_doc :: doc, metadata,
docs :: [{{kind, name, arity}, anno, signature, doc, metadata}]}
| {:error, :module_not_found | :chunk_not_found | {:invalid_chunk, binary}}
when annotation: :erl_anno.anno(),
beam_language: :elixir | :erlang | :lfe | :alpaca | atom(),
doc_content: %{binary => binary} | :none | :hidden,
doc_element:
{{kind :: atom, function_name :: atom, arity}, annotation, signature, doc_content,
metadata},
| future_formats
when anno: :erl_anno.anno(),
beam_language: atom,
format: binary,
doc: %{binary => binary} | :none | :hidden,
kind: atom,
name: atom,
signature: [binary],
metadata: map
def fetch_docs(module_or_path)
metadata: map,
future_formats: term
def fetch_docs(module) when is_atom(module) do
case :code.get_object_code(module) do
{_module, bin, _beam_path} -> do_fetch_docs(bin)
@@ -1093,8 +1092,8 @@ defmodule Code do
end
end
def fetch_docs(path) when is_binary(path) do
do_fetch_docs(String.to_charlist(path))
def fetch_docs(binpath) when is_binary(binpath) do
do_fetch_docs(String.to_charlist(binpath))
end
@docs_chunk 'Docs'
@@ -1122,7 +1121,8 @@ defmodule Code do
longer available, and therefore this function always returns `nil`.
Use `Code.fetch_docs/1` instead.
"""
@deprecated "Code.get_docs/2 always returns nil as its outdated documentation is no longer stored on BEAM files. Use Code.fetch_docs/1 instead"
@doc deprecated:
"Code.get_docs/2 always returns nil as its outdated documentation is no longer stored on BEAM files. Use Code.fetch_docs/1 instead"
@spec get_docs(module, :moduledoc | :docs | :callback_docs | :type_docs | :all) :: nil
def get_docs(_module, _kind) do
nil
+17 -47
View File
@@ -367,24 +367,24 @@ defmodule Code.Formatter do
end
defp quoted_to_algebra(
{{:., _, [List, :to_charlist]}, meta, [entries]} = quoted,
{{:., _, [String, :to_charlist]}, _, [{:<<>>, meta, entries}]} = quoted,
context,
state
) do
cond do
not list_interpolated?(entries) ->
not interpolated?(entries) ->
remote_to_algebra(quoted, context, state)
meta[:format] == :list_heredoc ->
{doc, state} =
entries
|> prepend_heredoc_line()
|> list_interpolation_to_algebra(:heredoc, state, @single_heredoc, @single_heredoc)
|> interpolation_to_algebra(:heredoc, state, @single_heredoc, @single_heredoc)
{force_unfit(doc), state}
true ->
list_interpolation_to_algebra(entries, @single_quote, state, @single_quote, @single_quote)
interpolation_to_algebra(entries, @single_quote, state, @single_quote, @single_quote)
end
end
@@ -779,16 +779,13 @@ defmodule Code.Formatter do
concat(concat(group(left), op_string), group(right))
true ->
eol? = eol?(meta)
next_break_fits? =
op in @next_break_fits_operators and next_break_fits?(right_arg, state) and not eol?
op in @next_break_fits_operators and next_break_fits?(right_arg, state) and
not Keyword.get(meta, :eol, false)
with_next_break_fits(next_break_fits?, right, fn right ->
op_string = " " <> op_string
right = nest(glue(op_string, group(right)), nesting, :break)
right = if eol?, do: force_unfit(right), else: right
concat(group(left), group(right))
concat(group(left), group(nest(glue(op_string, group(right)), nesting, :break)))
end)
end
@@ -887,7 +884,7 @@ defmodule Code.Formatter do
{docs, comments?, state} =
quoted_to_algebra_with_comments(operands, [], min_line, max_line, 1, state, fun)
if comments? or eol?(meta) do
if comments? or Keyword.get(meta, :eol, false) do
{docs |> Enum.reduce(&line(&2, &1)) |> force_unfit(), state}
else
{docs |> Enum.reduce(&glue(&2, &1)), state}
@@ -1062,8 +1059,6 @@ defmodule Code.Formatter do
defp deprecated(Enum, :partition, 2), do: {"split_with", "~> 1.4"}
defp deprecated(Code, :unload_files, 2), do: {"unrequire_files", "~> 1.7"}
defp deprecated(Code, :loaded_files, 2), do: {"required_files", "~> 1.7"}
defp deprecated(Kernel.ParallelCompiler, :files, 2), do: {"compile", "~> 1.6"}
defp deprecated(Kernel.ParallelCompiler, :files_to_path, 2), do: {"compile_to_path", "~> 1.6"}
defp deprecated(_, _, _), do: :error
defp remote_target_to_algebra({:fn, _, [_ | _]} = quoted, state) do
@@ -1150,7 +1145,7 @@ defmodule Code.Formatter do
end
args = if keyword?, do: left ++ right, else: left ++ [right]
many_eol? = match?([_, _ | _], args) and eol?(meta)
many_eol? = match?([_, _ | _], args) and Keyword.get(meta, :eol, false)
no_generators? = no_generators?(args)
to_algebra_fun = &quoted_to_algebra(&1, context, &2)
@@ -1306,14 +1301,6 @@ defmodule Code.Formatter do
## Interpolation
defp list_interpolated?(entries) do
Enum.all?(entries, fn
{{:., _, [Kernel, :to_string]}, _, [_]} -> true
entry when is_binary(entry) -> true
_ -> false
end)
end
defp interpolated?(entries) do
Enum.all?(entries, fn
{:::, _, [{{:., _, [Kernel, :to_string]}, _, [_]}, {:binary, _, _}]} -> true
@@ -1330,23 +1317,6 @@ defmodule Code.Formatter do
["\n" | entries]
end
defp list_interpolation_to_algebra([entry | entries], escape, state, acc, last)
when is_binary(entry) do
acc = concat(acc, escape_string(entry, escape))
list_interpolation_to_algebra(entries, escape, state, acc, last)
end
defp list_interpolation_to_algebra([entry | entries], escape, state, acc, last) do
{{:., _, [Kernel, :to_string]}, meta, [quoted]} = entry
{doc, state} = block_to_algebra(quoted, line(meta), end_line(meta), state)
doc = surround("\#{", doc, "}")
list_interpolation_to_algebra(entries, escape, state, concat(acc, doc), last)
end
defp list_interpolation_to_algebra([], _escape, state, acc, last) do
{concat(acc, last), state}
end
defp interpolation_to_algebra([entry | entries], escape, state, acc, last)
when is_binary(entry) do
acc = concat(acc, escape_string(entry, escape))
@@ -1402,7 +1372,7 @@ defmodule Code.Formatter do
defp bitstring_to_algebra(meta, args, state) do
last = length(args) - 1
join = if eol?(meta), do: :line, else: :flex_break
join = if Keyword.get(meta, :eol, false), do: :line, else: :flex_break
to_algebra_fun = &bitstring_segment_to_algebra(&1, &2, last)
{args_doc, join, state} =
@@ -1470,7 +1440,7 @@ defmodule Code.Formatter do
## Literals
defp list_to_algebra(meta, args, state) do
join = if eol?(meta), do: :line, else: :break
join = if Keyword.get(meta, :eol, false), do: :line, else: :break
fun = &quoted_to_algebra(&1, :parens_arg, &2)
{args_doc, _join, state} =
@@ -1480,7 +1450,7 @@ defmodule Code.Formatter do
end
defp map_to_algebra(meta, name_doc, [{:|, _, [left, right]}], state) do
join = if eol?(meta), do: :line, else: :break
join = if Keyword.get(meta, :eol, false), do: :line, else: :break
fun = &quoted_to_algebra(&1, :parens_arg, &2)
{left_doc, state} = fun.(left, state)
@@ -1497,7 +1467,7 @@ defmodule Code.Formatter do
end
defp map_to_algebra(meta, name_doc, args, state) do
join = if eol?(meta), do: :line, else: :break
join = if Keyword.get(meta, :eol, false), do: :line, else: :break
fun = &quoted_to_algebra(&1, :parens_arg, &2)
{args_doc, _join, state} =
@@ -1508,7 +1478,7 @@ defmodule Code.Formatter do
end
defp tuple_to_algebra(meta, args, join, state) do
join = if eol?(meta), do: :line, else: join
join = if Keyword.get(meta, :eol, false), do: :line, else: join
fun = &quoted_to_algebra(&1, :parens_arg, &2)
{args_doc, join, state} =
@@ -1791,7 +1761,7 @@ defmodule Code.Formatter do
## Clauses
defp maybe_force_clauses(doc, clauses) do
if Enum.any?(clauses, fn {:->, meta, _} -> eol?(meta) end) do
if Enum.any?(clauses, fn {:->, meta, _} -> Keyword.get(meta, :eol, false) end) do
force_unfit(doc)
else
doc
@@ -2127,7 +2097,7 @@ defmodule Code.Formatter do
(not interpolated?(entries) and eol_or_comments?(meta, state))
end
defp next_break_fits?({{:., _, [List, :to_charlist]}, meta, [[_ | _]]}, _state) do
defp next_break_fits?({{:., _, [String, :to_charlist]}, _, [{:<<>>, meta, [_ | _]}]}, _state) do
meta[:format] == :list_heredoc
end
@@ -2161,7 +2131,7 @@ defmodule Code.Formatter do
end
defp eol_or_comments?(meta, %{comments: comments}) do
eol?(meta) or
Keyword.get(meta, :eol, false) or
(
min_line = line(meta)
max_line = end_line(meta)
+1 -1
View File
@@ -87,7 +87,7 @@ defmodule Code.Identifier do
:alias
true ->
case :elixir_config.get(:identifier_tokenizer, String.Tokenizer).tokenize(charlist) do
case :elixir_config.safe_get(:identifier_tokenizer, String.Tokenizer).tokenize(charlist) do
{kind, _acc, [], _, _, special} ->
if kind == :identifier and not :lists.member(?@, special) do
:callable_local
+29 -15
View File
@@ -152,23 +152,37 @@ defmodule Code.Typespec do
end
end
# TODO: Do not rely on abstract_code when OTP 20+ support is dropped (v1.8).
# We should then be able to simplify this code and use `with`.
defp typespecs_abstract_code(module) do
with {module, binary} <- get_module_and_beam(module),
{:ok, {_, [debug_info: {:debug_info_v1, backend, data}]}} <-
:beam_lib.chunks(binary, [:debug_info]) do
case data do
{:elixir_v1, %{}, specs} ->
# Fast path to avoid translation to Erlang from Elixir.
{:ok, specs}
case get_module_and_beam(module) do
{module, binary} ->
case :beam_lib.chunks(binary, [:debug_info]) do
{:ok, {_, [debug_info: {:debug_info_v1, backend, data}]}} ->
case data do
{:elixir_v1, %{}, specs} ->
# Fast path to avoid translation to Erlang from Elixir.
{:ok, specs}
_ ->
case backend.debug_info(:erlang_v1, module, data, []) do
{:ok, abstract_code} -> {:ok, abstract_code}
_ -> :error
end
end
else
_ -> :error
_ ->
case backend.debug_info(:erlang_v1, module, data, []) do
{:ok, abstract_code} -> {:ok, abstract_code}
_ -> :error
end
end
_ ->
case :beam_lib.chunks(binary, [:abstract_code]) do
{:ok, {_, [{:abstract_code, {_raw_abstract_v1, abstract_code}}]}} ->
{:ok, abstract_code}
_ ->
:error
end
end
:error ->
:error
end
end
+1 -11
View File
@@ -41,7 +41,7 @@ defprotocol Collectable do
implementation for `MapSet`. In this implementation "collecting" elements
simply means inserting them in the set through `MapSet.put/2`.
defimpl Collectable, for: MapSet do
defimpl Collectable do
def into(original) do
collector_fun = fn
set, {:cont, elem} -> MapSet.put(set, elem)
@@ -79,16 +79,6 @@ end
defimpl Collectable, for: List do
def into(original) do
if original != [] do
IO.warn(
"the Collectable protocol is deprecated for non-empty lists. The behaviour of " <>
"things like Enum.into/2 or \"for\" comprehensions with an :into option is incorrect " <>
"when collecting into non-empty lists. If you're collecting into a non-empty keyword " <>
"list, consider using Keyword.merge/2 instead. If you're collecting into a non-empty " <>
"list, consider concatenating the two lists with the ++ operator."
)
end
fun = fn
list, {:cont, x} -> [x | list]
list, :done -> original ++ :lists.reverse(list)
+1 -1
View File
@@ -295,7 +295,7 @@ defmodule Dict do
end
@deprecated message
@spec fetch!(t, key) :: value
@spec fetch!(t, key) :: value | no_return
def fetch!(dict, key) do
target(dict).fetch!(dict, key)
end
+19 -24
View File
@@ -6,7 +6,7 @@ defmodule DynamicSupervisor do
that are started in the given order when the supervisor starts. A
`DynamicSupervisor` starts with no children. Instead, children are
started on demand via `start_child/2`. When a dynamic supervisor
terminates, all children are shut down at the same time, with no guarantee
terminates, all children are shutdown at the same time, with no guarantee
of ordering.
## Examples
@@ -58,9 +58,7 @@ defmodule DynamicSupervisor do
end
See the `Supervisor` docs for a discussion of when you may want to use
module-based supervisors. The `@doc` annotation immediately preceding
`use DymamicSupervisor` will be attached to the generated `child_spec/1`
function.
module-based supervisors.
## Name registration
@@ -91,7 +89,7 @@ defmodule DynamicSupervisor do
def init(initial_arg) do
children = [
# Or the deprecated: worker(MyWorker, [initial_arg])
%{id: MyWorker, start: {MyWorker, :start_link, [initial_arg]}}
%{id: MyWorker, start: {MyWorker, :start_link, [initial_arg]})
]
Supervisor.init(children, strategy: :simple_one_for_one)
@@ -137,7 +135,7 @@ defmodule DynamicSupervisor do
Developers typically invoke `DynamicSupervisor.init/1` at the end of
their init callback to return the proper supervision flags.
"""
@callback init(init_arg :: term) :: {:ok, sup_flags()} | :ignore
@callback init(args :: term) :: {:ok, sup_flags()} | :ignore
@typedoc "The supervisor flags returned on init"
@type sup_flags() :: %{
@@ -172,7 +170,6 @@ defmodule DynamicSupervisor do
| :ignore
| {:error, {:already_started, pid} | :max_children | term}
# In this struct, `args` refers to the arguments passed to init/1 (the `init_arg`).
defstruct [
:args,
:extra_arguments,
@@ -211,14 +208,12 @@ defmodule DynamicSupervisor do
defmacro __using__(opts) do
quote location: :keep, bind_quoted: [opts: opts] do
@behaviour DynamicSupervisor
if Module.get_attribute(__MODULE__, :doc) == nil do
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
end
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
def child_spec(arg) do
default = %{
id: __MODULE__,
@@ -282,8 +277,8 @@ defmodule DynamicSupervisor do
"""
@doc since: "1.6.0"
@spec start_link(module, term, GenServer.options()) :: Supervisor.on_start()
def start_link(mod, init_arg, opts \\ []) do
GenServer.start_link(__MODULE__, {mod, init_arg, opts[:name]}, opts)
def start_link(mod, args, opts \\ []) do
GenServer.start_link(__MODULE__, {mod, args, opts[:name]}, opts)
end
@doc """
@@ -310,7 +305,7 @@ defmodule DynamicSupervisor do
this function returns `{:error, :max_children}`.
"""
@doc since: "1.6.0"
@spec start_child(Supervisor.supervisor(), Supervisor.child_spec() | {module, term} | module) ::
@spec start_child(Supervisor.supervisor(), :supervisor.child_spec() | {module, term} | module) ::
on_start_child()
def start_child(supervisor, {_, _, _, _, _, _} = child_spec) do
validate_and_start_child(supervisor, child_spec)
@@ -467,13 +462,13 @@ defmodule DynamicSupervisor do
end
@doc """
Receives a set of `options` that initializes a dynamic supervisor.
Receives a set of options that initializes a dynamic supervisor.
This is typically invoked at the end of the `c:init/1` callback of
module-based supervisors. See the "Module-based supervisors" section
module-based supervisors. See the sections "Module-based supervisors"
in the module documentation for more information.
The `options` received by this function are also supported by `start_link/2`.
The options received by this function are also supported by `start_link/2`.
This function returns a tuple containing the supervisor options.
@@ -532,11 +527,11 @@ defmodule DynamicSupervisor do
## Callbacks
@impl true
def init({mod, init_arg, name}) do
def init({mod, args, name}) do
Process.put(:"$initial_call", {:supervisor, mod, 1})
Process.flag(:trap_exit, true)
case mod.init(init_arg) do
case mod.init(args) do
{:ok, flags} when is_map(flags) ->
name =
cond do
@@ -545,7 +540,7 @@ defmodule DynamicSupervisor do
is_tuple(name) -> name
end
state = %DynamicSupervisor{mod: mod, args: init_arg, name: name}
state = %DynamicSupervisor{mod: mod, args: args, name: name}
case init(state, flags) do
{:ok, state} -> {:ok, state}
@@ -750,8 +745,8 @@ defmodule DynamicSupervisor do
end
@impl true
def code_change(_, %{mod: mod, args: init_arg} = state, _) do
case mod.init(init_arg) do
def code_change(_, %{mod: mod, args: args} = state, _) do
case mod.init(args) do
{:ok, flags} when is_map(flags) ->
case init(state, flags) do
{:ok, state} -> {:ok, state}
+123 -159
View File
@@ -31,7 +31,7 @@ defprotocol Enumerable do
while also guaranteeing the resource will be closed at the end of the
enumeration. This protocol also allows suspension of the enumeration,
which is useful when interleaving between many enumerables is required
(as in the `zip/1` and `zip/2` functions).
(as in zip).
This protocol requires four functions to be implemented, `reduce/3`,
`count/1`, `member?/2`, and `slice/1`. The core of the protocol is the
@@ -61,7 +61,7 @@ defprotocol Enumerable do
@typedoc """
The reducer function.
Should be called with the `enumerable` element and the
Should be called with the enumerable element and the
accumulator contents.
Returns the accumulator for the next enumeration step.
@@ -107,7 +107,7 @@ defprotocol Enumerable do
number of elements in the slice.
The `start` position is a number `>= 0` and guaranteed to
exist in the `enumerable`. The length is a number `>= 1` in a way
exist in the enumerable. The length is a number `>= 1` in a way
that `start + length <= count`, where `count` is the maximum
amount of elements in the enumerable.
@@ -117,11 +117,11 @@ defprotocol Enumerable do
@type slicing_fun :: (start :: non_neg_integer, length :: pos_integer -> [term()])
@doc """
Reduces the `enumerable` into an element.
Reduces the enumerable into an element.
Most of the operations in `Enum` are implemented in terms of reduce.
This function should apply the given `t:reducer/0` function to each
item in the `enumerable` and proceed as expected by the returned
item in the enumerable and proceed as expected by the returned
accumulator.
See the documentation of the types `t:result/0` and `t:acc/0` for
@@ -141,10 +141,10 @@ defprotocol Enumerable do
def reduce(enumerable, acc, fun)
@doc """
Retrieves the number of elements in the `enumerable`.
Retrieves the number of elements in the enumerable.
It should return `{:ok, count}` if you can count the number of elements
in the `enumerable`.
in the enumerable.
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
built on top of `reduce/3` that runs in linear time will be used.
@@ -153,10 +153,10 @@ defprotocol Enumerable do
def count(enumerable)
@doc """
Checks if an `element` exists within the `enumerable`.
Checks if an element exists within the enumerable.
It should return `{:ok, boolean}` if you can check the membership of a
given element in the `enumerable` with `===/2` without traversing the whole
given element in the enumerable with `===/2` without traversing the whole
enumerable.
Otherwise it should return `{:error, __MODULE__}` and a default algorithm
@@ -168,8 +168,8 @@ defprotocol Enumerable do
@doc """
Returns a function that slices the data structure contiguously.
It should return `{:ok, size, slicing_fun}` if the `enumerable` has
a known bound and can access a position in the `enumerable` without
It should return `{:ok, size, slicing_fun}` if the enumerable has
a known bound and can access a position in the enumerable without
traversing all previous elements.
Otherwise it should return `{:error, __MODULE__}` and a default
@@ -180,7 +180,7 @@ defprotocol Enumerable do
The `size` value returned by this function is used for boundary checks,
therefore it is extremely important that this function only returns `:ok`
if retrieving the `size` of the `enumerable` is cheap, fast and takes constant
if retrieving the `size` of the enumerable is cheap, fast and takes constant
time. Otherwise the simplest of operations, such as `Enum.at(enumerable, 0)`,
will become too expensive.
@@ -249,10 +249,7 @@ defmodule Enum do
@type t :: Enumerable.t()
@type acc :: any
@type element :: any
@typedoc "Zero-based index. It can also be a negative integer."
@type index :: integer
@type default :: any
require Stream.Reducers, as: R
@@ -276,10 +273,9 @@ defmodule Enum do
end
@doc """
Returns `true` if the given `fun` evaluates to a truthy value (neither `false` nor `nil`)
on all of the items in the `enumerable`.
Returns `true` if the given `fun` evaluates to true on all of the items in the enumerable.
It stops the iteration at the first invocation that returns either `false` or `nil`.
It stops the iteration at the first invocation that returns `false` or `nil`.
## Examples
@@ -290,7 +286,7 @@ defmodule Enum do
false
If no function is given, it defaults to checking if
all items in the `enumerable` are truthy values.
all items in the enumerable are truthy values.
iex> Enum.all?([1, 2, 3])
true
@@ -315,7 +311,7 @@ defmodule Enum do
end
@doc """
Returns `true` if the given `fun` evaluates to true on any of the items in the `enumerable`.
Returns `true` if the given `fun` evaluates to true on any of the items in the enumerable.
It stops the iteration at the first invocation that returns a truthy value (neither `false` nor `nil`).
@@ -328,7 +324,7 @@ defmodule Enum do
true
If no function is given, it defaults to checking if at least one item
in the `enumerable` is a truthy value.
in the enumerable is a truthy value.
iex> Enum.any?([false, false, false])
false
@@ -412,7 +408,7 @@ defmodule Enum do
@doc """
Returns list of lists containing `count` items each, where
each new chunk starts `step` elements into the `enumerable`.
each new chunk starts `step` elements into the enumerable.
`step` is optional and, if not passed, defaults to `count`, i.e.
chunks do not overlap.
@@ -525,7 +521,7 @@ defmodule Enum do
end
@doc """
Given an enumerable of enumerables, concatenates the `enumerables` into
Given an enumerable of enumerables, concatenates the enumerables into
a single list.
## Examples
@@ -544,8 +540,8 @@ defmodule Enum do
end
@doc """
Concatenates the enumerable on the `right` with the enumerable on the
`left`.
Concatenates the enumerable on the right with the enumerable on the
left.
This function produces the same result as the `Kernel.++/2` operator
for lists.
@@ -569,7 +565,7 @@ defmodule Enum do
end
@doc """
Returns the size of the `enumerable`.
Returns the size of the enumerable.
## Examples
@@ -593,7 +589,7 @@ defmodule Enum do
end
@doc """
Returns the count of items in the `enumerable` for which `fun` returns
Returns the count of items in the enumerable for which `fun` returns
a truthy value.
## Examples
@@ -655,7 +651,7 @@ defmodule Enum do
end
@doc """
Drops the `amount` of items from the `enumerable`.
Drops the `amount` of items from the enumerable.
If a negative `amount` is given, the `amount` of last values will be dropped.
The `enumerable` will be enumerated once to retrieve the proper index and
@@ -699,7 +695,7 @@ defmodule Enum do
end
@doc """
Returns a list of every `nth` item in the `enumerable` dropped,
Returns a list of every `nth` item in the enumerable dropped,
starting with the first element.
The first item is always dropped, unless `nth` is 0.
@@ -732,7 +728,7 @@ defmodule Enum do
end
@doc """
Drops items at the beginning of the `enumerable` while `fun` returns a
Drops items at the beginning of the enumerable while `fun` returns a
truthy value.
## Examples
@@ -752,13 +748,13 @@ defmodule Enum do
end
@doc """
Invokes the given `fun` for each item in the `enumerable`.
Invokes the given `fun` for each item in the enumerable.
Returns `:ok`.
## Examples
Enum.each(["some", "example"], fn x -> IO.puts(x) end)
Enum.each(["some", "example"], fn(x) -> IO.puts x end)
"some"
"example"
#=> :ok
@@ -780,7 +776,7 @@ defmodule Enum do
end
@doc """
Determines if the `enumerable` is empty.
Determines if the enumerable is empty.
Returns `true` if `enumerable` is empty, otherwise `false`.
@@ -846,7 +842,7 @@ defmodule Enum do
Finds the element at the given `index` (zero-based).
Raises `OutOfBoundsError` if the given `index` is outside the range of
the `enumerable`.
the enumerable.
## Examples
@@ -860,7 +856,7 @@ defmodule Enum do
** (Enum.OutOfBoundsError) out of bounds error
"""
@spec fetch!(t, index) :: element
@spec fetch!(t, index) :: element | no_return
def fetch!(enumerable, index) do
case slice_any(enumerable, index, 1) do
[value] -> value
@@ -869,11 +865,11 @@ defmodule Enum do
end
@doc """
Filters the `enumerable`, i.e. returns only those elements
Filters the enumerable, i.e. returns only those elements
for which `fun` returns a truthy value.
See also `reject/2` which discards all elements where the
function returns a truthy value.
function a truthy value.
## Examples
@@ -887,13 +883,10 @@ defmodule Enum do
discard the invalid one in one pass:
strings = ["1234", "abc", "12ab"]
Enum.flat_map(strings, fn string ->
case Integer.parse(string) do
# transform to integer
{int, _rest} -> [int]
# skip the value
:error -> []
{int, _rest} -> [int] # transform to integer
:error -> [] # skip the value
end
end)
@@ -1046,7 +1039,7 @@ defmodule Enum do
end
@doc """
Maps and reduces an `enumerable`, flattening the given results (only one level deep).
Maps and reduces an enumerable, flattening the given results (only one level deep).
It expects an accumulator and a function that receives each enumerable
item, and must return a tuple containing a new enumerable (often a list)
@@ -1091,11 +1084,11 @@ defmodule Enum do
end
@doc """
Splits the `enumerable` into groups based on `key_fun`.
Splits the enumerable into groups based on `key_fun`.
The result is a map where each key is given by `key_fun`
and each value is a list of elements given by `value_fun`.
The order of elements within each list is preserved from the `enumerable`.
The order of elements within each list is preserved from the enumerable.
However, like all maps, the resulting map is unordered.
## Examples
@@ -1171,14 +1164,10 @@ defmodule Enum do
@doc """
Inserts the given `enumerable` into a `collectable`.
Note that passing a non-empty list as the `collectable` is deprecated. If you're collecting
into a non-empty keyword list, consider using `Keyword.merge/2`. If you're collecting into a
non-empty list, consider something like `to_list(enumerable) ++ collectable`.
## Examples
iex> Enum.into([1, 2], [])
[1, 2]
iex> Enum.into([1, 2], [0])
[0, 1, 2]
iex> Enum.into([a: 1, b: 2], %{})
%{a: 1, b: 2}
@@ -1191,10 +1180,8 @@ defmodule Enum do
"""
@spec into(Enumerable.t(), Collectable.t()) :: Collectable.t()
def into(enumerable, collectable)
def into(enumerable, []) do
to_list(enumerable)
def into(enumerable, collectable) when is_list(collectable) do
collectable ++ to_list(enumerable)
end
def into(%_{} = enumerable, collectable) do
@@ -1271,12 +1258,12 @@ defmodule Enum do
end
@doc """
Joins the given `enumerable` into a binary using `joiner` as a
Joins the given enumerable into a binary using `joiner` as a
separator.
If `joiner` is not passed at all, it defaults to the empty binary.
All items in the `enumerable` must be convertible to a binary,
All items in the enumerable must be convertible to a binary,
otherwise an error is raised.
## Examples
@@ -1372,7 +1359,7 @@ defmodule Enum do
end
@doc """
Maps and joins the given `enumerable` in one pass.
Maps and joins the given enumerable in one pass.
`joiner` can be either a binary or a list and the result will be of
the same type as `joiner`.
@@ -1408,7 +1395,7 @@ defmodule Enum do
end
@doc """
Invokes the given function to each item in the `enumerable` to reduce
Invokes the given function to each item in the enumerable to reduce
it to a single element, while keeping an accumulator.
Returns a tuple where the first element is the mapped enumerable and
@@ -1442,7 +1429,7 @@ defmodule Enum do
end
@doc """
Returns the maximal element in the `enumerable` according
Returns the maximal element in the enumerable according
to Erlang's term ordering.
If multiple elements are considered maximal, the first one that was found
@@ -1478,14 +1465,13 @@ defmodule Enum do
For selecting a maximum value out of two consider using `Kernel.max/2`.
"""
@spec max(t, (() -> empty_result)) :: element | empty_result when empty_result: any
def max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(empty_fallback, 0) do
@spec max(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any
def max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end) do
aggregate(enumerable, &Kernel.max/2, empty_fallback)
end
@doc """
Returns the maximal element in the `enumerable` as calculated
Returns the maximal element in the enumerable as calculated
by the given function.
If multiple elements are considered maximal, the first one that was found
@@ -1506,10 +1492,9 @@ defmodule Enum do
nil
"""
@spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result
@spec max_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return
when empty_result: any
def max_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
def max_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end) do
first_fun = &{&1, fun.(&1)}
reduce_fun = fn entry, {_, fun_max} = old ->
@@ -1524,7 +1509,7 @@ defmodule Enum do
end
@doc """
Checks if `element` exists within the `enumerable`.
Checks if `element` exists within the enumerable.
Membership is tested with the match (`===/2`) operator.
@@ -1564,7 +1549,7 @@ defmodule Enum do
end
@doc """
Returns the minimal element in the `enumerable` according
Returns the minimal element in the enumerable according
to Erlang's term ordering.
If multiple elements are considered minimal, the first one that was found
@@ -1600,14 +1585,13 @@ defmodule Enum do
For selecting a minimal value out of two consider using `Kernel.min/2`.
"""
@spec min(t, (() -> empty_result)) :: element | empty_result when empty_result: any
def min(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(empty_fallback, 0) do
@spec min(t, (() -> empty_result)) :: element | empty_result | no_return when empty_result: any
def min(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end) do
aggregate(enumerable, &Kernel.min/2, empty_fallback)
end
@doc """
Returns the minimal element in the `enumerable` as calculated
Returns the minimal element in the enumerable as calculated
by the given function.
If multiple elements are considered minimal, the first one that was found
@@ -1628,10 +1612,9 @@ defmodule Enum do
nil
"""
@spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result
@spec min_by(t, (element -> any), (() -> empty_result)) :: element | empty_result | no_return
when empty_result: any
def min_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
def min_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end) do
first_fun = &{&1, fun.(&1)}
reduce_fun = fn entry, {_, fun_min} = old ->
@@ -1664,15 +1647,15 @@ defmodule Enum do
{nil, nil}
"""
@spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result
@spec min_max(t, (() -> empty_result)) :: {element, element} | empty_result | no_return
when empty_result: any
def min_max(enumerable, empty_fallback \\ fn -> raise Enum.EmptyError end)
def min_max(first..last, empty_fallback) when is_function(empty_fallback, 0) do
def min_max(first..last, _empty_fallback) do
{Kernel.min(first, last), Kernel.max(first, last)}
end
def min_max(enumerable, empty_fallback) when is_function(empty_fallback, 0) do
def min_max(enumerable, empty_fallback) do
first_fun = &{&1, &1}
reduce_fun = fn entry, {min, max} ->
@@ -1707,10 +1690,12 @@ defmodule Enum do
{nil, nil}
"""
@spec min_max_by(t, (element -> any), (() -> empty_result)) :: {element, element} | empty_result
@spec min_max_by(t, (element -> any), (() -> empty_result)) ::
{element, element} | empty_result | no_return
when empty_result: any
def min_max_by(enumerable, fun, empty_fallback \\ fn -> raise Enum.EmptyError end)
when is_function(fun, 1) and is_function(empty_fallback, 0) do
def min_max_by(enumerable, fun, empty_fallback) do
first_fun = fn entry ->
fun_entry = fun.(entry)
{{entry, entry}, {fun_entry, fun_entry}}
@@ -1788,7 +1773,7 @@ defmodule Enum do
end
@doc """
Returns a random element of an `enumerable`.
Returns a random element of an enumerable.
Raises `Enum.EmptyError` if `enumerable` is empty.
@@ -1818,7 +1803,7 @@ defmodule Enum do
776
"""
@spec random(t) :: element
@spec random(t) :: element | no_return
def random(enumerable)
def random(enumerable) when is_list(enumerable) do
@@ -1853,11 +1838,11 @@ defmodule Enum do
Raises `Enum.EmptyError` if `enumerable` is empty.
The first element of the `enumerable` is used as the initial value
The first element of the enumerable is used as the initial value
of the accumulator. Then the function is invoked with the next
element and the accumulator. The result returned by the function
is used as the accumulator for the next iteration, recursively.
When the `enumerable` is done, the last accumulator is returned.
When the enumerable is done, the last accumulator is returned.
Since the first element of the enumerable is used as the initial
value of the accumulator, `fun` will only be executed `n - 1` times
@@ -1922,8 +1907,8 @@ defmodule Enum do
def my_map(enumerable, fun) do
enumerable
|> Enum.reduce([], fn x, acc -> [fun.(x) | acc] end)
|> Enum.reverse()
|> Enum.reduce([], fn(x, acc) -> [fun.(x) | acc] end)
|> Enum.reverse
end
In the example above, `Enum.reduce/3` accumulates the result of each call
@@ -1961,28 +1946,21 @@ defmodule Enum do
end
@doc """
Reduces `enumerable` until `fun` returns `{:halt, term}`.
Reduces the enumerable until `fun` returns `{:halt, term}`.
The return value for `fun` is expected to be
* `{:cont, acc}` to continue the reduction with `acc` as the new
accumulator or
* `{:halt, acc}` to halt the reduction
If `fun` returns `{:halt, acc}` the reduction is halted and the function
returns `acc`. Otherwise, if the enumerable is exhausted, the function returns
the accumulator of the last `{:cont, acc}`.
* `{:halt, acc}` to halt the reduction and return `acc` as the return
value of this function
## Examples
iex> Enum.reduce_while(1..100, 0, fn x, acc ->
...> if x < 5, do: {:cont, acc + x}, else: {:halt, acc}
...> if x < 3, do: {:cont, acc + x}, else: {:halt, acc}
...> end)
10
iex> Enum.reduce_while(1..100, 0, fn x, acc ->
...> if x > 0, do: {:cont, acc + x}, else: {:halt, acc}
...> end)
5050
3
"""
@spec reduce_while(t, any, (element, any -> {:cont, any} | {:halt, any})) :: any
@@ -2054,10 +2032,10 @@ defmodule Enum do
end
@doc """
Reverses the `enumerable` in the range from initial `start_index`
Reverses the enumerable in the range from initial position `start`
through `count` elements.
If `count` is greater than the size of the rest of the `enumerable`,
If `count` is greater than the size of the rest of the enumerable,
then this function will reverse the rest of the enumerable.
## Examples
@@ -2067,23 +2045,23 @@ defmodule Enum do
"""
@spec reverse_slice(t, non_neg_integer, non_neg_integer) :: list
def reverse_slice(enumerable, start_index, count)
when is_integer(start_index) and start_index >= 0 and is_integer(count) and count >= 0 do
def reverse_slice(enumerable, start, count)
when is_integer(start) and start >= 0 and is_integer(count) and count >= 0 do
list = reverse(enumerable)
length = length(list)
count = Kernel.min(count, length - start_index)
count = Kernel.min(count, length - start)
if count > 0 do
reverse_slice(list, length, start_index + count, count, [])
reverse_slice(list, length, start + count, count, [])
else
:lists.reverse(list)
end
end
@doc """
Applies the given function to each element in the `enumerable`,
Applies the given function to each element in the enumerable,
storing the result in a list and passing it as the accumulator
for the next computation. Uses the first element in the `enumerable`
for the next computation. Uses the first element in the enumerable
as the starting value.
## Examples
@@ -2099,7 +2077,7 @@ defmodule Enum do
end
@doc """
Applies the given function to each element in the `enumerable`,
Applies the given function to each element in the enumerable,
storing the result in a list and passing it as the accumulator
for the next computation. Uses the given `acc` as the starting value.
@@ -2143,21 +2121,17 @@ defmodule Enum do
end
@doc """
Returns a subset list of the given `enumerable` by `index_range`.
Returns a subset list of the given enumerable, from `range.first` to `range.last` positions.
`index_range` must be a `Range`. Given an `enumerable`, it drops
elements before `index_range.first` (zero-base), then takes elements
until element `index_range.last` (inclusively).
Given `enumerable`, it drops elements until element position `range.first`,
then takes elements until element position `range.last` (inclusive).
Indexes are normalized, meaning that negative indexes will be counted
from the end (e.g. `-1` means the last element of the `enumerable`).
Positions are normalized, meaning that negative positions will be counted from the end
(e.g. `-1` means the last element of the enumerable).
If `range.last` is out of bounds, then it is assigned as the position of the last element.
If `index_range.last` is out of bounds, then it is assigned as the index
of the last element.
If the normalized `index_range.first` is out of bounds of the given
`enumerable`, or this one is greater than the normalized `index_range.last`,
then `[]` is returned.
If the normalized `range.first` position is out of bounds of the given enumerable,
or this one is greater than the normalized `range.last` position, then `[]` is returned.
## Examples
@@ -2167,11 +2141,11 @@ defmodule Enum do
iex> Enum.slice(1..10, 5..20)
[6, 7, 8, 9, 10]
# last five elements (negative indexes)
# last five elements (negative positions)
iex> Enum.slice(1..30, -5..-1)
[26, 27, 28, 29, 30]
# last five elements (mixed positive and negative indexes)
# last five elements (mixed positive and negative positions)
iex> Enum.slice(1..30, 25..-1)
[26, 27, 28, 29, 30]
@@ -2179,15 +2153,13 @@ defmodule Enum do
iex> Enum.slice(1..10, 11..20)
[]
# index_range.first is greater than index_range.last
# range.first is greater than range.last
iex> Enum.slice(1..10, 6..5)
[]
"""
@doc since: "1.6.0"
@spec slice(t, Range.t()) :: list
def slice(enumerable, index_range)
def slice(enumerable, first..last) do
{count, fun} = slice_count_and_fun(enumerable)
corr_first = if first >= 0, do: first, else: first + count
@@ -2202,14 +2174,15 @@ defmodule Enum do
end
@doc """
Returns a subset list of the given `enumerable`, from `start_index` (zero-based)
with `amount` number of elements if available.
Returns a subset list of the given enumerable, from `start` position with `amount` of elements if available.
Given an `enumerable`, it drops elements right before element `start_index`,
then takes `amount` of elements, returning as many elements as possible if there are not enough
elements.
Given `enumerable`, it drops elements until element position `start`,
then takes `amount` of elements until the end of the enumerable.
It returns `[]` if `amount` is `0` or if `start_index` is out of bounds.
If `start` is out of bounds, it returns `[]`.
If `amount` is greater than `enumerable` length, it returns as many elements as possible.
If `amount` is zero, then `[]` is returned.
## Examples
@@ -2223,25 +2196,25 @@ defmodule Enum do
iex> Enum.slice(1..10, 5, 0)
[]
# out of bound start index
# out of bound start position
iex> Enum.slice(1..10, 10, 5)
[]
# out of bound start index (negative)
# out of bound start position (negative)
iex> Enum.slice(1..10, -11, 5)
[]
"""
@spec slice(t, index, non_neg_integer) :: list
def slice(_enumerable, start_index, 0) when is_integer(start_index), do: []
def slice(_enumerable, start, 0) when is_integer(start), do: []
def slice(enumerable, start_index, amount)
when is_integer(start_index) and is_integer(amount) and amount >= 0 do
slice_any(enumerable, start_index, amount)
def slice(enumerable, start, amount)
when is_integer(start) and is_integer(amount) and amount >= 0 do
slice_any(enumerable, start, amount)
end
@doc """
Sorts the `enumerable` according to Erlang's term ordering.
Sorts the enumerable according to Erlang's term ordering.
Uses the merge sort algorithm.
@@ -2261,7 +2234,7 @@ defmodule Enum do
end
@doc """
Sorts the `enumerable` by the given function.
Sorts the enumerable by the given function.
This function uses the merge sort algorithm. The given function should compare
two arguments, and return `true` if the first argument precedes the second one.
@@ -2296,10 +2269,10 @@ defmodule Enum do
end
@doc """
Sorts the mapped results of the `enumerable` according to the provided `sorter`
Sorts the mapped results of the enumerable according to the provided `sorter`
function.
This function maps each element of the `enumerable` using the provided `mapper`
This function maps each element of the enumerable using the provided `mapper`
function. The enumerable is then sorted by the mapped elements
using the `sorter` function, which defaults to `Kernel.<=/2`.
@@ -2344,7 +2317,7 @@ defmodule Enum do
elements in the first one.
If `count` is a negative number, it starts counting from the
back to the beginning of the `enumerable`.
back to the beginning of the enumerable.
Be aware that a negative `count` implies the `enumerable`
will be enumerated twice: once to calculate the position, and
@@ -2392,22 +2365,13 @@ defmodule Enum do
@doc """
Splits enumerable in two at the position of the element for which
`fun` returns a falsy value (`false` or `nil`) for the first time.
It returns a two-element tuple with two lists of elements.
The element that triggered the split is part of the second list.
`fun` returns `false` for the first time.
## Examples
iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 3 end)
{[1, 2], [3, 4]}
iex> Enum.split_while([1, 2, 3, 4], fn x -> x < 0 end)
{[], [1, 2, 3, 4]}
iex> Enum.split_while([1, 2, 3, 4], fn x -> x > 0 end)
{[1, 2, 3, 4], []}
"""
@spec split_while(t, (element -> as_boolean(term))) :: {list, list}
def split_while(enumerable, fun) when is_list(enumerable) do
@@ -2450,7 +2414,7 @@ defmodule Enum do
end
@doc """
Takes the first `amount` items from the `enumerable`.
Takes the first `amount` items from the enumerable.
If a negative `amount` is given, the `amount` of last values will be taken.
The `enumerable` will be enumerated once to retrieve the proper index and
@@ -2500,7 +2464,7 @@ defmodule Enum do
end
@doc """
Returns a list of every `nth` item in the `enumerable`,
Returns a list of every `nth` item in the enumerable,
starting with the first element.
The first item is always included, unless `nth` is 0.
@@ -2606,7 +2570,7 @@ defmodule Enum do
end
@doc """
Takes the items from the beginning of the `enumerable` while `fun` returns
Takes the items from the beginning of the enumerable while `fun` returns
a truthy value.
## Examples
@@ -2700,10 +2664,10 @@ defmodule Enum do
end
@doc """
Opposite of `zip/2`. Extracts two-element tuples from the
given `enumerable` and groups them together.
Opposite of `Enum.zip/2`; extracts a two-element tuples from the
enumerable and groups them together.
It takes an `enumerable` with items being two-element tuples and returns
It takes an enumerable with items being two-element tuples and returns
a tuple with two lists, each of which is formed by the first and
second element of each tuple, respectively.
@@ -2730,7 +2694,7 @@ defmodule Enum do
end
@doc """
Returns the `enumerable` with each element wrapped in a tuple
Returns the enumerable with each element wrapped in a tuple
alongside its index.
If an `offset` is given, we will index from the given offset instead of from zero.
+7 -50
View File
@@ -150,7 +150,7 @@ defmodule Exception do
Attaches information to exceptions for extra debugging.
This operation is potentially expensive, as it reads data
from the file system, parses beam files, evaluates code and
from the filesystem, parses beam files, evaluates code and
so on.
If the exception module implements the optional `c:blame/2`
@@ -186,6 +186,8 @@ defmodule Exception do
This function returns either `{:ok, definition, clauses}` or `:error`.
Where `definition` is `:def`, `:defp`, `:defmacro` or `:defmacrop`.
Note this functionality requires Erlang/OTP 20, otherwise `:error`
is always returned.
"""
@doc since: "1.5.0"
@spec blame_mfa(module, function, args :: [term]) ::
@@ -788,10 +790,6 @@ defmodule BadFunctionError do
defexception [:term]
@impl true
def message(%{term: term}) when is_function(term) do
"function #{inspect(term)} is invalid, likely because it points to an old version of the code"
end
def message(exception) do
"expected a function, got: #{inspect(exception.term)}"
end
@@ -856,7 +854,7 @@ defmodule CondClauseError do
@impl true
def message(_exception) do
"no cond clause evaluated to a truthy value"
"no cond clause evaluated to a true value"
end
end
@@ -946,8 +944,7 @@ defmodule UndefinedFunctionError do
end
defp hint(module, function, arity, true) do
behaviour_hint(module, function, arity) <>
hint_for_loaded_module(module, function, arity, nil)
hint_for_loaded_module(module, function, arity, nil)
end
defp hint(_module, _function, _arity, _loaded?) do
@@ -973,10 +970,9 @@ defmodule UndefinedFunctionError do
result =
case Keyword.take(exports, [function]) do
[] ->
candidates = exports -- deprecated_functions_for(module)
base = Atom.to_string(function)
for {key, val} <- candidates,
for {key, val} <- exports,
dist = String.jaro_distance(base, Atom.to_string(key)),
dist >= @function_threshold,
do: {dist, key, val}
@@ -998,33 +994,6 @@ defmodule UndefinedFunctionError do
[" * ", Code.Identifier.inspect_as_function(fun), ?/, Integer.to_string(arity), ?\n]
end
defp behaviour_hint(module, function, arity) do
case behaviours_for(module) do
[] ->
""
behaviours ->
case Enum.find(behaviours, &expects_callback?(&1, function, arity)) do
nil -> ""
behaviour -> ", but the behaviour #{inspect(behaviour)} expects it to be present"
end
end
rescue
# In case the module was removed while we are computing this
UndefinedFunctionError -> ""
end
defp behaviours_for(module) do
:attributes
|> module.module_info()
|> Keyword.get(:behaviour, [])
end
defp expects_callback?(behaviour, function, arity) do
callbacks = behaviour.behaviour_info(:callbacks)
Enum.member?(callbacks, {function, arity})
end
defp exports_for(module) do
if function_exported?(module, :__info__, 1) do
module.__info__(:macros) ++ module.__info__(:functions)
@@ -1036,18 +1005,6 @@ defmodule UndefinedFunctionError do
UndefinedFunctionError ->
[]
end
defp deprecated_functions_for(module) do
if function_exported?(module, :__info__, 1) do
for {name_arity, _message} <- module.__info__(:deprecated), do: name_arity
else
[]
end
rescue
# In case the module was removed while we are computing this
UndefinedFunctionError ->
[]
end
end
defmodule FunctionClauseError do
@@ -1176,7 +1133,7 @@ defmodule KeyError do
def message(exception = %{message: nil}), do: message(exception.key, exception.term)
def message(%{message: message}), do: message
defp message(key, term) do
def message(key, term) do
message = "key #{inspect(key)} not found"
if term != nil do
+100 -164
View File
@@ -114,35 +114,20 @@ defmodule File do
| {:read_ahead, pos_integer | false}
| {:delayed_write, non_neg_integer, non_neg_integer}
@type erlang_time ::
{{year :: non_neg_integer(), month :: 1..12, day :: 1..31},
{hour :: 0..23, minute :: 0..59, second :: 0..59}}
@type posix_time :: integer()
@doc """
Returns `true` if the path is a regular file.
This function follows symbolic links, so if a symbolic link points to a
regular file, `true` is returned.
## Options
The supported options are:
* `:raw` - a single atom to bypass the file server and only check
for the file locally
## Examples
File.regular?(__ENV__.file)
#=> true
File.regular? __ENV__.file #=> true
"""
@spec regular?(Path.t(), [regular_option]) :: boolean
when regular_option: :raw
def regular?(path, opts \\ []) do
:elixir_utils.read_file_type(IO.chardata_to_string(path), opts) == {:ok, :regular}
@spec regular?(Path.t()) :: boolean
def regular?(path) do
:elixir_utils.read_file_type(IO.chardata_to_string(path)) == {:ok, :regular}
end
@doc """
@@ -151,13 +136,6 @@ defmodule File do
This function follows symbolic links, so if a symbolic link points to a
directory, `true` is returned.
## Options
The supported options are:
* `:raw` - a single atom to bypass the file server and only check
for the file locally
## Examples
File.dir?("./test")
@@ -172,29 +150,21 @@ defmodule File do
File.dir?("~/Downloads")
#=> false
"~/Downloads" |> Path.expand() |> File.dir?()
"~/Downloads" |> Path.expand |> File.dir?
#=> true
"""
@spec dir?(Path.t(), [dir_option]) :: boolean
when dir_option: :raw
def dir?(path, opts \\ []) do
:elixir_utils.read_file_type(IO.chardata_to_string(path), opts) == {:ok, :directory}
@spec dir?(Path.t()) :: boolean
def dir?(path) do
:elixir_utils.read_file_type(IO.chardata_to_string(path)) == {:ok, :directory}
end
@doc """
Returns `true` if the given path exists.
It can be a regular file, directory, socket, symbolic link, named pipe, or device file.
It can be regular file, directory, socket, symbolic link, named pipe or device file.
Returns `false` for symbolic links pointing to non-existing targets.
## Options
The supported options are:
* `:raw` - a single atom to bypass the file server and only check
for the file locally
## Examples
File.exists?("test/")
@@ -207,11 +177,9 @@ defmodule File do
#=> true
"""
@spec exists?(Path.t(), [exists_option]) :: boolean
when exists_option: :raw
def exists?(path, opts \\ []) do
opts = [{:time, :posix}] ++ opts
match?({:ok, _}, :file.read_file_info(IO.chardata_to_string(path), opts))
@spec exists?(Path.t()) :: boolean
def exists?(path) do
match?({:ok, _}, :file.read_file_info(IO.chardata_to_string(path)))
end
@doc """
@@ -237,10 +205,9 @@ defmodule File do
end
@doc """
Same as `mkdir/1`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
Same as `mkdir/1`, but raises an exception in case of failure. Otherwise `:ok`.
"""
@spec mkdir!(Path.t()) :: :ok
@spec mkdir!(Path.t()) :: :ok | no_return
def mkdir!(path) do
case mkdir(path) do
:ok ->
@@ -301,10 +268,9 @@ defmodule File do
end
@doc """
Same as `mkdir_p/1`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
Same as `mkdir_p/1`, but raises an exception in case of failure. Otherwise `:ok`.
"""
@spec mkdir_p!(Path.t()) :: :ok
@spec mkdir_p!(Path.t()) :: :ok | no_return
def mkdir_p!(path) do
case mkdir_p(path) do
:ok ->
@@ -340,10 +306,10 @@ defmodule File do
end
@doc """
Returns a binary with the contents of the given filename,
or raises a `File.Error` exception if an error occurs.
Returns a binary with the contents of the given filename or raises
`File.Error` if an error occurs.
"""
@spec read!(Path.t()) :: binary
@spec read!(Path.t()) :: binary | no_return
def read!(path) do
case read(path) do
{:ok, binary} ->
@@ -388,10 +354,10 @@ defmodule File do
end
@doc """
Same as `stat/2` but returns the `File.Stat` directly,
or raises a `File.Error` exception if an error is returned.
Same as `stat/2` but returns the `File.Stat` directly, or
throws `File.Error` if an error is returned.
"""
@spec stat!(Path.t(), stat_options) :: File.Stat.t()
@spec stat!(Path.t(), stat_options) :: File.Stat.t() | no_return
def stat!(path, opts \\ []) do
case stat(path, opts) do
{:ok, info} ->
@@ -439,10 +405,10 @@ defmodule File do
end
@doc """
Same as `lstat/2` but returns the `File.Stat` struct directly,
or raises a `File.Error` exception if an error is returned.
Same as `lstat/2` but returns the `File.Stat` struct directly, or
throws `File.Error` if an error is returned.
"""
@spec lstat!(Path.t(), stat_options) :: File.Stat.t()
@spec lstat!(Path.t(), stat_options) :: File.Stat.t() | no_return
def lstat!(path, opts \\ []) do
case lstat(path, opts) do
{:ok, info} ->
@@ -481,11 +447,11 @@ defmodule File do
end
@doc """
Same as `read_link/1` but returns the target directly,
or raises a `File.Error` exception if an error is returned.
Same as `read_link/1` but returns the target directly or throws `File.Error` if an error is
returned.
"""
@doc since: "1.5.0"
@spec read_link!(Path.t()) :: binary
@spec read_link!(Path.t()) :: binary | no_return
def read_link!(path) do
case read_link(path) do
{:ok, resolved} ->
@@ -497,7 +463,7 @@ defmodule File do
end
@doc """
Writes the given `File.Stat` back to the file system at the given
Writes the given `File.Stat` back to the filesystem at the given
path. Returns `:ok` or `{:error, reason}`.
"""
@spec write_stat(Path.t(), File.Stat.t(), stat_options) :: :ok | {:error, posix}
@@ -507,10 +473,10 @@ defmodule File do
end
@doc """
Same as `write_stat/3` but raises a `File.Error` exception if it fails.
Same as `write_stat/3` but raises an exception if it fails.
Returns `:ok` otherwise.
"""
@spec write_stat!(Path.t(), File.Stat.t(), stat_options) :: :ok
@spec write_stat!(Path.t(), File.Stat.t(), stat_options) :: :ok | no_return
def write_stat!(path, stat, opts \\ []) do
case write_stat(path, stat, opts) do
:ok ->
@@ -528,60 +494,32 @@ defmodule File do
Updates modification time (mtime) and access time (atime) of
the given file.
The file is created if it doesn't exist. Requires datetime in UTC
(as returned by `:erlang.universaltime()`) or an integer
representing the POSIX timestamp (as returned by `System.os_time(:second)`).
## Examples
File.touch("/tmp/a.txt", {{2018, 1, 30}, {13, 59, 59}})
#=> :ok
File.touch("/fakedir/b.txt", {{2018, 1, 30}, {13, 59, 59}})
{:error, :enoent}
File.touch("/tmp/a.txt", 1544519753)
#=> :ok
The file is created if it doesn’t exist. Requires datetime in UTC.
"""
@spec touch(Path.t(), erlang_time() | posix_time()) :: :ok | {:error, posix}
def touch(path, time \\ System.os_time(:second))
def touch(path, time) when is_tuple(time) do
@spec touch(Path.t(), :calendar.datetime()) :: :ok | {:error, posix}
def touch(path, time \\ :calendar.universal_time()) do
path = IO.chardata_to_string(path)
with {:error, :enoent} <- :elixir_utils.change_universal_time(path, time),
:ok <- write(path, "", [:append]),
do: :elixir_utils.change_universal_time(path, time)
case :elixir_utils.change_universal_time(path, time) do
{:error, :enoent} -> touch_new(path, time)
other -> other
end
end
def touch(path, time) when is_integer(time) do
path = IO.chardata_to_string(path)
with {:error, :enoent} <- :elixir_utils.change_posix_time(path, time),
:ok <- write(path, "", [:append]),
do: :elixir_utils.change_posix_time(path, time)
defp touch_new(path, time) do
case write(path, "", [:append]) do
:ok -> :elixir_utils.change_universal_time(path, time)
{:error, _reason} = error -> error
end
end
@doc """
Same as `touch/2` but raises a `File.Error` exception if it fails.
Returns `:ok` otherwise.
The file is created if it doesn't exist. Requires datetime in UTC
(as returned by `:erlang.universaltime()`) or an integer
representing the POSIX timestamp (as returned by `System.os_time(:second)`).
## Examples
File.touch!("/tmp/a.txt", {{2018, 1, 30}, {13, 59, 59}})
#=> :ok
File.touch!("/fakedir/b.txt", {{2018, 1, 30}, {13, 59, 59}})
#=> ** (File.Error) could not touch "/fakedir/b.txt": no such file or directory
File.touch!("/tmp/a.txt", 1544519753)
Same as `touch/2` but raises an exception if it fails.
Returns `:ok` otherwise. Requires datetime in UTC.
"""
@spec touch!(Path.t(), erlang_time() | posix_time()) :: :ok
def touch!(path, time \\ System.os_time(:second)) do
@spec touch!(Path.t(), :calendar.datetime()) :: :ok | no_return
def touch!(path, time \\ :calendar.universal_time()) do
case touch(path, time) do
:ok ->
:ok
@@ -605,11 +543,12 @@ defmodule File do
end
@doc """
Same as `ln/2` but raises a `File.LinkError` exception if it fails.
Returns `:ok` otherwise.
Same as `ln/2` but raises an exception if it fails.
Returns `:ok` otherwise
"""
@doc since: "1.5.0"
@spec ln!(Path.t(), Path.t()) :: :ok
@spec ln!(Path.t(), Path.t()) :: :ok | no_return
def ln!(existing, new) do
case ln(existing, new) do
:ok ->
@@ -638,10 +577,11 @@ defmodule File do
end
@doc """
Same as `ln_s/2` but raises a `File.LinkError` exception if it fails.
Returns `:ok` otherwise.
Same as `ln_s/2` but raises an exception if it fails.
Returns `:ok` otherwise
"""
@spec ln_s!(Path.t(), Path.t()) :: :ok
@spec ln_s!(Path.t(), Path.t()) :: :ok | no_return
def ln_s!(existing, new) do
case ln_s(existing, new) do
:ok ->
@@ -685,11 +625,11 @@ defmodule File do
end
@doc """
The same as `copy/3` but raises a `File.CopyError` exception if it fails.
The same as `copy/3` but raises an `File.CopyError` if it fails.
Returns the `bytes_copied` otherwise.
"""
@spec copy!(Path.t() | io_device, Path.t() | io_device, pos_integer | :infinity) ::
non_neg_integer
non_neg_integer | no_return
def copy!(source, destination, bytes_count \\ :infinity) do
case copy(source, destination, bytes_count) do
{:ok, bytes_count} ->
@@ -719,10 +659,10 @@ defmodule File do
## Examples
# Rename file "a.txt" to "b.txt"
File.rename("a.txt", "b.txt")
File.rename "a.txt", "b.txt"
# Rename directory "samples" to "tmp"
File.rename("samples", "tmp")
File.rename "samples", "tmp"
"""
@spec rename(Path.t(), Path.t()) :: :ok | {:error, posix}
@@ -767,10 +707,10 @@ defmodule File do
end
@doc """
The same as `cp/3`, but raises a `File.CopyError` exception if it fails.
The same as `cp/3`, but raises `File.CopyError` if it fails.
Returns `:ok` otherwise.
"""
@spec cp!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok
@spec cp!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: :ok | no_return
def cp!(source, destination, callback \\ fn _, _ -> true end) do
case cp(source, destination, callback) do
:ok ->
@@ -816,15 +756,15 @@ defmodule File do
## Examples
# Copies file "a.txt" to "b.txt"
File.cp_r("a.txt", "b.txt")
File.cp_r "a.txt", "b.txt"
# Copies all files in "samples" to "tmp"
File.cp_r("samples", "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 ->
File.cp_r "samples", "tmp", fn source, destination ->
IO.gets("Overwriting #{destination} by #{source}. Type y to confirm. ") == "y\n"
end)
end
"""
@spec cp_r(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) ::
@@ -847,10 +787,10 @@ defmodule File do
end
@doc """
The same as `cp_r/3`, but raises a `File.CopyError` exception if it fails.
The same as `cp_r/3`, but raises `File.CopyError` if it fails.
Returns the list of copied files otherwise.
"""
@spec cp_r!(Path.t(), Path.t(), (Path.t(), Path.t() -> boolean)) :: [binary]
@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
case cp_r(source, destination, callback) do
{:ok, files} ->
@@ -999,10 +939,9 @@ defmodule File do
end
@doc """
Same as `write/3` but raises a `File.Error` exception if it fails.
Returns `:ok` otherwise.
Same as `write/3` but raises an exception if it fails, returns `:ok` otherwise.
"""
@spec write!(Path.t(), iodata, [mode]) :: :ok
@spec write!(Path.t(), iodata, [mode]) :: :ok | no_return
def write!(path, content, modes \\ []) do
modes = normalize_modes(modes, false)
@@ -1079,10 +1018,9 @@ defmodule File do
end
@doc """
Same as `rm/1`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
Same as `rm/1`, but raises an exception in case of failure. Otherwise `:ok`.
"""
@spec rm!(Path.t()) :: :ok
@spec rm!(Path.t()) :: :ok | no_return
def rm!(path) do
case rm(path) do
:ok ->
@@ -1117,8 +1055,7 @@ defmodule File do
end
@doc """
Same as `rmdir/1`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
Same as `rmdir/1`, but raises an exception in case of failure. Otherwise `:ok`.
"""
@spec rmdir!(Path.t()) :: :ok | {:error, posix}
def rmdir!(path) do
@@ -1145,10 +1082,10 @@ defmodule File do
## Examples
File.rm_rf("samples")
File.rm_rf "samples"
#=> {:ok, ["samples", "samples/1.txt"]}
File.rm_rf("unknown")
File.rm_rf "unknown"
#=> {:ok, []}
"""
@@ -1208,7 +1145,7 @@ defmodule File do
# On Windows, symlinks are treated as directory and must be removed
# with rmdir/1. But on Unix, we remove them via rm/1. So we first try
# to remove it as a directory and, if we get :enotdir, we fall back to
# to remove it as a directory and, if we get :enotdir, we fallback to
# a file removal.
defp do_rm_directory(path, {:ok, acc} = entry) do
case rmdir(path) do
@@ -1239,10 +1176,10 @@ defmodule File do
end
@doc """
Same as `rm_rf/1` but raises a `File.Error` exception in case of failures,
Same as `rm_rf/1` but raises `File.Error` in case of failures,
otherwise the list of files or directories removed.
"""
@spec rm_rf!(Path.t()) :: [binary]
@spec rm_rf!(Path.t()) :: [binary] | no_return
def rm_rf!(path) do
case rm_rf(path) do
{:ok, files} ->
@@ -1364,7 +1301,7 @@ defmodule File do
## Examples
File.open("file.txt", [:read, :write], fn file ->
File.open("file.txt", [:read, :write], fn(file) ->
IO.read(file, :line)
end)
@@ -1387,13 +1324,14 @@ defmodule File do
end
@doc """
Similar to `open/2` but raises a `File.Error` exception if the file
could not be opened. Returns the IO device otherwise.
Similar to `open/2` but raises an error if file could not be opened.
Returns the IO device otherwise.
See `open/2` for the list of available modes.
"""
@spec open!(Path.t(), [mode | :ram]) :: io_device
@spec open!(Path.t(), (io_device -> res)) :: res when res: var
@spec open!(Path.t(), [mode | :ram]) :: io_device | no_return
@spec open!(Path.t(), (io_device -> res)) :: res | no_return when res: var
def open!(path, modes_or_function \\ []) do
case open(path, modes_or_function) do
{:ok, io_device_or_function_result} ->
@@ -1405,14 +1343,13 @@ defmodule File do
end
@doc """
Similar to `open/3` but raises a `File.Error` exception if the file
could not be opened.
Similar to `open/3` but raises an error if file could not be opened.
If it succeeds opening the file, it returns the `function` result on the IO device.
See `open/2` for the list of available `modes`.
"""
@spec open!(Path.t(), [mode | :ram], (io_device -> res)) :: res when res: var
@spec open!(Path.t(), [mode | :ram], (io_device -> res)) :: res | no_return when res: var
def open!(path, modes, function) do
case open(path, modes, function) do
{:ok, function_result} ->
@@ -1449,9 +1386,9 @@ defmodule File do
defp fix_drive_letter(original), do: original
@doc """
The same as `cwd/0`, but raises a `File.Error` exception if it fails.
The same as `cwd/0`, but raises an exception if it fails.
"""
@spec cwd!() :: binary
@spec cwd!() :: binary | no_return
def cwd!() do
case cwd() do
{:ok, cwd} ->
@@ -1473,9 +1410,9 @@ defmodule File do
end
@doc """
The same as `cd/1`, but raises a `File.Error` exception if it fails.
The same as `cd/1`, but raises an exception if it fails.
"""
@spec cd!(Path.t()) :: :ok
@spec cd!(Path.t()) :: :ok | no_return
def cd!(path) do
case cd(path) do
:ok ->
@@ -1524,9 +1461,10 @@ defmodule File do
end
@doc """
The same as `ls/1` but raises a `File.Error` exception in case of an error.
The same as `ls/1` but raises `File.Error`
in case of an error.
"""
@spec ls!(Path.t()) :: [binary]
@spec ls!(Path.t()) :: [binary] | no_return
def ls!(path \\ ".") do
case ls(path) do
{:ok, value} ->
@@ -1598,6 +1536,7 @@ defmodule File do
#=> path: "./test/test.data", raw: true}
See `Stream.run/1` for an example of streaming into a file.
"""
@spec stream!(Path.t(), stream_mode, :line | pos_integer) :: File.Stream.t()
def stream!(path, modes \\ [], line_or_bytes \\ :line) do
@@ -1612,7 +1551,7 @@ defmodule File do
## Permissions
File permissions are specified by adding together the following octal modes:
File permissions are specified by adding together the following octal flags:
* `0o400` - read permission: owner
* `0o200` - write permission: owner
@@ -1637,10 +1576,9 @@ defmodule File do
end
@doc """
Same as `chmod/2`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
Same as `chmod/2`, but raises an exception in case of failure. Otherwise `:ok`.
"""
@spec chmod!(Path.t(), non_neg_integer) :: :ok
@spec chmod!(Path.t(), non_neg_integer) :: :ok | no_return
def chmod!(path, mode) do
case chmod(path, mode) do
:ok ->
@@ -1665,10 +1603,9 @@ defmodule File do
end
@doc """
Same as `chgrp/2`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
Same as `chgrp/2`, but raises an exception in case of failure. Otherwise `:ok`.
"""
@spec chgrp!(Path.t(), non_neg_integer) :: :ok
@spec chgrp!(Path.t(), non_neg_integer) :: :ok | no_return
def chgrp!(path, gid) do
case chgrp(path, gid) do
:ok ->
@@ -1693,10 +1630,9 @@ defmodule File do
end
@doc """
Same as `chown/2`, but raises a `File.Error` exception in case of failure.
Otherwise `:ok`.
Same as `chown/2`, but raises an exception in case of failure. Otherwise `:ok`.
"""
@spec chown!(Path.t(), non_neg_integer) :: :ok
@spec chown!(Path.t(), non_neg_integer) :: :ok | no_return
def chown!(path, uid) do
case chown(path, uid) do
:ok ->
+2 -17
View File
@@ -12,7 +12,7 @@ defmodule File.Stat do
* `size` - size of file in bytes.
* `type` - `:device | :directory | :regular | :other | :symlink`; the type of the
* `type` - `:device | :directory | :regular | :other`; the type of the
file.
* `access` - `:read | :write | :read_write | :none`; the current system
@@ -58,22 +58,7 @@ defmodule File.Stat do
pairs = :lists.zip(keys, vals)
defstruct keys
@type t :: %__MODULE__{
size: non_neg_integer(),
type: :device | :directory | :regular | :other | :symlink,
access: :read | :write | :read_write | :none,
atime: :calendar.datetime(),
mtime: :calendar.datetime(),
ctime: :calendar.datetime(),
mode: non_neg_integer(),
links: non_neg_integer(),
major_device: non_neg_integer(),
minor_device: non_neg_integer(),
inode: non_neg_integer(),
uid: non_neg_integer(),
gid: non_neg_integer()
}
@type t :: %__MODULE__{}
@doc """
Converts a `File.Stat` struct to a `:file_info` record.
+23 -42
View File
@@ -149,10 +149,6 @@ defmodule Float do
@spec floor(float, precision_range) :: float
def floor(number, precision \\ 0)
def floor(number, 0) when is_float(number) do
:math.floor(number)
end
def floor(number, precision) when is_float(number) and precision in @precision_range do
round(number, precision, :floor)
end
@@ -196,10 +192,6 @@ defmodule Float do
@spec ceil(float, precision_range) :: float
def ceil(number, precision \\ 0)
def ceil(number, 0) when is_float(number) do
:math.ceil(number)
end
def ceil(number, precision) when is_float(number) and precision in @precision_range do
round(number, precision, :ceil)
end
@@ -256,26 +248,25 @@ defmodule Float do
# and could be implemented in the future.
def round(float, precision \\ 0)
def round(float, 0) when is_float(float) do
float |> :erlang.round() |> :erlang.float()
end
def round(float, precision) when is_float(float) and precision in @precision_range do
round(float, precision, :half_up)
end
def round(float, precision) when is_float(float) do
def round(number, precision) when is_float(number) do
raise ArgumentError, invalid_precision_message(precision)
end
defp round(0.0, _precision, _rounding), do: 0.0
defp round(float, precision, rounding) do
<<sign::1, exp::11, significant::52-bitstring>> = <<float::float>>
{num, count, _} = decompose(significant, 1)
{num, count, _} = decompose(significant)
count = count - exp + 1023
cond do
# There is no decimal precision
# zero or minus zero
count <= 0 or (0 == exp and <<0::52>> == significant) ->
float
# Precision beyond 15 digits
count >= 104 ->
case rounding do
@@ -382,8 +373,6 @@ defmodule Float do
## Examples
iex> Float.ratio(0.0)
{0, 1}
iex> Float.ratio(3.14)
{7070651414971679, 2251799813685248}
iex> Float.ratio(-3.14)
@@ -399,35 +388,27 @@ defmodule Float do
"""
@doc since: "1.4.0"
@spec ratio(float) :: {integer, pos_integer}
def ratio(0.0), do: {0, 1}
@spec ratio(float) :: {pos_integer | neg_integer, pos_integer}
def ratio(float) when is_float(float) do
case <<float::float>> do
<<sign::1, 0::11, significant::52-bitstring>> ->
{num, _, den} = decompose(significant, 0)
{sign(sign, num), shift_left(den, 1022)}
<<sign::1, exp::11, significant::52-bitstring>> = <<float::float>>
{num, _, den} = decompose(significant)
num = sign(sign, num)
<<sign::1, exp::11, significant::52-bitstring>> ->
{num, _, den} = decompose(significant, 1)
num = sign(sign, num)
case exp - 1023 do
exp when exp > 0 ->
{den, exp} = shift_right(den, exp)
{shift_left(num, exp), den}
case exp - 1023 do
exp when exp > 0 ->
{den, exp} = shift_right(den, exp)
{shift_left(num, exp), den}
exp when exp < 0 ->
{num, shift_left(den, -exp)}
exp when exp < 0 ->
{num, shift_left(den, -exp)}
0 ->
{num, den}
end
0 ->
{num, den}
end
end
defp decompose(significant, initial) do
decompose(significant, 1, 0, 2, 1, initial)
defp decompose(significant) do
decompose(significant, 1, 0, 2, 1, 1)
end
defp decompose(<<1::1, bits::bitstring>>, count, last_count, power, _last_power, acc) do
@@ -442,11 +423,11 @@ defmodule Float do
{acc, last_count, last_power}
end
@compile {:inline, sign: 2, shift_left: 2}
defp sign(0, num), do: num
defp sign(1, num), do: -num
defp shift_left(num, times), do: num <<< times
defp shift_left(num, 0), do: num
defp shift_left(num, times), do: shift_left(num <<< 1, times - 1)
defp shift_right(num, 0), do: {num, 0}
defp shift_right(1, times), do: {1, times}
+71 -134
View File
@@ -61,9 +61,7 @@ defmodule GenServer do
Every time you do a `GenServer.call/3`, the client will send a message
that must be handled by the `c:handle_call/3` callback in the GenServer.
A `cast/2` message must be handled by `c:handle_cast/2`. There are 7 possible
callbacks to be implemented when you use a `GenServer`. The only required
callback is `init/1`.
A `cast/2` message must be handled by `c:handle_cast/2`.
## Client / Server APIs
@@ -113,46 +111,25 @@ 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.
## How to supervise
## use GenServer and callbacks
A `GenServer` is most commonly started under a supervision tree.
When we invoke `use GenServer`, it automatically defines a `child_spec/1`
function that allows us to start the `Stack` directly under a supervisor.
To start a default stack of `[:hello]` under a supervisor, one may do:
There are 7 callbacks to be implemented when you use a `GenServer`.
The only required callback is `init/1`.
children = [
{Stack, [:hello]}
]
Supervisor.start_link(children, strategy: :one_for_all)
Note you can also start it simply as `Stack`, which is the same as
`{Stack, []}`:
children = [
Stack # The same as {Stack, []}
]
Supervisor.start_link(children, strategy: :one_for_all)
In both cases, `Stack.start_link/1` is always invoked.
`use GenServer` also accepts a list of options which configures the
child specification and therefore how it runs under a supervisor.
The generated `child_spec/1` can be customized with the following options:
`use GenServer` also defines a `child_spec/1` function, allowing the
defined module to be put under a supervision tree. The generated
`child_spec/1` can be customized with the following options:
* `:id` - the child specification identifier, defaults to the current module
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
* `:restart` - when the child should be restarted, defaults to `:permanent`
* `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down
* `:shutdown` - how to shut down the child
For example:
use GenServer, restart: :transient, shutdown: 10_000
See the "Child specification" section in the `Supervisor` module for more
detailed information. The `@doc` annotation immediately preceding
`use GenServer` will be attached to the generated `child_spec/1` function.
See the `Supervisor` docs for more information.
## Name registration
@@ -181,8 +158,7 @@ defmodule GenServer do
{:ok, _} = GenServer.start_link(Stack, [:hello], name: MyStack)
# Now messages can be sent directly to MyStack
GenServer.call(MyStack, :pop)
#=> :hello
GenServer.call(MyStack, :pop) #=> :hello
Once the server is started, the remaining functions in this module (`call/3`,
`cast/2`, and friends) will also accept an atom, or any `{:global, ...}` or
@@ -219,32 +195,25 @@ defmodule GenServer do
defmodule MyApp.Periodically do
use GenServer
def start_link(_) do
def start_link do
GenServer.start_link(__MODULE__, %{})
end
@impl true
def init(state) do
# Schedule work to be performed on start
schedule_work()
schedule_work() # Schedule work to be performed on start
{:ok, state}
end
@impl true
def handle_info(:work, state) do
# Do the desired work here
...
# Reschedule once more
schedule_work()
schedule_work() # Reschedule once more
{:noreply, state}
end
defp schedule_work do
# In 2 hours
Process.send_after(self(), :work, 2 * 60 * 60 * 1000)
defp schedule_work() do
Process.send_after(self(), :work, 2 * 60 * 60 * 1000) # In 2 hours
end
end
@@ -331,48 +300,29 @@ defmodule GenServer do
*DBG* <0.122.0> got cast {push,1}
*DBG* <0.122.0> new state [1]
:ok
iex> :sys.get_state(pid)
[1]
iex> Stack.pop(pid)
*DBG* <0.122.0> got call pop from <0.80.0>
*DBG* <0.122.0> sent 1 to <0.80.0>, new state []
1
iex> :sys.statistics(pid, :get)
{:ok,
[
start_time: {{2016, 7, 16}, {12, 29, 41}},
current_time: {{2016, 7, 16}, {12, 29, 50}},
reductions: 117,
messages_in: 2,
messages_out: 0
]}
[start_time: {{2016, 7, 16}, {12, 29, 41}},
current_time: {{2016, 7, 16}, {12, 29, 50}},
reductions: 117, messages_in: 2, messages_out: 0]}
iex> :sys.no_debug(pid) # turn off all debug handlers
:ok
iex> :sys.get_status(pid)
{:status, #PID<0.122.0>, {:module, :gen_server},
[
[
"$initial_call": {Stack, :init, 1}, # process dictionary
"$ancestors": [#PID<0.80.0>, #PID<0.51.0>]
],
:running, # :running | :suspended
#PID<0.80.0>, # parent
[], # debugger state
[
header: 'Status for generic server <0.122.0>', # module status
data: [
{'Status', :running},
{'Parent', #PID<0.80.0>},
{'Logged events', []}
],
data: [{'State', [1]}]
]
]}
[["$initial_call": {Stack, :init, 1}, # pdict
"$ancestors": [#PID<0.80.0>, #PID<0.51.0>]],
:running, # :running | :suspended
#PID<0.80.0>, # parent
[], # debugger state
[header: 'Status for generic server <0.122.0>', # module status
data: [{'Status', :running}, {'Parent', #PID<0.80.0>},
{'Logged events', []}], data: [{'State', [1]}]]]}
## Learn more
@@ -380,10 +330,10 @@ defmodule GenServer do
guide provides a tutorial-like introduction. The documentation and links
in Erlang can also provide extra insight.
* [GenServer - Elixir's Getting Started Guide](https://elixir-lang.org/getting-started/mix-otp/genserver.html)
* [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)
* [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)
"""
@@ -391,7 +341,7 @@ defmodule GenServer do
Invoked when the server is started. `start_link/3` or `start/3` will
block until it returns.
`init_arg` is the argument term (second argument) passed to `start_link/3`.
`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.
@@ -428,7 +378,7 @@ defmodule GenServer do
`{:error, reason}` and the process to exit with reason `reason` without
entering the loop or calling `c:terminate/2`.
"""
@callback init(init_arg :: term) ::
@callback init(args :: term) ::
{:ok, state}
| {:ok, state, timeout | :hibernate | {:continue, term}}
| :ignore
@@ -500,7 +450,7 @@ defmodule GenServer do
{:reply, reply, new_state}
| {:reply, reply, new_state, timeout | :hibernate | {:continue, term}}
| {:noreply, new_state}
| {:noreply, new_state, timeout | :hibernate | {:continue, term}}
| {:noreply, new_state, timeout | :hibernate, {:continue, term}}
| {:stop, reason, reply, new_state}
| {:stop, reason, new_state}
when reply: term, new_state: term, reason: term
@@ -590,20 +540,13 @@ defmodule GenServer do
* 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 will receive an exit
signal when the tree is shutting down. The exit signal is based on
the shutdown strategy in the child's specification, where we this
value can be:
* `:brutal_kill`: the `GenServer` is killed and so `c:terminate/2` is not called.
* a timeout value, where the supervisor will send the exit signal `:shutdown` and
the `GenServer` will have the duration of the timeout to terminate.
If after duration of this timeout the process is still alive, it will be killed
immediately.
For a more in-depth explanation, please read the "Shutdown values (:shutdown)"
section in the `Supervisor` module.
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 `c: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 `c: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
@@ -619,7 +562,7 @@ defmodule GenServer do
receiving a `GenServer`'s exit signal and do not need to be closed manually
in `c:terminate/2`.
If `reason` is neither `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is
If `reason` is not `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is
logged.
This callback is optional.
@@ -697,7 +640,6 @@ defmodule GenServer do
| {:name, name}
| {:timeout, timeout}
| {:spawn_opt, Process.spawn_opt()}
| {:hibernate_after, timeout}
@typedoc "Debug options supported by the `start*` functions"
@type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t()}]
@@ -718,18 +660,15 @@ defmodule GenServer do
quote location: :keep, bind_quoted: [opts: opts] do
@behaviour GenServer
if Module.get_attribute(__MODULE__, :doc) == nil do
@doc """
Returns a specification to start this module under a supervisor.
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
end
def child_spec(init_arg) do
See `Supervisor`.
"""
def child_spec(arg) do
default = %{
id: __MODULE__,
start: {__MODULE__, :start_link, [init_arg]}
start: {__MODULE__, :start_link, [arg]}
}
Supervisor.child_spec(default, unquote(Macro.escape(opts)))
@@ -811,8 +750,8 @@ defmodule GenServer do
We will inject a default implementation for now:
def init(init_arg) do
{:ok, init_arg}
def init(args) do
{:ok, args}
end
You can copy the implementation above or define your own that converts \
@@ -823,8 +762,8 @@ defmodule GenServer do
quote do
@doc false
def init(init_arg) do
{:ok, init_arg}
def init(args) do
{:ok, args}
end
defoverridable init: 1
@@ -838,7 +777,7 @@ defmodule GenServer do
This is often used to start the `GenServer` as part of a supervision tree.
Once the server is started, the `c:init/1` function of the given `module` is
called with `init_arg` as its argument to initialize the server. To ensure a
called with `args` as its arguments to initialize the server. To ensure a
synchronized start-up procedure, this function does not return until `c:init/1`
has returned.
@@ -861,10 +800,6 @@ defmodule GenServer do
* `:spawn_opt` - if present, its value is passed as options to the
underlying process as in `Process.spawn/4`
* `:hibernate_after` - if present, the GenServer process awaits any message for
the given number of milliseconds and if no message is received, the process goes
into hibernation automatically (by calling `:proc_lib.hibernate/3`).
## Return values
If the server is successfully created and initialized, this function returns
@@ -878,8 +813,8 @@ defmodule GenServer do
`{:error, reason}` or `:ignore`, respectively.
"""
@spec start_link(module, any, options) :: on_start
def start_link(module, init_arg, options \\ []) when is_atom(module) and is_list(options) do
do_start(:link, module, init_arg, options)
def start_link(module, args, options \\ []) when is_atom(module) and is_list(options) do
do_start(:link, module, args, options)
end
@doc """
@@ -888,23 +823,23 @@ defmodule GenServer do
See `start_link/3` for more information.
"""
@spec start(module, any, options) :: on_start
def start(module, init_arg, options \\ []) when is_atom(module) and is_list(options) do
do_start(:nolink, module, init_arg, options)
def start(module, args, options \\ []) when is_atom(module) and is_list(options) do
do_start(:nolink, module, args, options)
end
defp do_start(link, module, init_arg, options) do
defp do_start(link, module, args, options) do
case Keyword.pop(options, :name) do
{nil, opts} ->
:gen.start(:gen_server, link, module, init_arg, opts)
:gen.start(:gen_server, link, module, args, opts)
{atom, opts} when is_atom(atom) ->
:gen.start(:gen_server, link, {:local, atom}, module, init_arg, opts)
:gen.start(:gen_server, link, {:local, atom}, module, args, opts)
{{:global, _term} = tuple, opts} ->
:gen.start(:gen_server, link, tuple, module, init_arg, opts)
:gen.start(:gen_server, link, tuple, module, args, opts)
{{:via, via_module, _term} = tuple, opts} when is_atom(via_module) ->
:gen.start(:gen_server, link, tuple, module, init_arg, opts)
:gen.start(:gen_server, link, tuple, module, args, opts)
{other, _} ->
raise ArgumentError, """
@@ -1003,13 +938,11 @@ defmodule GenServer do
`c: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 semantics differ
depending on the used Erlang/OTP version.
Before Erlang/OTP 21, the call is going to block until a
connection happens. This was done to guarantee ordering.
Starting with Erlang/OTP 21, both Erlang and Elixir do
not block the call.
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.
"""
@spec cast(server, term) :: :ok
def cast(server, request)
@@ -1135,8 +1068,12 @@ defmodule GenServer do
def reply(client, reply)
def reply({to, tag}, reply) when is_pid(to) do
send(to, {tag, reply})
:ok
try do
send(to, {tag, reply})
:ok
catch
_, _ -> :ok
end
end
@doc """
+5 -69
View File
@@ -20,7 +20,7 @@ defprotocol Inspect do
## Examples
Many times, inspecting a structure can be implemented in function
of existing entities. For example, here is `MapSet`'s `inspect/2`
of existing entities. For example, here is `MapSet`'s `inspect`
implementation:
defimpl Inspect, for: MapSet do
@@ -39,8 +39,8 @@ defprotocol Inspect do
other string `">"`.
Since regular strings are valid entities in an algebra document,
an implementation of the `Inspect` protocol may simply return a
string, although that will devoid it of any pretty-printing.
an implementation of inspect may simply return a string,
although that will devoid it of any pretty-printing.
## Error handling
@@ -48,30 +48,12 @@ defprotocol Inspect do
Elixir will raise an `ArgumentError` error and will automatically fall back
to a raw representation for printing the structure.
You can however access the underlying error by invoking the `Inspect`
implementation directly. For example, to test `Inspect.MapSet` above,
You can however access the underlying error by invoking the Inspect
implementation directly. For example, to test Inspect.MapSet above,
you can invoke it as:
Inspect.MapSet.inspect(MapSet.new(), %Inspect.Opts{})
## Deriving
The `Inspect` protocol can be derived to hide certain fields from
structs, so they don't show up in logs, inspects and similar. This
is especially useful for fields containing private information.
The options `:only` and `:except` can be used with `@derive` to
specify which fields should and should not appear in the
algebra document:
defmodule User do
@derive {Inspect, only: [:id, :name]}
defstruct [:id, :name, :address]
end
inspect(%User{id: 1, name: "Homer", address: "742 Evergreen Terrace"})
#=> #User<id: 1, name: "Homer", ...>
"""
# Handle structs in Any
@@ -390,39 +372,6 @@ defimpl Inspect, for: Reference do
end
defimpl Inspect, for: Any do
defmacro __deriving__(module, struct, options) do
fields =
struct
|> Map.drop([:__exception__, :__struct__])
|> Map.keys()
only = Keyword.get(options, :only, fields)
except = Keyword.get(options, :except, [])
filtered_fields =
fields
|> Enum.reject(&(&1 in except))
|> Enum.filter(&(&1 in only))
inspect_module =
if fields == only and except == [] do
quote(do: Inspect.Map)
else
quote(do: Inspect.Any)
end
quote do
defimpl Inspect, for: unquote(module) do
def inspect(struct, opts) do
map = Map.take(struct, unquote(filtered_fields))
colorless_opts = %{opts | syntax_colors: []}
name = Inspect.Atom.inspect(unquote(module), colorless_opts)
unquote(inspect_module).inspect(map, name, opts)
end
end
end
end
def inspect(%module{} = struct, opts) do
try do
module.__struct__
@@ -439,17 +388,4 @@ defimpl Inspect, for: Any do
end
end
end
def inspect(map, name, opts) do
# Use the :limit option and an extra element to force
# `container_doc/6` to append "...".
opts = %{opts | limit: min(opts.limit, map_size(map))}
map = :maps.to_list(map) ++ ["..."]
open = color("#" <> name <> "<", :map, opts)
sep = color(",", :map, opts)
close = color(">", :map, opts)
container_doc(open, map, close, opts, &Inspect.List.keyword/2, separator: sep, break: :strict)
end
end
+33 -43
View File
@@ -1,6 +1,6 @@
defmodule Inspect.Opts do
@moduledoc """
Defines the options used by the `Inspect` protocol.
Defines the Inspect.Opts used by the Inspect protocol.
The following fields are available:
@@ -15,8 +15,8 @@ defmodule Inspect.Opts do
When the default `:infer`, the binary will be printed as a string if it
is printable, otherwise in bit syntax.
* `:charlists` - when `:as_charlists` all lists will be printed as charlists,
non-printable elements will be escaped.
* `:charlists` - when `:as_charlists` all lists will be printed as char
lists, non-printable elements will be escaped.
When `:as_lists` all lists will be printed as lists.
@@ -29,7 +29,7 @@ defmodule Inspect.Opts do
the number of items to a particular number, use `:infinity`.
* `:printable_limit` - limits the number of bytes that are printed for strings
and charlists. Defaults to 4096. If you don't want to limit the number of items
and char lists. Defaults to 4096. If you don't want to limit the number of items
to a particular number, use `:infinity`.
* `:pretty` - if set to `true` enables pretty printing, defaults to `false`.
@@ -148,7 +148,7 @@ defmodule Inspect.Algebra do
## Implementation details
The implementation of `Inspect.Algebra` is based on the Strictly Pretty
The implementation of Inspect.Algebra is based on the Strictly Pretty
paper by [Lindig][0] which builds on top of previous pretty printing
algorithms but is tailored to strict languages, such as Elixir.
The core idea in the paper is the use of explicit document groups which
@@ -312,7 +312,7 @@ defmodule Inspect.Algebra do
attempts to put as much as possible on the same line. If they are not simple,
only one entry is shown per line if they do not fit.
The limit in the given `inspect_opts` is respected and when reached this
The limit in the given `Inspect.Opts` is respected and when reached this
function stops processing and outputs `"..."` instead.
## Options
@@ -324,22 +324,18 @@ defmodule Inspect.Algebra do
## Examples
iex> inspect_opts = %Inspect.Opts{limit: :infinity}
iex> fun = fn i, _opts -> to_string(i) end
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]", inspect_opts, fun)
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]",
...> %Inspect.Opts{limit: :infinity}, fn i, _opts -> to_string(i) end)
iex> Inspect.Algebra.format(doc, 5) |> IO.iodata_to_binary()
"[1,\n 2,\n 3,\n 4,\n 5]"
iex> inspect_opts = %Inspect.Opts{limit: 3}
iex> fun = fn i, _opts -> to_string(i) end
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]", inspect_opts, fun)
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]",
...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end)
iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary()
"[1, 2, 3, ...]"
iex> inspect_opts = %Inspect.Opts{limit: 3}
iex> fun = fn i, _opts -> to_string(i) end
iex> opts = [separator: "!"]
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]", inspect_opts, fun, opts)
iex> doc = Inspect.Algebra.container_doc("[", Enum.to_list(1..5), "]",
...> %Inspect.Opts{limit: 3}, fn i, _opts -> to_string(i) end, separator: "!")
iex> Inspect.Algebra.format(doc, 20) |> IO.iodata_to_binary()
"[1! 2! 3! ...]"
@@ -347,7 +343,7 @@ defmodule Inspect.Algebra do
@doc since: "1.6.0"
@spec container_doc(t, [any], t, Inspect.Opts.t(), (term, Inspect.Opts.t() -> t), keyword()) ::
t
def container_doc(left, collection, right, inspect_opts, fun, opts \\ [])
def container_doc(left, collection, right, inspect, fun, opts \\ [])
when is_doc(left) and is_list(collection) and is_doc(right) and is_function(fun, 2) and
is_list(opts) do
case collection do
@@ -359,7 +355,7 @@ defmodule Inspect.Algebra do
separator = Keyword.get(opts, :separator, @container_separator)
{docs, simple?} =
container_each(collection, inspect_opts.limit, inspect_opts, fun, [], break == :maybe)
container_each(collection, inspect.limit, inspect, fun, [], break == :maybe)
flex? = simple? or break == :flex
docs = fold_doc(docs, &join(&1, &2, flex?, separator))
@@ -410,16 +406,14 @@ defmodule Inspect.Algebra do
defp simple?(:doc_nil), do: true
defp simple?(other), do: is_binary(other)
# TODO: Remove on 2.0
@doc false
@deprecated "Use a combination of concat/2 and nest/2 instead"
# TODO: Deprecate on Elixir v1.8
def surround(left, doc, right) when is_doc(left) and is_doc(doc) and is_doc(right) do
concat(concat(left, nest(doc, 1)), right)
end
# TODO: Remove on 2.0
@doc false
@deprecated "Use Inspect.Algebra.container_doc/6 instead"
# TODO: Deprecate on Elixir v1.8
def surround_many(
left,
docs,
@@ -741,24 +735,22 @@ defmodule Inspect.Algebra do
## Examples
iex> doc =
...> Inspect.Algebra.group(
...> Inspect.Algebra.concat(
...> Inspect.Algebra.group(
...> Inspect.Algebra.concat(
...> "Hello,",
...> Inspect.Algebra.concat(
...> Inspect.Algebra.break(),
...> "A"
...> )
...> )
...> ),
iex> doc = Inspect.Algebra.group(
...> Inspect.Algebra.concat(
...> Inspect.Algebra.group(
...> Inspect.Algebra.concat(
...> Inspect.Algebra.break(),
...> "B"
...> "Hello,",
...> Inspect.Algebra.concat(
...> Inspect.Algebra.break,
...> "A"
...> )
...> )
...> ),
...> Inspect.Algebra.concat(
...> Inspect.Algebra.break,
...> "B"
...> )
...> )
...> ))
iex> Inspect.Algebra.format(doc, 80)
["Hello,", " ", "A", " ", "B"]
iex> Inspect.Algebra.format(doc, 6)
@@ -795,8 +787,7 @@ defmodule Inspect.Algebra do
...> Inspect.Algebra.concat(
...> "Hughes",
...> Inspect.Algebra.line()
...> ),
...> "Wadler"
...> ), "Wadler"
...> )
iex> Inspect.Algebra.format(doc, 80)
["Hughes", "\n", "Wadler"]
@@ -831,10 +822,9 @@ defmodule Inspect.Algebra do
## Examples
iex> docs = ["A", "B", "C"]
iex> docs =
...> Inspect.Algebra.fold_doc(docs, fn doc, acc ->
...> Inspect.Algebra.concat([doc, "!", acc])
...> end)
iex> docs = Inspect.Algebra.fold_doc(docs, fn(doc, acc) ->
...> Inspect.Algebra.concat([doc, "!", acc])
...> end)
iex> Inspect.Algebra.format(docs, 80)
["A", "!", "B", "!", "C"]
+2 -2
View File
@@ -4,7 +4,7 @@ defmodule Integer do
Some functions that work on integers are found in `Kernel`:
* `abs/1`
* `abs/2`
* `div/2`
* `max/2`
* `min/2`
@@ -158,7 +158,7 @@ defmodule Integer do
Returns the integer represented by the ordered `digits`.
An optional `base` value may be provided representing the radix for the `digits`.
Base has to be an integer greater than or equal to `2`.
Base has to be an integer greater or equal than `2`.
## Examples
+13 -13
View File
@@ -36,7 +36,7 @@ defmodule IO do
@type device :: atom | pid
@type nodata :: {:error, term} | :eof
@type chardata :: String.t() | maybe_improper_list(char | chardata, String.t() | [])
@type chardata() :: :unicode.chardata()
defmacrop is_iodata(data) do
quote do
@@ -147,10 +147,10 @@ defmodule IO do
## Examples
IO.write("sample")
IO.write "sample"
#=> sample
IO.write(:stderr, "error")
IO.write :stderr, "error"
#=> error
"""
@@ -183,10 +183,10 @@ defmodule IO do
## Examples
IO.puts("Hello World!")
IO.puts "Hello World!"
#=> Hello World!
IO.puts(:stderr, "error")
IO.puts :stderr, "error"
#=> error
"""
@@ -207,7 +207,7 @@ defmodule IO do
## Examples
stacktrace = [{MyApp, :main, 1, [file: 'my_app.ex', line: 4]}]
IO.warn("variable bar is unused", stacktrace)
IO.warn "variable bar is unused", stacktrace
#=> warning: variable bar is unused
#=> my_app.ex:4: MyApp.main/1
@@ -232,7 +232,7 @@ defmodule IO do
## Examples
IO.warn("variable bar is unused")
IO.warn "variable bar is unused"
#=> warning: variable bar is unused
#=> (iex) evaluator.ex:108: IEx.Evaluator.eval/4
@@ -263,7 +263,7 @@ defmodule IO do
## Examples
IO.inspect(<<0, 1, 2>>, width: 40)
IO.inspect <<0, 1, 2>>, width: 40
Prints:
@@ -271,7 +271,7 @@ defmodule IO do
We can use the `:label` option to decorate the output:
IO.inspect(1..100, label: "a wonderful range")
IO.inspect 1..100, label: "a wonderful range"
Prints:
@@ -283,7 +283,7 @@ defmodule IO do
|> IO.inspect(label: "before")
|> Enum.map(&(&1 * 2))
|> IO.inspect(label: "after")
|> Enum.sum()
|> Enum.sum
Prints:
@@ -374,7 +374,7 @@ defmodule IO do
To display "What is your name?" as a prompt and await user input:
IO.gets("What is your name?\n")
IO.gets "What is your name?\n"
"""
@spec gets(device, chardata | String.Chars.t()) :: chardata | nodata
@@ -403,7 +403,7 @@ defmodule IO do
Here is an example on how we mimic an echo server
from the command line:
Enum.each(IO.stream(:stdio, :line), &IO.write(&1))
Enum.each IO.stream(:stdio, :line), &IO.write(&1)
"""
@spec stream(device, :line | pos_integer) :: Enumerable.t()
@@ -457,7 +457,7 @@ defmodule IO do
"string"
"""
@spec chardata_to_string(chardata) :: String.t()
@spec chardata_to_string(chardata) :: String.t() | no_return
def chardata_to_string(string) when is_binary(string) do
string
end
+8 -16
View File
@@ -56,7 +56,7 @@ defmodule IO.ANSI.Docs do
end
@doc """
Prints documentation metadata (only `delegate_to`, `deprecated`, `guard`, and `since` for now).
Prints documentation metadata (only `since` and `deprecated` for now).
See `default_options/0` for docs on the supported options.
"""
@@ -66,7 +66,7 @@ defmodule IO.ANSI.Docs do
print_each_metadata(metadata, options) && IO.write("\n")
end
@metadata_filter [:deprecated, :guard, :since]
@metadata_filter [:deprecated, :since]
defp print_each_metadata(metadata, options) do
Enum.reduce(metadata, false, fn
@@ -75,13 +75,6 @@ defmodule IO.ANSI.Docs do
indent = String.duplicate(" ", length_without_escape(label, 0) + 1)
write_with_wrap([label | String.split(value, @spaces)], options[:width], indent, true)
{key, value}, _printed when is_boolean(value) and key in @metadata_filter ->
IO.puts([metadata_label(key, options), ' ', to_string(value)])
{:delegate_to, {m, f, a}}, _printed ->
label = metadata_label(:delegate_to, options)
IO.puts([label, ' ', Exception.format_mfa(m, f, a)])
_metadata, printed ->
printed
end)
@@ -98,7 +91,7 @@ defmodule IO.ANSI.Docs do
@doc """
Prints the documentation body.
In addition to the printing string, takes a set of `options`
In addition to the printing string, takes a set of options
defined in `default_options/0`.
"""
@spec print(String.t(), keyword) :: :ok
@@ -524,8 +517,7 @@ defmodule IO.ANSI.Docs do
end
defp escape_underlines_in_link(text) do
# Regular expression adapted from https://tools.ietf.org/html/rfc3986#appendix-B
~r{[a-z][a-z0-9\+\-\.]*://\S*}i
~r{https?\S*}
|> Regex.recompile!()
|> Regex.replace(text, &String.replace(&1, "_", "\\_"))
end
@@ -539,9 +531,8 @@ defmodule IO.ANSI.Docs do
# We have four entries: **, *, _ and `.
#
# The first three behave the same while the last one is simpler
# when it comes to delimiters as it ignores spaces and escape
# characters. But, since the first has two characters, we need to
# handle 3 cases:
# when it comes to delimiters. But, since the first has two
# characters, we need to handle 3 cases:
#
# 1. **
# 2. _ and *
@@ -603,7 +594,8 @@ defmodule IO.ANSI.Docs do
end
# An escape is not valid inside `
defp handle_inline(<<?\\, mark, rest::binary>>, limit, buffer, acc, options) when limit != ?` do
defp handle_inline(<<?\\, mark, rest::binary>>, limit, buffer, acc, options)
when not (mark == limit and mark == ?`) do
handle_inline(rest, limit, [mark | buffer], acc, options)
end
+120 -269
View File
File diff suppressed because it is too large Load Diff
+1 -1
View File
@@ -162,7 +162,7 @@ defmodule Kernel.LexicalTracker do
end
def handle_cast({:remote_struct, module, line}, state) do
state = add_remote_dispatch(state, module, {:__struct__, 0}, line, :compile)
state = add_remote_dispatch(state, module, {:__struct__, 1}, line, :compile)
structs = :maps.put(module, true, state.structs)
{:noreply, %{state | structs: structs}}
end
+16 -36
View File
@@ -45,7 +45,7 @@ defmodule Kernel.ParallelCompiler do
It returns `{:ok, modules, warnings}` or `{:error, errors, warnings}`.
Both errors and warnings are a list of three-element tuples containing
Both errors and warnings are a list of three element tuples containing
the file, line and the formatted error/warning.
## Options
@@ -90,7 +90,7 @@ defmodule Kernel.ParallelCompiler do
It returns `{:ok, modules, warnings}` or `{:error, errors, warnings}`.
Both errors and warnings are a list of three-element tuples containing
Both errors and warnings are a list of three element tuples containing
the file, line and the formatted error/warning.
## Options
@@ -107,9 +107,8 @@ defmodule Kernel.ParallelCompiler do
spawn_workers(files, :require, options)
end
# TODO: Remove on 2.0
# TODO: Deprecate on Elixir v1.8
@doc false
@deprecated "Use Kernel.ParallelCompiler.compile/2 instead"
def files(files, options \\ []) when is_list(options) do
case spawn_workers(files, :compile, options) do
{:ok, modules, _} -> modules
@@ -117,9 +116,8 @@ defmodule Kernel.ParallelCompiler do
end
end
# TODO: Remove on 2.0
# TODO: Deprecate on Elixir v1.8
@doc false
@deprecated "Use Kernel.ParallelCompiler.compile_to_path/2 instead"
def files_to_path(files, path, options \\ []) when is_binary(path) and is_list(options) do
case spawn_workers(files, {:compile, path}, options) do
{:ok, modules, _} -> modules
@@ -252,16 +250,14 @@ defmodule Kernel.ParallelCompiler do
when length(waiting) == length(queued) do
# The goal of this function is to find leaves in the dependency graph,
# i.e. to find code that depends on code that we know is not being defined.
without_definition =
for {pid, _, _, _} <- queued,
entry = waiting_on_without_definition(waiting, pid),
do: entry
# Note we only release modules because those can be rescued. A missing
# struct is a guaranteed compile error, so we never release it and treat
# it exclusively a missing entry/deadlock.
pending =
for {:module, _, ref, on, _} <- without_definition,
for {pid, _, _, _} <- queued,
entry = waiting_on_without_definition(waiting, pid),
{kind, _, ref, on, _} = entry,
kind == :module,
do: {on, {ref, :not_found}}
# Instead of releasing all files at once, we release them in groups
@@ -281,16 +277,8 @@ defmodule Kernel.ParallelCompiler do
spawn_workers(refs, waiting, queued, result, warnings, state)
[] ->
# There is a deadlock. Instead of printing a deadlock, let's release
# structs, as a missing struct error is clearer than a deadlock one.
structs = for {:struct, _, ref, _, _} <- without_definition, do: {ref, :not_found}
if structs != [] do
spawn_workers(structs, waiting, queued, result, warnings, state)
else
errors = handle_deadlock(waiting, queued)
{:error, errors, warnings}
end
errors = handle_deadlock(waiting, queued)
{:error, errors, warnings}
end
end
@@ -391,11 +379,7 @@ defmodule Kernel.ParallelCompiler do
discard_down(child_pid)
print_error(file, kind, reason, stack)
cancel_waiting_timer(queued, child_pid)
queued
|> List.keydelete(child_pid, 0)
|> terminate()
terminate(queued)
{:error, [to_error(file, kind, reason, stack)], warnings}
{:DOWN, ref, :process, _pid, reason} ->
@@ -418,13 +402,9 @@ defmodule Kernel.ParallelCompiler do
defp handle_down(queued, ref, reason) do
case List.keyfind(queued, ref, 1) do
{child_pid, ^ref, file, _timer_ref} ->
{_child, ^ref, file, _timer_ref} ->
print_error(file, :exit, reason, [])
queued
|> List.keydelete(child_pid, 0)
|> terminate()
terminate(queued)
{:error, [to_error(file, :exit, reason, [])]}
_ ->
@@ -470,9 +450,9 @@ defmodule Kernel.ParallelCompiler do
end
defp terminate(queued) do
for {pid, _, _, _} <- queued, do: Process.exit(pid, :kill)
for {pid, _, _, _} <- queued, do: discard_down(pid)
:ok
for {pid, _, _, _} <- queued do
Process.exit(pid, :kill)
end
end
defp print_error(file, kind, reason, stack) do
+1 -2
View File
@@ -1,8 +1,7 @@
defmodule Kernel.ParallelRequire do
# TODO: Remove on 2.0
# TODO: Deprecate on Elixir v1.8
@moduledoc false
@deprecated "Use Kernel.ParallelCompiler.require/2 instead"
def files(files, callbacks \\ [])
def files(files, callback) when is_function(callback, 1) do
+50 -149
View File
@@ -4,7 +4,7 @@ defmodule Kernel.SpecialForms do
cannot be overridden by the developer.
We define them in this module. Some of these forms are lexical (like
`alias/2`, `case/2`, etc.). The macros `{}/1` and `<<>>/1` are also special
`alias/2`, `case/2`, etc). The macros `{}/1` and `<<>>/1` are also special
forms used to define tuple and binary data structures respectively.
This module also documents macros that return information about Elixir's
@@ -239,24 +239,6 @@ defmodule Kernel.SpecialForms do
iex> {name, species}
{"Frank", "Walrus"}
The size can be a variable:
iex> name_size = 5
iex> <<name::binary-size(name_size), " the ", species::binary>> = <<"Frank the Walrus">>
iex> {name, species}
{"Frank", "Walrus"}
And the variable can be defined in the match itself (prior to its use):
iex> <<name_size::size(8), name::binary-size(name_size), " the ", species::binary>> = <<5, "Frank the Walrus">>
iex> {name, species}
{"Frank", "Walrus"}
However, the size cannot be defined in the match outside the binary/bitstring match:
{name_size, <<name::binary-size(name_size), _rest::binary>>} = {5, <<"Frank the Walrus">>}
** (CompileError): undefined variable "name_size" in bitstring segment
Failing to specify the size for the non-last causes compilation to fail:
<<name::binary, " the ", species::binary>> = <<"Frank the Walrus">>
@@ -391,7 +373,7 @@ defmodule Kernel.SpecialForms do
## Syntax
The right side of `.` may be a word starting with an uppercase letter, which represents
The right side of `.` may be a word starting in upcase, which represents
an alias, a word starting with lowercase or underscore, any valid language
operator or any name wrapped in single- or double-quotes. Those are all valid
examples:
@@ -408,7 +390,7 @@ defmodule Kernel.SpecialForms do
iex> Kernel."+"(1, 2)
3
Wrapping the function name in single- or double-quotes is always a
Note that wrapping the function name in single- or double-quotes is always a
remote call. Therefore `Kernel."Foo"` will attempt to call the function "Foo"
and not return the alias `Kernel.Foo`. This is done by design as module names
are more strict than function names.
@@ -506,7 +488,7 @@ defmodule Kernel.SpecialForms do
Keyword.values #=> uses MyKeyword.values
Elixir.Keyword.values #=> uses Keyword.values
Notice that calling `alias` without the `:as` option automatically
Notice that calling `alias` without the `as:` option automatically
sets an alias based on the last part of the module. For example:
alias Foo.Bar.Baz
@@ -566,7 +548,7 @@ defmodule Kernel.SpecialForms do
## Alias shortcut
`require/2` also accepts `:as` as an option so it automatically sets
`require/2` also accepts `as:` as an option so it automatically sets
up an alias. Please check `alias/2` for more information.
"""
@@ -705,13 +687,10 @@ defmodule Kernel.SpecialForms do
defmacro __CALLER__, do: error!([])
@doc """
Returns the stacktrace for the currently handled exception.
Returns the stacktrace for the curently handled exception.
It is available only in the `catch` and `rescue` clauses of `try/1`
expressions.
To retrieve the stacktrace of the current process, use
`Process.info(self(), :current_stacktrace)` instead.
"""
defmacro __STACKTRACE__, do: error!([])
@@ -783,7 +762,7 @@ defmodule Kernel.SpecialForms do
...> end
{:sum, [], [1, 2, 3]}
## Elixir's AST (Abstract Syntax Tree)
## Explanation
Any Elixir code can be represented using Elixir data structures.
The building block of Elixir macros is a tuple with three elements,
@@ -803,35 +782,10 @@ defmodule Kernel.SpecialForms do
function call. The third argument may be an atom, which is
usually a variable (or a local call).
Besides the tuple described above, Elixir has a few literals that
are also part of its AST. Those literals return themselves when
quoted. They are:
:sum #=> Atoms
1 #=> Integers
2.0 #=> Floats
[1, 2] #=> Lists
"strings" #=> Strings
{key, value} #=> Tuples with two elements
Any other value, such as a map or a four-element tuple, must be escaped
(`Macro.escape/1`) before being introduced into an AST.
## Options
* `:unquote` - when `false`, disables unquoting. This means any `unquote`
call will be kept as is in the AST, instead of replaced by the `unquote`
arguments. For example:
iex> quote do
...> unquote("hello")
...> end
"hello"
iex> quote unquote: false do
...> unquote("hello")
...> end
{:unquote, [], ["hello"]}
* `: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
quote. Read the Stacktrace information section below for more
@@ -848,10 +802,22 @@ defmodule Kernel.SpecialForms do
* `:bind_quoted` - passes a binding to the macro. Whenever a binding is
given, `unquote/1` is automatically disabled.
## Quote literals
Besides the tuple described above, Elixir has a few literals that
when quoted return themselves. They are:
:sum #=> Atoms
1 #=> Integers
2.0 #=> Floats
[1, 2] #=> Lists
"strings" #=> Strings
{key, value} #=> Tuples with two elements
## Quote and macros
`quote/2` is commonly used with macros for code generation. As an exercise,
let's define a macro that multiplies a number by itself (squared). In practice,
let's define a macro that multiplies a number by itself (squared). Note
there is no reason to define such as a macro (and it would actually be
seen as a bad practice), but it is simple enough that it allows us to focus
on the important aspects of quotes and macros:
@@ -990,8 +956,8 @@ defmodule Kernel.SpecialForms do
NoHygiene.interference
a #=> 1
You cannot even access variables defined in the same module unless
you explicitly give it a context:
Note that you cannot even access variables defined in the same
module unless you explicitly give it a context:
defmodule Hygiene do
defmacro write do
@@ -1189,7 +1155,7 @@ defmodule Kernel.SpecialForms do
When using `location: :keep` and invalid arguments are given to
`Sample.add/2`, the stacktrace information will point to the file
and line inside the quote. Without `location: :keep`, the error is
reported to where `defadd` was invoked. `location: :keep` affects
reported to where `defadd` was invoked. Note `location: :keep` affects
only definitions inside the quote.
## Binding and unquote fragments
@@ -1268,61 +1234,37 @@ defmodule Kernel.SpecialForms do
defmacro quote(opts, block), do: error!([opts, block])
@doc """
Unquotes the given expression inside a quoted expression.
This function expects a valid Elixir AST, also known as
quoted expression, as argument. If you would like to `unquote`
any value, such as a map or a four-element tuple, you should
call `Macro.escape/1` before unquoting.
Unquotes the given expression from inside a macro.
## Examples
Imagine the situation you have a quoted expression and
Imagine the situation you have a variable `value` and
you want to inject it inside some quote. The first attempt
would be:
value =
quote do
13
end
value = 13
quote do
sum(1, value, 3)
end
Which would then return:
{:sum, [], [1, {:value, [], Elixir}, 3]}
{:sum, [], [1, {:value, [], quoted}, 3]}
Which is not the expected result. For this, we use `unquote`:
Which is not the expected result. For this, we use unquote:
iex> value =
...> quote do
...> 13
...> end
iex> value = 13
iex> quote do
...> sum(1, unquote(value), 3)
...> end
{:sum, [], [1, 13, 3]}
If you want to unquote a value that is not a quoted expression,
such as a map, you need to call `Macro.escape/1` before:
iex> value = %{foo: :bar}
iex> quote do
...> process_map(unquote(Macro.escape(value)))
...> end
{:process_map, [], [{:%{}, [], [foo: :bar]}]}
If you forget to escape it, Elixir will raise an error
when compiling the code.
"""
defmacro unquote(:unquote)(expr), do: error!([expr])
@doc """
Unquotes the given list expanding its arguments.
Similar to `unquote/1`.
Unquotes the given list expanding its arguments. Similar
to `unquote/1`.
## Examples
@@ -1361,7 +1303,7 @@ defmodule Kernel.SpecialForms do
iex> for n <- [1, 2, 3, 4, 5, 6], rem(n, 2) == 0, do: n
[2, 4, 6]
Generators can also be used to filter as it removes any value
Note generators can also be used to filter as it removes any value
that doesn't match the pattern on the left side of `<-`:
iex> users = [user: "john", admin: "meg", guest: "barbara"]
@@ -1381,7 +1323,7 @@ defmodule Kernel.SpecialForms do
filters or inside the block, are not reflected outside of the
comprehension.
## The `:into` and `:uniq` options
## Into
In the examples above, the result returned by the comprehension was
always a list. The returned result can be configured by passing an
@@ -1401,57 +1343,18 @@ defmodule Kernel.SpecialForms do
String.upcase(line)
end
Similarly, `uniq: true` can also be given to comprehensions to guarantee
the results are only added to the collection if they were not returned
## Uniq
`uniq: true` can also be given to comprehensions to guarantee that
that results are only added to the collection if they were not returned
before. For example:
iex> for x <- [1, 1, 2, 3], uniq: true, do: x * 2
iex> for(x <- [1, 1, 2, 3], uniq: true, do: x * 2)
[2, 4, 6]
iex> for <<x <- "abcabc">>, uniq: true, into: "", do: <<x - 32>>
iex> for(<<x <- "abcabc">>, uniq: true, into: "", do: <<x - 32>>)
"ABC"
## The `:reduce` option
While the `:into` option allows us to customize the comprehension behaviour
to a given data type, such as putting all of the values inside a map or inside
a binary, it is not always enough.
For example, imagine that you have a binary with letters where you want to
count how many times each lowercase letter happens, ignoring all uppercase
ones. For instance, for the string `"AbCabCABc"`, we want to return the map
`%{"a" => 1, "b" => 2, "c" => 1}`.
If we were to use `:into`, we would need a data type that computes the
frequency of each element it holds. While there is no such data type in
Elixir, you could implement one yourself.
A simpler option would be to use comprehensions for the mapping and
filtering of letters, and then we invoke `Enum.reduce/3` to build a map,
for example:
iex> letters = for <<x <- "AbCabCABc">>, x in ?a..?z, do: <<x>>
iex> Enum.reduce(letters, %{}, fn x, acc -> Map.update(acc, x, 1, & &1 + 1) end)
%{"a" => 1, "b" => 2, "c" => 1}
While the above is straight-forward, it has the downside of traversing the
data at least twice. If you are expecting long strings as inputs, this can
be quite expensive.
Luckily, comprehensions also support the `:reduce` option, which would allow
us to fuse both steps above into a single step:
iex> for <<x <- "AbCabCABc">>, x in ?a..?z, reduce: %{} do
...> acc -> Map.update(acc, <<x>>, 1, & &1 + 1)
...> end
%{"a" => 1, "b" => 2, "c" => 1}
When the `:reduce` key is given, its value is used as the initial accumulator
and the `do` block must be changed to use `->` clauses, where the left side
of `->` receives the accumulated value of the previous iteration and the
expression on the right side must return the new accumulator value. Once there are no more
elements, the final accumulated value is returned. If there are no elements
at all, then the initial accumulator value is returned.
"""
defmacro for(args), do: error!([args])
@@ -1485,9 +1388,8 @@ defmodule Kernel.SpecialForms do
...> end
{:ok, "admin"}
As in `for/1`, variables bound inside `with/1` won't leak.
Expressions without `<-` may also be used in clauses. For instance,
you can perform regular matches with the `=` operator:
As in `for/1`, variables bound inside `with/1` won't leak;
"bare expressions" may also be inserted between the clauses:
iex> width = nil
iex> opts = %{width: 10, height: 15}
@@ -1500,9 +1402,8 @@ defmodule Kernel.SpecialForms do
iex> width
nil
The behaviour of any expression in a clause is the same as outside.
For example, `=` will raise a `MatchError` instead of returning the
non-matched value:
Note that if a "bare expression" fails to match, it will raise a `MatchError`
instead of returning the non-matched value:
with :foo = :bar, do: :ok
#=> ** (MatchError) no match of right hand side value: :bar
@@ -1534,8 +1435,7 @@ defmodule Kernel.SpecialForms do
...> end
{:error, :wrong_data}
If an `else` block is used and there are no matching clauses, a `WithClauseError`
exception is raised.
If there is no matching `else` condition, then a `WithClauseError` exception is raised.
"""
defmacro with(args), do: error!([args])
@@ -1824,9 +1724,10 @@ defmodule Kernel.SpecialForms do
the expression. `catch`, `rescue`, and `else` clauses work based on
pattern matching (similar to the `case` special form).
Calls inside `try/1` are not tail recursive since the VM needs to keep
the stacktrace in case an exception happens. To retrieve the stacktrace,
access `__STACKTRACE__/0` inside the `rescue` or `catch` clause.
Note that calls inside `try/1` are not tail recursive since the VM
needs to keep the stacktrace in case an exception happens. To
retrieve the stacktrace, access `__STACKTRACE__/0` inside the `rescue`
or `catch` clause.
## `rescue` clauses
+227 -434
View File
@@ -197,10 +197,10 @@ defmodule Kernel.Typespec do
defp spec_to_signature(other), do: type_to_signature(other)
defp type_to_signature({:::, _, [{name, _, context}, _]})
when is_atom(name) and name != ::: and is_atom(context),
when is_atom(name) and is_atom(context),
do: {name, 0}
defp type_to_signature({:::, _, [{name, _, args}, _]}) when is_atom(name) and name != :::,
defp type_to_signature({:::, _, [{name, _, args}, _]}) when is_atom(name),
do: {name, length(args)}
defp type_to_signature(_), do: :error
@@ -209,71 +209,17 @@ defmodule Kernel.Typespec do
@doc false
def translate_typespecs_for_module(_set, bag) do
type_typespecs = take_typespecs(bag, [:type, :opaque, :typep])
defined_type_pairs = collect_defined_type_pairs(type_typespecs)
state = %{
defined_type_pairs: defined_type_pairs,
used_type_pairs: [],
local_vars: %{},
undefined_type_error_enabled?: true
}
{types, state} = :lists.mapfoldl(&translate_type/2, state, type_typespecs)
{specs, state} = :lists.mapfoldl(&translate_spec/2, state, take_typespecs(bag, :spec))
{callbacks, state} = :lists.mapfoldl(&translate_spec/2, state, take_typespecs(bag, :callback))
{macrocallbacks, state} =
:lists.mapfoldl(&translate_spec/2, state, take_typespecs(bag, :macrocallback))
optional_callbacks = :lists.flatten(get_typespecs(bag, :optional_callbacks))
used_types = filter_used_types(types, state)
{used_types, specs, callbacks, macrocallbacks, optional_callbacks}
types = Enum.map(take_typespecs(bag, [:type, :opaque, :typep]), &translate_type/1)
specs = Enum.map(take_typespecs(bag, :spec), &translate_spec/1)
callbacks = Enum.map(take_typespecs(bag, :callback), &translate_spec/1)
macrocallbacks = Enum.map(take_typespecs(bag, :macrocallback), &translate_spec/1)
optional_callbacks = List.flatten(get_typespecs(bag, :optional_callbacks))
{types, specs, callbacks, macrocallbacks, optional_callbacks}
end
defp collect_defined_type_pairs(type_typespecs) do
fun = fn {_kind, expr, pos}, type_pairs ->
%{file: file, line: line} = env = :elixir_locals.get_cached_env(pos)
case type_to_signature(expr) do
{name, arity} = type_pair ->
if built_in_type?(name, arity) do
message = "type #{name}/#{arity} is a built-in type and it cannot be redefined"
compile_error(env, message)
end
if Map.has_key?(type_pairs, type_pair) do
compile_error(env, "type #{name}/#{arity} is already defined")
end
Map.put(type_pairs, type_pair, {file, line})
:error ->
compile_error(env, "invalid type specification: #{Macro.to_string(expr)}")
end
end
:lists.foldl(fun, %{}, type_typespecs)
end
defp filter_used_types(types, state) do
fun = fn {_kind, {name, arity} = type_pair, _line, _type, export} ->
if not export and not :lists.member(type_pair, state.used_type_pairs) do
%{^type_pair => {file, line}} = state.defined_type_pairs
:elixir_errors.warn(line, file, "type #{name}/#{arity} is unused")
false
else
true
end
end
:lists.filter(fun, types)
end
defp translate_type({kind, {:::, _, [{name, _, args}, definition]}, pos}, state) do
defp translate_type({kind, {:::, _, [{name, _, args}, definition]}, pos})
when is_atom(name) and name != ::: do
caller = :elixir_locals.get_cached_env(pos)
state = clean_local_state(state)
args =
if is_atom(args) do
@@ -282,15 +228,12 @@ defmodule Kernel.Typespec do
for(arg <- args, do: variable(arg))
end
vars = :lists.filter(&match?({:var, _, _}, &1), args)
var_names = :lists.map(&elem(&1, 2), vars)
state = :lists.foldl(&update_local_vars(&2, &1), state, var_names)
{spec, state} = typespec(definition, var_names, caller, state)
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(args)
ensure_no_unused_local_vars!(caller, state.local_vars)
{kind, export} =
case kind do
:type -> {:type, true}
@@ -298,10 +241,14 @@ defmodule Kernel.Typespec do
:opaque -> {:opaque, true}
end
invalid_args = :lists.filter(&(not valid_variable_ast?(&1)), args)
if builtin_type?(name, arity) do
compile_error(caller, "type #{name}/#{arity} is a builtin type and it cannot be redefined")
end
invalid_args = Enum.reject(args, &valid_variable_ast?/1)
unless invalid_args == [] do
invalid_args = :lists.join(", ", :lists.map(&Macro.to_string/1, invalid_args))
invalid_args = invalid_args |> Enum.map(&Macro.to_string/1) |> Enum.join(", ")
message =
"@type definitions expect all arguments to be variables. The type " <>
@@ -310,91 +257,83 @@ defmodule Kernel.Typespec do
compile_error(caller, message)
end
if underspecified?(kind, arity, spec) do
message = "@#{kind} type #{name}/#{arity} is underspecified and therefore meaningless"
:elixir_errors.warn(caller.line, caller.file, message)
end
{{kind, {name, arity}, caller.line, type, export}, state}
{kind, {name, arity}, caller.line, type, export}
end
defp valid_variable_ast?({variable_name, _, context})
when is_atom(variable_name) and is_atom(context),
defp translate_type({_kind, other, pos}) do
caller = :elixir_locals.get_cached_env(pos)
type_spec = Macro.to_string(other)
compile_error(caller, "invalid type specification: #{type_spec}")
end
defp valid_variable_ast?({variable_name, _, atom})
when is_atom(variable_name) and is_atom(atom),
do: true
defp valid_variable_ast?(_), do: false
defp underspecified?(:opaque, 0, {:type, _, type, []}) when type in [:any, :term], do: true
defp underspecified?(_kind, _arity, _spec), do: false
defp translate_spec({kind, {:when, _meta, [spec, guard]}, pos}, state) do
defp translate_spec({kind, {:when, _meta, [spec, guard]}, pos}) do
caller = :elixir_locals.get_cached_env(pos)
translate_spec(kind, spec, guard, caller, state)
translate_spec(kind, spec, guard, caller)
end
defp translate_spec({kind, spec, pos}, state) do
defp translate_spec({kind, spec, pos}) do
caller = :elixir_locals.get_cached_env(pos)
translate_spec(kind, spec, [], caller, state)
translate_spec(kind, spec, [], caller)
end
defp translate_spec(kind, {:::, meta, [{name, _, args}, return]}, guard, caller, state)
defp translate_spec(kind, {:::, meta, [{name, _, args}, return]}, guard, caller)
when is_atom(name) and name != ::: do
translate_spec(kind, meta, name, args, return, guard, caller, state)
translate_spec(kind, meta, name, args, return, guard, caller)
end
defp translate_spec(_kind, {name, _meta, _args} = spec, _guard, caller, _state)
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, _state) do
defp translate_spec(_kind, spec, _guard, caller) do
spec = Macro.to_string(spec)
compile_error(caller, "invalid type specification: #{spec}")
end
defp translate_spec(kind, meta, name, args, return, guard, caller, state) when is_atom(args),
do: translate_spec(kind, meta, name, [], return, guard, caller, state)
defp translate_spec(kind, meta, name, args, return, guard, caller) when is_atom(args),
do: translate_spec(kind, meta, name, [], return, guard, caller)
defp translate_spec(kind, meta, name, args, return, guard, caller, state) do
defp translate_spec(kind, meta, name, args, return, guard, caller) do
ensure_no_defaults!(args)
state = clean_local_state(state)
unless Keyword.keyword?(guard) do
error = "expected keywords as guard in type specification, got: #{Macro.to_string(guard)}"
compile_error(caller, error)
end
line = line(meta)
vars = Keyword.keys(guard)
{fun_args, state} = fn_args(meta, args, return, vars, caller, state)
spec = {:type, line, :fun, fun_args}
spec = {:type, line(meta), :fun, fn_args(meta, args, return, vars, caller)}
{spec, state} =
case guard_to_constraints(guard, vars, meta, caller, state) do
{[], state} -> {spec, state}
{constraints, state} -> {{:type, line, :bounded_fun, [spec, constraints]}, state}
spec =
case guard_to_constraints(guard, vars, meta, caller) do
[] -> spec
constraints -> {:type, line(meta), :bounded_fun, [spec, constraints]}
end
ensure_no_unused_local_vars!(caller, state.local_vars)
arity = length(args)
{{kind, {name, arity}, caller.line, spec}, state}
{kind, {name, arity}, caller.line, spec}
end
# TODO: Remove char_list type by 2.0
defp built_in_type?(:char_list, 0), do: true
defp built_in_type?(:charlist, 0), do: true
defp built_in_type?(:as_boolean, 1), do: true
defp built_in_type?(:struct, 0), do: true
defp built_in_type?(:nonempty_charlist, 0), do: true
defp built_in_type?(:keyword, 0), do: true
defp built_in_type?(:keyword, 1), do: true
defp built_in_type?(:var, 0), do: true
defp built_in_type?(name, arity), do: :erl_internal.is_type(name, arity)
defp builtin_type?(:char_list, 0), do: true
defp builtin_type?(:charlist, 0), do: true
defp builtin_type?(:as_boolean, 1), do: true
defp builtin_type?(:struct, 0), do: true
defp builtin_type?(:nonempty_charlist, 0), do: true
defp builtin_type?(:keyword, 0), do: true
defp builtin_type?(:keyword, 1), do: true
defp builtin_type?(name, arity), do: :erl_internal.is_type(name, arity)
defp ensure_no_defaults!(args) do
fun = fn
Enum.each(args, fn
{:::, _, [left, right]} ->
ensure_not_default(left)
ensure_not_default(right)
@@ -403,9 +342,7 @@ defmodule Kernel.Typespec do
other ->
ensure_not_default(other)
other
end
:lists.foreach(fun, args)
end)
end
defp ensure_not_default({:\\, _, [_, _]}) do
@@ -414,22 +351,21 @@ defmodule Kernel.Typespec do
defp ensure_not_default(_), do: :ok
defp guard_to_constraints(guard, vars, meta, caller, state) do
defp guard_to_constraints(guard, vars, meta, caller) do
line = line(meta)
fun = fn
{_name, {:var, _, context}}, {constraints, state} when is_atom(context) ->
{constraints, state}
Enum.flat_map(guard, fn
{_name, {:var, _, context}} when is_atom(context) ->
[]
{name, type}, {constraints, state} ->
{spec, state} = typespec(type, vars, caller, state)
constraint = [{:atom, line, :is_subtype}, [{:var, line, name}, spec]]
state = update_local_vars(state, name)
{[{:type, line, :constraint, constraint} | constraints], state}
end
{name, type} ->
constraint = [
{:atom, line, :is_subtype},
[{:var, line, name}, typespec(type, vars, caller)]
]
{constraints, state} = :lists.foldl(fun, {[], state}, guard)
{:lists.reverse(constraints), state}
[{:type, line, :constraint, constraint}]
end)
end
## To typespec conversion
@@ -439,33 +375,29 @@ defmodule Kernel.Typespec do
end
# Handle unions
defp typespec({:|, meta, [_, _]} = exprs, vars, caller, state) do
defp typespec({:|, meta, [_, _]} = exprs, vars, caller) do
exprs = collect_union(exprs)
{union, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, exprs)
{{:type, line(meta), :union, union}, state}
union = for e <- exprs, do: typespec(e, vars, caller)
{:type, line(meta), :union, union}
end
# Handle binaries
defp typespec({:<<>>, meta, []}, _, _, state) do
line = line(meta)
{{:type, line, :binary, [{:integer, line, 0}, {:integer, line, 0}]}, state}
defp typespec({:<<>>, meta, []}, _, _) do
{:type, line(meta), :binary, [{:integer, line(meta), 0}, {:integer, line(meta), 0}]}
end
defp typespec(
{:<<>>, meta, [{:::, unit_meta, [{:_, _, ctx1}, {:*, _, [{:_, _, ctx2}, unit]}]}]},
_,
_,
state
_
)
when is_atom(ctx1) and is_atom(ctx2) and is_integer(unit) and unit >= 0 do
line = line(meta)
{{:type, line, :binary, [{:integer, line, 0}, {:integer, line(unit_meta), unit}]}, state}
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}]}
end
defp typespec({:<<>>, meta, [{:::, size_meta, [{:_, _, ctx}, size]}]}, _, _, state)
when is_atom(ctx) and is_integer(size) and size >= 0 do
line = line(meta)
{{:type, line, :binary, [{:integer, line(size_meta), size}, {:integer, line, 0}]}, state}
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}]}
end
defp typespec(
@@ -478,230 +410,160 @@ defmodule Kernel.Typespec do
]
},
_,
_,
state
_
)
when is_atom(ctx1) and is_atom(ctx2) and is_atom(ctx3) and is_integer(size) and
is_integer(unit) and size >= 0 and unit >= 0 do
is_integer(unit) do
args = [{:integer, line(size_meta), size}, {:integer, line(unit_meta), unit}]
{{:type, line(meta), :binary, args}, state}
end
defp typespec({:<<>>, _meta, _args}, _vars, caller, _state) do
message =
"invalid binary specification, expected <<_::size>>, <<_::_*unit>>, " <>
"or <<_::size, _::_*unit>> with size and unit being non-negative integers"
compile_error(caller, message)
{:type, line(meta), :binary, args}
end
## Handle maps and structs
defp typespec({:map, meta, args}, _vars, _caller, state) when args == [] or is_atom(args) do
{{:type, line(meta), :map, :any}, state}
defp typespec({:map, meta, args}, _vars, _caller) when args == [] or is_atom(args) do
{:type, line(meta), :map, :any}
end
defp typespec({:%{}, meta, fields} = map, vars, caller, state) do
fun = fn
{k, v}, state when is_atom(k) ->
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta), :map_field_exact, [arg1, arg2]}, state}
defp typespec({:%{}, meta, fields} = map, vars, caller) do
fields =
Enum.map(fields, fn
{k, v} when is_atom(k) ->
args = [typespec(k, vars, caller), typespec(v, vars, caller)]
{:type, line(meta), :map_field_exact, args}
{{:required, meta2, [k]}, v}, state ->
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta2), :map_field_exact, [arg1, arg2]}, state}
{{:required, meta2, [k]}, v} ->
args = [typespec(k, vars, caller), typespec(v, vars, caller)]
{:type, line(meta2), :map_field_exact, args}
{{:optional, meta2, [k]}, v}, state ->
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta2), :map_field_assoc, [arg1, arg2]}, state}
{{:optional, meta2, [k]}, v} ->
args = [typespec(k, vars, caller), typespec(v, vars, caller)]
{:type, line(meta2), :map_field_assoc, args}
{k, v}, state ->
# TODO: Warn on Elixir v1.8 (since v1.6 is the first version to drop support for 18 and
# older)
# warning =
# "invalid map specification. %{foo => bar} is deprecated in favor of " <>
# "%{required(foo) => bar} and %{optional(foo) => bar}."
# :elixir_errors.warn(caller.line, caller.file, warning)
{arg1, state} = typespec(k, vars, caller, state)
{arg2, state} = typespec(v, vars, caller, state)
{{:type, line(meta), :map_field_assoc, [arg1, arg2]}, state}
{k, v} ->
# TODO: Warn on Elixir v1.8 (since v1.6 is the first version to drop support for 18 and
# older)
# warning =
# "invalid map specification. %{foo => bar} is deprecated in favor of " <>
# "%{required(foo) => bar} and %{optional(foo) => bar}."
# :elixir_errors.warn(caller.line, caller.file, warning)
args = [typespec(k, vars, caller), typespec(v, vars, caller)]
{:type, line(meta), :map_field_assoc, args}
{:|, _, [_, _]}, _state ->
error =
"invalid map specification. When using the | operator in the map key, " <>
"make sure to wrap the key type in parentheses: #{Macro.to_string(map)}"
{:|, _, [_, _]} ->
error =
"invalid map specification. When using the | operator in the map key, " <>
"make sure to wrap the key type in parentheses: #{Macro.to_string(map)}"
compile_error(caller, error)
compile_error(caller, error)
_, _state ->
compile_error(caller, "invalid map specification: #{Macro.to_string(map)}")
end
_ ->
compile_error(caller, "invalid map specification: #{Macro.to_string(map)}")
end)
{fields, state} = :lists.mapfoldl(fun, state, fields)
{{:type, line(meta), :map, fields}, state}
{:type, line(meta), :map, fields}
end
defp typespec({:%, _, [name, {:%{}, meta, fields}]}, vars, caller, state) do
defp typespec({:%, _, [name, {:%{}, meta, fields}]}, vars, caller) do
# We cannot set a function name to avoid tracking
# as a compile time dependency, because for structs it actually is one.
module = Macro.expand(name, caller)
struct =
module
|> Macro.struct!(caller)
|> Map.delete(:__struct__)
|> Map.to_list()
if module == caller.module do
Module.get_attribute(module, :struct) ||
compile_error(caller, "struct is not defined for #{Macro.to_string(name)}")
else
module.__struct__
end
struct = struct |> Map.from_struct() |> Map.to_list()
unless Keyword.keyword?(fields) do
compile_error(caller, "expected key-value pairs in struct #{Macro.to_string(name)}")
end
types =
:lists.map(
fn {field, _} -> {field, Keyword.get(fields, field, quote(do: term()))} end,
struct
)
Enum.map(struct, fn {field, _} ->
{field, Keyword.get(fields, field, quote(do: term()))}
end)
fun = fn {field, _} ->
Enum.each(fields, fn {field, _} ->
unless Keyword.has_key?(struct, field) do
compile_error(
caller,
"undefined field #{inspect(field)} on struct #{Macro.to_string(name)}"
)
compile_error(caller, "undefined field #{field} on struct #{Macro.to_string(name)}")
end
end
end)
:lists.foreach(fun, fields)
typespec({:%{}, meta, [__struct__: module] ++ types}, vars, caller, state)
typespec({:%{}, meta, [__struct__: module] ++ types}, vars, caller)
end
# Handle records
defp typespec({:record, meta, [atom]}, vars, caller, state) do
typespec({:record, meta, [atom, []]}, vars, caller, state)
defp typespec({:record, meta, [atom]}, vars, caller) do
typespec({:record, meta, [atom, []]}, vars, caller)
end
defp typespec({:record, meta, [tag, field_specs]}, vars, caller, state)
when is_atom(tag) and is_list(field_specs) do
defp typespec({:record, meta, [tag, field_specs]}, vars, caller) do
# We cannot set a function name to avoid tracking
# as a compile time dependency because for records it actually is one.
case Macro.expand({tag, [], [{:{}, [], []}]}, caller) do
{_, _, [name, fields | _]} when is_list(fields) ->
types =
:lists.map(
fn {field, _} -> Keyword.get(field_specs, field, quote(do: term())) end,
fields
)
Enum.map(fields, fn {field, _} ->
Keyword.get(field_specs, field, quote(do: term()))
end)
fun = fn {field, _} ->
Enum.each(field_specs, fn {field, _} ->
unless Keyword.has_key?(fields, field) do
compile_error(caller, "undefined field #{field} on record #{inspect(tag)}")
end
end
end)
:lists.foreach(fun, field_specs)
typespec({:{}, meta, [name | types]}, vars, caller, state)
typespec({:{}, meta, [name | types]}, vars, caller)
_ ->
compile_error(caller, "unknown record #{inspect(tag)}")
end
end
defp typespec({:record, _meta, [_tag, _field_specs]}, _vars, caller, _state) do
message = "invalid record specification, expected the record name to be an atom literal"
compile_error(caller, message)
end
# Handle ranges
defp typespec({:.., meta, [left, right]}, vars, caller, state) do
{left, state} = typespec(left, vars, caller, state)
{right, state} = typespec(right, vars, caller, state)
:ok = validate_range(left, right, caller)
{{:type, line(meta), :range, [left, right]}, state}
defp typespec({:.., meta, args}, vars, caller) do
args = for arg <- args, do: typespec(arg, vars, caller)
{:type, line(meta), :range, args}
end
# Handle special forms
defp typespec({:__MODULE__, _, atom}, vars, caller, state) when is_atom(atom) do
typespec(caller.module, vars, caller, state)
defp typespec({:__MODULE__, _, atom}, vars, caller) when is_atom(atom) do
typespec(caller.module, vars, caller)
end
defp typespec({:__aliases__, _, _} = alias, vars, caller, state) do
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}})
typespec(atom, vars, caller, state)
typespec(atom, vars, caller)
end
# Handle funs
defp typespec([{:->, meta, [args, return]}], vars, caller, state)
when is_list(args) do
{args, state} = fn_args(meta, args, return, vars, caller, state)
{{:type, line(meta), :fun, args}, state}
defp typespec([{:->, meta, [arguments, return]}], vars, caller) when is_list(arguments) do
args = fn_args(meta, arguments, return, vars, caller)
{:type, line(meta), :fun, args}
end
# Handle type operator
defp typespec(
{:::, meta, [{var_name, var_meta, context}, expr]} = ann_type,
vars,
caller,
state
)
when is_atom(var_name) and is_atom(context) do
case typespec(expr, vars, caller, state) do
{{:ann_type, _, _}, _state} ->
message =
"invalid type annotation. Type annotations cannot be nested: " <>
"#{Macro.to_string(ann_type)}"
# TODO: make this an error in elixir 2.0 and remove the code below
:elixir_errors.warn(caller.line, caller.file, message)
# This may be generating an invalid typespec but we need to generate it
# to avoid breaking existing code that was valid but only broke dialyzer
{right, state} = typespec(expr, vars, caller, state)
{{:ann_type, line(meta), [{:var, line(var_meta), var_name}, right]}, state}
{right, state} ->
{{:ann_type, line(meta), [{:var, line(var_meta), var_name}, right]}, state}
end
end
defp typespec({:::, meta, [left, right]} = expr, vars, caller, state) do
message =
"invalid type annotation. When using the | operator to represent the union of types, " <>
"make sure to wrap type annotations in parentheses: #{Macro.to_string(expr)}"
# TODO: make this an error in Elixir 2.0, and remove the code below and the
# :undefined_type_error_enabled? key from the state
:elixir_errors.warn(caller.line, caller.file, message)
# This may be generating an invalid typespec but we need to generate it
# to avoid breaking existing code that was valid but only broke dialyzer
state = %{state | undefined_type_error_enabled?: false}
{left, state} = typespec(left, vars, caller, state)
state = %{state | undefined_type_error_enabled?: true}
{right, state} = typespec(right, vars, caller, state)
{{:ann_type, line(meta), [left, right]}, state}
defp typespec({:::, meta, [var, expr]}, vars, caller) do
left = typespec(var, [elem(var, 0) | vars], caller)
right = typespec(expr, vars, caller)
{:ann_type, line(meta), [left, right]}
end
# Handle unary ops
defp typespec({op, meta, [integer]}, _, _, state) when op in [:+, :-] and is_integer(integer) do
line = line(meta)
{{:op, line, op, {:integer, line, integer}}, state}
defp typespec({op, meta, [integer]}, _, _) when op in [:+, :-] and is_integer(integer) do
{:op, line(meta), op, {:integer, line(meta), integer}}
end
# Handle remote calls in the form of @module_attribute.type.
# These are not handled by the general remote type clause as calling
# Macro.expand/2 on the remote does not expand module attributes (but expands
# things like __MODULE__).
defp typespec(
{{:., meta, [{:@, _, [{attr, _, _}]}, name]}, _, args} = orig,
vars,
caller,
state
) do
defp typespec({{:., meta, [{:@, _, [{attr, _, _}]}, name]}, _, args} = orig, vars, caller) do
remote = Module.get_attribute(caller.module, attr)
unless is_atom(remote) and remote != nil do
@@ -711,14 +573,12 @@ defmodule Kernel.Typespec do
compile_error(caller, message)
end
{remote_spec, state} = typespec(remote, vars, caller, state)
{name_spec, state} = typespec(name, vars, caller, state)
type = {remote_spec, meta, name_spec, args}
remote_type(type, vars, caller, state)
type = {typespec(remote, vars, caller), meta, typespec(name, vars, caller), args}
remote_type(type, vars, caller)
end
# Handle remote calls
defp typespec({{:., meta, [remote, name]}, _, args} = orig, vars, caller, state) do
defp typespec({{:., meta, [remote, name]}, _, args} = orig, vars, caller) do
# We set a function name to avoid tracking
# aliases in typespecs as compile time dependencies.
remote = Macro.expand(remote, %{caller | function: {:typespec, 0}})
@@ -727,43 +587,40 @@ defmodule Kernel.Typespec do
compile_error(caller, "invalid remote in typespec: #{Macro.to_string(orig)}")
end
{remote_spec, state} = typespec(remote, vars, caller, state)
{name_spec, state} = typespec(name, vars, caller, state)
type = {remote_spec, meta, name_spec, args}
remote_type(type, vars, caller, state)
type = {typespec(remote, vars, caller), meta, typespec(name, vars, caller), args}
remote_type(type, vars, caller)
end
# Handle tuples
defp typespec({:tuple, meta, []}, _vars, _caller, state) do
{{:type, line(meta), :tuple, :any}, state}
defp typespec({:tuple, meta, []}, _vars, _caller) do
{:type, line(meta), :tuple, :any}
end
defp typespec({:{}, meta, t}, vars, caller, state) when is_list(t) do
{args, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, t)
{{:type, line(meta), :tuple, args}, state}
defp typespec({:{}, meta, t}, vars, caller) when is_list(t) do
args = for e <- t, do: typespec(e, vars, caller)
{:type, line(meta), :tuple, args}
end
defp typespec({left, right}, vars, caller, state) do
typespec({:{}, [], [left, right]}, vars, caller, state)
defp typespec({left, right}, vars, caller) do
typespec({:{}, [], [left, right]}, vars, caller)
end
# Handle blocks
defp typespec({:__block__, _meta, [arg]}, vars, caller, state) do
typespec(arg, vars, caller, state)
defp typespec({:__block__, _meta, [arg]}, vars, caller) do
typespec(arg, vars, caller)
end
# Handle variables or local calls
defp typespec({name, meta, atom}, vars, caller, state) when is_atom(atom) do
if :lists.member(name, vars) do
state = update_local_vars(state, name)
{{:var, line(meta), name}, state}
defp typespec({name, meta, atom}, vars, caller) when is_atom(atom) do
if name in vars do
{:var, line(meta), name}
else
typespec({name, meta, []}, vars, caller, state)
typespec({name, meta, []}, vars, caller)
end
end
# Handle local calls
defp typespec({:string, meta, args}, vars, caller, state) do
defp typespec({:string, meta, arguments}, vars, caller) do
warning =
"string() type use is discouraged. " <>
"For character lists, use charlist() type, for strings, String.t()\n" <>
@@ -771,11 +628,11 @@ defmodule Kernel.Typespec do
:elixir_errors.warn(caller.line, caller.file, warning)
{args, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, args)
{{:type, line(meta), :string, args}, state}
arguments = for arg <- arguments, do: typespec(arg, vars, caller)
{:type, line(meta), :string, arguments}
end
defp typespec({:nonempty_string, meta, args}, vars, caller, state) do
defp typespec({:nonempty_string, meta, arguments}, vars, caller) do
warning =
"nonempty_string() type use is discouraged. " <>
"For non-empty character lists, use nonempty_charlist() type, for strings, String.t()\n" <>
@@ -783,105 +640,85 @@ defmodule Kernel.Typespec do
:elixir_errors.warn(caller.line, caller.file, warning)
{args, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, args)
{{:type, line(meta), :nonempty_string, args}, state}
arguments = for arg <- arguments, do: typespec(arg, vars, caller)
{:type, line(meta), :nonempty_string, arguments}
end
# TODO: Remove char_list type by 2.0
defp typespec({type, _meta, []}, vars, caller, state) when type in [:charlist, :char_list] do
defp typespec({type, _meta, []}, vars, caller) when type in [:charlist, :char_list] do
if type == :char_list do
warning = "the char_list() type is deprecated, use charlist()"
:elixir_errors.warn(caller.line, caller.file, warning)
end
typespec(quote(do: :elixir.charlist()), vars, caller, state)
typespec(quote(do: :elixir.charlist()), vars, caller)
end
defp typespec({:nonempty_charlist, _meta, []}, vars, caller, state) do
typespec(quote(do: :elixir.nonempty_charlist()), vars, caller, state)
defp typespec({:nonempty_charlist, _meta, []}, vars, caller) do
typespec(quote(do: :elixir.nonempty_charlist()), vars, caller)
end
defp typespec({:struct, _meta, []}, vars, caller, state) do
typespec(quote(do: :elixir.struct()), vars, caller, state)
defp typespec({:struct, _meta, []}, vars, caller) do
typespec(quote(do: :elixir.struct()), vars, caller)
end
defp typespec({:as_boolean, _meta, [arg]}, vars, caller, state) do
typespec(quote(do: :elixir.as_boolean(unquote(arg))), vars, caller, state)
defp typespec({:as_boolean, _meta, [arg]}, vars, caller) do
typespec(quote(do: :elixir.as_boolean(unquote(arg))), vars, caller)
end
defp typespec({:keyword, _meta, args}, vars, caller, state) when length(args) <= 1 do
typespec(quote(do: :elixir.keyword(unquote_splicing(args))), vars, caller, state)
defp typespec({:keyword, _meta, args}, vars, caller) when length(args) <= 1 do
typespec(quote(do: :elixir.keyword(unquote_splicing(args))), vars, caller)
end
defp typespec({:fun, meta, args}, vars, caller, state) do
{args, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, args)
{{:type, line(meta), :fun, args}, state}
defp typespec({:fun, meta, args}, vars, caller) do
args = for arg <- args, do: typespec(arg, vars, caller)
{:type, line(meta), :fun, args}
end
defp typespec({name, meta, args}, vars, caller, state) do
{args, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, args)
arity = length(args)
case :erl_internal.is_type(name, arity) do
true ->
{{:type, line(meta), name, args}, state}
false ->
if state.undefined_type_error_enabled? and
not Map.has_key?(state.defined_type_pairs, {name, arity}) do
compile_error(caller, "type #{name}/#{arity} undefined")
end
state =
if :lists.member({name, arity}, state.used_type_pairs) do
state
else
%{state | used_type_pairs: [{name, arity} | state.used_type_pairs]}
end
{{:user_type, line(meta), name, args}, state}
end
defp typespec({name, meta, arguments}, vars, caller) do
arguments = for arg <- arguments, do: typespec(arg, vars, caller)
arity = length(arguments)
type = if :erl_internal.is_type(name, arity), do: :type, else: :user_type
{type, line(meta), name, arguments}
end
# Handle literals
defp typespec(atom, _, _, state) when is_atom(atom) do
{{:atom, 0, atom}, state}
defp typespec(atom, _, _) when is_atom(atom) do
{:atom, 0, atom}
end
defp typespec(integer, _, _, state) when is_integer(integer) do
{{:integer, 0, integer}, state}
defp typespec(integer, _, _) when is_integer(integer) do
{:integer, 0, integer}
end
defp typespec([], vars, caller, state) do
typespec({nil, [], []}, vars, caller, state)
defp typespec([], vars, caller) do
typespec({nil, [], []}, vars, caller)
end
defp typespec([{:..., _, atom}], vars, caller, state) when is_atom(atom) do
typespec({:nonempty_list, [], []}, vars, caller, state)
defp typespec([{:..., _, atom}], vars, caller) when is_atom(atom) do
typespec({:nonempty_list, [], []}, vars, caller)
end
defp typespec([spec, {:..., _, atom}], vars, caller, state) when is_atom(atom) do
typespec({:nonempty_list, [], [spec]}, vars, caller, state)
defp typespec([spec, {:..., _, atom}], vars, caller) when is_atom(atom) do
typespec({:nonempty_list, [], [spec]}, vars, caller)
end
defp typespec([spec], vars, caller, state) do
typespec({:list, [], [spec]}, vars, caller, state)
defp typespec([spec], vars, caller) do
typespec({:list, [], [spec]}, vars, caller)
end
defp typespec(list, vars, caller, state) when is_list(list) do
[head | tail] = :lists.reverse(list)
defp typespec(list, vars, caller) when is_list(list) do
[head | tail] = Enum.reverse(list)
union =
:lists.foldl(
fn elem, acc -> {:|, [], [validate_kw(elem, list, caller), acc]} end,
validate_kw(head, list, caller),
tail
)
Enum.reduce(tail, validate_kw(head, list, caller), fn elem, acc ->
{:|, [], [validate_kw(elem, list, caller), acc]}
end)
typespec({:list, [], [union]}, vars, caller, state)
typespec({:list, [], [union]}, vars, caller)
end
defp typespec(other, _vars, caller, _state) do
defp typespec(other, _vars, caller) do
compile_error(caller, "unexpected expression in typespec: #{Macro.to_string(other)}")
end
@@ -891,9 +728,9 @@ defmodule Kernel.Typespec do
raise CompileError, file: caller.file, line: caller.line, description: desc
end
defp remote_type({remote, meta, name, args}, vars, caller, state) do
{args, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, args)
{{:remote_type, line(meta), [remote, name, args]}, state}
defp remote_type({remote, meta, name, arguments}, vars, caller) do
arguments = for arg <- arguments, do: typespec(arg, vars, caller)
{:remote_type, line(meta), [remote, name, arguments]}
end
defp collect_union({:|, _, [a, b]}), do: [a | collect_union(b)]
@@ -905,43 +742,20 @@ defmodule Kernel.Typespec do
compile_error(caller, "unexpected list in typespec: #{Macro.to_string(original)}")
end
defp validate_range({:op, _, :-, {:integer, meta, first}}, last, caller) do
validate_range({:integer, meta, -first}, last, caller)
end
defp validate_range(first, {:op, _, :-, {:integer, meta, last}}, caller) do
validate_range(first, {:integer, meta, -last}, caller)
end
defp validate_range({:integer, _, first}, {:integer, _, last}, _caller) when first < last do
:ok
end
defp validate_range(_, _, caller) do
message =
"invalid range specification, expected both sides to be integers, " <>
"with the left side lower than the right side"
compile_error(caller, message)
end
defp fn_args(meta, args, return, vars, caller, state) do
{fun_args, state} = fn_args(meta, args, vars, caller, state)
{spec, state} = typespec(return, vars, caller, state)
case [fun_args, spec] do
[{:type, _, :any}, {:type, _, :any, []}] -> {[], state}
x -> {x, state}
defp fn_args(meta, args, return, vars, caller) do
case [fn_args(meta, args, vars, caller), typespec(return, vars, caller)] do
[{:type, _, :any}, {:type, _, :any, []}] -> []
x -> x
end
end
defp fn_args(meta, [{:..., _, _}], _vars, _caller, state) do
{{:type, line(meta), :any}, state}
defp fn_args(meta, [{:..., _, _}], _vars, _caller) do
{:type, line(meta), :any}
end
defp fn_args(meta, args, vars, caller, state) do
{args, state} = :lists.mapfoldl(&typespec(&1, vars, caller, &2), state, args)
{{:type, line(meta), :product, args}, state}
defp fn_args(meta, args, vars, caller) do
args = for arg <- args, do: typespec(arg, vars, caller)
{:type, line(meta), :product, args}
end
defp variable({name, meta, args}) when is_atom(name) and is_atom(args) do
@@ -949,25 +763,4 @@ defmodule Kernel.Typespec do
end
defp variable(expr), do: expr
defp clean_local_state(state) do
%{state | local_vars: %{}}
end
defp update_local_vars(%{local_vars: local_vars} = state, var_name) do
case Map.fetch(local_vars, var_name) do
{:ok, :used_once} -> %{state | local_vars: Map.put(local_vars, var_name, :used_multiple)}
{:ok, :used_multiple} -> state
:error -> %{state | local_vars: Map.put(local_vars, var_name, :used_once)}
end
end
defp ensure_no_unused_local_vars!(caller, local_vars) do
fun = fn
{name, :used_once} -> compile_error(caller, "type variable #{name} is unused")
_ -> :ok
end
:lists.foreach(fun, :maps.to_list(local_vars))
end
end
+20 -31
View File
@@ -157,7 +157,7 @@ defmodule Kernel.Utils do
macro.
Secondly, if the expression is being used outside of a guard, we want to unquote
`value`, but only once, and then re-use the unquoted form throughout the expression.
`value`––but only once, and then re-use the unquoted form throughout the expression.
This helper does exactly that: takes the AST for an expression and a list of
variable references it should be aware of, and rewrites it into a new expression
@@ -170,17 +170,14 @@ defmodule Kernel.Utils do
> variable_references = [value: Elixir]
> Kernel.Utils.defguard(expression, variable_references) |> Macro.to_string |> IO.puts
case Macro.Env.in_guard?(__CALLER__) do
true ->
quote do
is_integer(unquote(value)) and rem(unquote(value), 2) == 0
end
false ->
quote do
value = unquote(value)
is_integer(value) and rem(value, 2) == 0
end
case Macro.Env.in_guard? __CALLER__ do
true -> quote do
is_integer(unquote(value)) and rem(unquote(value), 2) == 0
end
false -> quote do
value = unquote(value)
is_integer(value) and rem(value, 2) == 0
end
end
"""
@@ -228,36 +225,25 @@ defmodule Kernel.Utils do
# Prefaces `guard` with unquoted versions of `refs`.
defp unquote_refs_once(guard, refs) do
{guard, used_refs} =
Macro.postwalk(guard, %{}, fn
{_, used_refs} =
Macro.postwalk(guard, [], fn
{ref, meta, context} = var, acc when is_atom(ref) and is_atom(context) ->
pair = {ref, var_context(meta, context)}
case pair in refs do
true ->
case acc do
%{^pair => {new_var, _}} ->
{new_var, acc}
%{} ->
generated = String.to_atom("arg" <> Integer.to_string(map_size(acc)))
new_var = Macro.var(generated, Elixir)
{new_var, Map.put(acc, pair, {new_var, var})}
end
false ->
{var, acc}
case pair in refs and pair not in acc do
true -> {var, [pair | acc]}
false -> {var, acc}
end
node, acc ->
{node, acc}
end)
all_used = for ref <- :lists.reverse(refs), used = :maps.get(ref, used_refs, nil), do: used
{vars, exprs} = :lists.unzip(all_used)
vars = for {ref, context} <- :lists.reverse(used_refs), do: context_to_var(ref, context)
exprs = for var <- vars, do: literal_unquote(var)
quote do
{unquote_splicing(vars)} = {unquote_splicing(Enum.map(exprs, &literal_unquote/1))}
{unquote_splicing(vars)} = {unquote_splicing(exprs)}
unquote(guard)
end
end
@@ -270,6 +256,9 @@ defmodule Kernel.Utils do
{:unquote, [], List.wrap(ast)}
end
defp context_to_var(ref, ctx) when is_atom(ctx), do: {ref, [], ctx}
defp context_to_var(ref, ctx) when is_integer(ctx), do: {ref, [counter: ctx], nil}
defp var_context(meta, kind) do
case :lists.keyfind(:counter, 1, meta) do
{:counter, counter} -> counter
+22 -25
View File
@@ -20,18 +20,15 @@ defmodule Keyword do
iex> [{:active, :once}]
[active: :once]
The two syntaxes are completely equivalent. Like atoms, keywords
must be composed of Unicode characters such as letters, numbers,
underscore, and `@`. If the keyword has a character that does not
belong to the category above, such as spaces, you can wrap it in
quotes:
The two syntaxes are completely equivalent. If the keyword has foreign
characters, such as spaces, you can wrap it in quotes:
iex> ["exit on close": true]
["exit on close": true]
Wrapping a keyword in quotes does not make it a string. Keywords are
always atoms. If you use quotes when all characters are a valid part
of a keyword without quotes, Elixir will warn.
always atoms and quotes should only be used to handle foreign characters.
In fact, if you attempt use quotes when not necessary, Elixir will warn.
Note that when keyword lists are passed as the last argument to a function,
if the short-hand syntax is used then the square brackets around the keyword list
@@ -84,7 +81,7 @@ defmodule Keyword do
iex> Keyword.keyword?([])
true
iex> Keyword.keyword?(a: 1)
iex> Keyword.keyword?([a: 1])
true
iex> Keyword.keyword?([{Foo, 1}])
true
@@ -322,7 +319,7 @@ defmodule Keyword do
{1, []}
"""
@spec get_and_update!(t, key, (value -> {get, value})) :: {get, t} when get: term
@spec get_and_update!(t, key, (value -> {get, value})) :: {get, t} | no_return when get: term
def get_and_update!(keywords, key, fun) do
get_and_update!(keywords, key, fun, [])
end
@@ -382,7 +379,7 @@ defmodule Keyword do
** (KeyError) key :b not found in: [a: 1]
"""
@spec fetch!(t, key) :: value
@spec fetch!(t, key) :: value | no_return
def fetch!(keywords, key) when is_list(keywords) and is_atom(key) do
case :lists.keyfind(key, 1, keywords) do
{^key, value} -> value
@@ -420,9 +417,9 @@ defmodule Keyword do
## Examples
iex> Keyword.keys(a: 1, b: 2)
iex> Keyword.keys([a: 1, b: 2])
[:a, :b]
iex> Keyword.keys(a: 1, b: 2, a: 3)
iex> Keyword.keys([a: 1, b: 2, a: 3])
[:a, :b, :a]
"""
@@ -438,9 +435,9 @@ defmodule Keyword do
## Examples
iex> Keyword.values(a: 1, b: 2)
iex> Keyword.values([a: 1, b: 2])
[1, 2]
iex> Keyword.values(a: 1, b: 2, a: 3)
iex> Keyword.values([a: 1, b: 2, a: 3])
[1, 2, 3]
"""
@@ -704,8 +701,8 @@ defmodule Keyword do
@spec merge(t, t) :: t
def merge(keywords1, keywords2)
def merge(keywords1, []) when is_list(keywords1), do: keywords1
def merge([], keywords2) when is_list(keywords2), do: keywords2
def merge(keywords1, []), do: keywords1
def merge([], keywords2), do: keywords2
def merge(keywords1, keywords2) when is_list(keywords1) and is_list(keywords2) do
if keyword?(keywords2) do
@@ -715,13 +712,13 @@ defmodule Keyword do
_ ->
raise ArgumentError,
"expected a keyword list as the first argument, got: #{inspect(keywords1)}"
message: "expected a keyword list as the first argument, got: #{inspect(keywords1)}"
end
:lists.filter(fun, keywords1) ++ keywords2
else
raise ArgumentError,
"expected a keyword list as the second argument, got: #{inspect(keywords2)}"
message: "expected a keyword list as the second argument, got: #{inspect(keywords2)}"
end
end
@@ -744,17 +741,17 @@ defmodule Keyword do
[b: 2, a: 4, d: 4]
iex> Keyword.merge([a: 1, b: 2], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->
...> v1 + v2
...> v1 + v2
...> end)
[b: 2, a: 4, d: 4, a: 5]
iex> Keyword.merge([a: 1, b: 2, a: 3], [a: 3, d: 4, a: 5], fn :a, v1, v2 ->
...> v1 + v2
...> v1 + v2
...> end)
[b: 2, a: 4, d: 4, a: 8]
iex> Keyword.merge([a: 1, b: 2], [:a, :b], fn :a, v1, v2 ->
...> v1 + v2
...> v1 + v2
...> end)
** (ArgumentError) expected a keyword list as the second argument, got: [:a, :b]
@@ -766,7 +763,7 @@ defmodule Keyword do
do_merge(keywords2, [], keywords1, keywords1, fun, keywords2)
else
raise ArgumentError,
"expected a keyword list as the first argument, got: #{inspect(keywords1)}"
message: "expected a keyword list as the first argument, got: #{inspect(keywords1)}"
end
end
@@ -788,7 +785,7 @@ defmodule Keyword do
defp do_merge(_other, _acc, _rest, _original, _fun, keywords2) do
raise ArgumentError,
"expected a keyword list as the second argument, got: #{inspect(keywords2)}"
message: "expected a keyword list as the second argument, got: #{inspect(keywords2)}"
end
@doc """
@@ -826,7 +823,7 @@ defmodule Keyword do
** (KeyError) key :b not found in: [a: 1]
"""
@spec update!(t, key, (value -> value)) :: t
@spec update!(t, key, (value -> value)) :: t | no_return
def update!(keywords, key, fun) do
update!(keywords, key, fun, keywords)
end
@@ -1038,7 +1035,7 @@ defmodule Keyword do
## Examples
iex> Keyword.to_list(a: 1)
iex> Keyword.to_list([a: 1])
[a: 1]
"""
+87 -239
View File
@@ -63,7 +63,7 @@ defmodule List do
iex> list ++ [4] # slow
[1, 2, 3, 4]
Additionally, getting a list's length and accessing it by index are
Additonally, getting a list's length and accessing it by index are
linear time operations. Negative indexes are also supported but
they imply the list will be iterated twice, once to calculate the
proper index and another time to perform the operation.
@@ -87,16 +87,14 @@ defmodule List do
instead of Elixir strings. One example of such functions
is `Application.loaded_applications/0`:
Application.loaded_applications()
#=> [
#=> {:stdlib, 'ERTS CXC 138 10', '2.6'},
#=> {:compiler, 'ERTS CXC 138 10', '6.0.1'},
#=> {:elixir, 'elixir', '1.0.0'},
#=> {:kernel, 'ERTS CXC 138 10', '4.1'},
#=> {:logger, 'logger', '1.0.0'}
#=> ]
Application.loaded_applications
#=> [{:stdlib, 'ERTS CXC 138 10', '2.6'},
#=> {:compiler, 'ERTS CXC 138 10', '6.0.1'},
#=> {:elixir, 'elixir', '1.0.0'},
#=> {:kernel, 'ERTS CXC 138 10', '4.1'},
#=> {:logger, 'logger', '1.0.0'}]
A list can be checked if it is made of printable ASCII
A list can be checked if it is made of printable ascii
codepoints with `ascii_printable?/2`.
"""
@@ -288,17 +286,14 @@ defmodule List do
end
@doc """
Receives a list of tuples and if the identified item by `key` at `position`
exists, it is replaced with `new_tuple`.
Receives a list of tuples and replaces the item
identified by `key` at `position` if it exists.
## Examples
iex> List.keyreplace([a: 1, b: 2], :a, 0, {:a, 3})
[a: 3, b: 2]
iex> List.keyreplace([a: 1, b: 2], :a, 1, {:a, 3})
[a: 1, b: 2]
"""
@spec keyreplace([tuple], any, non_neg_integer, tuple) :: [tuple]
def keyreplace(list, key, position, new_tuple) do
@@ -325,7 +320,7 @@ defmodule List do
@doc """
Receives a `list` of tuples and replaces the item
identified by `key` at `position` with `new_tuple`.
identified by `key` at `position`.
If the item does not exist, it is added to the end of the `list`.
@@ -448,28 +443,14 @@ defmodule List do
do_zip(list_of_lists, [])
end
@doc ~S"""
Checks if `list` is a charlist made only of printable ASCII characters.
@doc """
Checks if a list is a charlist made only of printable ASCII characters.
A printable charlist in Elixir contains only ASCII characters.
Takes an optional `limit` as a second argument. `ascii_printable?/2` only
checks the printability of the list up to the `limit`.
A printable charlist in Elixir contains only the printable characters in the
standard seven-bit ASCII character encoding, which are characters ranging from
32 to 126 in decimal notation, plus the following control characters:
* `?\a` - Bell
* `?\b` - Backspace
* `?\t` - Horizontal tab
* `?\n` - Line feed
* `?\v` - Vertical tab
* `?\f` - Form feed
* `?\r` - Carriage return
* `?\e` - Escape
For more information read the [Character groups](https://en.wikipedia.org/wiki/ASCII#Character_groups)
section in the Wikipedia article of the [ASCII](https://en.wikipedia.org/wiki/ASCII) standard.
## Examples
iex> List.ascii_printable?('abc')
@@ -481,85 +462,63 @@ defmodule List do
iex> List.ascii_printable?('abc' ++ [0], 2)
true
Improper lists are not printable, even if made only of ASCII characters:
Improper lists are not printable, even if made only of ascii characters:
iex> List.ascii_printable?('abc' ++ ?d)
false
"""
@doc since: "1.6.0"
@spec ascii_printable?(list, limit) :: boolean
when limit: :infinity | non_neg_integer
def ascii_printable?(list, limit \\ :infinity)
when is_list(list) and (limit == :infinity or (is_integer(limit) and limit >= 0)) do
ascii_printable_guarded?(list, limit)
end
def ascii_printable?(list, counter \\ :infinity)
defp ascii_printable_guarded?(_, 0) do
def ascii_printable?(_, 0) do
true
end
defp ascii_printable_guarded?([char | rest], counter)
when is_integer(char) and char >= 32 and char <= 126 do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([char | rest], counter)
when is_integer(char) and char >= 32 and char <= 126 do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\n | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\n | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\r | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\r | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\t | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\t | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\v | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\v | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\b | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\b | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\f | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\f | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\e | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\e | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([?\a | rest], counter) do
ascii_printable_guarded?(rest, decrement(counter))
def ascii_printable?([?\a | rest], counter) do
ascii_printable?(rest, decrement(counter))
end
defp ascii_printable_guarded?([], _counter), do: true
defp ascii_printable_guarded?(_, _counter), do: false
def ascii_printable?([], _counter), do: true
def ascii_printable?(_, _counter), do: false
@compile {:inline, decrement: 1}
defp decrement(:infinity), do: :infinity
defp decrement(counter), do: counter - 1
@doc """
Returns `true` if `list` is an improper list. Otherwise returns `false`.
## Examples
iex> List.improper?([1, 2 | 3])
true
iex> List.improper?([1, 2, 3])
false
"""
@doc since: "1.8.0"
@spec improper?(maybe_improper_list) :: boolean
def improper?(list) when is_list(list) and length(list) >= 0, do: false
def improper?(list) when is_list(list), do: true
@doc """
Returns a list with `value` inserted at the specified `index`.
@@ -582,19 +541,11 @@ defmodule List do
"""
@spec insert_at(list, integer, any) :: list
def insert_at(list, index, value) when is_list(list) and is_integer(index) do
case index do
-1 ->
list ++ [value]
_ when index < 0 ->
case length(list) + index + 1 do
index when index < 0 -> [value | list]
index -> do_insert_at(list, index, value)
end
_ ->
do_insert_at(list, index, value)
def insert_at(list, index, value) when is_integer(index) do
if index < 0 do
do_insert_at(list, length(list) + index + 1, value)
else
do_insert_at(list, index, value)
end
end
@@ -620,12 +571,9 @@ defmodule List do
"""
@spec replace_at(list, integer, any) :: list
def replace_at(list, index, value) when is_list(list) and is_integer(index) do
def replace_at(list, index, value) when is_integer(index) do
if index < 0 do
case length(list) + index do
index when index < 0 -> list
index -> do_replace_at(list, index, value)
end
do_replace_at(list, length(list) + index, value)
else
do_replace_at(list, index, value)
end
@@ -653,12 +601,9 @@ defmodule List do
"""
@spec update_at([elem], integer, (elem -> any)) :: list when elem: var
def update_at(list, index, fun) when is_list(list) and is_function(fun) and is_integer(index) do
def update_at(list, index, fun) when is_function(fun, 1) and is_integer(index) do
if index < 0 do
case length(list) + index do
index when index < 0 -> list
index -> do_update_at(list, index, fun)
end
do_update_at(list, length(list) + index, fun)
else
do_update_at(list, index, fun)
end
@@ -748,18 +693,15 @@ defmodule List do
@doc """
Converts a charlist to an atom.
Elixir supports conversions from charlists which contains any Unicode
codepoint.
Currently Elixir does not support conversions from charlists
which contains Unicode codepoints greater than 0xFF.
Inlined by the compiler.
## Examples
iex> List.to_atom('Elixir')
:Elixir
iex> List.to_atom('🌢 Elixir')
:"🌢 Elixir"
iex> List.to_atom('elixir')
:elixir
"""
@spec to_atom(charlist) :: atom
@@ -771,8 +713,8 @@ defmodule List do
Converts a charlist to an existing atom. Raises an `ArgumentError`
if the atom does not exist.
Elixir supports conversions from charlists which contains any Unicode
codepoint.
Currently Elixir does not support conversions from charlists
which contains Unicode codepoints greater than 0xFF.
Inlined by the compiler.
@@ -782,10 +724,6 @@ defmodule List do
iex> List.to_existing_atom('my_atom')
:my_atom
iex> _ = :"🌢 Elixir"
iex> List.to_existing_atom('🌢 Elixir')
:"🌢 Elixir"
iex> List.to_existing_atom('this_atom_will_never_exist')
** (ArgumentError) argument error
@@ -910,58 +848,6 @@ defmodule List do
end
end
@doc """
Converts a list of integers representing codepoints, lists or
strings into a charlist.
Notice that this function expects a list of integers 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).
## Examples
iex> List.to_charlist([0x00E6, 0x00DF])
'æß'
iex> List.to_charlist([0x0061, "bc"])
'abc'
iex> List.to_charlist([0x0064, "ee", ['p']])
'deep'
"""
@doc since: "1.8.0"
@spec to_charlist(:unicode.charlist()) :: charlist()
def to_charlist(list) when is_list(list) do
try do
:unicode.characters_to_list(list)
rescue
ArgumentError ->
raise ArgumentError, """
cannot convert the given list to a charlist.
To be converted to a charlist, a list must contain only:
* strings
* integers representing Unicode codepoints
* or a list containing one of these three elements
Please check the given list or call inspect/1 to get the list representation, got:
#{inspect(list)}
"""
else
result when is_list(result) ->
result
{:error, encoded, rest} ->
raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :invalid
{:incomplete, encoded, rest} ->
raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :incomplete
end
end
@doc """
Returns a keyword list that represents an *edit script*.
@@ -975,8 +861,6 @@ defmodule List do
corresponding key is `:del`), or left alone (if the corresponding key is
`:eq`) in `list1` in order to be closer to `list2`.
See `myers_difference/3` if you want to handle nesting in the diff scripts.
## Examples
iex> List.myers_difference([1, 4, 2, 3], [1, 2, 3, 4])
@@ -986,49 +870,19 @@ defmodule List do
@doc since: "1.4.0"
@spec myers_difference(list, list) :: [{:eq | :ins | :del, list}]
def myers_difference(list1, list2) when is_list(list1) and is_list(list2) do
myers_difference_with_diff_script(list1, list2, nil)
end
@doc """
Returns a keyword list that represents an *edit script* with nested diffs.
This is an extension of `myers_difference/2` where a `diff_script` function
can be given in case it is desired to compute nested differences. The function
may return a list with the inner edit script or `nil` in case there is no
such script. The returned inner edit script will be under the `:diff` key.
## Examples
iex> List.myers_difference(["a", "db", "c"], ["a", "bc"], &String.myers_difference/2)
[eq: ["a"], diff: [del: "d", eq: "b", ins: "c"], del: ["c"]]
"""
@doc since: "1.8.0"
@spec myers_difference(list, list, (term, term -> script | nil)) :: script
when script: [{:eq | :ins | :del | :diff, list}]
def myers_difference(list1, list2, diff_script)
when is_list(list1) and is_list(list2) and is_function(diff_script) do
myers_difference_with_diff_script(list1, list2, diff_script)
end
defp myers_difference_with_diff_script(list1, list2, diff_script) do
path = {0, list1, list2, []}
find_script(0, length(list1) + length(list2), [path], diff_script)
find_script(0, length(list1) + length(list2), [path])
end
defp find_script(envelope, max, paths, diff_script) do
case each_diagonal(-envelope, envelope, paths, [], diff_script) do
defp find_script(envelope, max, paths) do
case each_diagonal(-envelope, envelope, paths, []) do
{:done, edits} -> compact_reverse(edits, [])
{:next, paths} -> find_script(envelope + 1, max, paths, diff_script)
{:next, paths} -> find_script(envelope + 1, max, paths)
end
end
defp compact_reverse([], acc), do: acc
defp compact_reverse([{:diff, _} = fragment | rest], acc) do
compact_reverse(rest, [fragment | acc])
end
defp compact_reverse([{kind, elem} | rest], [{kind, result} | acc]) do
compact_reverse(rest, [{kind, [elem | result]} | acc])
end
@@ -1041,68 +895,50 @@ defmodule List do
compact_reverse(rest, [{kind, [elem]} | acc])
end
defp each_diagonal(diag, limit, _paths, next_paths, _diff_script) when diag > limit do
defp each_diagonal(diag, limit, _paths, next_paths) when diag > limit do
{:next, :lists.reverse(next_paths)}
end
defp each_diagonal(diag, limit, paths, next_paths, diff_script) do
{path, rest} = proceed_path(diag, limit, paths, diff_script)
defp each_diagonal(diag, limit, paths, next_paths) do
{path, rest} = proceed_path(diag, limit, paths)
case follow_snake(path) do
{:cont, path} -> each_diagonal(diag + 2, limit, rest, [path | next_paths], diff_script)
{:cont, path} -> each_diagonal(diag + 2, limit, rest, [path | next_paths])
{:done, edits} -> {:done, edits}
end
end
defp proceed_path(0, 0, [path], _diff_script), do: {path, []}
defp proceed_path(0, 0, [path]), do: {path, []}
defp proceed_path(diag, limit, [path | _] = paths, diff_script) when diag == -limit do
{move_down(path, diff_script), paths}
defp proceed_path(diag, limit, [path | _] = paths) when diag == -limit do
{move_down(path), paths}
end
defp proceed_path(diag, limit, [path], diff_script) when diag == limit do
{move_right(path, diff_script), []}
defp proceed_path(diag, limit, [path]) when diag == limit do
{move_right(path), []}
end
defp proceed_path(_diag, _limit, [path1, path2 | rest], diff_script) do
defp proceed_path(_diag, _limit, [path1, path2 | rest]) do
if elem(path1, 0) > elem(path2, 0) do
{move_right(path1, diff_script), [path2 | rest]}
{move_right(path1), [path2 | rest]}
else
{move_down(path2, diff_script), [path2 | rest]}
{move_down(path2), [path2 | rest]}
end
end
defp move_right({y, [elem1 | rest1] = list1, [elem2 | rest2], edits}, diff_script)
when diff_script != nil do
if diff = diff_script.(elem1, elem2) do
{y + 1, rest1, rest2, [{:diff, diff} | edits]}
else
{y, list1, rest2, [{:ins, elem2} | edits]}
end
end
defp move_right({y, list1, [elem | rest], edits}, _diff_script) do
defp move_right({y, list1, [elem | rest], edits}) do
{y, list1, rest, [{:ins, elem} | edits]}
end
defp move_right({y, list1, [], edits}, _diff_script) do
defp move_right({y, list1, [], edits}) do
{y, list1, [], edits}
end
defp move_down({y, [elem1 | rest1], [elem2 | rest2] = list2, edits}, diff_script)
when diff_script != nil do
if diff = diff_script.(elem1, elem2) do
{y + 1, rest1, rest2, [{:diff, diff} | edits]}
else
{y + 1, rest1, list2, [{:del, elem1} | edits]}
end
end
defp move_down({y, [elem | rest], list2, edits}, _diff_script) do
defp move_down({y, [elem | rest], list2, edits}) do
{y + 1, rest, list2, [{:del, elem} | edits]}
end
defp move_down({y, [], list2, edits}, _diff_script) do
defp move_down({y, [], list2, edits}) do
{y + 1, [], list2, edits}
end
@@ -1126,6 +962,10 @@ defmodule List do
[]
end
defp do_replace_at(list, index, _value) when index < 0 do
list
end
defp do_replace_at([_old | rest], 0, value) do
[value | rest]
end
@@ -1140,7 +980,7 @@ defmodule List do
[value]
end
defp do_insert_at(list, 0, value) do
defp do_insert_at(list, index, value) when index <= 0 do
[value | list]
end
@@ -1154,6 +994,10 @@ defmodule List do
[fun.(value) | list]
end
defp do_update_at(list, index, _fun) when index < 0 do
list
end
defp do_update_at([head | tail], index, fun) do
[head | do_update_at(tail, index - 1, fun)]
end
@@ -1168,6 +1012,10 @@ defmodule List do
{default, :lists.reverse(acc)}
end
defp do_pop_at(list, index, default, []) when index < 0 do
{default, list}
end
defp do_pop_at([head | tail], 0, _default, acc) do
{head, :lists.reverse(acc, tail)}
end
+22 -49
View File
@@ -95,7 +95,7 @@ defmodule Macro do
`div/2` function, so that the AST for that function will become `{:div, [],
[100, 5]}` (`div(100, 5)`).
"""
@spec unpipe(t()) :: [t()]
@spec unpipe(Macro.t()) :: [Macro.t()]
def unpipe(expr) do
:lists.reverse(unpipe(expr, []))
end
@@ -111,7 +111,7 @@ defmodule Macro do
@doc """
Pipes `expr` into the `call_args` at the given `position`.
"""
@spec pipe(t(), t(), integer) :: t()
@spec pipe(Macro.t(), Macro.t(), integer) :: Macro.t() | no_return
def pipe(expr, call_args, position)
def pipe(expr, {:&, _, _} = call_args, _integer) do
@@ -131,17 +131,13 @@ defmodule Macro do
raise ArgumentError, bad_pipe(expr, call_args)
end
def pipe(expr, {unquote, _, []}, _integer) when unquote in [:unquote, :unquote_splicing] do
raise ArgumentError,
"cannot pipe #{to_string(expr)} into the special form #{unquote}/1 " <>
"since #{unquote}/1 is used to build the Elixir AST itself"
end
# {:fn, _, _} is what we get when we pipe into an anonymous function without
# calling it, e.g., `:foo |> (fn x -> x end)`.
def pipe(expr, {:fn, _, _}, _integer) do
expr_str = to_string(expr)
raise ArgumentError,
"cannot pipe #{to_string(expr)} into an anonymous function without" <>
"cannot pipe #{expr_str} into an anonymous function without" <>
" calling the function; use something like (fn ... end).() or" <>
" define the anonymous function as a regular private function"
end
@@ -166,7 +162,7 @@ defmodule Macro do
defp bad_pipe(expr, call_args) do
"cannot pipe #{to_string(expr)} into #{to_string(call_args)}, " <>
"can only pipe into local calls foo(), remote calls Foo.bar() or anonymous function calls foo.()"
"can only pipe into local calls foo(), remote calls Foo.bar() or anonymous functions calls foo.()"
end
@doc """
@@ -202,7 +198,7 @@ defmodule Macro do
## Examples
iex> Macro.generate_arguments(2, __MODULE__)
[{:arg1, [], __MODULE__}, {:arg2, [], __MODULE__}]
[{:var1, [], __MODULE__}, {:var2, [], __MODULE__}]
"""
@doc since: "1.5.0"
@@ -210,7 +206,7 @@ defmodule Macro do
def generate_arguments(amount, context)
when is_integer(amount) and amount > 0 and is_atom(context) do
for id <- 1..amount, do: var(String.to_atom("arg" <> Integer.to_string(id)), context)
for id <- 1..amount, do: Macro.var(String.to_atom("var" <> Integer.to_string(id)), context)
end
@doc """
@@ -346,7 +342,7 @@ defmodule Macro do
:error
"""
@spec decompose_call(t()) :: {atom, [t()]} | {t(), atom, [t()]} | :error
@spec decompose_call(Macro.t()) :: {atom, [Macro.t()]} | {Macro.t(), atom, [Macro.t()]} | :error
def decompose_call(ast)
def decompose_call({{:., _, [remote, function]}, _, args})
@@ -384,7 +380,7 @@ defmodule Macro do
nodes. Note this option changes the semantics of escaped code and
it should only be used when escaping ASTs, never values. Defaults
to false.
As an example, `ExUnit` stores the AST of every assertion, so when
an assertion fails we can show code snippets to users. Without this
option, each time the test module is compiled, we get a different
@@ -393,7 +389,7 @@ defmodule Macro do
the metadata, we ensure that the module is deterministic and reduce
the amount of data `ExUnit` needs to keep around.
## Comparison to `Kernel.SpecialForms.quote/2`
## Comparison to `Kernel.quote/2`
The `escape/2` function is sometimes confused with `Kernel.SpecialForms.quote/2`,
because the above examples behave the same with both. The key difference is
@@ -419,29 +415,11 @@ defmodule Macro do
bound), while `Kernel.SpecialForms.quote/2` produces syntax trees for
expressions.
"""
@spec escape(term, keyword) :: t()
@spec escape(term, keyword) :: Macro.t()
def escape(expr, opts \\ []) do
unquote = Keyword.get(opts, :unquote, false)
kind = if Keyword.get(opts, :prune_metadata, false), do: :prune_metadata, else: :default
:elixir_quote.escape(expr, kind, unquote)
end
@doc """
Expands the struct given by `module` in the given `env`.
This is useful when a struct needs to be expanded at
compilation time and the struct being expanded may or may
not have been compiled. This function is even capable of
expanding structs defined under the module being compiled.
It will raise `CompileError` if the struct is not available.
"""
@doc since: "1.8.0"
@spec struct!(module, Macro.Env.t()) :: %{__struct__: module} when module: module()
def struct!(module, env) when is_atom(module) do
if module == env.module do
Module.get_attribute(module, :struct)
end || :elixir_map.load_struct([line: env.line], module, [], env)
elem(:elixir_quote.escape(expr, kind, unquote), 0)
end
@doc """
@@ -547,7 +525,7 @@ defmodule Macro do
def unescape_map(?s), do: ?\s
def unescape_map(?t), do: ?\t
def unescape_map(?v), do: ?\v
def unescape_map(e), do: e
def unescape_map(e), do: e
If the `unescape_map/1` function returns `false`, the char is
not escaped and the backslash is kept in the string.
@@ -560,7 +538,7 @@ defmodule Macro do
Using the `unescape_map/1` function defined above is easy:
Macro.unescape_string("example\\n", &unescape_map(&1))
Macro.unescape_string "example\\n", &unescape_map(&1)
"""
@spec unescape_string(String.t(), (non_neg_integer -> non_neg_integer | false)) :: String.t()
@@ -609,7 +587,7 @@ defmodule Macro do
"one + two"
"""
@spec to_string(t(), (t(), String.t() -> String.t())) :: String.t()
@spec to_string(Macro.t(), (Macro.t(), String.t() -> String.t())) :: String.t()
def to_string(tree, fun \\ fn _ast, string -> string end)
# Variables
@@ -758,13 +736,9 @@ defmodule Macro do
{list, last} = split_last(args)
result =
if kw_blocks?(last) do
case list do
[] -> call_to_string(target, fun) <> kw_blocks_to_string(last, fun)
_ -> call_to_string_with_args(target, list, fun) <> kw_blocks_to_string(last, fun)
end
else
call_to_string_with_args(target, args, fun)
case kw_blocks?(last) do
true -> call_to_string_with_args(target, list, fun) <> kw_blocks_to_string(last, fun)
false -> call_to_string_with_args(target, args, fun)
end
fun.(ast, result)
@@ -1191,7 +1165,7 @@ defmodule Macro do
defmacro defmodule_with_length(name, do: block) do
expanded = Macro.expand(name, __CALLER__)
length = length(Atom.to_charlist(expanded))
length = length(Atom.to_charlist(expanded))
quote do
defmodule unquote(name) do
@@ -1278,7 +1252,7 @@ defmodule Macro do
case expand do
{:ok, receiver, quoted} ->
next = :elixir_module.next_counter(module)
next = :erlang.unique_integer()
{:elixir_quote.linify_with_context_counter(0, {receiver, next}, quoted), true}
{:ok, Kernel, op, [arg]} when op in [:+, :-] ->
@@ -1309,7 +1283,7 @@ defmodule Macro do
case expand do
{:ok, receiver, quoted} ->
next = :elixir_module.next_counter(env.module)
next = :erlang.unique_integer()
{:elixir_quote.linify_with_context_counter(0, {receiver, next}, quoted), true}
:error ->
@@ -1408,7 +1382,6 @@ defmodule Macro do
"Hello10"
"""
@spec underscore(atom | String.t()) :: String.t()
def underscore(atom) when is_atom(atom) do
"Elixir." <> rest = Atom.to_string(atom)
underscore(rest)
+8 -8
View File
@@ -28,7 +28,7 @@ defmodule Macro.Env do
element is the function name and the second its arity; returns
`nil` if not inside a function
* `context` - the context of the environment; it can be `nil`
(default context), `:guard` (inside a guard) or `:match` (inside a match)
(default context), inside a guard or inside a match
* `aliases` - a list of two-element tuples, where the first
element is the aliased name and the second one the actual name
* `requires` - the list of required modules
@@ -57,20 +57,20 @@ defmodule Macro.Env do
@type file :: binary
@type line :: non_neg_integer
@type aliases :: [{module, module}]
@type macro_aliases :: [{module, {term, module}}]
@type macro_aliases :: [{module, {integer, module}}]
@type context :: :match | :guard | nil
@type requires :: [module]
@type functions :: [{module, [name_arity]}]
@type macros :: [{module, [name_arity]}]
@type context_modules :: [module]
@type lexical_tracker :: pid | nil
@type variable :: {atom, atom | term}
@type var :: {atom, atom | non_neg_integer}
@typep vars :: [variable]
@typep vars :: [var]
@typep var_type :: :term
@typep var_version :: non_neg_integer
@typep unused_vars :: %{{variable, var_version} => non_neg_integer | false}
@typep current_vars :: %{variable => {var_version, var_type}}
@typep unused_vars :: %{{var, var_version} => non_neg_integer | false}
@typep current_vars :: %{var => {var_version, var_type}}
@typep prematch_vars :: current_vars | :warn | :raise | :pin | :apply
@typep contextual_vars :: [atom]
@@ -132,7 +132,7 @@ defmodule Macro.Env do
atom or an integer.
"""
@doc since: "1.7.0"
@spec vars(t) :: [variable]
@spec vars(t) :: [var]
def vars(env)
def vars(%{__struct__: Macro.Env, current_vars: current_vars}) do
@@ -143,7 +143,7 @@ defmodule Macro.Env do
Checks if a variable belongs to the environment.
"""
@doc since: "1.7.0"
@spec has_var?(t, variable) :: boolean()
@spec has_var?(t, var) :: boolean()
def has_var?(env, var)
def has_var?(%{__struct__: Macro.Env, current_vars: current_vars}, var) do
+3 -3
View File
@@ -165,7 +165,7 @@ defmodule Map do
iex> Map.new([{:b, 1}, {:a, 2}])
%{a: 2, b: 1}
iex> Map.new(a: 1, a: 2, a: 3)
iex> Map.new([a: 1, a: 2, a: 3])
%{a: 3}
"""
@@ -262,7 +262,7 @@ defmodule Map do
** (KeyError) key :b not found in: %{a: 1}
"""
@spec fetch!(map, key) :: value
@spec fetch!(map, key) :: value | no_return
def fetch!(map, key) do
:maps.get(key, map)
end
@@ -824,7 +824,7 @@ defmodule Map do
{1, %{}}
"""
@spec get_and_update!(map, key, (value -> {get, value} | :pop)) :: {get, map}
@spec get_and_update!(map, key, (value -> {get, value} | :pop)) :: {get, map} | no_return
when get: term
def get_and_update!(map, key, fun) when is_function(fun, 1) do
value = fetch!(map, key)
-1
View File
@@ -398,7 +398,6 @@ defmodule MapSet do
import Inspect.Algebra
def inspect(map_set, opts) do
opts = %Inspect.Opts{opts | charlists: :as_lists}
concat(["#MapSet<", Inspect.List.inspect(MapSet.to_list(map_set), opts), ">"])
end
end
+69 -100
View File
@@ -41,7 +41,7 @@ defmodule Module do
@callback default_port() :: integer
@doc "Parses the given URL"
@callback parse(uri_info :: URI.t()) :: URI.t()
@callback parse(uri_info :: URI.t) :: URI.t
end
And then a module may use it as:
@@ -60,25 +60,14 @@ defmodule Module do
To aid in the correct implementation of behaviours, you may optionally declare
`@impl` for implemented callbacks of a behaviour. This makes callbacks
explicit and can help you to catch errors in your code. The compiler will warn
in these cases:
you if you mark a function as `@impl` when in fact it is not a callback, and
vice-versa. It also helps with maintainability by making it clear to other
developers that the function's purpose is to implement a callback.
* if you mark a function with `@impl` when that function is not a callback.
* if you don't mark a function with `@impl` when other functions are marked
with `@impl`. If you mark one function with `@impl`, you must mark all
other callbacks for that behaviour as `@impl`.
`@impl` works on a per-context basis. If you generate a function through a macro
and mark it with `@impl`, that won't affect the module where that function is
generated in.
`@impl` also helps with maintainability by making it clear to other developers
that the function is implementing a callback.
Using `@impl`, the example above can be rewritten as:
Using `@impl` the example above can be rewritten as:
defmodule URI.HTTP do
@behaviour URI.Parser
@behaviour URI.parser
@impl true
def default_port(), do: 80
@@ -93,16 +82,14 @@ defmodule Module do
@behaviour Bar
@behaviour Baz
# Will warn if neither Bar nor Baz specify a callback named bar/0.
@impl true
@impl true # will warn if neither Bar nor Baz specify a callback named bar/0
def bar(), do: :ok
# Will warn if Baz does not specify a callback named baz/0.
@impl Baz
@impl Baz # will warn if Baz does not specify a callback named baz/0
def baz(), do: :ok
end
The code is now more readable, as it is now clear which functions are
Readability of the code is increased, as it is now clear which functions are
part of your API and which ones are callback implementations. To reinforce this
idea, `@impl true` automatically marks the function as `@doc false`, disabling
documentation unless `@doc` is explicitly set.
@@ -141,7 +128,7 @@ defmodule Module do
Using the `@deprecated` attribute will also be reflected in the
documentation of the given function and macro. You can choose between
the `@deprecated` attribute and the documentation metadata to provide
hard-deprecations (with warnings) and soft-deprecations (without warnings):
hard-deprecations (with warnings) and soft-deprecations (with warnings):
This is a soft-deprecation as it simply annotates the documentation
as deprecated:
@@ -289,9 +276,9 @@ defmodule Module do
Accepts the function name (as an atom) of a function in the current module or
`{function_name, 0}` tuple where `function_name` is the name of a function in
the current module. The function must be public and have an arity of 0 (no
arguments). If the function does not return `:ok`, the loading of the module
will be aborted. For example:
the current module. The function must have arity 0 (no arguments) and has to
return `:ok`, otherwise the loading of the module will be aborted. For
example:
defmodule MyModule do
@on_load :load_check
@@ -369,7 +356,7 @@ defmodule Module do
@after_compile __MODULE__
def __after_compile__(env, _bytecode) do
IO.inspect(env)
IO.inspect env
end
end
@@ -445,12 +432,12 @@ defmodule Module do
defmodule Hooks do
def on_def(_env, kind, name, args, guards, body) do
IO.puts("Defining #{kind} named #{name} with args:")
IO.inspect(args)
IO.puts("and guards")
IO.inspect(guards)
IO.puts("and body")
IO.puts(Macro.to_string(body))
IO.puts "Defining #{kind} named #{name} with args:"
IO.inspect args
IO.puts "and guards"
IO.inspect guards
IO.puts "and body"
IO.puts Macro.to_string(body)
end
end
@@ -513,7 +500,7 @@ defmodule Module do
* `:attributes` - a list with all persisted attributes
"""
@callback __info__(:functions | :macros | :module | :md5 | :compile | :attributes) :: term()
def __info__(kind)
@doc """
Checks if a module is open.
@@ -537,16 +524,11 @@ defmodule Module do
## Examples
defmodule Foo do
contents =
quote do
def sum(a, b), do: a + b
end
Module.eval_quoted(__MODULE__, contents)
contents = quote do: (def sum(a, b), do: a + b)
Module.eval_quoted __MODULE__, contents
end
Foo.sum(1, 2)
#=> 3
Foo.sum(1, 2) #=> 3
For convenience, you can pass any `Macro.Env` struct, such
as `__ENV__/0`, as the first argument or as options. Both
@@ -554,16 +536,11 @@ defmodule Module do
from the environment:
defmodule Foo do
contents =
quote do
def sum(a, b), do: a + b
end
Module.eval_quoted(__ENV__, contents)
contents = quote do: (def sum(a, b), do: a + b)
Module.eval_quoted __ENV__, contents
end
Foo.sum(1, 2)
#=> 3
Foo.sum(1, 2) #=> 3
Note that if you pass a `Macro.Env` struct as first argument
while also passing `opts`, they will be merged with `opts`
@@ -618,8 +595,7 @@ defmodule Module do
Module.create(Hello, contents, Macro.Env.location(__ENV__))
Hello.world()
#=> true
Hello.world #=> true
## Differences from `defmodule`
@@ -646,7 +622,7 @@ defmodule Module do
raise ArgumentError, "expected :file to be given as option"
end
next = :elixir_module.next_counter(nil)
next = :erlang.unique_integer()
line = Keyword.get(opts, :line, 0)
quoted = :elixir_quote.linify_with_context_counter(line, {module, next}, quoted)
:elixir_module.compile(module, quoted, [], :elixir.env_for_eval(opts))
@@ -905,9 +881,9 @@ defmodule Module do
## Examples
defmodule Example do
Module.defines?(__MODULE__, {:version, 0}) #=> false
Module.defines? __MODULE__, {:version, 0} #=> false
def version, do: 1
Module.defines?(__MODULE__, {:version, 0}) #=> true
Module.defines? __MODULE__, {:version, 0} #=> true
end
"""
@@ -931,9 +907,9 @@ defmodule Module do
## Examples
defmodule Example do
Module.defines?(__MODULE__, {:version, 0}, :def) #=> false
Module.defines? __MODULE__, {:version, 0}, :defp #=> false
def version, do: 1
Module.defines?(__MODULE__, {:version, 0}, :def) #=> true
Module.defines? __MODULE__, {:version, 0}, :defp #=> false
end
"""
@@ -979,7 +955,7 @@ defmodule Module do
defmodule Example do
def version, do: 1
Module.definitions_in(__MODULE__) #=> [{:version, 0}]
Module.definitions_in __MODULE__ #=> [{:version, 0}]
end
"""
@@ -998,8 +974,8 @@ defmodule Module do
defmodule Example do
def version, do: 1
Module.definitions_in(__MODULE__, :def) #=> [{:version, 0}]
Module.definitions_in(__MODULE__, :defp) #=> []
Module.definitions_in __MODULE__, :def #=> [{:version, 0}]
Module.definitions_in __MODULE__, :defp #=> []
end
"""
@@ -1138,7 +1114,7 @@ defmodule Module do
## Examples
defmodule MyModule do
Module.put_attribute(__MODULE__, :custom_threshold_for_lib, 10)
Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10
end
"""
@@ -1167,12 +1143,12 @@ defmodule Module do
## Examples
defmodule Foo do
Module.put_attribute(__MODULE__, :value, 1)
Module.get_attribute(__MODULE__, :value) #=> 1
Module.put_attribute __MODULE__, :value, 1
Module.get_attribute __MODULE__, :value #=> 1
Module.register_attribute(__MODULE__, :value, accumulate: true)
Module.put_attribute(__MODULE__, :value, 1)
Module.get_attribute(__MODULE__, :value) #=> [1]
Module.register_attribute __MODULE__, :value, accumulate: true
Module.put_attribute __MODULE__, :value, 1
Module.get_attribute __MODULE__, :value #=> [1]
end
"""
@@ -1189,8 +1165,8 @@ defmodule Module do
## Examples
defmodule MyModule do
Module.put_attribute(__MODULE__, :custom_threshold_for_lib, 10)
Module.delete_attribute(__MODULE__, :custom_threshold_for_lib)
Module.put_attribute __MODULE__, :custom_threshold_for_lib, 10
Module.delete_attribute __MODULE__, :custom_threshold_for_lib
end
"""
@@ -1226,7 +1202,7 @@ defmodule Module do
When registering an attribute, two options can be given:
* `:accumulate` - several calls to the same attribute will
accumulate instead of overriding the previous one. New attributes
accumulate instead of override the previous one. New attributes
are always added to the top of the accumulated list.
* `:persist` - the attribute will be persisted in the Erlang
@@ -1237,7 +1213,9 @@ defmodule Module do
## Examples
defmodule MyModule do
Module.register_attribute(__MODULE__, :custom_threshold_for_lib, accumulate: true)
Module.register_attribute __MODULE__,
:custom_threshold_for_lib,
accumulate: true, persist: false
@custom_threshold_for_lib 10
@custom_threshold_for_lib 20
@@ -1463,7 +1441,9 @@ defmodule Module do
message =
"@behaviour #{inspect(behaviour)} does not exist (in module #{inspect(env.module)})"
:elixir_errors.warn(env.line, env.file, message)
unless standard_behaviour?(behaviour) do
:elixir_errors.warn(env.line, env.file, message)
end
acc
@@ -1471,7 +1451,9 @@ defmodule Module do
message =
"module #{inspect(behaviour)} is not a behaviour (in module #{inspect(env.module)})"
:elixir_errors.warn(env.line, env.file, message)
unless standard_behaviour?(behaviour) do
:elixir_errors.warn(env.line, env.file, message)
end
acc
@@ -1502,6 +1484,16 @@ defmodule Module do
Map.put(acc, callback, {kind, behaviour, original in optional_callbacks})
end
defp standard_behaviour?(behaviour) do
behaviour in [
Collectable,
Enumerable,
Inspect,
List.Chars,
String.Chars
]
end
defp check_callbacks(env, callbacks, all_definitions) do
for {callback, {kind, behaviour, optional?}} <- callbacks do
case :lists.keyfind(callback, 1, all_definitions) do
@@ -1766,8 +1758,9 @@ defmodule Module do
end
end
# Optimize some attributes by avoiding writing to the attributes key
# in the bag table since we handle them internally.
# This is the same list of attributes as in :elixir_module.
# We do not insert into the :attributes key in the bag table
# because those attributes are deleted on every definition.
defp put_attribute(module, key, value, line, set, _bag)
when key in [:doc, :typedoc, :moduledoc, :impl, :deprecated] do
try do
@@ -1786,18 +1779,6 @@ defmodule Module do
:ets.insert(set, {key, value, line})
end
defp put_attribute(_module, :on_load, value, line, set, bag) do
try do
:ets.lookup_element(set, :on_load, 3)
catch
:error, :badarg ->
:ets.insert(set, {:on_load, value, line})
:ets.insert(bag, {:attributes, :on_load})
else
_ -> raise ArgumentError, "the @on_load attribute can only be set once per module"
end
end
defp put_attribute(_module, key, value, line, set, bag) do
try do
:ets.lookup_element(set, key, 3)
@@ -1883,9 +1864,9 @@ defmodule Module do
do: {atom, :__on_definition__}
defp preprocess_attribute(key, _value)
when key in [:type, :typep, :opaque, :spec, :callback, :macrocallback] do
when key in [:type, :typep, :export_type, :opaque, :spec, :callback, :macrocallback] do
raise ArgumentError,
"attributes type, typep, opaque, spec, callback, and macrocallback " <>
"attributes type, typep, export_type, opaque, spec, callback, and macrocallback " <>
"must be set directly via the @ notation"
end
@@ -1947,18 +1928,6 @@ defmodule Module do
"representing the replacement for the deprecated entity, got: #{inspect(value)}"
end
defp validate_doc_meta(:delegate_to, value) do
case value do
{m, f, a} when is_atom(m) and is_atom(f) and is_integer(a) and a >= 0 ->
:ok
_ ->
raise ArgumentError,
":delegate_to is a built-in documentation metadata key. It should be a three-element " <>
"tuple in the form of {module, function, arity}, got: #{inspect(value)}"
end
end
defp validate_doc_meta(_, _), do: :ok
defp get_doc_info(table, env) do
+10 -28
View File
@@ -4,7 +4,7 @@
#
# ## Implementation
#
# The implementation uses ETS to track all dependencies
# The implementation uses ets to track all dependencies
# resembling a graph. The keys and what they point to are:
#
# * `:reattach` points to `{name, arity}`
@@ -18,9 +18,9 @@ defmodule Module.LocalsTracker do
@doc """
Adds and tracks defaults for a definition into the tracker.
"""
def add_defaults({_set, bag}, _kind, {name, arity} = pair, defaults, meta) do
def add_defaults({_set, bag}, _kind, {name, arity} = pair, defaults) do
for i <- :lists.seq(arity - defaults, arity - 1) do
put_edge(bag, {:local, {name, i}}, {pair, get_line(meta)})
put_edge(bag, {:local, {name, i}}, pair)
end
:ok
@@ -29,9 +29,9 @@ defmodule Module.LocalsTracker do
@doc """
Adds a local dispatch from-to the given target.
"""
def add_local({_set, bag}, from, to, meta) when is_tuple(from) and is_tuple(to) do
def add_local({_set, bag}, from, to) when is_tuple(from) and is_tuple(to) do
if from != to do
put_edge(bag, {:local, from}, {to, get_line(meta)})
put_edge(bag, {:local, from}, to)
end
:ok
@@ -56,14 +56,14 @@ defmodule Module.LocalsTracker do
@doc """
Reattach a previously yanked node.
"""
def reattach({_set, bag}, tuple, _kind, function, out_neighbours, meta) do
for out_neighbour <- out_neighbours do
put_edge(bag, {:local, function}, out_neighbour)
def reattach({_set, bag}, tuple, _kind, function, out_neigh) do
for to <- out_neigh do
put_edge(bag, {:local, function}, to)
end
# Make a call from the old function to the new one
if function != tuple do
put_edge(bag, {:local, function}, {tuple, get_line(meta)})
put_edge(bag, {:local, function}, tuple)
end
# Finally marked the new one as reattached
@@ -98,19 +98,6 @@ defmodule Module.LocalsTracker do
{unreachable(reachable, reattached, private), collect_warnings(reachable, private)}
end
@doc """
Collect undefined functions based on local calls and existing definitions
"""
def collect_undefined_locals({set, bag}, all_defined) do
undefined =
for {pair, _, _, _} <- all_defined,
{local, line} <- out_neighbours(bag, {:local, pair}),
not :ets.member(set, {:def, local}),
do: {build_meta(line), local}
:lists.usort(undefined)
end
defp unreachable(reachable, reattached, private) do
for {tuple, kind, _, _} <- private,
not reachable?(tuple, kind, reachable, reattached),
@@ -183,7 +170,7 @@ defmodule Module.LocalsTracker do
defp reachable_from(bag, local, vertices) do
vertices = Map.put(vertices, local, true)
Enum.reduce(out_neighbours(bag, {:local, local}), vertices, fn {local, _line}, acc ->
Enum.reduce(out_neighbours(bag, {:local, local}), vertices, fn {_, _} = local, acc ->
case acc do
%{^local => true} -> acc
_ -> reachable_from(bag, local, acc)
@@ -191,11 +178,6 @@ defmodule Module.LocalsTracker do
end)
end
defp get_line(meta), do: Keyword.get(meta, :line)
defp build_meta(nil), do: []
defp build_meta(line), do: [line: line]
## Lightweight digraph implementation
defp put_edge(d, from, to) do
+30 -68
View File
@@ -1,23 +1,6 @@
defmodule OptionParser do
@moduledoc """
Functions for parsing command line options.
The main function in this module is `parse/2`, which allows
developers to parse a list of arguments into options:
iex> OptionParser.parse(["--debug"], strict: [debug: :boolean])
{[debug: true], [], []}
`OptionParser` provides some conveniences out of the box,
such as aliases and automatic handling of negation switches.
The `parse_head/2` function is an alternative to `parse/2`
which stops parsing as soon as it finds a value that is not
a switch nor a value for a previous switch.
This module also provides low-level functions, such as `next/2`,
for parsing switches manually, as well as `split/1` and `to_argv/1`
for parsing from and converting switches to strings.
This module contains functions to parse command line options.
"""
@type argv :: [String.t()]
@@ -57,10 +40,8 @@ defmodule OptionParser do
iex> OptionParser.parse(["--source", "lib"], strict: [source: :string])
{[source: "lib"], [], []}
iex> OptionParser.parse(
...> ["--source-path", "lib", "test/enum_test.exs", "--verbose"],
...> strict: [source_path: :string, verbose: :boolean]
...> )
iex> OptionParser.parse(["--source-path", "lib", "test/enum_test.exs", "--verbose"],
...> strict: [source_path: :string, verbose: :boolean])
{[source_path: "lib", verbose: true], ["test/enum_test.exs"], []}
We will explore the valid switches and operation modes of option parser below.
@@ -82,9 +63,10 @@ defmodule OptionParser do
* `:switches` - defines some switches and their types. This function
still attempts to parse switches that are not in this list.
Both these options accept a keyword list where the key is an atom
defining the name of the switch and value is the `type` of the
switch (see the "Types" section below for more information).
Both these options accept a keyword list of `{name, type}` tuples where `name`
is an atom defining the name of the switch and `type` is an atom that
specifies the type for the value of this switch (see the "Types" section below
for the possible types and more information about type casting).
Note that you should only supply the `:switches` or the `:strict` option.
If you supply both, an `ArgumentError` exception will be raised.
@@ -183,10 +165,8 @@ defmodule OptionParser do
iex> OptionParser.parse(["--unlock", "path/to/file"], strict: [unlock: :boolean])
{[unlock: true], ["path/to/file"], []}
iex> OptionParser.parse(
...> ["--unlock", "--limit", "0", "path/to/file"],
...> strict: [unlock: :boolean, limit: :integer]
...> )
iex> OptionParser.parse(["--unlock", "--limit", "0", "path/to/file"],
...> strict: [unlock: :boolean, limit: :integer])
{[unlock: true, limit: 0], ["path/to/file"], []}
iex> OptionParser.parse(["--limit", "3"], strict: [limit: :integer])
@@ -204,16 +184,11 @@ defmodule OptionParser do
iex> OptionParser.parse(["--unknown", "xyz"], strict: [])
{[], ["xyz"], [{"--unknown", nil}]}
iex> OptionParser.parse(
...> ["--limit", "3", "--unknown", "xyz"],
...> switches: [limit: :integer]
...> )
iex> OptionParser.parse(["--limit", "3", "--unknown", "xyz"],
...> switches: [limit: :integer])
{[limit: 3, unknown: "xyz"], [], []}
iex> OptionParser.parse(
...> ["--unlock", "path/to/file", "--unlock", "path/to/another/file"],
...> strict: [unlock: :keep]
...> )
iex> OptionParser.parse(["--unlock", "path/to/file", "--unlock", "path/to/another/file"], strict: [unlock: :keep])
{[unlock: "path/to/file", unlock: "path/to/another/file"], [], []}
"""
@@ -244,17 +219,14 @@ defmodule OptionParser do
** (OptionParser.ParseError) 1 error found!
--unknown : Unknown option
iex> OptionParser.parse!(
...> ["-l", "xyz", "-f", "bar"],
...> switches: [limit: :integer, foo: :integer],
...> aliases: [l: :limit, f: :foo]
...> )
iex> OptionParser.parse!(["-l", "xyz", "-f", "bar"],
...> switches: [limit: :integer, foo: :integer], aliases: [l: :limit, f: :foo])
** (OptionParser.ParseError) 2 errors found!
-l : Expected type integer, got "xyz"
-f : Expected type integer, got "bar"
"""
@spec parse!(argv, options) :: {parsed, argv}
@spec parse!(argv, options) :: {parsed, argv} | no_return
def parse!(argv, opts \\ []) when is_list(argv) and is_list(opts) do
case parse(argv, opts) do
{parsed, args, []} -> {parsed, args}
@@ -270,16 +242,12 @@ defmodule OptionParser do
## Example
iex> OptionParser.parse_head(
...> ["--source", "lib", "test/enum_test.exs", "--verbose"],
...> switches: [source: :string, verbose: :boolean]
...> )
iex> OptionParser.parse_head(["--source", "lib", "test/enum_test.exs", "--verbose"],
...> switches: [source: :string, verbose: :boolean])
{[source: "lib"], ["test/enum_test.exs", "--verbose"], []}
iex> OptionParser.parse_head(
...> ["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
...> switches: [source: :string, verbose: :boolean, unlock: :boolean]
...> )
iex> OptionParser.parse_head(["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
...> switches: [source: :string, verbose: :boolean, unlock: :boolean])
{[verbose: true, source: "lib"], ["test/enum_test.exs", "--unlock"], []}
"""
@@ -299,29 +267,23 @@ defmodule OptionParser do
## Examples
iex> OptionParser.parse_head!(
...> ["--source", "lib", "path/to/file", "--verbose"],
...> switches: [source: :string, verbose: :boolean]
...> )
iex> OptionParser.parse_head!(["--source", "lib", "path/to/file", "--verbose"],
...> switches: [source: :string, verbose: :boolean])
{[source: "lib"], ["path/to/file", "--verbose"]}
iex> OptionParser.parse_head!(
...> ["--number", "lib", "test/enum_test.exs", "--verbose"],
...> strict: [number: :integer]
...> )
iex> OptionParser.parse_head!(["--number", "lib", "test/enum_test.exs", "--verbose"],
...> strict: [number: :integer])
** (OptionParser.ParseError) 1 error found!
--number : Expected type integer, got "lib"
iex> OptionParser.parse_head!(
...> ["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
...> strict: [verbose: :integer, source: :integer]
...> )
iex> OptionParser.parse_head!(["--verbose", "--source", "lib", "test/enum_test.exs", "--unlock"],
...> strict: [verbose: :integer, source: :integer])
** (OptionParser.ParseError) 2 errors found!
--verbose : Missing argument of type integer
--source : Expected type integer, got "lib"
"""
@spec parse_head!(argv, options) :: {parsed, argv}
@spec parse_head!(argv, options) :: {parsed, argv} | no_return
def parse_head!(argv, opts \\ []) when is_list(argv) and is_list(opts) do
case parse_head(argv, opts) do
{parsed, args, []} -> {parsed, args}
@@ -485,7 +447,7 @@ defmodule OptionParser do
It is advised to pass to `to_argv/2` the same set of `options`
given to `parse/2`. Some switches can only be reconstructed
correctly with the `:switches` information in hand.
correctly with the `switches` information in hand.
## Examples
@@ -495,7 +457,7 @@ defmodule OptionParser do
["--bool", "--no-bool"]
Some switches will output different values based on the switches
types:
flag:
iex> OptionParser.to_argv([number: 2], switches: [])
["--number", "2"]
@@ -504,8 +466,8 @@ defmodule OptionParser do
"""
@spec to_argv(Enumerable.t(), options) :: argv
def to_argv(enum, options \\ []) do
switches = Keyword.get(options, :switches, [])
def to_argv(enum, opts \\ []) do
switches = Keyword.get(opts, :switches, [])
Enum.flat_map(enum, fn
{_key, nil} -> []
+8 -14
View File
@@ -12,7 +12,7 @@ defmodule Path do
that require it (like `wildcard/2` and `expand/1`).
"""
@type t :: IO.chardata()
@type t :: :unicode.chardata()
@doc """
Converts the given path to an absolute one. Unlike
@@ -30,16 +30,15 @@ defmodule Path do
### Windows
Path.absname("foo")
Path.absname("foo").
#=> "D:/usr/local/foo"
Path.absname("../x")
Path.absname("../x").
#=> "D:/usr/local/../x"
"""
@spec absname(t) :: binary
def absname(path) do
absname(path, File.cwd!())
absname(path, System.cwd!())
end
@doc """
@@ -151,7 +150,7 @@ defmodule Path do
"""
@spec expand(t) :: binary
def expand(path) do
expand_dot(absname(expand_home(path), File.cwd!()))
expand_dot(absname(expand_home(path), System.cwd!()))
end
@doc """
@@ -172,15 +171,14 @@ defmodule Path do
#=> "/quux/baz/foo/bar"
Path.expand("foo/bar/../bar", "/baz")
#=> "/baz/foo/bar"
"/baz/foo/bar"
Path.expand("/foo/bar/../bar", "/baz")
#=> "/foo/bar"
"/foo/bar"
"""
@spec expand(t, t) :: binary
def expand(path, relative_to) do
expand_dot(absname(absname(expand_home(path), expand_home(relative_to)), File.cwd!()))
expand_dot(absname(absname(expand_home(path), expand_home(relative_to)), System.cwd!()))
end
@doc """
@@ -618,10 +616,6 @@ defmodule Path do
exactly the same character in the same position will match. Note
that matching is case-sensitive: `"a"` will not match `"A"`.
Directory separators must always be written as `/`, even on Windows.
You may call `Path.expand/1` to normalize the path before invoking
this function.
By default, the patterns `*` and `?` do not match files starting
with a dot `.`. See the `:match_dot` option in the "Options" section
below.
+10 -14
View File
@@ -127,11 +127,11 @@ defmodule Port do
While most UNIX command line tools will exit once its communication channels
are closed, not all command line applications will do so. While we encourage
graceful termination by detecting if stdin/stdout has been closed, we do not
always have control over how third-party software terminates. In those cases,
always have control over how 3rd party software terminates. In those cases,
you can wrap the application in a script that checks for stdin. Here is such
script in Bash:
script in bash:
#!/bin/bash
#!/bin/sh
"$@" &
pid=$!
while read line ; do
@@ -141,17 +141,13 @@ defmodule Port do
Now instead of:
Port.open(
{:spawn_executable, "/path/to/program"},
args: ["a", "b", "c"]
)
Port.open({:spawn_executable, "/path/to/program"},
[args: ["a", "b", "c"]])
You may invoke:
Port.open(
{:spawn_executable, "/path/to/wrapper"},
args: ["/path/to/program", "a", "b", "c"]
)
Port.open({:spawn_executable, "/path/to/wrapper"},
[args: ["/path/to/program", "a", "b", "c"]])
"""
@@ -265,12 +261,12 @@ defmodule Port do
or `{name, node}` (when monitoring by a port name);
* `reason` is the exit reason.
See `:erlang.monitor/2` for more information.
See `:erlang.monitor/2` for more info.
Inlined by the compiler.
"""
@doc since: "1.6.0"
@spec monitor(port | {name, node} | name) :: reference when name: atom
@spec monitor(port | {name :: atom, node :: atom} | name :: atom) :: reference
def monitor(port) do
:erlang.monitor(:port, port)
end
@@ -282,7 +278,7 @@ defmodule Port do
obtained by calling `monitor/1`, that monitoring is turned off.
If the monitoring is already turned off, nothing happens.
See `:erlang.demonitor/2` for more information.
See `:erlang.demonitor/2` for more info.
Inlined by the compiler.
"""
+44 -149
View File
@@ -14,19 +14,11 @@ defmodule Process do
While this module provides low-level conveniences to work with processes,
developers typically use abstractions such as `Agent`, `GenServer`,
`Registry`, `Supervisor` and `Task` for building their systems and
`Registry`, `Supervisor` and `Task` for building their systems and
resort to this module for gathering information, trapping exits, links
and monitoring.
"""
@typedoc """
A process destination.
A remote or local PID, a local port, a locally registered name, or a tuple in
the form of `{registered_name, node}` for a registered name at another node.
"""
@type dest :: pid | port | (registered_name :: atom) | {registered_name :: atom, node}
@doc """
Tells whether the given process is alive on the local node.
@@ -38,6 +30,15 @@ defmodule Process do
Inlined by the compiler.
"""
@typedoc """
A process destination.
A remote or local PID, a local port, a locally registered name, or a tuple in
the form of `{registered_name, node}` for a registered name at another node.
"""
@type dest :: pid | port | registered_name :: atom | {registered_name :: atom, node}
@spec alive?(pid) :: boolean
defdelegate alive?(pid), to: :erlang, as: :is_process_alive
@@ -52,17 +53,6 @@ defmodule Process do
@doc """
Returns the value for the given `key` in the process dictionary,
or `default` if `key` is not set.
## Examples
# Assuming :locale was not set
iex> Process.get(:locale, "pt")
"pt"
iex> Process.put(:locale, "fr")
nil
iex> Process.get(:locale, "pt")
"fr"
"""
@spec get(term, default :: term) :: term
def get(key, default \\ nil) do
@@ -76,17 +66,6 @@ defmodule Process do
Returns all keys in the process dictionary.
Inlined by the compiler.
## Examples
# Assuming :locale was not set
iex> :locale in Process.get_keys()
false
iex> Process.put(:locale, "pt")
nil
iex> :locale in Process.get_keys()
true
"""
@spec get_keys() :: [term]
defdelegate get_keys(), to: :erlang
@@ -103,15 +82,15 @@ defmodule Process do
Stores the given `key`-`value` pair in the process dictionary.
The return value of this function is the value that was previously stored
under `key`, or `nil` in case no value was stored under it.
under `key`, or `nil` in case no value was stored under `key`.
## Examples
# Assuming :locale was not set
iex> Process.put(:locale, "en")
nil
iex> Process.put(:locale, "fr")
"en"
Process.put(:locale, "en")
#=> nil
Process.put(:locale, "fr")
#=> "en"
"""
@spec put(term, term) :: term | nil
@@ -127,11 +106,11 @@ defmodule Process do
## Examples
iex> Process.put(:comments, ["comment", "other comment"])
iex> Process.delete(:comments)
["comment", "other comment"]
iex> Process.delete(:comments)
nil
Process.put(:comments, ["comment", "other comment"])
Process.delete(:comments)
#=> ["comment", "other comment"]
Process.delete(:comments)
#=> nil
"""
@spec delete(term) :: term | nil
@@ -191,10 +170,10 @@ defmodule Process do
In other words, **do not**:
Task.start_link(fn ->
Task.start_link fn ->
do_something()
...
end)
end
# Wait until work is done
Process.sleep(2000)
@@ -202,18 +181,16 @@ defmodule Process do
But **do**:
parent = self()
Task.start_link(fn ->
Task.start_link fn ->
do_something()
send(parent, :work_is_done)
send parent, :work_is_done
...
end)
end
receive do
:work_is_done -> :ok
after
# Optional timeout
30_000 -> :timeout
30_000 -> :timeout # Optional timeout
end
For cases like the one above, `Task.async/1` and `Task.await/2` are
@@ -222,9 +199,9 @@ defmodule Process do
Similarly, if you are waiting for a process to terminate,
monitor that process instead of sleeping. **Do not**:
Task.start_link(fn ->
Task.start_link fn ->
...
end)
end
# Wait until task terminates
Process.sleep(2000)
@@ -232,17 +209,15 @@ defmodule Process do
Instead **do**:
{:ok, pid} =
Task.start_link(fn ->
Task.start_link fn ->
...
end)
end
ref = Process.monitor(pid)
receive do
{:DOWN, ^ref, _, _, _} -> :task_is_down
after
# Optional timeout
30_000 -> :timeout
30_000 -> :timeout # Optional timeout
end
"""
@@ -293,9 +268,6 @@ defmodule Process do
which is looked up at the time of delivery. No error is produced if the name does
not refer to a process.
The message is not sent immediately. Therefore, `dest` can receive other messages
in-between even when `time` is `0`.
This function returns a timer reference, which can be read with `read_timer/1`
or canceled with `cancel_timer/1`.
@@ -401,14 +373,6 @@ defmodule Process do
check `:erlang.spawn_opt/4`.
Inlined by the compiler.
## Examples
Process.spawn(fn -> 1 + 2 end, [:monitor])
#=> {#PID<0.93.0>, #Reference<0.18808174.1939079169.202418>}
Process.spawn(fn -> 1 + 2 end, [:link])
#=> #PID<0.95.0>
"""
@spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}
defdelegate spawn(fun, opts), to: :erlang, as: :spawn_opt
@@ -448,26 +412,12 @@ defmodule Process do
If the process is already dead when calling `Process.monitor/1`, a
`:DOWN` message is delivered immediately.
See [the need for monitoring](https://elixir-lang.org/getting-started/mix-otp/genserver.html#the-need-for-monitoring)
for an example. See `:erlang.monitor/2` for more information.
See [the need for monitoring](http://elixir-lang.org/getting-started/mix-otp/genserver.html#the-need-for-monitoring)
for an example. See `:erlang.monitor/2` for more info.
Inlined by the compiler.
## Examples
pid = spawn(fn -> 1 + 2 end)
#=> #PID<0.118.0>
Process.monitor(pid)
#=> #Reference<0.906660723.3006791681.40191>
Process.exit(pid, :kill)
#=> true
receive do
msg -> msg
end
#=> {:DOWN, #Reference<0.906660723.3006791681.40191>, :process, #PID<0.118.0>, :noproc}
"""
@spec monitor(pid | {name, node} | name) :: reference when name: atom
@spec monitor(pid | {name :: atom, node :: atom} | name :: atom) :: reference
def monitor(item) do
:erlang.monitor(:process, item)
end
@@ -479,17 +429,9 @@ defmodule Process do
obtained by calling `monitor/1`, that monitoring is turned off.
If the monitoring is already turned off, nothing happens.
See `:erlang.demonitor/2` for more information.
See `:erlang.demonitor/2` for more info.
Inlined by the compiler.
## Examples
pid = spawn(fn -> 1 + 2 end)
ref = Process.monitor(pid)
Process.demonitor(ref)
#=> true
"""
@spec demonitor(reference, options :: [:flush | :info]) :: boolean
defdelegate demonitor(monitor_ref, options \\ []), to: :erlang
@@ -502,15 +444,9 @@ defmodule Process do
alive. This means that for such process, `alive?/1` will return `false` but
its PID will be part of the list of PIDs returned by this function.
See `:erlang.processes/0` for more information.
See `:erlang.processes/0` for more info.
Inlined by the compiler.
## Examples
Process.list()
#=> [#PID<0.0.0>, #PID<0.1.0>, #PID<0.2.0>, #PID<0.3.0>, ...]
"""
@spec list() :: [pid]
defdelegate list(), to: :erlang, as: :processes
@@ -533,7 +469,7 @@ defmodule Process do
emit an exit signal to all its other linked processes. The behaviour when
`pid1` is trapping exits is described in `exit/2`.
See `:erlang.link/1` for more information.
See `:erlang.link/1` for more info.
Inlined by the compiler.
"""
@@ -549,7 +485,7 @@ defmodule Process do
The return value of this function is always `true`.
See `:erlang.unlink/1` for more information.
See `:erlang.unlink/1` for more info.
Inlined by the compiler.
"""
@@ -576,15 +512,6 @@ defmodule Process do
* `true`
* `:undefined`
## Examples
Process.register(self(), :test)
#=> true
send(:test, :hello)
#=> :hello
send(:wrong_name, :hello)
#=> ** (ArgumentError) argument error
"""
@spec register(pid | port, atom) :: true
def register(pid_or_port, name)
@@ -612,16 +539,6 @@ defmodule Process do
to any PID or port.
Inlined by the compiler.
## Examples
Process.register(self(), :test)
#=> true
Process.unregister(:test)
#=> true
Process.unregister(:wrong_name)
#=> ** (ArgumentError) argument error
"""
@spec unregister(atom) :: true
defdelegate unregister(name), to: :erlang
@@ -630,16 +547,7 @@ defmodule Process do
Returns the PID or port identifier registered under `name` or `nil` if the
name is not registered.
See `:erlang.whereis/1` for more information.
## Examples
Process.register(self(), :test)
Process.whereis(:test)
#=> #PID<0.84.0>
Process.whereis(:wrong_name)
#=> nil
See `:erlang.whereis/1` for more info.
"""
@spec whereis(atom) :: pid | port | nil
def whereis(name) do
@@ -650,12 +558,6 @@ defmodule Process do
Returns the PID of the group leader for the calling process.
Inlined by the compiler.
## Examples
Process.group_leader()
#=> #PID<0.53.0>
"""
@spec group_leader() :: pid
defdelegate group_leader(), to: :erlang
@@ -677,13 +579,6 @@ defmodule Process do
Returns a list of names which have been registered using `register/2`.
Inlined by the compiler.
## Examples
Process.register(self(), :test)
Process.registered()
#=> [:test, :elixir_config, :inet_db, ...]
"""
@spec registered() :: [atom]
defdelegate registered(), to: :erlang
@@ -699,7 +594,7 @@ defmodule Process do
Returns the old value of `flag`.
See `:erlang.process_flag/2` for more information.
See `:erlang.process_flag/2` for more info.
Inlined by the compiler.
"""
@@ -726,7 +621,7 @@ defmodule Process do
The allowed values for `flag` are only a subset of those allowed in `flag/2`,
namely `:save_calls`.
See `:erlang.process_flag/3` for more information.
See `:erlang.process_flag/3` for more info.
Inlined by the compiler.
"""
@@ -739,7 +634,7 @@ defmodule Process do
Use this only for debugging information.
See `:erlang.process_info/1` for more information.
See `:erlang.process_info/1` for more info.
"""
@spec info(pid) :: keyword | nil
def info(pid) do
@@ -750,7 +645,7 @@ defmodule Process do
Returns information about the process identified by `pid`,
or returns `nil` if the process is not alive.
See `:erlang.process_info/2` for more information.
See `:erlang.process_info/2` for more info.
"""
@spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil
def info(pid, spec)
@@ -775,7 +670,7 @@ defmodule Process do
which is useful if the process does not expect to receive any messages
in the near future.
See `:erlang.hibernate/3` for more information.
See `:erlang.hibernate/3` for more info.
Inlined by the compiler.
"""
+154 -79
View File
@@ -22,7 +22,7 @@ defmodule Protocol do
type_args = :lists.map(fn _ -> quote(do: term) end, :lists.seq(2, arity))
type_args = [quote(do: t) | type_args]
varify = fn pos -> Macro.var(String.to_atom("arg" <> Integer.to_string(pos)), __MODULE__) end
varify = fn pos -> Macro.var(String.to_atom("var" <> Integer.to_string(pos)), __MODULE__) end
call_args = :lists.map(varify, :lists.seq(2, arity))
call_args = [quote(do: term) | call_args]
@@ -58,7 +58,7 @@ defmodule Protocol do
Returns `:ok` if so, otherwise raises `ArgumentError`.
"""
@spec assert_protocol!(module) :: :ok
@spec assert_protocol!(module) :: :ok | no_return
def assert_protocol!(module) do
assert_protocol!(module, "")
end
@@ -85,7 +85,7 @@ defmodule Protocol do
Returns `:ok` if so, otherwise raises `ArgumentError`.
"""
@spec assert_impl!(module, module) :: :ok
@spec assert_impl!(module, module) :: :ok | no_return
def assert_impl!(protocol, base) do
assert_impl!(protocol, base, "")
end
@@ -168,7 +168,8 @@ defmodule Protocol do
"""
defmacro derive(protocol, module, options \\ []) do
quote do
Protocol.__derive__([{unquote(protocol), unquote(options)}], unquote(module), __ENV__)
module = unquote(module)
Protocol.__derive__([{unquote(protocol), unquote(options)}], module, __ENV__)
end
end
@@ -185,7 +186,7 @@ defmodule Protocol do
## Examples
# Get Elixir's ebin directory path and retrieve all protocols
# Get Elixir's ebin and retrieve all protocols
iex> path = :code.lib_dir(:elixir, :ebin)
iex> mods = Protocol.extract_protocols([path])
iex> Enumerable in mods
@@ -214,7 +215,7 @@ defmodule Protocol do
## Examples
# Get Elixir's ebin directory path and retrieve all protocols
# Get Elixir's ebin and retrieve all protocols
iex> path = :code.lib_dir(:elixir, :ebin)
iex> mods = Protocol.extract_impls(Enumerable, [path])
iex> List in mods
@@ -283,15 +284,15 @@ defmodule Protocol do
are retrieved with the help of `extract_impls/2`.
It returns the updated version of the protocol bytecode.
If the first element of the tuple is `:ok`, it means
the protocol was consolidated.
A given bytecode or protocol implementation can be checked
to be consolidated or not by analyzing the protocol
attribute:
Protocol.consolidated?(Enumerable)
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
nor loads the new bytecode for the compiled module.
However each implementation must be available and
@@ -302,24 +303,30 @@ defmodule Protocol do
| {:error, :not_a_protocol}
| {:error, :no_beam_info}
def consolidate(protocol, types) when is_atom(protocol) do
with {:ok, ast_info, specs, compile_info} <- beam_protocol(protocol),
{:ok, definitions} <- change_debug_info(protocol, ast_info, types),
do: compile(definitions, specs, compile_info)
with {:ok, ast_info, chunks_info} <- beam_protocol(protocol),
{:ok, code} <- change_debug_info(ast_info, types),
do: compile(protocol, code, chunks_info)
end
defp beam_protocol(protocol) do
chunk_ids = [:debug_info, 'Docs', 'ExDp']
chunk_ids = [:abstract_code, :attributes, :compile_info, 'Docs', 'ExDp']
opts = [:allow_missing_chunks]
case :beam_lib.chunks(beam_file(protocol), chunk_ids, opts) do
{:ok, {^protocol, [{:debug_info, debug_info} | chunks]}} ->
{:debug_info_v1, _backend, {:elixir_v1, info, specs}} = debug_info
%{attributes: attributes, definitions: definitions} = info
chunks = :lists.map(fn {name, value} -> {List.to_string(name), value} end, chunks)
{:ok, {^protocol, entries}} ->
[
{:abstract_code, {_raw, abstract_code}},
{:attributes, attributes},
{:compile_info, compile_info} | extra_chunks
] = entries
extra_chunks =
for {name, contents} when is_binary(contents) <- extra_chunks,
do: {List.to_string(name), contents}
case attributes[:protocol] do
[fallback_to_any: any] ->
{:ok, {any, definitions}, specs, {info, chunks}}
{:ok, {protocol, any, abstract_code}, {compile_info, extra_chunks}}
_ ->
{:error, :not_a_protocol}
@@ -339,83 +346,148 @@ defmodule Protocol do
# Change the debug information to the optimized
# impl_for/1 dispatch version.
defp change_debug_info(protocol, {any, definitions}, types) do
defp change_debug_info({protocol, any, code}, types) do
types = if any, do: types, else: List.delete(types, Any)
all = [Any] ++ for {_guard, mod} <- __built_in__(), do: mod
all = [Any] ++ for {_guard, mod} <- __builtin__(), do: mod
structs = types -- all
case List.keytake(definitions, {:__protocol__, 1}, 0) do
{protocol_def, definitions} ->
{impl_for, definitions} = List.keytake(definitions, {:impl_for, 1}, 0)
{struct_impl_for, definitions} = List.keytake(definitions, {:struct_impl_for, 1}, 0)
protocol_def = change_protocol(protocol_def, types)
impl_for = change_impl_for(impl_for, protocol, types)
struct_impl_for = change_struct_impl_for(struct_impl_for, protocol, types, structs)
{:ok, [protocol_def, impl_for, struct_impl_for] ++ definitions}
nil ->
{:error, :not_a_protocol}
case change_impl_for(code, protocol, types, structs, false, []) do
{:ok, ret} -> {:ok, ret}
other -> other
end
end
defp change_protocol({_name, _kind, meta, clauses}, types) do
defp change_impl_for(
[{:function, line, :__protocol__, 1, clauses} | tail],
protocol,
types,
structs,
_,
acc
) do
abstract_types = :erl_parse.abstract(:lists.usort(types))
clauses =
Enum.map(clauses, fn
{meta, [:consolidated?], [], _} -> {meta, [:consolidated?], [], true}
{meta, [:impls], [], _} -> {meta, [:impls], [], {:consolidated, types}}
clause -> clause
{:clause, l, [{:atom, _, :consolidated?}], [], [{:atom, _, _}]} ->
{:clause, l, [{:atom, 0, :consolidated?}], [], [{:atom, 0, true}]}
{:clause, l, [{:atom, _, :impls}], [], [{:atom, _, _}]} ->
tuple = {:tuple, 0, [{:atom, 0, :consolidated}, abstract_types]}
{:clause, l, [{:atom, 0, :impls}], [], [tuple]}
{:clause, _, _, _, _} = c ->
c
end)
{{:__protocol__, 1}, :def, meta, clauses}
acc = [{:function, line, :__protocol__, 1, clauses} | acc]
change_impl_for(tail, protocol, types, structs, true, acc)
end
defp change_impl_for({_name, _kind, meta, _clauses}, protocol, types) do
defp change_impl_for(
[{:function, line, :impl_for, 1, _} | tail],
protocol,
types,
structs,
protocol?,
acc
) do
fallback = if Any in types, do: load_impl(protocol, Any)
line = meta[:line]
clauses =
for {guard, mod} <- __built_in__(),
for {guard, mod} <- __builtin__(),
mod in types,
do: built_in_clause_for(mod, guard, protocol, meta, line)
do: builtin_clause_for(mod, guard, protocol, line)
struct_clause = struct_clause_for(meta, line)
fallback_clause = fallback_clause_for(fallback, protocol, meta)
clauses = [struct_clause] ++ clauses ++ [fallback_clause]
clauses =
[struct_clause_for(line) | clauses] ++ [fallback_clause_for(fallback, protocol, line)]
{{:impl_for, 1}, :def, meta, clauses}
acc = [{:function, line, :impl_for, 1, clauses} | acc]
change_impl_for(tail, protocol, types, structs, protocol?, acc)
end
defp change_struct_impl_for({_name, _kind, meta, _clauses}, protocol, types, structs) do
defp change_impl_for(
[{:function, line, :struct_impl_for, 1, _} | tail],
protocol,
types,
structs,
protocol?,
acc
) do
fallback = if Any in types, do: load_impl(protocol, Any)
clauses = for struct <- structs, do: each_struct_clause_for(struct, protocol, meta)
clauses = clauses ++ [fallback_clause_for(fallback, protocol, meta)]
clauses = for struct <- structs, do: each_struct_clause_for(struct, protocol, line)
clauses = clauses ++ [fallback_clause_for(fallback, protocol, line)]
{{:struct_impl_for, 1}, :defp, meta, clauses}
acc = [{:function, line, :struct_impl_for, 1, clauses} | acc]
change_impl_for(tail, protocol, types, structs, protocol?, acc)
end
defp built_in_clause_for(mod, guard, protocol, meta, line) do
x = quote(line: line, do: x)
guard = quote(line: line, do: :erlang.unquote(guard)(unquote(x)))
body = load_impl(protocol, mod)
{meta, [x], [guard], body}
defp change_impl_for(
[{:attribute, line, :spec, {{:__protocol__, 1}, funspecs}} | tail],
protocol,
types,
structs,
protocol?,
acc
) do
new_specs =
for spec <- funspecs do
case spec do
{:type, line, :fun, [{:type, _, :product, [{:atom, _, :consolidated?}]}, _]} ->
product = {:type, line, :product, [{:atom, 0, :consolidated?}]}
{:type, line, :fun, [product, {:atom, 0, true}]}
{:type, line, :fun, [{:type, _, :product, [{:atom, _, :impls}]}, _]} ->
impls = for mod <- types, do: {:atom, 0, mod}
list = {:type, 0, :list, [{:type, 0, :union, impls}]}
tuple = {:type, 0, :tuple, [{:atom, 0, :consolidated}, list]}
{:type, line, :fun, [{:type, line, :product, [{:atom, 0, :impls}]}, tuple]}
other ->
other
end
end
acc = [{:attribute, line, :spec, {{:__protocol__, 1}, new_specs}} | acc]
change_impl_for(tail, protocol, types, structs, protocol?, acc)
end
defp struct_clause_for(meta, line) do
x = quote(line: line, do: x)
head = quote(line: line, do: %{__struct__: unquote(x)})
guard = quote(line: line, do: :erlang.is_atom(unquote(x)))
body = quote(line: line, do: struct_impl_for(unquote(x)))
{meta, [head], [guard], body}
defp change_impl_for([head | tail], protocol, info, types, protocol?, acc) do
change_impl_for(tail, protocol, info, types, protocol?, [head | acc])
end
defp each_struct_clause_for(struct, protocol, meta) do
{meta, [struct], [], load_impl(protocol, struct)}
defp change_impl_for([], _protocol, _info, _types, protocol?, acc) do
if protocol? do
{:ok, Enum.reverse(acc)}
else
{:error, :not_a_protocol}
end
end
defp fallback_clause_for(value, _protocol, meta) do
{meta, [quote(do: _)], [], value}
defp builtin_clause_for(mod, guard, protocol, line) do
remote = {:remote, line, {:atom, line, :erlang}, {:atom, line, guard}}
guard = {:call, line, remote, [{:var, line, :x}]}
body = {:atom, line, load_impl(protocol, mod)}
{:clause, line, [{:var, line, :x}], [[guard]], [body]}
end
defp struct_clause_for(line) do
map_field_exact = {:map_field_exact, line, {:atom, line, :__struct__}, {:var, line, :x}}
arg = {:map, line, [map_field_exact]}
is_atom = {:remote, line, {:atom, line, :erlang}, {:atom, line, :is_atom}}
guard = {:call, line, is_atom, [{:var, line, :x}]}
body = {:call, line, {:atom, line, :struct_impl_for}, [{:var, line, :x}]}
{:clause, line, [arg], [[guard]], [body]}
end
defp each_struct_clause_for(struct, protocol, line) do
{:clause, line, [{:atom, line, struct}], [], [{:atom, line, load_impl(protocol, struct)}]}
end
defp fallback_clause_for(value, _protocol, line) do
{:clause, line, [{:var, line, :_}], [], [{:atom, line, value}]}
end
defp load_impl(protocol, for) do
@@ -423,9 +495,11 @@ defmodule Protocol do
end
# Finally compile the module and emit its bytecode.
defp compile(definitions, specs, {info, chunks}) do
info = %{info | definitions: definitions}
{:ok, :elixir_erl.consolidate(info, specs, chunks)}
defp compile(protocol, code, {compile_info, extra_chunks}) do
opts = Keyword.take(compile_info, [:source])
opts = if Code.compiler_options()[:debug_info], do: [:debug_info | opts], else: opts
{:ok, ^protocol, binary, _warnings} = :compile.forms(code, [:return | opts])
{:ok, :elixir_erl.add_beam_chunks(binary, extra_chunks)}
end
## Definition callbacks
@@ -467,7 +541,7 @@ defmodule Protocol do
end
defp after_defprotocol do
quote bind_quoted: [built_in: __built_in__()] do
quote bind_quoted: [builtin: __builtin__()] do
any_impl_for =
if @fallback_to_any do
quote do: unquote(__MODULE__.Any).__impl__(:target)
@@ -475,10 +549,6 @@ defmodule Protocol do
nil
end
# Disable dialyzer checks - before and after consolidation
# the types could be more strict
@dialyzer {:nowarn_function, __protocol__: 1, impl_for: 1, impl_for!: 1}
@doc false
@spec impl_for(term) :: atom | nil
Kernel.def(impl_for(data))
@@ -487,7 +557,7 @@ defmodule Protocol do
#
# It simply delegates to struct_impl_for which is then
# optimized during protocol consolidation.
Kernel.def impl_for(%struct{}) do
Kernel.def impl_for(%{__struct__: struct}) when :erlang.is_atom(struct) do
struct_impl_for(struct)
end
@@ -504,7 +574,7 @@ defmodule Protocol do
end
end
end,
built_in
builtin
)
# Define a catch-all impl_for/1 clause to pacify Dialyzer (since
@@ -554,8 +624,8 @@ defmodule Protocol do
@doc false
@spec __protocol__(:module) :: __MODULE__
@spec __protocol__(:functions) :: unquote(Protocol.__functions_spec__(@functions))
@spec __protocol__(:consolidated?) :: boolean
@spec __protocol__(:impls) :: :not_consolidated | {:consolidated, [module]}
@spec __protocol__(:consolidated?) :: false
@spec __protocol__(:impls) :: :not_consolidated
Kernel.def(__protocol__(:module), do: __MODULE__)
Kernel.def(__protocol__(:functions), do: unquote(:lists.sort(@functions)))
Kernel.def(__protocol__(:consolidated?), do: false)
@@ -618,7 +688,12 @@ defmodule Protocol do
@doc false
def __derive__(derives, for, %Macro.Env{} = env) when is_atom(for) do
struct = Macro.struct!(for, env)
struct =
if for == env.module do
Module.get_attribute(for, :struct) || raise "struct is not defined for #{inspect(for)}"
else
for.__struct__
end
foreach = fn
proto when is_atom(proto) ->
@@ -685,7 +760,7 @@ defmodule Protocol do
## Helpers
@doc false
def __built_in__ do
def __builtin__ do
[
is_tuple: Tuple,
is_atom: Atom,
+4 -35
View File
@@ -2,8 +2,8 @@ defmodule Range do
@moduledoc """
Defines a range.
A range represents a sequence of one or many,
ascending or descending, consecutive integers.
A range represents a discrete number of values where
the first and last values are integers.
Ranges can be either increasing (`first <= last`) or
decreasing (`first > last`). Ranges are also always
@@ -36,16 +36,12 @@ defmodule Range do
iex> Enum.member?(range, 8)
true
Such function calls are efficient memory-wise no matter the
size of the range. The implementation of the `Enumerable`
protocol uses logic based solely on the endpoints and does
not materialize the whole list of integers.
"""
defstruct first: nil, last: nil
@type t :: %__MODULE__{first: integer, last: integer}
@type t(first, last) :: %__MODULE__{first: first, last: last}
@type t :: %Range{first: integer, last: integer}
@type t(first, last) :: %Range{first: first, last: last}
@doc """
Creates a new range.
@@ -61,33 +57,6 @@ defmodule Range do
"got: #{inspect(first)}..#{inspect(last)}"
end
@doc """
Checks if two ranges are disjoint.
## Examples
iex> Range.disjoint?(1..5, 6..9)
true
iex> Range.disjoint?(5..1, 6..9)
true
iex> Range.disjoint?(1..5, 5..9)
false
iex> Range.disjoint?(1..5, 2..7)
false
"""
@doc since: "1.8.0"
@spec disjoint?(t, t) :: boolean
def disjoint?(first1..last1, first2..last2) do
{first1, last1} = normalize(first1, last1)
{first2, last2} = normalize(first2, last2)
last2 < first1 or last1 < first2
end
@compile inline: [normalize: 2]
defp normalize(first, last) when first > last, do: {last, first}
defp normalize(first, last), do: {first, last}
# TODO: Remove by 2.0
@doc false
@deprecated "Pattern match on first..last instead"
+65 -108
View File
@@ -28,10 +28,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}"
@type user :: record(:user, name: String.t, age: integer)
# expands to: "@type user :: {:user, String.t, integer}"
end
"""
@@ -62,11 +62,11 @@ defmodule Record do
* `:includes` - (a list of directories as binaries) if the record being
extracted depends on relative includes, this option allows developers
to specify the directory where those relative includes exist.
to specify the directory those relative includes exist
* `:macros` - (keyword list of macro names and values) if the record
being extracted depends on the values of macros, this option allows
the value of those macros to be set.
being extract depends on the values of macros, this option allows
the value of those macros to be set
These options are expected to be literals (including the binary values) at
compile time.
@@ -74,21 +74,10 @@ defmodule Record do
## Examples
iex> Record.extract(:file_info, from_lib: "kernel/include/file.hrl")
[
size: :undefined,
type: :undefined,
access: :undefined,
atime: :undefined,
mtime: :undefined,
ctime: :undefined,
mode: :undefined,
links: :undefined,
major_device: :undefined,
minor_device: :undefined,
inode: :undefined,
uid: :undefined,
gid: :undefined
]
[size: :undefined, type: :undefined, access: :undefined, atime: :undefined,
mtime: :undefined, ctime: :undefined, mode: :undefined, links: :undefined,
major_device: :undefined, minor_device: :undefined, inode: :undefined,
uid: :undefined, gid: :undefined]
"""
@spec extract(name :: atom, keyword) :: keyword
@@ -112,7 +101,6 @@ defmodule Record do
that contains the record definitions to extract; with this option, this
function uses the same path lookup used by the `-include` attribute used in
Erlang modules.
* `:from_lib` - (binary representing a path to a file) path to the Erlang
file that contains the record definitions to extract; with this option,
this function uses the same path lookup used by the `-include_lib`
@@ -187,7 +175,7 @@ defmodule Record do
defmodule User do
require Record
Record.defrecord(:user, name: "meg", age: "25")
Record.defrecord :user, [name: "meg", age: "25"]
end
In the example above, a set of macros named `user` but with different
@@ -227,7 +215,7 @@ defmodule Record do
defmodule User do
require Record
Record.defrecord(:user, Customer, name: nil)
Record.defrecord :user, Customer, name: nil
end
require User
@@ -240,7 +228,7 @@ defmodule Record do
a record after extracting it from an Erlang library that uses anonymous
functions for defaults.
Record.defrecord(:my_rec, Record.extract(...))
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>.
@@ -249,25 +237,14 @@ defmodule Record do
defmodule MyRec do
require Record
Record.defrecord(:my_rec, Record.extract(...) |> Keyword.merge(fun_field: &__MODULE__.foo/2))
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
defined_arity =
Enum.find(0..2, fn arity ->
Module.defines?(__MODULE__, {name, arity})
end)
if defined_arity do
raise ArgumentError,
"cannot define record #{inspect(name)} because a definition #{name}/#{defined_arity} already exists"
end
tag = tag || name
fields = Record.__fields__(:defrecord, kv)
defmacro unquote(name)(args \\ []) do
@@ -285,18 +262,7 @@ defmodule Record do
"""
defmacro defrecordp(name, tag \\ nil, kv) do
quote bind_quoted: [name: name, tag: tag, kv: kv] do
defined_arity =
Enum.find(0..2, fn arity ->
Module.defines?(__MODULE__, {name, arity})
end)
if defined_arity do
raise ArgumentError,
"cannot define record #{inspect(name)} because a definition #{name}/#{defined_arity} already exists"
end
tag = tag || name
fields = Record.__fields__(:defrecordp, kv)
defmacrop unquote(name)(args \\ []) do
@@ -379,30 +345,38 @@ defmodule Record do
# Gets the index of field.
defp index(tag, fields, field) do
find_index(fields, field, 1) ||
if index = find_index(fields, field, 0) do
# Convert to Elixir index
index - 1
else
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(field)}"
end
end
# Creates a new record with the given default fields and keyword values.
defp create(tag, fields, keyword, caller) do
# Using {} here is safe, since it's not valid AST
default = if Macro.Env.in_match?(caller), do: {:_, [], nil}, else: {}
{default, keyword} = Keyword.pop(keyword, :_, default)
in_match = Macro.Env.in_match?(caller)
keyword = apply_underscore(fields, keyword)
{elements, remaining} =
Enum.map_reduce(fields, keyword, fn {key, field_default}, remaining ->
case Keyword.pop(remaining, key, default) do
{{}, remaining} -> {Macro.escape(field_default), remaining}
{default, remaining} -> {default, remaining}
end
{match, remaining} =
Enum.map_reduce(fields, keyword, fn {field, default}, each_keyword ->
new_fields =
case Keyword.fetch(each_keyword, field) do
{:ok, value} -> value
:error when in_match -> {:_, [], nil}
:error -> Macro.escape(default)
end
{new_fields, Keyword.delete(each_keyword, field)}
end)
case remaining do
[] ->
quote(do: {unquote(tag), unquote_splicing(elements)})
{:{}, [], [tag | match]}
[{key, _} | _] ->
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
_ ->
keys = for {key, _} <- remaining, do: key
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(hd(keys))}"
end
end
@@ -412,65 +386,35 @@ defmodule Record do
raise ArgumentError, "cannot invoke update style macro inside match"
end
if Keyword.has_key?(keyword, :_) do
message = "updating a record with a default (:_) is equivalent to creating a new record"
IO.warn(message, Macro.Env.stacktrace(caller))
create(tag, fields, keyword, caller)
else
case build_updates(keyword, fields, [], [], []) do
{updates, [], []} ->
build_update(updates, var)
keyword = apply_underscore(fields, keyword)
{updates, vars, exprs} ->
quote do
{unquote_splicing(:lists.reverse(vars))} = {unquote_splicing(:lists.reverse(exprs))}
unquote(build_update(updates, var))
end
Enum.reduce(keyword, var, fn {key, value}, acc ->
index = find_index(fields, key, 0)
{:error, key} ->
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
if index do
quote do
:erlang.setelement(unquote(index), unquote(acc), unquote(value))
end
else
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
end
end
end
defp build_update(updates, initial) do
updates
|> Enum.sort(fn {left, _}, {right, _} -> right <= left end)
|> Enum.reduce(initial, fn {key, value}, acc ->
quote(do: :erlang.setelement(unquote(key), unquote(acc), unquote(value)))
end)
end
defp build_updates([{key, value} | rest], fields, updates, vars, exprs) do
if index = find_index(fields, key, 2) do
if simple_argument?(value) do
build_updates(rest, fields, [{index, value} | updates], vars, exprs)
else
var = Macro.var(key, __MODULE__)
build_updates(rest, fields, [{index, var} | updates], [var | vars], [value | exprs])
end
else
{:error, key}
end
end
defp build_updates([], _fields, updates, vars, exprs), do: {updates, vars, exprs}
defp simple_argument?({name, _, ctx}) when is_atom(name) and is_atom(ctx), do: true
defp simple_argument?(other), do: Macro.quoted_literal?(other)
# Gets a record key from the given var.
defp get(tag, fields, var, key) do
index =
find_index(fields, key, 2) ||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
index = find_index(fields, key, 0)
quote do
:erlang.element(unquote(index), unquote(var))
if index do
quote do
:erlang.element(unquote(index), unquote(var))
end
else
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(key)}"
end
end
defp find_index([{k, _} | _], k, i), do: i
defp find_index([{k, _} | _], k, i), do: i + 2
defp find_index([{_, _} | t], k, i), do: find_index(t, k, i + 1)
defp find_index([], _k, _i), do: nil
@@ -502,4 +446,17 @@ defmodule Record do
defp join_keyword([], [], acc), do: :lists.reverse(acc)
defp join_keyword(rest_fields, _rest_values, acc), do: length(acc) + length(rest_fields)
defp apply_underscore(fields, keyword) do
case Keyword.fetch(keyword, :_) do
{:ok, default} ->
fields
|> Enum.map(fn {k, _} -> {k, default} end)
|> Keyword.merge(keyword)
|> Keyword.delete(:_)
:error ->
keyword
end
end
end
+13 -8
View File
@@ -7,7 +7,7 @@ defmodule Regex do
in the [`:re` module documentation](http://www.erlang.org/doc/man/re.html).
Regular expressions in Elixir can be created using the sigils
`~r` (see `Kernel.sigil_r/2`) or `~R` (see `Kernel.sigil_R/2`):
[`~r`](`Kernel.sigil_r/2`) or [`~R`](`Kernel.sigil_R/2`):
# A simple regular expression that matches foo anywhere in the string
~r/foo/
@@ -58,7 +58,7 @@ defmodule Regex do
* `dotall` (s) - causes dot to match newlines and also set newline to
anycrlf; the new line setting can be overridden by setting `(*CR)` or
`(*LF)` or `(*CRLF)` or `(*ANY)` according to `:re` documentation
`(*LF)` or `(*CRLF)` or `(*ANY)` according to re documentation
* `multiline` (m) - causes `^` and `$` to mark the beginning and end of
each line; use `\A` and `\z` to match the end or beginning of the string
@@ -79,7 +79,7 @@ defmodule Regex do
* `no_auto_capture` - not available, use `?:` instead
* `newline` - not available, use `(*CR)` or `(*LF)` or `(*CRLF)` or
`(*ANYCRLF)` or `(*ANY)` at the beginning of the regexp according to the
`:re` documentation
re documentation
## Captures
@@ -118,7 +118,7 @@ defmodule Regex do
The given options can either be a binary with the characters
representing the same regex options given to the
`~r` (see `Kernel.sigil_r/2`) sigil, or a list of options, as
[`~r`](`Kernel.sigil_r/2`) sigil, or a list of options, as
expected by the Erlang's `:re` module.
It returns `{:ok, regex}` in case of success,
@@ -134,7 +134,7 @@ defmodule Regex do
"""
@spec compile(binary, binary | [term]) :: {:ok, t} | {:error, any}
def compile(source, options \\ "") when is_binary(source) do
def compile(source, options \\ "") do
compile(source, options, version())
end
@@ -152,7 +152,7 @@ defmodule Regex do
compile(source, options, "", version)
end
defp compile(source, opts, doc_opts, version) do
defp compile(source, opts, doc_opts, version) when is_binary(source) do
case :re.compile(source, opts) do
{:ok, re_pattern} ->
{:ok, %Regex{re_pattern: re_pattern, re_version: version, source: source, opts: doc_opts}}
@@ -166,7 +166,7 @@ defmodule Regex do
Compiles the regular expression and raises `Regex.CompileError` in case of errors.
"""
@spec compile!(binary, binary | [term]) :: t
def compile!(source, options \\ "") when is_binary(source) do
def compile!(source, options \\ "") do
case compile(source, options) do
{:ok, regex} -> regex
{:error, {reason, at}} -> raise Regex.CompileError, "#{reason} at position #{at}"
@@ -211,8 +211,13 @@ defmodule Regex do
"""
@doc since: "1.4.0"
@spec version :: term()
# TODO: No longer check for function_exported? on OTP 20+.
def version do
{:re.version(), :erlang.system_info(:endian)}
if function_exported?(:re, :version, 0) do
{:re.version(), :erlang.system_info(:endian)}
else
{"8.33 2013-05-29", :erlang.system_info(:endian)}
end
end
@doc """
+31 -60
View File
@@ -32,26 +32,10 @@ defmodule Registry do
{:ok, _} = Agent.start_link(fn -> 0 end, name: name)
Agent.get(name, & &1)
#=> 0
Agent.update(name, &(&1 + 1))
Agent.update(name, & &1 + 1)
Agent.get(name, & &1)
#=> 1
In the previous example, we were not interested in associating a value to the
process:
Registry.lookup(Registry.ViaTest, "agent")
#=> [{self(), nil}]
However, in some cases it may be desired to associate a value to the process
using the alternate `{:via, Registry, {registry, key, value}}` tuple:
{:ok, _} = Registry.start_link(keys: :unique, name: Registry.ViaTest)
name = {:via, Registry, {Registry.ViaTest, "agent", :hello}}
{:ok, _} = Agent.start_link(fn -> 0 end, name: name)
Registry.lookup(Registry.ViaTest, "agent")
#=> [{self(), :hello}]
To this point, we have been starting `Registry` using `start_link/1`.
Typically the registry is started as part of a supervision tree though:
{Registry, keys: :unique, name: Registry.ViaTest}
@@ -99,7 +83,6 @@ defmodule Registry do
errors:
require Logger
Registry.dispatch(Registry.DispatcherTest, "hello", fn entries ->
for {pid, {module, function}} <- entries do
try do
@@ -107,7 +90,7 @@ defmodule Registry do
catch
kind, reason ->
formatted = Exception.format(kind, reason, __STACKTRACE__)
Logger.error("Registry.dispatch/3 failed with #{formatted}")
Logger.error "Registry.dispatch/3 failed with #{formatted}"
end
end
end)
@@ -128,15 +111,9 @@ defmodule Registry do
schedulers online, which will make the registry more performant on highly
concurrent environments:
{:ok, _} =
Registry.start_link(
keys: :duplicate,
name: Registry.PubSubTest,
partitions: System.schedulers_online()
)
{:ok, _} = Registry.start_link(keys: :duplicate, name: Registry.PubSubTest,
partitions: System.schedulers_online)
{:ok, _} = Registry.register(Registry.PubSubTest, "hello", [])
Registry.dispatch(Registry.PubSubTest, "hello", fn entries ->
for {pid, _} <- entries, do: send(pid, {:broadcast, "world"})
end)
@@ -206,10 +183,8 @@ defmodule Registry do
## Via callbacks
@doc false
def whereis_name({registry, key}), do: whereis_name(registry, key)
def whereis_name({registry, key, _value}), do: whereis_name(registry, key)
defp whereis_name(registry, key) do
@doc since: "1.4.0"
def whereis_name({registry, key}) do
case key_info!(registry) do
{:unique, partitions, key_ets} ->
key_ets = key_ets || key_ets!(registry, key, partitions)
@@ -228,17 +203,16 @@ defmodule Registry do
end
@doc false
def register_name({registry, key}, pid), do: register_name(registry, key, nil, pid)
def register_name({registry, key, value}, pid), do: register_name(registry, key, value, pid)
defp register_name(registry, key, value, pid) when pid == self() do
case register(registry, key, value) do
@doc since: "1.4.0"
def register_name({registry, key}, pid) when pid == self() do
case register(registry, key, nil) do
{:ok, _} -> :yes
{:error, _} -> :no
end
end
@doc false
@doc since: "1.4.0"
def send({registry, key}, msg) do
case lookup(registry, key) do
[{pid, _}] -> Kernel.send(pid, msg)
@@ -247,6 +221,7 @@ defmodule Registry do
end
@doc false
@doc since: "1.4.0"
def unregister_name({registry, key}) do
unregister(registry, key)
end
@@ -264,23 +239,21 @@ defmodule Registry do
Supervisor.start_link([
{Registry, keys: :unique, name: MyApp.Registry}
], strategy: :one_for_one)
])
For intensive workloads, the registry may also be partitioned (by specifying
the `:partitions` option). If partitioning is required then a good default is to
set the number of partitions to the number of schedulers available:
Registry.start_link(
keys: :unique,
name: MyApp.Registry,
partitions: System.schedulers_online()
)
Registry.start_link(keys: :unique, name: MyApp.Registry,
partitions: System.schedulers_online())
or:
Supervisor.start_link([
{Registry, keys: :unique, name: MyApp.Registry, partitions: System.schedulers_online()}
], strategy: :one_for_one)
{Registry, keys: :unique, name: MyApp.Registry,
partitions: System.schedulers_online()}
])
## Options
@@ -610,11 +583,9 @@ defmodule Registry do
[{self(), {1, :atom, 1}}, {self(), {2, :atom, 2}}]
iex> Registry.match(Registry.MatchTest, "hello", {:"$1", :_, :"$1"}) |> Enum.sort()
[{self(), {1, :atom, 1}}, {self(), {2, :atom, 2}}]
iex> guards = [{:>, :"$1", 1}]
iex> Registry.match(Registry.MatchTest, "hello", {:_, :_, :"$1"}, guards)
iex> Registry.match(Registry.MatchTest, "hello", {:_, :_, :"$1"}, [{:>, :"$1", 1}])
[{self(), {2, :atom, 2}}]
iex> guards = [{:is_atom, :"$1"}]
iex> Registry.match(Registry.MatchTest, "hello", {:_, :"$1", :_}, guards) |> Enum.sort()
iex> Registry.match(Registry.MatchTest, "hello", {:_, :"$1", :_}, [{:is_atom, :"$1"}]) |> Enum.sort()
[{self(), {1, :atom, 1}}, {self(), {2, :atom, 2}}]
"""
@@ -907,7 +878,7 @@ defmodule Registry do
key_ets = key_ets || key_ets!(registry, key_partition)
{pid_server, pid_ets} = pid_ets || pid_ets!(registry, pid_partition)
# Notice we write first to the pid_ets table because it will
# Notice we write first to the pid ets table because it will
# always be able to do the cleanup. If we register first to the
# key one and the process crashes, the key will stay there forever.
Process.link(pid_server)
@@ -1089,20 +1060,20 @@ defmodule Registry do
In the example below we register the current process under the same
key in a duplicate registry but with different values:
iex> Registry.start_link(keys: :duplicate, name: Registry.CountMatchTest)
iex> {:ok, _} = Registry.register(Registry.CountMatchTest, "hello", {1, :atom, 1})
iex> {:ok, _} = Registry.register(Registry.CountMatchTest, "hello", {2, :atom, 2})
iex> Registry.count_match(Registry.CountMatchTest, "hello", {1, :_, :_})
iex> Registry.start_link(keys: :duplicate, name: Registry.MatchTest)
iex> {:ok, _} = Registry.register(Registry.MatchTest, "hello", {1, :atom, 1})
iex> {:ok, _} = Registry.register(Registry.MatchTest, "hello", {2, :atom, 2})
iex> Registry.count_match(Registry.MatchTest, "hello", {1, :_, :_})
1
iex> Registry.count_match(Registry.CountMatchTest, "hello", {2, :_, :_})
iex> Registry.count_match(Registry.MatchTest, "hello", {2, :_, :_})
1
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:_, :atom, :_})
iex> Registry.count_match(Registry.MatchTest, "hello", {:_, :atom, :_})
2
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:"$1", :_, :"$1"})
iex> Registry.count_match(Registry.MatchTest, "hello", {:"$1", :_, :"$1"})
2
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:_, :_, :"$1"}, [{:>, :"$1", 1}])
iex> Registry.count_match(Registry.MatchTest, "hello", {:_, :_, :"$1"}, [{:>, :"$1", 1}])
1
iex> Registry.count_match(Registry.CountMatchTest, "hello", {:_, :"$1", :_}, [{:is_atom, :"$1"}])
iex> Registry.count_match(Registry.MatchTest, "hello", {:_, :"$1", :_}, [{:is_atom, :"$1"}])
2
"""
@@ -1233,7 +1204,7 @@ end
defmodule Registry.Partition do
@moduledoc false
# This process owns the equivalent key and pid ETS tables
# This process owns the equivalent key and pid ets tables
# and is responsible for monitoring processes that map to
# its own pid table.
use GenServer
@@ -1325,7 +1296,7 @@ defmodule Registry.Partition do
for {_pid, key, key_ets} <- entries do
key_ets =
case key_ets do
# In case the fake key_ets is being used. See unregister_match/2.
# In case the fake key ets is being used. See unregister_match/2.
{key_ets, _} ->
key_ets
+12 -27
View File
@@ -95,10 +95,7 @@ defmodule Stream do
@type acc :: any
@type element :: any
@typedoc "Zero-based index."
@type index :: non_neg_integer
@type default :: any
# Require Stream.Reducers and its callbacks
@@ -1244,8 +1241,7 @@ defmodule Stream do
fn acc, fun ->
inner = &do_cycle_each(&1, &2, fun)
outer = &Enumerable.reduce(enumerable, &1, inner)
reduce = check_cycle_first_element(outer)
do_cycle(reduce, outer, acc)
do_cycle(outer, outer, acc)
end
end
@@ -1264,6 +1260,9 @@ defmodule Stream do
{:stream_cycle, acc} ->
{:halted, acc}
else
{state, []} when state in [:done, :halted] ->
raise ArgumentError, "cannot cycle over empty enumerable"
{state, acc} when state in [:done, :halted] ->
do_cycle(cycle, cycle, {:cont, acc})
@@ -1279,18 +1278,6 @@ defmodule Stream do
end
end
defp check_cycle_first_element(reduce) do
fn acc ->
case reduce.(acc) do
{state, []} when state in [:done, :halted] ->
raise ArgumentError, "cannot cycle over empty enumerable"
other ->
other
end
end
end
@doc """
Emits a sequence of values, starting with `start_value`. Successive
values are generated by calling `next_fun` on the previous value.
@@ -1359,16 +1346,14 @@ defmodule Stream do
## Examples
Stream.resource(
fn -> File.open!("sample") end,
fn file ->
case IO.read(file, :line) do
data when is_binary(data) -> {[data], file}
_ -> {:halt, file}
end
end,
fn file -> File.close(file) end
)
Stream.resource(fn -> File.open!("sample") end,
fn file ->
case IO.read(file, :line) do
data when is_binary(data) -> {[data], file}
_ -> {:halt, file}
end
end,
fn file -> File.close(file) end)
"""
@spec resource((() -> acc), (acc -> {[element], acc} | {:halt, acc}), (acc -> term)) ::
+1 -1
View File
@@ -25,7 +25,7 @@ defmodule Stream.Reducers do
end
after_fun = fn {acc_buffer, acc_count} ->
if leftover == :discard or acc_count == 0 or acc_count >= count do
if leftover == :discard or acc_count == 0 or (step > count and acc_count >= count) do
{:cont, []}
else
{:cont, :lists.reverse(acc_buffer, Enum.take(leftover, count - acc_count)), []}
+36 -158
View File
@@ -183,7 +183,7 @@ defmodule String do
## Patterns
Many functions in this module work with patterns. For example,
`String.split/2` can split a string into multiple strings given
`String.split/2` can split a string into multiple patterns given
a pattern. This pattern can be a string, a list of strings or
a compiled pattern:
@@ -198,15 +198,15 @@ defmodule String do
["foo", "bar", ""]
The compiled pattern is useful when the same match will
be done over and over again. Note though that the compiled
be done over and over again. Note though the compiled
pattern cannot be stored in a module attribute as the pattern
is generated at runtime and does not survive compile time.
is generated at runtime and does not survive compile term.
"""
@typedoc """
A UTF-8 encoded binary.
The types `String.t()` and `binary()` are equivalent to analysis tools.
Note `String.t()` and `binary()` are equivalent to analysis tools.
Although, for those reading the documentation, `String.t()` implies
it is a UTF-8 encoded binary.
"""
@@ -307,9 +307,9 @@ defmodule String do
defdelegate split(binary), to: String.Break
@doc ~S"""
Divides a string into parts based on a pattern.
Divides a string into substrings based on a pattern.
Returns a list of these parts. The pattern can
Returns a list of these substrings. The pattern can
be a string, a list of strings, a regular expression,
or a compiled pattern.
@@ -387,15 +387,15 @@ defmodule String do
iex> String.split("abc", "", parts: 3)
["", "a", "bc"]
Be aware that this function can split within or across grapheme boundaries.
Note this function can split within or across grapheme boundaries.
For example, take the grapheme "é" which is made of the characters
"e" and the acute accent. The following will split the string into two parts:
"e" and the acute accent. The following returns the acute accent separately:
iex> String.split(String.normalize("é", :nfd), "e")
["", "́"]
However, if "é" is represented by the single character "e with acute"
accent, then it will split the string into just one part:
accent, then it will return "e with acute":
iex> String.split(String.normalize("é", :nfc), "e")
["é"]
@@ -460,10 +460,10 @@ defmodule String do
This is in contrast to `split/3` which splits the
entire string upfront.
This function does not support regular expressions
by design. When using regular expressions, it is often
more efficient to have the regular expressions traverse
the string at once than in parts, like this function does.
Note splitter does not support regular expressions
(as it is often more efficient to have the regular
expressions traverse the string at once than in
multiple passes).
## Options
@@ -632,24 +632,8 @@ defmodule String do
"leña"
"""
# TODO: Fully deprecate it on v1.10
@doc deprecated:
"Use :unicode.characters_to_nfc_binary/1 or :unicode.characters_to_nfd_binary/1 instead"
def normalize(string, form)
def normalize(string, :nfd) do
case :unicode.characters_to_nfd_binary(string) do
string when is_binary(string) -> string
{:error, bad, rest} -> bad <> normalize(rest, :nfd)
end
end
def normalize(string, :nfc) do
case :unicode.characters_to_nfc_binary(string) do
string when is_binary(string) -> string
{:error, bad, rest} -> bad <> normalize(rest, :nfc)
end
end
@spec normalize(t, atom) :: t
defdelegate normalize(string, form), to: String.Normalizer
@doc """
Converts all characters in the given string to uppercase according to `mode`.
@@ -832,7 +816,7 @@ defmodule String do
"ola ola world"
"""
@spec replace_leading(t, t, t) :: t
@spec replace_leading(t, t, t) :: t | no_return
def replace_leading(string, match, replacement)
when is_binary(string) and is_binary(match) and is_binary(replacement) do
if match == "" do
@@ -889,7 +873,7 @@ defmodule String do
"hello mundo mundo"
"""
@spec replace_trailing(t, t, t) :: t
@spec replace_trailing(t, t, t) :: t | no_return
def replace_trailing(string, match, replacement)
when is_binary(string) and is_binary(match) and is_binary(replacement) do
if match == "" do
@@ -1145,7 +1129,7 @@ defmodule String do
When `count` is less than or equal to the length of `string`,
given `string` is returned.
Raises `ArgumentError` if the given `padding` contains a non-string element.
Raises `ArgumentError` if the given `padding` contains non-string element.
## Examples
@@ -1187,7 +1171,7 @@ defmodule String do
When `count` is less than or equal to the length of `string`,
given `string` is returned.
Raises `ArgumentError` if the given `padding` contains a non-string element.
Raises `ArgumentError` if the given `padding` contains non-string element.
## Examples
@@ -1487,46 +1471,23 @@ defmodule String do
@spec codepoints(t) :: [codepoint]
defdelegate codepoints(string), to: String.Unicode
@doc ~S"""
@doc """
Returns the next codepoint in a string.
The result is a tuple with the codepoint and the
remainder of the string or `nil` in case
the string reached its end.
As with other functions in the `String` module, `next_codepoint/1`
works with binaries that are invalid UTF-8. If the string starts
with a sequence of bytes that is not valid in UTF-8 encoding, the
first element of the returned tuple is a binary with the first byte.
As with other functions in the String module, this
function does not check for the validity of the codepoint.
That said, if an invalid codepoint is found, it will
be returned by this function.
## Examples
iex> String.next_codepoint("olá")
{"o", "lá"}
iex> invalid = "\x80\x80OK" # first two bytes are invalid in UTF-8
iex> {_, rest} = String.next_codepoint(invalid)
{<<128>>, <<128, 79, 75>>}
iex> String.next_codepoint(rest)
{<<128>>, "OK"}
## Comparison with binary pattern matching
Binary pattern matching provides a similar way to decompose
a string:
iex> <<codepoint::utf8, rest::binary>> = "Elixir"
"Elixir"
iex> codepoint
69
iex> rest
"lixir"
though not entirely equivalent because `codepoint` comes as
an integer, and the pattern won't match invalid UTF-8.
Binary pattern matching, however, is simpler and more efficient,
so pick the option that better suits your use case.
"""
@compile {:inline, next_codepoint: 1}
@spec next_codepoint(t) :: {codepoint, t} | nil
@@ -2101,17 +2062,17 @@ defmodule String do
iex> String.contains?("elixir of life", ["", "other"])
true
Be aware that this function can match within or across grapheme boundaries.
Note this function can match within or across grapheme boundaries.
For example, take the grapheme "é" which is made of the characters
"e" and the acute accent. The following returns `true`:
iex> String.contains?(:unicode.characters_to_nfd_binary("é"), "e")
iex> String.contains?(String.normalize("é", :nfd), "e")
true
However, if "é" is represented by the single character "e with acute"
accent, then it will return `false`:
iex> String.contains?(:unicode.characters_to_nfc_binary("é"), "e")
iex> String.contains?(String.normalize("é", :nfc), "e")
false
"""
@@ -2131,7 +2092,7 @@ defmodule String do
@doc """
Converts a string into a charlist.
Specifically, this function takes a UTF-8 encoded binary and returns a list of its integer
Specifically, this functions takes a UTF-8 encoded binary and returns a list of its integer
codepoints. It is similar to `codepoints/1` except that the latter returns a list of codepoints as
strings.
@@ -2169,7 +2130,8 @@ defmodule String do
By default, the maximum number of atoms is `1_048_576`. This limit
can be raised or lowered using the VM option `+t`.
The maximum atom size is of 255 Unicode codepoints.
The maximum atom size is of 255 characters. Prior to Erlang/OTP 20,
only latin1 characters are allowed.
Inlined by the compiler.
@@ -2187,7 +2149,8 @@ defmodule String do
@doc """
Converts a string to an existing atom.
The maximum atom size is of 255 Unicode codepoints.
The maximum atom size is of 255 characters. Prior to Erlang/OTP 20,
only latin1 characters are allowed.
Inlined by the compiler.
@@ -2209,11 +2172,6 @@ defmodule String do
@doc """
Returns an integer whose text representation is `string`.
`string` must be the string representation of an integer.
Otherwise, an `ArgumentError` will be raised. If you want
to parse a string that may contain an ill-formatted integer,
use `Integer.parse/1`.
Inlined by the compiler.
## Examples
@@ -2221,11 +2179,6 @@ defmodule String do
iex> String.to_integer("123")
123
Passing a string that does not represent an integer leads to an error:
String.to_integer("invalid data")
#=> ** (ArgumentError) argument error
"""
@spec to_integer(String.t()) :: integer
def to_integer(string) do
@@ -2275,90 +2228,15 @@ defmodule String do
end
@doc """
Computes the bag distance between two strings.
Returns a float value between 0 and 1 representing the bag
Returns a float value between 0 (equates to no similarity) and 1 (is an exact match)
representing [Jaro](https://en.wikipedia.org/wiki/Jaro–Winkler_distance)
distance between `string1` and `string2`.
The bag distance is meant to be an efficient approximation
of the distance between two strings to quickly rule out strings
that are largely different.
The algorithm is outlined in the "String Matching with Metric
Trees Using an Approximate Distance" paper by Ilaria Bartolini,
Paolo Ciaccia, and Marco Patella.
The Jaro distance metric is designed and best suited for short strings such as person names.
## Examples
iex> String.bag_distance("abc", "")
0.0
iex> String.bag_distance("abcd", "a")
0.25
iex> String.bag_distance("abcd", "ab")
0.5
iex> String.bag_distance("abcd", "abc")
0.75
iex> String.bag_distance("abcd", "abcd")
1.0
"""
@spec bag_distance(t, t) :: float
@doc since: "1.8.0"
def bag_distance(_string, ""), do: 0.0
def bag_distance("", _string), do: 0.0
def bag_distance(string1, string2) do
{bag1, length1} = string_to_bag(string1, %{}, 0)
{bag2, length2} = string_to_bag(string2, %{}, 0)
diff1 = bag_difference(bag1, bag2)
diff2 = bag_difference(bag2, bag1)
1 - max(diff1, diff2) / max(length1, length2)
end
defp string_to_bag(string, bag, length) do
case next_grapheme(string) do
{char, rest} ->
bag =
case bag do
%{^char => current} -> %{bag | char => current + 1}
%{} -> Map.put(bag, char, 1)
end
string_to_bag(rest, bag, length + 1)
nil ->
{bag, length}
end
end
defp bag_difference(bag1, bag2) do
Enum.reduce(bag1, 0, fn {char, count1}, sum ->
case bag2 do
%{^char => count2} -> sum + max(count1 - count2, 0)
%{} -> sum + count1
end
end)
end
@doc """
Computes the Jaro distance (similarity) between two strings.
Returns a float value between `0.0` (equates to no similarity) and `1.0`
(is an exact match) representing [Jaro](https://en.wikipedia.org/wiki/Jaro-Winkler_distance)
distance between `string1` and `string2`.
The Jaro distance metric is designed and best suited for short
strings such as person names. Elixir itself uses this function
to provide the "did you mean?" functionality. For instance, when you
are calling a function in a module and you have a typo in the
function name, we attempt to suggest the most similar function
name available, if any, based on the `jaro_distance/2` score.
## Examples
iex> String.jaro_distance("Dwayne", "Duane")
iex> String.jaro_distance("dwayne", "duane")
0.8222222222222223
iex> String.jaro_distance("even", "odd")
0.0
+4 -6
View File
@@ -31,14 +31,14 @@ defmodule StringIO do
## Examples
iex> StringIO.open("foo", [], fn pid ->
iex> StringIO.open("foo", [], fn(pid) ->
...> input = IO.gets(pid, ">")
...> IO.write(pid, "The input was #{input}")
...> StringIO.contents(pid)
...> end)
{:ok, {"", "The input was foo"}}
iex> StringIO.open("foo", [capture_prompt: true], fn pid ->
iex> StringIO.open("foo", [capture_prompt: true], fn(pid) ->
...> input = IO.gets(pid, ">")
...> IO.write(pid, "The input was #{input}")
...> StringIO.contents(pid)
@@ -91,7 +91,7 @@ defmodule StringIO do
iex> StringIO.contents(pid)
{"", ">"}
iex> StringIO.open("foo", fn pid ->
iex> StringIO.open("foo", fn(pid) ->
...> input = IO.gets(pid, ">")
...> IO.write(pid, "The input was #{input}")
...> StringIO.contents(pid)
@@ -101,7 +101,7 @@ defmodule StringIO do
"""
@spec open(binary, keyword) :: {:ok, pid}
@spec open(binary, (pid -> res)) :: {:ok, res} when res: var
def open(string, options_or_function \\ [])
def open(path, options_or_function \\ [])
def open(string, options_or_function) when is_binary(string) and is_list(options_or_function) do
GenServer.start_link(__MODULE__, {string, options_or_function}, [])
@@ -279,8 +279,6 @@ defmodule StringIO do
{_, _, _} ->
{{:error, req}, state}
end
rescue
ArgumentError -> {{:error, req}, state}
end
## get_chars
+149 -139
View File
@@ -97,11 +97,50 @@ defmodule Supervisor do
Supervisors support different strategies; in the example above, we
have chosen `:one_for_one`. Furthermore, each supervisor can have many
workers and/or supervisors as children, with each one having its own
configuration (as outlined in the "Child specification" section).
configuration (as outlined in the “Child specification” section).
The rest of this document will cover how child processes are specified,
how they can be started and stopped, different supervision strategies
and more.
The rest of this document will cover how child processes are started,
how they can be specified, different supervision strategies and more.
## Start and shutdown
When the supervisor starts, it traverses all child specifications and
then starts each child in the order they are defined. This is done by
calling the function defined under the `:start` key in the child
specification and typically defaults to `start_link/1`.
The `start_link/1` (or a custom) is then called for each child process.
The `start_link/1` function must return `{:ok, pid}` where `pid` is the
process identifier of a new process that is linked to the supervisor.
The child process usually starts its work by executing the `init/1`
callback. Generally speaking, the `init` callback is where we initialize
and configure the child process.
The shutdown process happens in reverse order.
When a supervisor shuts down, it terminates all children in the opposite
order they are listed. The termination happens by sending a shutdown exit
signal, via `Process.exit(child_pid, :shutdown)`, to the child process and
then awaiting for a time interval for the child process to terminate. This
interval defaults to 5000 milliseconds. If the child process does not
terminate in this interval, the supervisor abruptly terminates the child
with reason `:kill`. The shutdown time can be configured in the child
specification which is fully detailed in the next section.
If the child process is not trapping exits, it will shutdown immediately
when it receives the first exit signal. If the child process is trapping
exits, then the `terminate` callback is invoked, and the child process
must terminate in a reasonable time interval before being abruptly
terminated by the supervisor.
In other words, if it is important that a process cleans after itself
when your application or the supervision tree is shutting down, then
this process must trap exits and its child specification should specify
the proper `:shutdown` value, ensuring it terminates within a reasonable
interval.
Now that we understand the start and shutdown process, let's take a
complete look at all of the options provided in the child specification.
## Child specification
@@ -144,11 +183,11 @@ defmodule Supervisor do
terminated using `Process.exit(child, :kill)`.
* any integer >= 0 - the amount of time in milliseconds that the
supervisor will wait for its children to terminate after emitting a
supervisor will wait for children to terminate after emitting a
`Process.exit(child, :shutdown)` signal. If the child process is
not trapping exits, the initial `:shutdown` signal will terminate
the child process immediately. If the child process is trapping
exits, it has the given amount of time to terminate.
exits, it has the given amount of time in milliseconds to terminate.
If it doesn't terminate within the specified time, the child process
is unconditionally terminated by the supervisor via
`Process.exit(child, :kill)`.
@@ -156,7 +195,7 @@ defmodule Supervisor do
* `:infinity` - works as an integer except the supervisor will wait
indefinitely for the child to terminate. If the child process is a
supervisor, the recommended value is `:infinity` to give the supervisor
and its children enough time to shut down. This option can be used with
and its children enough time to shutdown. This option can be used with
regular workers but doing so is discouraged and requires extreme care.
If not used carefully, the child process will never terminate,
preventing your application from terminating as well.
@@ -208,31 +247,30 @@ defmodule Supervisor do
The supervisor will then invoke `Stack.child_spec([:hello])` to retrieve a
child specification. Now the `Stack` module is responsible for building its
own specification, for example, we could write:
own specification. By default, `use GenServer` defines a `Stack.child_spec/1`
function which returns the same child specification we had before:
def child_spec(arg) do
%{
id: Stack,
start: {Stack, :start_link, [arg]}
}
end
%{
id: Stack,
start: {Stack, :start_link, [[:hello]]}
}
Luckily for us, `use GenServer` already defines a `Stack.child_spec/1`
exactly like above. If you need to customize the `GenServer`, you can
pass the options directly to `use GenServer`:
use GenServer, restart: :transient
Finally, note it is also possible to simply pass the `Stack` module as
a child:
It is also possible to simply pass the `Stack` module as a child:
children = [
Stack
]
When only the module name is given, it is equivalent to `{Stack, []}`.
When only the module name is given, it is equivalent to `{Stack, []}`. In this
case, we will end-up with a child specification that looks like this:
%{
id: Stack,
start: {Stack, :start_link, [[]]}
}
By replacing the map specification by `{Stack, [:hello]}` or `Stack`, we keep
the child specification encapsulated in the `Stack` module, using the default
the child specification encapsulated in the Stack module, using the default
implementation defined by `use GenServer`. We can now share our `Stack` worker
with other developers and they can add it directly to their supervision tree
without worrying about the low-level details of the worker.
@@ -247,7 +285,7 @@ defmodule Supervisor do
* a module - such as `Stack`. In this case, `Stack.child_spec([])`
is called to retrieve the child specification
If you need to convert a tuple or a module child specification to a map or
If you need to convert how a tuple or module child specification to a map or
modify a child specification, you can use the `Supervisor.child_spec/2` function.
For example, to run the stack with a different `:id` and a `:shutdown` value of
10 seconds (10_000 milliseconds):
@@ -256,6 +294,55 @@ defmodule Supervisor do
Supervisor.child_spec({Stack, [:hello]}, id: MyStack, shutdown: 10_000)
]
The call to `Supervisor.child_spec/2` above will return the following specification:
%{
id: MyStack,
start: {Stack, :start_link, [[:hello]]},
shutdown: 10_000
}
You may also configure the child specification in the Stack module itself to
use a different `:id` or `:shutdown` value by passing options to `use GenServer`:
defmodule Stack do
use GenServer, id: MyStack, shutdown: 10_000
The options above will customize the `Stack.child_spec/1` function defined
by `use GenServer`. It accepts the same options as the `Supervisor.child_spec/2`
function.
You may also completely override the `child_spec/1` function in the Stack module
and return your own child specification. Note there is no guarantee the `child_spec/1`
function will be called by the Supervisor process, as other processes may invoke
it to retrieve the child specification before reaching the supervisor.
## Exit reasons and restarts
A supervisor restarts a child process depending on its `:restart`
configuration. For example, when `:restart` is set to `:transient`, the
supervisor does not restart the child in case it exits with reason `:normal`,
`:shutdown` or `{:shutdown, term}`.
So one may ask: which exit reason should I choose when exiting? There are
three options:
* `:normal` - in such cases, the exit won't be logged, there is no restart
in transient mode, and linked processes do not exit
* `:shutdown` or `{:shutdown, term}` - in such cases, the exit won't be
logged, there is no restart in transient mode, and linked processes exit
with the same reason unless they're trapping exits
* any other term - in such cases, the exit will be logged, there are
restarts in transient mode, and linked processes exit with the same
reason unless they're trapping exits
Notice that the supervisor that reaches maximum restart intensity will exit with
`:shutdown` reason. In this case the supervisor will only be restarted if its
child specification was defined with the `:restart` option set to `:permanent`
(the default).
## Module-based supervisors
In the example above, a supervisor was started by passing the supervision
@@ -266,12 +353,12 @@ defmodule Supervisor do
# Automatically defines child_spec/1
use Supervisor
def start_link(init_arg) do
Supervisor.start_link(__MODULE__, init_arg, name: __MODULE__)
def start_link(arg) do
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
end
@impl true
def init(_init_arg) do
def init(_arg) do
children = [
{Stack, [:hello]}
]
@@ -288,8 +375,7 @@ defmodule Supervisor do
`c:init/1` callback.
`use Supervisor` also defines a `child_spec/1` function which allows
us to run `MyApp.Supervisor` as a child of another supervisor or
at the top of your supervision tree as:
us to run `MyApp.Supervisor` as a child of another supervisor:
children = [
MyApp.Supervisor
@@ -301,35 +387,27 @@ defmodule Supervisor do
module only at the top of your supervision tree, generally in the
`c:Application.start/2` callback. We recommend using module-based
supervisors for any other supervisor in your application, so they
can run as a child of another supervisor in the tree. The `child_spec/1`
generated automatically by `Supervisor` can be customized with the
following options:
can run as a child of another supervision in the tree. The generated
`child_spec/1` can be customized with the following options:
* `:id` - the child specification identifier, defaults to the current module
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
* `:restart` - when the supervisor should be restarted, defaults to `:permanent`
The `@doc` annotation immediately preceding `use Supervisor` will be
attached to the generated `child_spec/1` function.
## `start_link/2`, `init/2`, and strategies
So far we have started the supervisor passing a single child as a tuple
as well as a strategy called `:one_for_one`:
children = [
Supervisor.start_link([
{Stack, [:hello]}
]
Supervisor.start_link(children, strategy: :one_for_one)
], strategy: :one_for_one)
or from inside the `c:init/1` callback:
children = [
Supervisor.init([
{Stack, [:hello]}
]
Supervisor.init(children, strategy: :one_for_one)
], strategy: :one_for_one)
The first argument given to `start_link/2` and `init/2` is a list of child
specifications as defined in the "child_spec/1" section above.
@@ -376,73 +454,10 @@ defmodule Supervisor do
differently when this strategy was used. See the `DynamicSupervisor` module
for more information and migration strategies.
### Name registration
## Name registration
A supervisor is bound to the same name registration rules as a `GenServer`.
Read more about these rules in the documentation for `GenServer`.
## Start and shutdown
When the supervisor starts, it traverses all child specifications and
then starts each child in the order they are defined. This is done by
calling the function defined under the `:start` key in the child
specification and typically defaults to `start_link/1`.
The `start_link/1` (or a custom) is then called for each child process.
The `start_link/1` function must return `{:ok, pid}` where `pid` is the
process identifier of a new process that is linked to the supervisor.
The child process usually starts its work by executing the `init/1`
callback. Generally speaking, the `init` callback is where we initialize
and configure the child process.
The shutdown process happens in reverse order.
When a supervisor shuts down, it terminates all children in the opposite
order they are listed. The termination happens by sending a shutdown exit
signal, via `Process.exit(child_pid, :shutdown)`, to the child process and
then awaiting for a time interval for the child process to terminate. This
interval defaults to 5000 milliseconds. If the child process does not
terminate in this interval, the supervisor abruptly terminates the child
with reason `:kill`. The shutdown time can be configured in the child
specification which is fully detailed in the next section.
If the child process is not trapping exits, it will shutdown immediately
when it receives the first exit signal. If the child process is trapping
exits, then the `terminate` callback is invoked, and the child process
must terminate in a reasonable time interval before being abruptly
terminated by the supervisor.
In other words, if it is important that a process cleans after itself
when your application or the supervision tree is shutting down, then
this process must trap exits and its child specification should specify
the proper `:shutdown` value, ensuring it terminates within a reasonable
interval.
## Exit reasons and restarts
A supervisor restarts a child process depending on its `:restart` configuration.
For example, when `:restart` is set to `:transient`, the supervisor does not
restart the child in case it exits with reason `:normal`, `:shutdown` or
`{:shutdown, term}`.
So one may ask: which exit reason should I choose when exiting? There are
three options:
* `:normal` - in such cases, the exit won't be logged, there is no restart
in transient mode, and linked processes do not exit
* `:shutdown` or `{:shutdown, term}` - in such cases, the exit won't be
logged, there is no restart in transient mode, and linked processes exit
with the same reason unless they're trapping exits
* any other term - in such cases, the exit will be logged, there are
restarts in transient mode, and linked processes exit with the same
reason unless they're trapping exits
Notice that the supervisor that reaches maximum restart intensity will exit with
`:shutdown` reason. In this case the supervisor will only be restarted if its
child specification was defined with the `:restart` option set to `:permanent`
(the default).
"""
@doc false
@@ -451,18 +466,15 @@ defmodule Supervisor do
import Supervisor.Spec
@behaviour Supervisor
if Module.get_attribute(__MODULE__, :doc) == nil do
@doc """
Returns a specification to start this module under a supervisor.
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
end
def child_spec(init_arg) do
See `Supervisor`.
"""
def child_spec(arg) do
default = %{
id: __MODULE__,
start: {__MODULE__, :start_link, [init_arg]},
start: {__MODULE__, :start_link, [arg]},
type: :supervisor
}
@@ -479,7 +491,7 @@ defmodule Supervisor do
Developers typically invoke `Supervisor.init/2` at the end of their
init callback to return the proper supervision flags.
"""
@callback init(init_arg :: term) ::
@callback init(args :: term) ::
{:ok, {:supervisor.sup_flags(), [:supervisor.child_spec()]}}
| :ignore
@@ -532,10 +544,10 @@ defmodule Supervisor do
@doc """
Starts a supervisor with the given children.
The children is a list of modules, two-element tuples with module and
The children is a list of modules, 2-element tuples with module and
arguments or a map with the child specification. A strategy is required
to be provided through the `:strategy` option. See
"start_link/2, init/2, and strategies" for examples and other options.
"start_link/2, init/2 and strategies" for examples and other options.
The options can also be used to register a supervisor name.
The supported values are described under the "Name registration"
@@ -565,11 +577,11 @@ defmodule Supervisor do
end
@doc """
Receives a list of `children` to initialize and a set of `options`.
Receives a list of children to initialize and a set of options.
This is typically invoked at the end of the `c:init/1` callback of
module-based supervisors. See the sections "Module-based supervisors"
and "start_link/2, init/2, and strategies" in the module
and "start_link/2, init/2 and strategies" in the module
documentation for more information.
This function returns a tuple containing the supervisor
@@ -577,12 +589,10 @@ defmodule Supervisor do
## Examples
def init(_init_arg) do
children = [
def init(_arg) do
Supervisor.init([
{Stack, [:hello]}
]
Supervisor.init(children, strategy: :one_for_one)
], strategy: :one_for_one)
end
## Options
@@ -594,15 +604,15 @@ defmodule Supervisor do
* `:max_restarts` - the maximum number of restarts allowed in
a time frame. Defaults to `3`.
* `:max_seconds` - the time frame in seconds in which `:max_restarts`
applies. Defaults to `5`.
* `:max_seconds` - the time frame in which `:max_restarts` applies.
Defaults to `5`.
The `:strategy` option is required and by default a maximum of 3 restarts
is allowed within 5 seconds. Check the `Supervisor` module for a detailed
description of the available strategies.
"""
@doc since: "1.5.0"
# TODO: Warn if simple_one_for_one strategy is used on Elixir v1.9
# TODO: Warn if simple_one_for_one strategy is used on Elixir v1.8.
@spec init([:supervisor.child_spec() | {module, term} | module], [init_option]) :: {:ok, tuple}
def init(children, options) when is_list(children) and is_list(options) do
unless strategy = options[:strategy] do
@@ -740,10 +750,10 @@ defmodule Supervisor do
end
@doc """
Starts a module-based supervisor process with the given `module` and `init_arg`.
Starts a module-based supervisor process with the given `module` and `arg`.
To start the supervisor, the `c:init/1` callback will be invoked in the given
`module`, with `init_arg` as its argument. The `c:init/1` callback must return a
`module`, with `arg` as its argument. The `c:init/1` callback must return a
supervisor specification which can be created with the help of the `init/2`
function.
@@ -762,19 +772,19 @@ defmodule Supervisor do
# all to start_link(children, options).
@spec start_link(module, term) :: on_start
@spec start_link(module, term, GenServer.options()) :: on_start
def start_link(module, init_arg, options \\ []) when is_list(options) do
def start_link(module, arg, options \\ []) when is_list(options) do
case Keyword.get(options, :name) do
nil ->
:supervisor.start_link(module, init_arg)
:supervisor.start_link(module, arg)
atom when is_atom(atom) ->
:supervisor.start_link({:local, atom}, module, init_arg)
:supervisor.start_link({:local, atom}, module, arg)
{:global, _term} = tuple ->
:supervisor.start_link(tuple, module, init_arg)
:supervisor.start_link(tuple, module, arg)
{:via, via_module, _term} = tuple when is_atom(via_module) ->
:supervisor.start_link(tuple, module, init_arg)
:supervisor.start_link(tuple, module, arg)
other ->
raise ArgumentError, """
@@ -820,7 +830,7 @@ defmodule Supervisor do
call(supervisor, {:start_child, child_spec})
end
# TODO: Deprecate this on Elixir v1.9. Remove and update typespec on v2.0.
# TODO: Deprecate this on Elixir v1.8. Remove and update typespec on v2.0.
def start_child(supervisor, args) when is_list(args) do
call(supervisor, {:start_child, args})
end
@@ -847,7 +857,7 @@ defmodule Supervisor do
when error: :not_found | :simple_one_for_one
def terminate_child(supervisor, child_id)
# TODO: Deprecate this clause on Elixir v1.9
# TODO: Deprecate this clause on Elixir v1.8
def terminate_child(supervisor, pid) when is_pid(pid) do
call(supervisor, {:terminate_child, pid})
end
+23 -27
View File
@@ -86,7 +86,7 @@ defmodule Supervisor.Spec do
In this case the supervisor will only be restarted if its child specification was defined with
the `:restart` option is set to `:permanent` (the default).
### Shutdown values (`:shutdown`)
### Shutdown values (:shutdown)
The following shutdown values are supported in the `:shutdown` option:
@@ -94,14 +94,14 @@ defmodule Supervisor.Spec do
using `Process.exit(child, :kill)`
* `:infinity` - if the child process is a supervisor, this is a mechanism
to give the subtree enough time to shut down; it can also be used with
to give the subtree enough time to shutdown; it can also be used with
workers with care
* a non-negative integer - the amount of time in milliseconds
* any integer - the value of `:shutdown` 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,
the child process is unconditionally terminated
If no exit signal is received within the specified time (the value of this
option, in milliseconds), the child process is unconditionally terminated
using `Process.exit(child, :kill)`
"""
@@ -109,7 +109,7 @@ defmodule Supervisor.Spec do
@moduledoc deprecated:
"Use the new child specifications outlined in the Supervisor module instead"
# TODO: Deprecate all functions in this module on Elixir v1.9.
# TODO: Deprecate all functions in this module on Elixir v1.8.
# Also deprecate entry in Supervisor.Default.
@typedoc "Supported strategies"
@@ -135,8 +135,8 @@ defmodule Supervisor.Spec do
{child_id, start_fun :: {module, atom, [term]}, restart, shutdown, worker, modules}
@doc """
Receives a list of `children` (workers or supervisors) to
supervise and a set of `options`.
Receives a list of children (workers or supervisors) to
supervise and a set of options.
Returns a tuple containing the supervisor specification. This tuple can be
used as the return value of the `c:init/1` callback when implementing a
@@ -216,16 +216,14 @@ defmodule Supervisor.Spec do
By default, the function `start_link` is invoked on the given
module. Overall, the default values for the options are:
[
id: module,
function: :start_link,
restart: :permanent,
shutdown: 5000,
modules: [module]
]
[id: module,
function: :start_link,
restart: :permanent,
shutdown: 5000,
modules: [module]]
See the "Supervisor and worker options" section in the `Supervisor.Spec` module for more
information on the available options.
Check the documentation for the `Supervisor.Spec` module for more
information on the options.
"""
@spec worker(
module,
@@ -244,21 +242,19 @@ defmodule Supervisor.Spec do
Defines the given `module` as a supervisor which will be started
with the given arguments.
supervisor(module, [], restart: :permanent)
supervisor(ExUnit.Runner, [], restart: :permanent)
By default, the function `start_link` is invoked on the given
module. Overall, the default values for the options are:
[
id: module,
function: :start_link,
restart: :permanent,
shutdown: :infinity,
modules: [module]
]
[id: module,
function: :start_link,
restart: :permanent,
shutdown: :infinity,
modules: [module]]
See the "Supervisor and worker options" section in the `Supervisor.Spec` module for more
information on the available options.
Check the documentation for the `Supervisor.Spec` module for more
information on the options.
"""
@spec supervisor(
module,
+48 -63
View File
@@ -73,13 +73,22 @@ defmodule System do
parts_per_second` seconds. For example, using the `:millisecond` time unit
is equivalent to using `1000` as the time unit (as the time will be returned
in 1/1000 seconds - milliseconds).
Keep in mind the Erlang API prior to version 19.1 will use `:milli_seconds`,
`:micro_seconds` and `:nano_seconds` as time units although Elixir normalizes
their spelling to match the SI convention.
"""
# TODO: Warn all old mappings once Elixir requires Erlang/OTP 19.1+ (on v1.8)
@type time_unit ::
:second
| :millisecond
| :microsecond
| :nanosecond
| pos_integer
| :seconds
| :milliseconds
| :microseconds
| :nanoseconds
@base_dir :filename.join(__DIR__, "../../..")
@version_file :filename.join(@base_dir, "VERSION")
@@ -101,7 +110,7 @@ defmodule System do
# Read and strip the version from the VERSION file.
defmacrop get_version do
case read_stripped(@version_file) do
"" -> raise "could not read the version number from VERSION"
"" -> raise RuntimeError, message: "could not read the version number from VERSION"
data -> data
end
end
@@ -140,7 +149,6 @@ defmodule System do
@doc """
Returns the endianness.
"""
@spec endianness() :: :little | :big
def endianness do
:erlang.system_info(:endian)
end
@@ -149,7 +157,6 @@ defmodule System do
Returns the endianness the system was compiled with.
"""
@endianness :erlang.system_info(:endian)
@spec compiled_endianness() :: :little | :big
def compiled_endianness do
@endianness
end
@@ -215,32 +222,32 @@ defmodule System do
Returns the current working directory or `nil` if one
is not available.
"""
# TODO: Remove by 2.0
@deprecated "Use File.cwd/0 instead"
@spec cwd() :: String.t() | nil
def cwd do
case File.cwd() do
{:ok, cwd} -> cwd
case :file.get_cwd() do
{:ok, base} -> IO.chardata_to_string(fix_drive_letter(base))
_ -> nil
end
end
defp fix_drive_letter([l, ?:, ?/ | rest] = original) when l in ?A..?Z do
case :os.type() do
{:win32, _} -> [l + ?a - ?A, ?:, ?/ | rest]
_ -> original
end
end
defp fix_drive_letter(original), do: original
@doc """
Current working directory, exception on error.
Returns the current working directory or raises `RuntimeError`.
"""
# TODO: Remove by 2.0
@deprecated "Use File.cwd!/0 instead"
@spec cwd!() :: String.t()
def cwd! do
case File.cwd() do
{:ok, cwd} ->
cwd
_ ->
raise "could not get a current working directory, the current location is not accessible"
end
cwd() ||
raise RuntimeError,
message:
"could not get a current working directory, the current location is not accessible"
end
@doc """
@@ -248,7 +255,6 @@ defmodule System do
Returns the user home directory (platform independent).
"""
@spec user_home() :: String.t() | nil
def user_home do
:elixir_config.get(:home)
end
@@ -259,9 +265,10 @@ defmodule System do
Same as `user_home/0` but raises `RuntimeError`
instead of returning `nil` if no user home is set.
"""
@spec user_home!() :: String.t()
def user_home! do
user_home() || raise "could not find the user home, please set the HOME environment variable"
user_home() ||
raise RuntimeError,
message: "could not find the user home, please set the HOME environment variable"
end
@doc ~S"""
@@ -278,17 +285,9 @@ defmodule System do
Returns `nil` if none of the above are writable.
"""
@spec tmp_dir() :: String.t() | nil
def tmp_dir do
write_env_tmp_dir('TMPDIR') || write_env_tmp_dir('TEMP') || write_env_tmp_dir('TMP') ||
write_tmp_dir('/tmp') || write_cwd_tmp_dir()
end
defp write_cwd_tmp_dir do
case File.cwd() do
{:ok, cwd} -> write_tmp_dir(cwd)
_ -> nil
end
write_tmp_dir('/tmp') || ((cwd = cwd()) && write_tmp_dir(cwd))
end
@doc """
@@ -297,10 +296,12 @@ defmodule System do
Same as `tmp_dir/0` but raises `RuntimeError`
instead of returning `nil` if no temp dir is set.
"""
@spec tmp_dir!() :: String.t()
def tmp_dir! do
tmp_dir() ||
raise "could not get a writable temporary directory, please set the TMPDIR environment variable"
raise RuntimeError,
message:
"could not get a writable temporary directory, " <>
"please set the TMPDIR environment variable"
end
defp write_env_tmp_dir(env) do
@@ -339,10 +340,8 @@ defmodule System do
The function must receive the exit status code as an argument.
"""
@spec at_exit((non_neg_integer -> any)) :: :ok
def at_exit(fun) when is_function(fun, 1) do
:elixir_config.update(:at_exit, &[fun | &1])
:ok
end
@doc """
@@ -455,13 +454,12 @@ defmodule System do
Note that the Erlang VM (and therefore this function) does not
return the current stacktrace but rather the stacktrace of the
latest exception. To retrieve the stacktrace of the current process,
use `Process.info(self(), :current_stacktrace)` instead.
latest exception.
"""
# TODO: Fully deprecate it on Elixir v1.9.
# It is currently partially deprecated in elixir_dispatch.erl
def stacktrace do
apply(:erlang, :get_stacktrace, [])
:erlang.get_stacktrace()
end
@doc """
@@ -883,39 +881,26 @@ defmodule System do
defp normalize_time_unit(:native), do: :native
defp normalize_time_unit(:second), do: :second
defp normalize_time_unit(:millisecond), do: :millisecond
defp normalize_time_unit(:microsecond), do: :microsecond
defp normalize_time_unit(:nanosecond), do: :nanosecond
defp normalize_time_unit(:second), do: :seconds
defp normalize_time_unit(:millisecond), do: :milli_seconds
defp normalize_time_unit(:microsecond), do: :micro_seconds
defp normalize_time_unit(:nanosecond), do: :nano_seconds
defp normalize_time_unit(:seconds), do: warn(:seconds, :second)
defp normalize_time_unit(:milliseconds), do: warn(:milliseconds, :millisecond)
defp normalize_time_unit(:microseconds), do: warn(:microseconds, :microsecond)
defp normalize_time_unit(:nanoseconds), do: warn(:nanoseconds, :nanosecond)
defp normalize_time_unit(:milli_seconds), do: warn(:milli_seconds, :millisecond)
defp normalize_time_unit(:micro_seconds), do: warn(:micro_seconds, :microsecond)
defp normalize_time_unit(:nano_seconds), do: warn(:nano_seconds, :nanosecond)
defp normalize_time_unit(:seconds), do: :seconds
defp normalize_time_unit(:milliseconds), do: :milli_seconds
defp normalize_time_unit(:microseconds), do: :micro_seconds
defp normalize_time_unit(:nanoseconds), do: :nano_seconds
defp normalize_time_unit(unit) when is_integer(unit) and unit > 0, do: unit
defp normalize_time_unit(erlang_unit)
when erlang_unit in [:milli_seconds, :micro_seconds, :nano_seconds] do
erlang_unit
end
defp normalize_time_unit(other) do
raise ArgumentError,
"unsupported time unit. Expected :second, :millisecond, " <>
":microsecond, :nanosecond, or a positive integer, " <> "got #{inspect(other)}"
end
defp warn(unit, replacement_unit) do
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
stacktrace = Enum.drop(stacktrace, 3)
:elixir_config.warn({System, unit}, stacktrace) &&
IO.warn(
"deprecated time unit: #{inspect(unit)}. A time unit should be " <>
":second, :millisecond, :microsecond, :nanosecond, or a positive integer",
stacktrace
)
replacement_unit
end
end
+93 -160
View File
@@ -9,7 +9,7 @@ defmodule Task do
by computing a value asynchronously:
task = Task.async(fn -> do_some_work() end)
res = do_some_other_work()
res = do_some_other_work()
res + Task.await(task)
Tasks spawned with `async` can be awaited on by their caller
@@ -62,8 +62,8 @@ defmodule Task do
a function to run:
Supervisor.start_link([
{Task, fn -> :some_work end}
], strategy: :one_for_one)
{Task, fn -> ... some function ... end}
])
However, if you want to invoke a specific module, function and
arguments, or give the task process a name, you need to define
@@ -85,21 +85,21 @@ defmodule Task do
Supervisor.start_link([
{MyTask, arg}
], strategy: :one_for_one)
])
Since these tasks are supervised and not directly linked to
the caller, they cannot be awaited on. `start_link/1`, unlike
`async/1`, returns `{:ok, pid}` (which is the result expecte
by supervisors).
the caller, they cannot be awaited on. Note `start_link/1`,
unlike `async/1`, returns `{:ok, pid}` (which is the result
expected by supervisors).
`use Task` defines a `child_spec/1` function, allowing the
Note `use Task` defines a `child_spec/1` function, allowing the
defined module to be put under a supervision tree. The generated
`child_spec/1` can be customized with the following options:
* `:id` - the child specification identifier, defaults to the current module
* `:start` - how to start the child process (defaults to calling `__MODULE__.start_link/1`)
* `:restart` - when the child should be restarted, defaults to `:temporary`
* `:shutdown` - how to shut down the child, either immediately or by giving it time to shut down
* `:shutdown` - how to shut down the child
Opposite to `GenServer`, `Agent` and `Supervisor`, a Task has
a default `:restart` of `:temporary`. This means the task will
@@ -112,10 +112,7 @@ defmodule Task do
use Task, restart: :permanent
See the "Child specification" section in the `Supervisor` module
for more detailed information. The `@doc` annotation immediately
preceding `use Task` will be attached to the generated `child_spec/1`
function.
See the `Supervisor` docs for more information.
## Dynamically supervised tasks
@@ -125,12 +122,9 @@ defmodule Task do
A short example is:
{:ok, pid} = Task.Supervisor.start_link()
task =
Task.Supervisor.async(pid, fn ->
# Do something
end)
task = Task.Supervisor.async(pid, fn ->
# Do something
end)
Task.await(task)
However, in the majority of cases, you want to add the task supervisor
@@ -138,7 +132,7 @@ defmodule Task do
Supervisor.start_link([
{Task.Supervisor, name: MyApp.TaskSupervisor}
], strategy: :one_for_one)
])
Now you can dynamically start supervised tasks:
@@ -150,22 +144,21 @@ defmodule Task do
Task.Supervisor.async(MyApp.TaskSupervisor, fn ->
# Do something
end)
|> Task.await()
end) |> Task.await()
Finally, check `Task.Supervisor` for other supported operations.
## Distributed tasks
Since Elixir provides a `Task.Supervisor`, it is easy to use one
Since Elixir provides a Task supervisor, it is easy to use one
to dynamically spawn tasks across nodes:
# On the remote node
Task.Supervisor.start_link(name: MyApp.DistSupervisor)
# On the client
supervisor = {MyApp.DistSupervisor, :remote@local}
Task.Supervisor.async(supervisor, MyMod, :my_fun, [arg1, arg2, arg3])
Task.Supervisor.async({MyApp.DistSupervisor, :remote@local},
MyMod, :my_fun, [arg1, arg2, arg3])
Note that, when working with distributed tasks, one should use the `Task.Supervisor.async/4` function
that expects explicit module, function and arguments, instead of `Task.Supervisor.async/2` that
@@ -188,34 +181,16 @@ defmodule Task do
* `:owner` - the PID of the process that started the task
"""
@enforce_keys [:pid, :ref, :owner]
defstruct pid: nil, ref: nil, owner: nil
@typedoc """
The Task type.
See `%Task{}` for information about each field of the structure.
"""
@type t :: %__MODULE__{
pid: pid() | nil,
ref: reference() | nil,
owner: pid() | nil
}
defguardp is_timeout(timeout)
when timeout == :infinity or (is_integer(timeout) and timeout >= 0)
@type t :: %__MODULE__{}
@doc """
Returns a specification to start a task under a supervisor.
`arg` is passed as the argument to `Task.start_link/1` in the `:start` field
of the spec.
For more information, see the `Supervisor` module,
the `Supervisor.child_spec/2` function and the `t:Supervisor.child_spec/0` type.
See `Supervisor`.
"""
@doc since: "1.5.0"
@spec child_spec(term) :: Supervisor.child_spec()
def child_spec(arg) do
%{
id: Task,
@@ -227,18 +202,12 @@ defmodule Task do
@doc false
defmacro __using__(opts) do
quote location: :keep, bind_quoted: [opts: opts] do
if Module.get_attribute(__MODULE__, :doc) == nil do
@doc """
Returns a specification to start this module under a supervisor.
`arg` is passed as the argument to `Task.start_link/1` in the `:start` field
of the spec.
For more information, see the `Supervisor` module,
the `Supervisor.child_spec/2` function and the `t:Supervisor.child_spec/0` type.
"""
end
@doc """
Returns a specification to start this module under a supervisor.
See `Supervisor`.
"""
@doc since: "1.5.0"
def child_spec(arg) do
default = %{
id: __MODULE__,
@@ -256,12 +225,10 @@ defmodule Task do
@doc """
Starts a process linked to the current process.
`fun` must be a zero-arity anonymous function.
This is often used to start the process as part of a supervision tree.
"""
@spec start_link((() -> any)) :: {:ok, pid}
def start_link(fun) when is_function(fun, 0) do
def start_link(fun) do
start_link(:erlang, :apply, [fun, []])
end
@@ -269,23 +236,19 @@ defmodule Task do
Starts a task as part of a supervision tree.
"""
@spec start_link(module, atom, [term]) :: {:ok, pid}
def start_link(module, function_name, args)
when is_atom(module) and is_atom(function_name) and is_list(args) do
mfa = {module, function_name, args}
Task.Supervised.start_link(get_owner(self()), get_callers(self()), mfa)
def start_link(mod, fun, args) do
Task.Supervised.start_link(get_info(self()), {mod, fun, args})
end
@doc """
Starts a task.
`fun` must be a zero-arity anonymous function.
This is only used when the task is used for side-effects
(i.e. no interest in the returned result) and it should not
be linked to the current process.
"""
@spec start((() -> any)) :: {:ok, pid}
def start(fun) when is_function(fun, 0) do
def start(fun) do
start(:erlang, :apply, [fun, []])
end
@@ -297,27 +260,24 @@ defmodule Task do
be linked to the current process.
"""
@spec start(module, atom, [term]) :: {:ok, pid}
def start(module, function_name, args)
when is_atom(module) and is_atom(function_name) and is_list(args) do
mfa = {module, function_name, args}
Task.Supervised.start(get_owner(self()), get_callers(self()), mfa)
def start(mod, fun, args) do
Task.Supervised.start(get_info(self()), {mod, fun, args})
end
@doc """
Starts a task that must be awaited on.
`fun` must be a zero-arity anonymous function.
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 information about the
general usage of `async/1` and `async/3`.
Read the `Task` module documentation for more info on general
usage of `async/1` and `async/3`.
See also `async/3`.
"""
@spec async((() -> any)) :: t
def async(fun) when is_function(fun, 0) do
def async(fun) do
async(:erlang, :apply, [fun, []])
end
@@ -328,8 +288,8 @@ defmodule Task do
Developers must eventually call `Task.await/2` or `Task.yield/2`
followed by `Task.shutdown/2` on the returned task.
Read the `Task` module documentation for more information about
the general usage of `async/1` and `async/3`.
Read the `Task` module documentation for more info on general
usage of `async/1` and `async/3`.
## Linking
@@ -385,52 +345,49 @@ defmodule Task do
and `result` is the return value of the task function.
"""
@spec async(module, atom, [term]) :: t
def async(module, function_name, args)
when is_atom(module) and is_atom(function_name) and is_list(args) do
mfa = {module, function_name, args}
def async(mod, fun, args) do
mfa = {mod, fun, args}
owner = self()
{:ok, pid} = Task.Supervised.start_link(get_owner(owner), get_callers(owner), :nomonitor, mfa)
pid = Task.Supervised.spawn_link(owner, get_info(owner), mfa)
ref = Process.monitor(pid)
send(pid, {owner, ref})
%Task{pid: pid, ref: ref, owner: owner}
end
@doc """
Returns a stream where the given function (`module` and `function_name`)
is mapped concurrently on each item in `enumerable`.
Returns a stream that runs the given `module`, `function`, and `args`
concurrently on each item in `enumerable`.
Each item of `enumerable` will be prepended to the given `args` and
processed by its own task. The tasks will be linked to an intermediate
process that is then linked to the current process. This means a failure
in a task terminates the current process and a failure in the current process
Each item will be prepended to the given `args` and processed by its
own task. The tasks will be linked to an intermediate process that is
then linked to the current process. This means a failure in a task
terminates the current process and a failure in the current process
terminates all tasks.
When streamed, each task will emit `{:ok, value}` upon successful
completion or `{:exit, reason}` if the caller is trapping exits.
The order of results depends on the value of the `:ordered` option.
Results are emitted in the same order as the original `enumerable`.
The level of concurrency and the time tasks are allowed to run can
be controlled via options (see the "Options" section below).
The level of concurrency can be controlled via the `:max_concurrency`
option and defaults to `System.schedulers_online/0`. A timeout
can also be given as an option representing the maximum amount of
time to wait without a task reply.
Consider using `Task.Supervisor.async_stream/6` to start tasks
Finally, consider using `Task.Supervisor.async_stream/6` to start tasks
under a supervisor. If you find yourself trapping exits to handle exits
inside the async stream, consider using `Task.Supervisor.async_stream_nolink/6`
to start tasks that are not linked to the calling process.
to start tasks that are not linked to the current process.
## Options
* `:max_concurrency` - sets the maximum number of tasks to run
at the same time. Defaults to `System.schedulers_online/0`.
* `:ordered` - whether the results should be returned in the same order
as the input stream. This option is useful when you have large
streams and don't want to buffer results before they are delivered.
This is also useful when you're using the tasks for side effects.
Defaults to `true`.
* `:timeout` - the maximum amount of time (in milliseconds) each
task is allowed to execute for. Defaults to `5000`.
* `:on_timeout` - what to do when a task times out. The possible
values are:
* `:exit` (default) - the process that spawned the tasks exits.
@@ -447,32 +404,22 @@ defmodule Task do
The concurrency can be increased or decreased using the `:max_concurrency`
option. For example, if the tasks are IO heavy, the value can be increased:
max_concurrency = System.schedulers_online() * 2
max_concurrency = System.schedulers_online * 2
stream = Task.async_stream(collection, Mod, :expensive_fun, [], max_concurrency: max_concurrency)
Enum.to_list(stream)
If you do not care about the results of the computation, you can run
the stream with `Stream.run/1`. Also set `ordered: false`, as you don't
care about the order of the results either:
stream = Task.async_stream(collection, Mod, :expensive_fun, [], ordered: false)
Stream.run(stream)
"""
@doc since: "1.4.0"
@spec async_stream(Enumerable.t(), module, atom, [term], keyword) :: Enumerable.t()
def async_stream(enumerable, module, function_name, args, options \\ [])
when is_atom(module) and is_atom(function_name) and is_list(args) do
build_stream(enumerable, {module, function_name, args}, options)
def async_stream(enumerable, module, function, args, options \\ [])
when is_atom(module) and is_atom(function) and is_list(args) do
build_stream(enumerable, {module, function, args}, options)
end
@doc """
Returns a stream that runs the given function `fun` concurrently
on each item in `enumerable`.
Works the same as `async_stream/5` but with an anonymous function instead of a
module-function-arguments tuple. `fun` must be a one-arity anonymous function.
Each `enumerable` item is passed as argument to the given function `fun` and
processed by its own task. The tasks will be linked to the current process,
similarly to `async/1`.
@@ -490,36 +437,27 @@ defmodule Task do
"""
@doc since: "1.4.0"
@spec async_stream(Enumerable.t(), (term -> term), keyword) :: Enumerable.t()
def async_stream(enumerable, fun, options \\ [])
when is_function(fun, 1) and is_list(options) do
def async_stream(enumerable, fun, options \\ []) when is_function(fun, 1) do
build_stream(enumerable, fun, options)
end
defp build_stream(enumerable, fun, options) do
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn [owner | _] = callers, mfa ->
{:ok, pid} = Task.Supervised.start_link(get_owner(owner), callers, :nomonitor, mfa)
{:ok, :link, pid}
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn owner, mfa ->
{:link, Task.Supervised.spawn_link(owner, get_info(owner), mfa)}
end)
end
# Returns a tuple with the node where this is executed and either the
# registered name of the given PID or the PID of where this is executed. Used
# registered name of the given pid or the pid of where this is executed. Used
# when exiting from tasks to print out from where the task was started.
defp get_owner(pid) do
defp get_info(pid) do
self_or_name =
case Process.info(pid, :registered_name) do
{:registered_name, name} when is_atom(name) -> name
_ -> pid
end
{node(), self_or_name, pid}
end
defp get_callers(owner) do
case :erlang.get(:"$callers") do
[_ | _] = list -> [owner | list]
_ -> [owner]
end
{node(), self_or_name}
end
@doc """
@@ -528,7 +466,7 @@ defmodule Task do
In case the task process dies, the current process will exit with the same
reason as the task.
A timeout in milliseconds or `:infinity`, can be given with a default value of `5000`. If the
A timeout, in milliseconds, can be given with default value of `5000`. If the
timeout is exceeded, then the current process will exit. If the task process
is linked to the current process which is the case when a task is started with
`async`, then the task process will also exit. If the task process is trapping
@@ -547,9 +485,7 @@ defmodule Task do
It is not recommended to `await` a long-running task inside an OTP
behaviour such as `GenServer`. Instead, you should match on the message
coming from a task inside your `c:GenServer.handle_info/2` callback. For
more information on the format of the message, see the documentation for
`async/1`.
coming from a task inside your `GenServer.handle_info/2` callback.
## Examples
@@ -558,12 +494,14 @@ defmodule Task do
2
"""
@spec await(t, timeout) :: term
def await(%Task{ref: ref, owner: owner} = task, timeout \\ 5000) when is_timeout(timeout) do
if owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
@spec await(t, timeout) :: term | no_return
def await(task, timeout \\ 5000)
def await(%Task{owner: owner} = task, _) when owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
def await(%Task{ref: ref} = task, timeout) do
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
@@ -580,7 +518,7 @@ defmodule Task do
@doc false
# TODO: Remove on 2.0
@deprecated "Pattern match directly on the message instead"
@deprecated "Pattern match on the message directly instead"
def find(tasks, {ref, reply}) when is_reference(ref) do
Enum.find_value(tasks, fn
%Task{ref: ^ref} = task ->
@@ -617,7 +555,7 @@ defmodule Task do
* it isn't linked to the caller
* the caller is trapping exits
A timeout, in milliseconds or `:infinity`, can be given with a default value
A timeout, in milliseconds, can be given with default value
of `5000`. If the time runs out before a message from
the task is received, this function will return `nil`
and the monitor will remain active. Therefore `yield/2` can be
@@ -634,9 +572,8 @@ defmodule Task do
case Task.yield(task, timeout) || Task.shutdown(task) do
{:ok, result} ->
result
nil ->
Logger.warn("Failed to get a result in #{timeout}ms")
Logger.warn "Failed to get a result in #{timeout}ms"
nil
end
@@ -645,11 +582,13 @@ defmodule Task do
handle this case and return the result.
"""
@spec yield(t, timeout) :: {:ok, term} | {:exit, term} | nil
def yield(%Task{ref: ref, owner: owner} = task, timeout \\ 5000) when is_timeout(timeout) do
if owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
def yield(task, timeout \\ 5000)
def yield(%Task{owner: owner} = task, _) when owner != self() do
raise ArgumentError, invalid_owner_error(task)
end
def yield(%Task{ref: ref} = task, timeout) do
receive do
{^ref, reply} ->
Process.demonitor(ref, [:flush])
@@ -671,10 +610,8 @@ defmodule Task do
This function receives a list of tasks and waits for their
replies in the given time interval. It returns a list
of two-element tuples, with the task as the first element
and the yielded result as the second. The tasks in the returned
list will be in the same order as the tasks supplied in the `tasks`
input argument.
of tuples of two elements, with the task as the first element
and the yielded result as the second.
Similarly to `yield/2`, each task's result will be
@@ -683,9 +620,6 @@ defmodule Task do
* `{:exit, reason}` if the task has died
* `nil` if the task keeps running past the timeout
A timeout, in milliseconds or `:infinity`, can be given with a default value
of `5000`.
Check `yield/2` for more information.
## Example
@@ -707,27 +641,26 @@ defmodule Task do
tasks_with_results = Task.yield_many(tasks, 5000)
results =
Enum.map(tasks_with_results, fn {task, res} ->
# Shut down the tasks that did not reply nor exit
res || Task.shutdown(task, :brutal_kill)
end)
results = Enum.map(tasks_with_results, fn {task, res} ->
# Shutdown the tasks that did not reply nor exit
res || Task.shutdown(task, :brutal_kill)
end)
# Here we are matching only on {:ok, value} and
# ignoring {:exit, _} (crashed tasks) and `nil` (no replies)
for {:ok, value} <- results do
IO.inspect(value)
IO.inspect value
end
In the example above, we create tasks that sleep from 1
up to 10 seconds and return the number of seconds they slept for.
up to 10 seconds and return the number of seconds they slept.
If you execute the code all at once, you should see 1 up to 5
printed, as those were the tasks that have replied in the
given time. All other tasks will have been shut down using
the `Task.shutdown/2` call.
"""
@spec yield_many([t], timeout) :: [{t, {:ok, term} | {:exit, term} | nil}]
def yield_many(tasks, timeout \\ 5000) when is_timeout(timeout) do
def yield_many(tasks, timeout \\ 5000) do
timeout_ref = make_ref()
timer_ref =
@@ -781,7 +714,7 @@ defmodule Task do
`{:exit, reason}` if the task died, otherwise `nil`.
The second argument is either a timeout or `:brutal_kill`. In case
of a timeout, a `:shutdown` exit signal is sent to the task process
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 case the task terminates abnormally
(possibly killed by another process), this function will exit with the same reason.
@@ -790,10 +723,10 @@ defmodule Task do
exiting with reason `:normal` or if 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 shut down all of its linked processes, including tasks, that
`:shutdown` to shutdown all of its linked processes, including tasks, that
are not trapping exits without generating any log messages.
If a task's monitor has already been demonitored or received and there is not
If a task's monitor has already been demonitored or received and there is not
a response waiting in the message queue this function will return
`{:exit, :noproc}` as the result or exit reason can not be determined.
"""
@@ -824,7 +757,7 @@ defmodule Task do
end
end
def shutdown(%Task{pid: pid} = task, timeout) when is_timeout(timeout) do
def shutdown(%Task{pid: pid} = task, timeout) do
mon = Process.monitor(pid)
exit(pid, :shutdown)
+96 -135
View File
@@ -2,37 +2,40 @@ defmodule Task.Supervised do
@moduledoc false
@ref_timeout 5000
def start(owner, callers, fun) do
{:ok, :proc_lib.spawn(__MODULE__, :noreply, [owner, callers, fun])}
def start(info, fun) do
{:ok, :proc_lib.spawn(__MODULE__, :noreply, [info, fun])}
end
def start_link(owner, callers, fun) do
{:ok, :proc_lib.spawn_link(__MODULE__, :noreply, [owner, callers, fun])}
def start_link(info, fun) do
{:ok, :proc_lib.spawn_link(__MODULE__, :noreply, [info, fun])}
end
def start_link(owner, callers, monitor, fun) do
{:ok, :proc_lib.spawn_link(__MODULE__, :reply, [owner, callers, monitor, fun])}
def start_link(caller, monitor, info, fun) do
{:ok, spawn_link(caller, monitor, info, fun)}
end
def reply({_, _, owner_pid} = owner, callers, monitor, mfa) do
def spawn_link(caller, monitor \\ :nomonitor, info, fun) do
:proc_lib.spawn_link(__MODULE__, :reply, [caller, monitor, info, fun])
end
def reply(caller, monitor, info, mfa) do
initial_call(mfa)
put_callers(callers)
case monitor do
:monitor ->
mref = Process.monitor(owner_pid)
reply(owner, owner_pid, mref, @ref_timeout, mfa)
mref = Process.monitor(caller)
reply(caller, mref, @ref_timeout, info, mfa)
:nomonitor ->
reply(owner, owner_pid, nil, :infinity, mfa)
reply(caller, nil, :infinity, info, mfa)
end
end
defp reply(owner, owner_pid, mref, timeout, mfa) do
defp reply(caller, mref, timeout, info, mfa) do
receive do
{^owner_pid, ref} ->
{^caller, ref} ->
_ = if mref, do: Process.demonitor(mref, [:flush])
send(owner_pid, {ref, invoke_mfa(owner, mfa)})
send(caller, {ref, do_apply(info, mfa)})
{:DOWN, ^mref, _, _, reason} when is_reference(mref) ->
exit({:shutdown, reason})
@@ -61,14 +64,9 @@ defmodule Task.Supervised do
end
end
def noreply(owner, callers, mfa) do
def noreply(info, mfa) do
initial_call(mfa)
put_callers(callers)
invoke_mfa(owner, mfa)
end
defp put_callers(callers) do
Process.put(:"$callers", callers)
do_apply(info, mfa)
end
defp initial_call(mfa) do
@@ -85,26 +83,44 @@ defmodule Task.Supervised do
{mod, fun, length(args)}
end
defp invoke_mfa(owner, {module, fun, args} = mfa) do
# TODO: Remove conditionals once we depend on Erlang/OTP 20+
defp do_apply(info, {module, fun, args} = mfa) do
try do
apply(module, fun, args)
catch
:error, value ->
reason = {value, __STACKTRACE__}
log(info, mfa, reason)
if :erlang.system_info(:otp_release) >= '20' do
:erlang.raise(:error, value, __STACKTRACE__)
else
exit(reason)
end
:throw, value ->
reason = {{:nocatch, value}, __STACKTRACE__}
log(info, mfa, reason)
if :erlang.system_info(:otp_release) >= '20' do
:erlang.raise(:throw, value, __STACKTRACE__)
else
exit(reason)
end
:exit, value
when value == :normal
when value == :shutdown
when tuple_size(value) == 2 and elem(value, 0) == :shutdown ->
:erlang.raise(:exit, value, __STACKTRACE__)
kind, value ->
log(owner, mfa, {log_value(kind, value), __STACKTRACE__})
:erlang.raise(kind, value, __STACKTRACE__)
:exit, value ->
log(info, mfa, {value, __STACKTRACE__})
:erlang.raise(:exit, value, __STACKTRACE__)
end
end
defp log_value(:throw, value), do: {:nocatch, value}
defp log_value(_, value), do: value
defp log(owner, mfa, reason) do
defp log(info, mfa, reason) do
{fun, args} = get_running(mfa)
message =
@@ -113,12 +129,11 @@ defmodule Task.Supervised do
'** When function == ~p~n' ++
'** arguments == ~p~n' ++ '** Reason for termination == ~n' ++ '** ~p~n'
:error_logger.format(message, [self(), get_from(owner), fun, args, get_reason(reason)])
:error_logger.format(message, [self(), get_from(info), fun, args, get_reason(reason)])
end
defp get_from({node, pid_or_name, _pid}) when node == node(), do: pid_or_name
defp get_from({node, name, _pid}) when is_atom(name), do: {node, name}
defp get_from({_node, _name, pid}), do: pid
defp get_from({node, pid_or_name}) when node == node(), do: pid_or_name
defp get_from(other), do: other
defp get_running({:erlang, :apply, [fun, []]}) when is_function(fun, 0), do: {fun, []}
defp get_running({mod, fun, args}), do: {Function.capture(mod, fun, length(args)), args}
@@ -153,7 +168,6 @@ defmodule Task.Supervised do
timeout = Keyword.get(options, :timeout, 5000)
on_timeout = Keyword.get(options, :on_timeout, :exit)
parent = self()
callers = get_callers()
{:trap_exit, trap_exit?} = Process.info(self(), :trap_exit)
@@ -163,10 +177,7 @@ defmodule Task.Supervised do
spawn_opts = [:link, :monitor]
{monitor_pid, monitor_ref} =
Process.spawn(
fn -> stream_monitor(callers, mfa, spawn, trap_exit?, timeout) end,
spawn_opts
)
Process.spawn(fn -> stream_monitor(parent, mfa, spawn, trap_exit?, timeout) end, spawn_opts)
# Now that we have the pid of the "monitor" process and the reference of the
# monitor we use to monitor such process, we can inform the monitor process
@@ -193,13 +204,6 @@ defmodule Task.Supervised do
)
end
defp get_callers do
case :erlang.get(:"$callers") do
[_ | _] = list -> [self() | list]
_ -> [self()]
end
end
defp stream_reduce({:halt, acc}, _max, _spawned, _delivered, _waiting, next, config) do
%{monitor_pid: monitor_pid, monitor_ref: monitor_ref, timeout: timeout} = config
stream_close(monitor_pid, monitor_ref, timeout)
@@ -425,26 +429,15 @@ defmodule Task.Supervised do
send(pid, {self(), {monitor_ref, spawned}})
Map.put(waiting, spawned, {pid, :running})
{:max_children, ^monitor_ref} ->
stream_close(monitor_pid, monitor_ref, timeout)
raise """
reached the maximum number of tasks for this task supervisor. The maximum number \
of tasks that are allowed to run at the same time under this supervisor can be \
configured with the :max_children option passed to Task.Supervisor.start_link/1. When \
using async_stream or async_stream_nolink, make sure to configure :max_concurrency to \
be lower or equal to :max_children and pay attention to whether other tasks are also \
spawned under the same task supervisor.\
"""
{:DOWN, ^monitor_ref, _, ^monitor_pid, reason} ->
stream_cleanup_inbox(monitor_pid, monitor_ref)
exit({reason, {__MODULE__, :stream, [timeout]}})
end
end
defp stream_monitor([parent_pid | _] = callers, mfa, spawn, trap_exit?, timeout) do
defp stream_monitor(parent_pid, mfa, spawn, trap_exit?, timeout) do
Process.flag(:trap_exit, trap_exit?)
parent_ref = Process.monitor(parent_pid)
# Let's wait for the parent process to tell this process the monitor ref
@@ -453,7 +446,7 @@ defmodule Task.Supervised do
receive do
{^parent_pid, monitor_ref} ->
config = %{
callers: callers,
parent_pid: parent_pid,
parent_ref: parent_ref,
mfa: mfa,
spawn: spawn,
@@ -470,7 +463,8 @@ defmodule Task.Supervised do
defp stream_monitor_loop(running_tasks, config) do
%{
callers: [parent_pid | _] = callers,
parent_pid: parent_pid,
parent_ref: parent_ref,
mfa: mfa,
spawn: spawn,
monitor_ref: monitor_ref,
@@ -481,35 +475,55 @@ defmodule Task.Supervised do
# The parent process is telling us to spawn a new task to process
# "value". We spawn it and notify the parent about its pid.
{:spawn, position, value} ->
case spawn.(callers, normalize_mfa_with_arg(mfa, value)) do
{:ok, type, pid} ->
ref = Process.monitor(pid)
{type, pid} = spawn.(parent_pid, normalize_mfa_with_arg(mfa, value))
ref = Process.monitor(pid)
# Schedule a timeout message to ourselves, unless the timeout was set to :infinity
timer_ref =
case timeout do
:infinity -> nil
timeout -> Process.send_after(self(), {:timeout, {monitor_ref, ref}}, timeout)
end
# Schedule a timeout message to ourselves, unless the timeout was set to :infinity
timer_ref =
case timeout do
:infinity -> nil
timeout -> Process.send_after(self(), {:timeout, {monitor_ref, ref}}, timeout)
end
send(parent_pid, {:spawned, {monitor_ref, position}, pid})
send(parent_pid, {:spawned, {monitor_ref, position}, pid})
running_tasks =
Map.put(running_tasks, ref, %{
position: position,
type: type,
pid: pid,
timer_ref: timer_ref,
timed_out?: false
})
task_info = %{
position: position,
type: type,
pid: pid,
timer_ref: timer_ref,
timed_out?: false
}
stream_monitor_loop(running_tasks, config)
running_tasks = Map.put(running_tasks, ref, task_info)
stream_monitor_loop(running_tasks, config)
{:error, :max_children} ->
send(parent_pid, {:max_children, monitor_ref})
stream_waiting_for_stop_loop(running_tasks, config)
# The parent process is telling us to stop because the stream is being
# closed. In this case, we forcibly kill all spawned processes and then
# exit gracefully ourselves.
{:stop, ^monitor_ref} ->
Process.flag(:trap_exit, true)
for {ref, %{pid: pid}} <- running_tasks do
Process.exit(pid, :kill)
receive do
{:DOWN, ^ref, _, _, _} -> :ok
end
end
exit(:normal)
# The parent process went down with a given reason. We kill all the
# spawned processes (that are also linked) with the same reason, and then
# exit ourselves with the same reason.
{:DOWN, ^parent_ref, _, _, reason} ->
for {_ref, %{type: :link, pid: pid}} <- running_tasks do
Process.exit(pid, reason)
end
exit(reason)
# One of the spawned processes went down. We inform the parent process of
# this and keep going.
{:DOWN, ref, _, _, reason} ->
@@ -543,62 +557,9 @@ defmodule Task.Supervised do
{:EXIT, _, _} ->
stream_monitor_loop(running_tasks, config)
other ->
handle_stop_or_parent_down(other, running_tasks, config)
stream_monitor_loop(running_tasks, config)
end
end
defp stream_waiting_for_stop_loop(running_tasks, config) do
receive do
message ->
handle_stop_or_parent_down(message, running_tasks, config)
stream_waiting_for_stop_loop(running_tasks, config)
end
end
# The parent process is telling us to stop because the stream is being
# closed. In this case, we forcibly kill all spawned processes and then
# exit gracefully ourselves.
defp handle_stop_or_parent_down(
{:stop, monitor_ref},
running_tasks,
%{monitor_ref: monitor_ref}
) do
Process.flag(:trap_exit, true)
for {_ref, %{pid: pid}} <- running_tasks, do: Process.exit(pid, :kill)
for {ref, _task} <- running_tasks do
receive do
{:DOWN, ^ref, _, _, _} -> :ok
end
end
exit(:normal)
end
# The parent process went down with a given reason. We kill all the
# spawned processes (that are also linked) with the same reason, and then
# exit ourselves with the same reason.
defp handle_stop_or_parent_down(
{:DOWN, parent_ref, _, _, reason},
running_tasks,
%{parent_ref: parent_ref}
) do
for {_ref, %{type: :link, pid: pid}} <- running_tasks do
Process.exit(pid, reason)
end
exit(reason)
end
# We ignore all other messages.
defp handle_stop_or_parent_down(_other, _running_tasks, _config) do
:ok
end
defp unlink_and_kill(pid) do
caller = self()
ref = make_ref()
+35 -120
View File
@@ -78,7 +78,7 @@ defmodule Task.Supervisor do
give them directly to `start_child` and `async`.
"""
@spec start_link([option]) :: Supervisor.on_start()
# TODO: Deprecate passing restart and shutdown here on Elixir v1.9.
# TODO: Deprecate passing restart and shutdown here on Elixir v1.8.
def start_link(options \\ []) do
{restart, options} = Keyword.pop(options, :restart, :temporary)
{shutdown, options} = Keyword.pop(options, :shutdown, 5000)
@@ -97,13 +97,10 @@ defmodule Task.Supervisor do
@doc """
Starts a task that can be awaited on.
The `supervisor` must be a reference as defined in `Supervisor`.
The `supervisor` must be a reference as defined in `Task.Supervisor`.
The task will still be linked to the caller, see `Task.async/3` for
more information and `async_nolink/2` for a non-linked variant.
Raises an error if `supervisor` has reached the maximum number of
children.
## Options
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
@@ -118,13 +115,10 @@ defmodule Task.Supervisor do
@doc """
Starts a task that can be awaited on.
The `supervisor` must be a reference as defined in `Supervisor`.
The `supervisor` must be a reference as defined in `Task.Supervisor`.
The task will still be linked to the caller, see `Task.async/3` for
more information and `async_nolink/2` for a non-linked variant.
Raises an error if `supervisor` has reached the maximum number of
children.
## Options
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
@@ -139,13 +133,10 @@ defmodule Task.Supervisor do
@doc """
Starts a task that can be awaited on.
The `supervisor` must be a reference as defined in `Supervisor`.
The `supervisor` must be a reference as defined in `Task.Supervisor`.
The task won't be linked to the caller, see `Task.async/3` for
more information.
Raises an error if `supervisor` has reached the maximum number of
children.
## Options
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
@@ -165,53 +156,6 @@ defmodule Task.Supervisor do
terminates, the caller's process will always receive a `:DOWN` message
with the same `ref` value that is held by the task struct. If the task
terminates normally, the reason in the `:DOWN` message will be `:normal`.
## Examples
Typically, you use `async_nolink/3` when there is a reasonable expectation that
the task may fail, and you don't want it to take down the caller. Let's see an
example where a `GenServer` is meant to run a single task and track its status:
defmodule MyApp.Server do
use GenServer
# ...
def start_task do
GenServer.call(__MODULE__, :start_task)
end
# In this case the task is already running, so we just return :ok.
def handle_call(:start_task, %{ref: ref} = state) when is_reference(ref) do
{:reply, :ok, state}
end
# The task is not running yet, so let's start it.
def handle_cast(:start_task, %{ref: nil} = state) do
task =
Task.Supervisor.async_nolink(MyApp.TaskSupervisor, fn ->
...
end)
# We return :ok and the server will continue running
{:reply, :ok, %{state | ref: task.ref}}
end
# The task completed successfully
def handle_info({ref, answer}, %{ref: ref} = state) do
# We don't care about the DOWN message now, so let's demonitor and flush it
Process.demonitor(ref, [:flush])
# Do something with the result and then return
{:noreply, %{state | ref: nil}}
end
# The task failed
def handle_info({:DOWN, ref, :process, _pid, _reason}, %{ref: ref} = state) do
# Log and possibly restart the task...
{:noreply, %{state | ref: nil}}
end
end
"""
@spec async_nolink(Supervisor.supervisor(), (() -> any), Keyword.t()) :: Task.t()
def async_nolink(supervisor, fun, options \\ []) do
@@ -221,13 +165,10 @@ defmodule Task.Supervisor do
@doc """
Starts a task that can be awaited on.
The `supervisor` must be a reference as defined in `Supervisor`.
The `supervisor` must be a reference as defined in `Task.Supervisor`.
The task won't be linked to the caller, see `Task.async/3` for
more information.
Raises an error if `supervisor` has reached the maximum number of
children.
Note this function requires the task supervisor to have `:temporary`
as the `:restart` option (the default), as `async_nolink/4` keeps a
direct reference to the task which is lost if the task is restarted.
@@ -238,8 +179,8 @@ defmodule Task.Supervisor do
end
@doc """
Returns a stream where the given function (`module` and `function`)
is mapped concurrently on each item in `enumerable`.
Returns a stream that runs the given `module`, `function`, and `args`
concurrently on each item in `enumerable`.
Each item will be prepended to the given `args` and processed by its
own task. The tasks will be spawned under the given `supervisor` and
@@ -247,38 +188,35 @@ defmodule Task.Supervisor do
When streamed, each task will emit `{:ok, value}` upon successful
completion or `{:exit, reason}` if the caller is trapping exits.
The order of results depends on the value of the `:ordered` option.
Results are emitted in the same order as the original `enumerable`.
The level of concurrency and the time tasks are allowed to run can
be controlled via options (see the "Options" section below).
The level of concurrency can be controlled via the `:max_concurrency`
option and defaults to `System.schedulers_online/0`. A timeout
can also be given as an option representing the maximum amount of
time to wait without a task reply.
If you find yourself trapping exits to handle exits inside
Finally, if you find yourself trapping exits to handle exits inside
the async stream, consider using `async_stream_nolink/6` to start tasks
that are not linked to the calling process.
that are not linked to the current process.
## Options
* `:max_concurrency` - sets the maximum number of tasks to run
at the same time. Defaults to `System.schedulers_online/0`.
* `:ordered` - whether the results should be returned in the same order
as the input stream. This option is useful when you have large
streams and don't want to buffer results before they are delivered.
This is also useful when you're using the tasks for side effects.
Defaults to `true`.
* `:timeout` - the maximum amount of time to wait (in milliseconds)
without receiving a task reply (across all running tasks).
Defaults to `5000`.
* `:on_timeout` - what do to when a task times out. The possible
values are:
* `:exit` (default) - the process that spawned the tasks exits.
* `:kill_task` - the task that timed out is killed. The value
emitted for that task is `{:exit, :timeout}`.
* `:shutdown` - `:brutal_kill` if the tasks must be killed directly on shutdown
or an integer indicating the timeout value. Defaults to `5000` milliseconds.
or an integer indicating the timeout value, defaults to 5000 milliseconds.
## Examples
@@ -314,8 +252,8 @@ defmodule Task.Supervisor do
end
@doc """
Returns a stream where the given function (`module` and `function`)
is mapped concurrently on each item in `enumerable`.
Returns a stream that runs the given `module`, `function`, and `args`
concurrently on each item in `enumerable`.
Each item in `enumerable` will be prepended to the given `args` and processed
by its own task. The tasks will be spawned under the given `supervisor` and
@@ -395,7 +333,7 @@ defmodule Task.Supervisor do
def start_child(supervisor, fun, options \\ []) do
restart = options[:restart]
shutdown = options[:shutdown]
args = [get_owner(self()), get_callers(self()), {:erlang, :apply, [fun, []]}]
args = [get_info(self()), {:erlang, :apply, [fun, []]}]
start_child_with_spec(supervisor, args, restart, shutdown)
end
@@ -411,7 +349,7 @@ defmodule Task.Supervisor do
when is_atom(fun) and is_list(args) do
restart = options[:restart]
shutdown = options[:shutdown]
args = [get_owner(self()), get_callers(self()), {module, fun, args}]
args = [get_info(self()), {module, fun, args}]
start_child_with_spec(supervisor, args, restart, shutdown)
end
@@ -422,58 +360,35 @@ defmodule Task.Supervisor do
GenServer.call(supervisor, {:start_task, args, restart, shutdown}, :infinity)
end
defp get_owner(pid) do
self_or_name =
case Process.info(pid, :registered_name) do
defp get_info(self) do
name =
case Process.info(self, :registered_name) do
{:registered_name, name} when is_atom(name) -> name
_ -> pid
_ -> self
end
{node(), self_or_name, pid}
end
defp get_callers(owner) do
case :erlang.get(:"$callers") do
[_ | _] = list -> [owner | list]
_ -> [owner]
end
{node(), name}
end
defp async(supervisor, link_type, module, fun, args, options) do
owner = self()
args = [get_owner(owner), get_callers(owner), :monitor, {module, fun, args}]
args = [owner, :monitor, get_info(owner), {module, fun, args}]
shutdown = options[:shutdown]
case start_child_with_spec(supervisor, args, :temporary, shutdown) do
{:ok, pid} ->
if link_type == :link, do: Process.link(pid)
ref = Process.monitor(pid)
send(pid, {owner, ref})
%Task{pid: pid, ref: ref, owner: owner}
{:error, :max_children} ->
raise """
reached the maximum number of tasks for this task supervisor. The maximum number \
of tasks that are allowed to run at the same time under this supervisor can be \
configured with the :max_children option passed to Task.Supervisor.start_link/1\
"""
end
{:ok, pid} = start_child_with_spec(supervisor, args, :temporary, shutdown)
if link_type == :link, do: Process.link(pid)
ref = Process.monitor(pid)
send(pid, {owner, ref})
%Task{pid: pid, ref: ref, owner: owner}
end
defp build_stream(supervisor, link_type, enumerable, fun, options) do
shutdown = options[:shutdown]
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn [owner | _] = callers, mfa ->
args = [get_owner(owner), callers, :monitor, mfa]
case start_child_with_spec(supervisor, args, :temporary, shutdown) do
{:ok, pid} ->
if link_type == :link, do: Process.link(pid)
{:ok, link_type, pid}
{:error, :max_children} ->
{:error, :max_children}
end
&Task.Supervised.stream(enumerable, &1, &2, fun, options, fn owner, mfa ->
args = [owner, :monitor, get_info(owner), mfa]
{:ok, pid} = start_child_with_spec(supervisor, args, :temporary, shutdown)
if link_type == :link, do: Process.link(pid)
{link_type, pid}
end)
end
end
+6 -6
View File
@@ -7,7 +7,7 @@ defmodule Tuple do
* `elem/2` - access a tuple by index
* `put_elem/3` - insert a value into a tuple by index
* `tuple_size/1` - get the number of elements in a tuple
Tuples are intended as fixed-size containers for multiple elements.
To manipulate a collection of elements, use a list instead. `Enum`
functions do not work on tuples.
@@ -20,18 +20,18 @@ defmodule Tuple do
{1, :two, "three"}
A tuple may contain elements of different types, which are stored
contiguously in memory. Accessing any element takes constant time,
but modifying a tuple, which produces a shallow copy, takes linear time.
contiguously in memory. Accessing any element takes constant time,
but modifying a tuple, which produces a shallow copy, takes linear time.
Tuples are good for reading data while lists are better for traversals.
Tuples are typically used either when a function has multiple return values
or for error handling. `File.read/1` returns `{:ok, contents}` if reading
the given file is successful, or else `{:error, reason}` such as when
or for error handling. `File.read/1` returns `{:ok, contents}` if reading
the given file is successful, or else `{:error, reason}` such as when
the file does not exist.
The functions in this module that add and remove elements from tuples are
rarely used in practice, as they typically imply tuples are being used as
collections. To append to a tuple, it is preferable to use pattern matching:
collections. To append to a tuple, it is preferrable to use pattern matching:
tuple = {:ok, :example}
+20 -53
View File
@@ -47,7 +47,7 @@ defmodule URI do
"""
@spec default_port(binary) :: nil | non_neg_integer
def default_port(scheme) when is_binary(scheme) do
:elixir_config.get({:uri, scheme}, nil)
:elixir_config.safe_get({:uri, scheme}, nil)
end
@doc """
@@ -322,8 +322,8 @@ defmodule URI do
## Examples
iex> URI.decode("https%3A%2F%2Felixir-lang.org")
"https://elixir-lang.org"
iex> URI.decode("http%3A%2F%2Felixir-lang.org")
"http://elixir-lang.org"
"""
@spec decode(binary) :: binary
@@ -390,53 +390,22 @@ defmodule URI do
## Examples
iex> URI.parse("https://elixir-lang.org/")
%URI{
authority: "elixir-lang.org",
fragment: nil,
host: "elixir-lang.org",
path: "/",
port: 443,
query: nil,
scheme: "https",
userinfo: nil
}
iex> URI.parse("http://elixir-lang.org/")
%URI{scheme: "http", path: "/", query: nil, fragment: nil,
authority: "elixir-lang.org", userinfo: nil,
host: "elixir-lang.org", port: 80}
iex> URI.parse("//elixir-lang.org/")
%URI{
authority: "elixir-lang.org",
fragment: nil,
host: "elixir-lang.org",
path: "/",
port: nil,
query: nil,
scheme: nil,
userinfo: nil
}
%URI{authority: "elixir-lang.org", fragment: nil, host: "elixir-lang.org",
path: "/", port: nil, query: nil, scheme: nil, userinfo: nil}
iex> URI.parse("/foo/bar")
%URI{
authority: nil,
fragment: nil,
host: nil,
path: "/foo/bar",
port: nil,
query: nil,
scheme: nil,
userinfo: nil
}
%URI{authority: nil, fragment: nil, host: nil, path: "/foo/bar",
port: nil, query: nil, scheme: nil, userinfo: nil}
iex> URI.parse("foo/bar")
%URI{
authority: nil,
fragment: nil,
host: nil,
path: "foo/bar",
port: nil,
query: nil,
scheme: nil,
userinfo: nil
}
%URI{authority: nil, fragment: nil, host: nil, path: "foo/bar",
port: nil, query: nil, scheme: nil, userinfo: nil}
"""
@spec parse(t | binary) :: t
@@ -447,7 +416,9 @@ defmodule URI do
def parse(string) when is_binary(string) do
# From https://tools.ietf.org/html/rfc3986#appendix-B
regex =
Regex.recompile!(~r{^(([a-z][a-z0-9\+\-\.]*):)?(//([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?}i)
Regex.recompile!(
~r/^(([a-z][a-z0-9\+\-\.]*):)?(\/\/([^\/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/i
)
parts = Regex.run(regex, string)
@@ -517,12 +488,8 @@ defmodule URI do
iex> URI.to_string(%URI{userinfo: "bar", host: "example.org", port: 81})
"//bar@example.org:81"
iex> URI.to_string(%URI{
...> authority: "foo@example.com:80",
...> userinfo: "bar",
...> host: "example.org",
...> port: 81
...> })
iex> URI.to_string(%URI{authority: "foo@example.com:80",
...> userinfo: "bar", host: "example.org", port: 81})
"//bar@example.org:81"
"""
@@ -537,10 +504,10 @@ defmodule URI do
## Examples
iex> URI.merge(URI.parse("http://google.com"), "/query") |> to_string()
iex> URI.merge(URI.parse("http://google.com"), "/query") |> to_string
"http://google.com/query"
iex> URI.merge("http://example.com", "http://google.com") |> to_string()
iex> URI.merge("http://example.com", "http://google.com") |> to_string
"http://google.com"
"""
+42 -74
View File
@@ -14,17 +14,13 @@ defmodule Version do
MAJOR.MINOR.PATCH
Pre-releases are supported by optionally appending a hyphen and a series of
period-separated identifiers immediately following the patch version.
Identifiers consist of only ASCII alphanumeric characters and hyphens (`[0-9A-Za-z-]`):
Pre-releases are supported by appending `-[0-9A-Za-z-\.]`:
"1.0.0-alpha.3"
Build information can be added by appending a plus sign and a series of
dot-separated identifiers immediately following the patch or pre-release version.
Identifiers consist of only ASCII alphanumeric characters and hyphens (`[0-9A-Za-z-]`):
Build information can be added by appending `+[0-9A-Za-z-\.]`:
"1.0.0-alpha.3+20130417140000.amd64"
"1.0.0-alpha.3+20130417140000"
## Struct
@@ -35,9 +31,9 @@ defmodule Version do
## Requirements
Requirements allow you to specify which versions of a given
dependency you are willing to work against. Requirements support the common
comparison operators such as `>`, `>=`, `<`, `<=`, `==`, `!=` that work as one would expect,
and additionally the special operator `~>` described in detail further below.
dependency you are willing to work against. Requirements support common
operators like `>=`, `<=`, `>`, `==`, and friends that
work as one would expect:
# Only version 2.0.0
"== 2.0.0"
@@ -55,11 +51,10 @@ defmodule Version do
"~> 2.0.0"
`~>` will never include pre-release versions of its upper bound,
regardless of the usage of the `:allow_pre` option, or whether the operand
is a pre-release version. It can also be used to set an upper bound on only the major
`~>` will never include pre-release versions of its upper bound.
It can also be used to set an upper bound on only the major
version part. See the table below for `~>` requirements and
their corresponding translations.
their corresponding translation.
`~>` | Translation
:------------- | :---------------------
@@ -69,28 +64,23 @@ defmodule Version do
`~> 2.0` | `>= 2.0.0 and < 3.0.0`
`~> 2.1` | `>= 2.1.0 and < 3.0.0`
The requirement operand after the `~>` is allowed to omit the patch version,
allowing us to express `~> 2.1` or `~> 2.1-dev`, something that wouldn't be allowed
when using the common comparison operators.
When the `:allow_pre` option is set `false` in `Version.match?/3`, the requirement
will not match a pre-release version unless the operand is a pre-release version.
When `allow_pre: false` is set, the requirement will not match a
pre-release version unless the operand is a pre-release version.
The default is to always allow pre-releases but note that in
Hex `:allow_pre` is set to `false`. See the table below for examples.
Requirement | Version | `:allow_pre` | Matches
:------------- | :---------- | :---------------- | :------
`~> 2.0` | `2.1.0` | `true` or `false` | `true`
`~> 2.0` | `3.0.0` | `true` or `false` | `false`
`~> 2.0.0` | `2.0.5` | `true` or `false` | `true`
`~> 2.0.0` | `2.1.0` | `true` or `false` | `false`
`~> 2.1.2` | `2.1.6-dev` | `true` | `true`
`~> 2.1.2` | `2.1.6-dev` | `false` | `false`
`~> 2.1-dev` | `2.2.0-dev` | `true` or `false` | `true`
`~> 2.1.2-dev` | `2.1.6-dev` | `true` or `false` | `true`
`>= 2.1.0` | `2.2.0-dev` | `true` | `true`
`>= 2.1.0` | `2.2.0-dev` | `false` | `false`
`>= 2.1.0-dev` | `2.2.6-dev` | `true` or `false` | `true`
Requirement | Version | `:allow_pre` | Matches
:------------- | :---------- | :----------- | :------
`~> 2.0` | `2.1.0` | - | `true`
`~> 2.0` | `3.0.0` | - | `false`
`~> 2.0.0` | `2.0.1` | - | `true`
`~> 2.0.0` | `2.1.0` | - | `false`
`~> 2.1.2` | `2.1.3-dev` | `true` | `true`
`~> 2.1.2` | `2.1.3-dev` | `false` | `false`
`~> 2.1-dev` | `2.2.0-dev` | `false` | `true`
`~> 2.1.2-dev` | `2.1.3-dev` | `false` | `true`
`>= 2.1.0` | `2.2.0-dev` | `false` | `false`
`>= 2.1.0-dev` | `2.2.3-dev` | `true` | `true`
"""
@@ -99,17 +89,20 @@ defmodule Version do
@type version :: String.t() | t
@type requirement :: String.t() | Version.Requirement.t()
@type major :: non_neg_integer
@type minor :: non_neg_integer
@type patch :: non_neg_integer
@type major :: String.t() | non_neg_integer
@type minor :: non_neg_integer | nil
@type patch :: non_neg_integer | nil
@type pre :: [String.t() | non_neg_integer]
@type build :: String.t() | nil
@type matchable ::
{major :: major, minor :: minor, patch :: patch, pre :: pre,
build_parts :: [String.t()]}
@type t :: %__MODULE__{major: major, minor: minor, patch: patch, pre: pre, build: build}
defmodule Requirement do
@moduledoc false
defstruct [:source, :matchspec, :compiled]
@type t :: %__MODULE__{source: String.t(), matchspec: :ets.match_spec(), compiled: boolean}
@type t :: %__MODULE__{}
end
defmodule InvalidRequirementError do
@@ -152,8 +145,8 @@ defmodule Version do
## Options
* `:allow_pre` (boolean) - when `false`, pre-release versions will not match
unless the operand is a pre-release version. Defaults to `true`.
For examples, please refer to the table above under the "Requirements" section.
unless the operand is a pre-release version. See the table above
for examples. Defaults to `true`.
## Examples
@@ -163,12 +156,6 @@ defmodule Version do
iex> Version.match?("2.0.0", "== 1.0.0")
false
iex> Version.match?("2.1.6-dev", "~> 2.1.2")
true
iex> Version.match?("2.1.6-dev", "~> 2.1.2", allow_pre: false)
false
iex> Version.match?("foo", "== 1.0.0")
** (Version.InvalidVersionError) invalid version: "foo"
@@ -180,7 +167,13 @@ defmodule Version do
def match?(version, requirement, opts \\ [])
def match?(version, requirement, opts) when is_binary(requirement) do
match?(version, parse_requirement!(requirement), opts)
case parse_requirement(requirement) do
{:ok, requirement} ->
match?(version, requirement, opts)
:error ->
raise InvalidRequirementError, requirement
end
end
def match?(version, %Requirement{matchspec: spec, compiled: false}, opts) do
@@ -276,7 +269,7 @@ defmodule Version do
@doc """
Parses a version string into a `Version`.
If `string` is an invalid version, a `Version.InvalidVersionError` is raised.
If `string` is an invalid version, an `InvalidVersionError` is raised.
## Examples
@@ -287,7 +280,7 @@ defmodule Version do
** (Version.InvalidVersionError) invalid version: "2.0-alpha1"
"""
@spec parse!(String.t()) :: t
@spec parse!(String.t()) :: t | no_return
def parse!(string) when is_binary(string) do
case parse(string) do
{:ok, version} -> version
@@ -319,32 +312,6 @@ defmodule Version do
end
end
@doc """
Parses a version requirement string into a `Version.Requirement` struct.
If `string` is an invalid requirement, a `Version.InvalidRequirementError` is raised.
## Examples
iex> Version.parse_requirement!("== 2.0.1")
#Version.Requirement<== 2.0.1>
iex> Version.parse_requirement!("== == 2.0.1")
** (Version.InvalidRequirementError) invalid requirement: "== == 2.0.1"
"""
@doc since: "1.8.0"
@spec parse_requirement!(String.t()) :: Requirement.t()
def parse_requirement!(string) when is_binary(string) do
case Version.Parser.parse_requirement(string) do
{:ok, spec} ->
%Requirement{source: string, matchspec: spec, compiled: false}
:error ->
raise InvalidRequirementError, string
end
end
@doc """
Compiles a requirement to its internal representation with
`:ets.match_spec_compile/1` for faster matching.
@@ -429,6 +396,7 @@ defmodule Version do
to_matchspec(lexed)
end
@spec parse_version(String.t()) :: {:ok, Version.matchable()} | :error
def parse_version(string, approximate? \\ false) when is_binary(string) do
destructure [version_with_pre, build], String.split(string, "+", parts: 2)
destructure [version, pre], String.split(version_with_pre, "-", parts: 2)
@@ -8,15 +8,13 @@ Elixir applies bug fixes only to the latest minor branch. Security patches are a
Elixir version | Support
:------------- | :-----------------------------
1.8 | Bug fixes and security patches
1.7 | Security patches only
1.7 | Bug fixes and security patches
1.6 | Security patches only
1.5 | Security patches only
1.4 | Security patches only
1.3 | Security patches only
New releases are announced in the read-only [announcements mailing list](https://groups.google.com/group/elixir-lang-ann). All security releases [will be tagged with `[security]`](https://groups.google.com/forum/#!searchin/elixir-lang-ann/%5Bsecurity%5D%7Csort:date).
There are currently no plans for a major v2 release.
Major Elixir releases may contain breaking changes and those will be explicitly outlined in the CHANGELOG. There are currently no plans for a major v2 release.
## Compatibility between non-major Elixir versions
@@ -49,8 +47,7 @@ Elixir version | Supported Erlang/OTP versions
1.4 | 18 - 19 (and Erlang/OTP 20 from v1.4.5)
1.5 | 18 - 20
1.6 | 19 - 20 (and Erlang/OTP 21 from v1.6.6)
1.7 | 19 - 22
1.8 | 20 - 22
1.7 | 19 - 21
While Elixir often adds compatibility to new Erlang/OTP versions on released branches, such as support for Erlang/OTP 20 in v1.4.5, those releases usually contain the minimum changes for Elixir to run without errors. Only the next minor release, in this case v1.5.0, does effectively leverage the new features provided by the latest Erlang/OTP release.
@@ -70,22 +67,12 @@ Elixir deprecations happen in 3 steps:
Deprecated feature | Hard-deprecated in | Replaced by (available since)
:----------------------------------------------- | :----------------- | :----------------------------
Passing a non-empty list to `Enum.into/2` | [v1.8] | `Kernel.++/2` or `Keyword.merge/2` (v1.0)
Passing a non-empty list to `:into` in `for` | [v1.8] | `Kernel.++/2` or `Keyword.merge/2` (v1.0)
`:seconds`, `:milliseconds`, etc. as time units | [v1.8] | `:second`, `:millisecond`, etc. (v1.4)
`Inspect.Algebra.surround/3` | [v1.8] | `Inspect.Algebra.concat/2` and `Inspect.Algebra.nest/2` (v1.0)
`Inspect.Algebra.surround_many/6` | [v1.8] | `Inspect.Algebra.container_doc/6` (v1.6)
`Kernel.ParallelCompiler.files/2` | [v1.8] | `Kernel.ParallelCompiler.compile/2` (v1.6)
`Kernel.ParallelCompiler.files_to_path/2` | [v1.8] | `Kernel.ParallelCompiler.compile_to_path/2` (v1.6)
`Kernel.ParallelRequire.files/2` | [v1.8] | `Kernel.ParallelCompiler.require/2` (v1.6)
`System.cwd/0` and `System.cwd!/0` | [v1.8] | `File.cwd/0` and `File.cwd!/0` (v1.0)
`mix compile.erlang` returning `{:ok, contents}` or `:error` as the callback in `Mix.Compilers.Erlang.compile/6`| [v1.8] | Return `{:ok, contents, warnings}` or `{:error, errors, warnings}`
`Code.get_docs/2` | [v1.7] | `Code.fetch_docs/1` (v1.7)
Calling `super/1` on GenServer callbacks | [v1.7] | Not calling `super/1` (v1.0)
`Enum.chunk/2`[`/3/4`](`Enum.chunk/4`) | [v1.7] | `Enum.chunk_every/2`[`/3/4`](`Enum.chunk_every/4`) (v1.5)
Calling `super` on GenServer callbacks | [v1.7] | Not calling super (v1.0)
`Enum.chunk/2`[`/3/4`](Enum.chunk/4) | [v1.7] | `Enum.chunk_every/2`[`/3/4`](`Enum.chunk_every/4`) (v1.5)
`not left in right` | [v1.7] | [`left not in right`](`Kernel.SpecialForms.in/2`) (v1.5)
`Registry.start_link/3` | [v1.7] | `Registry.start_link/1` (v1.5)
`Stream.chunk/2`[`/3/4`](`Stream.chunk/4`) | [v1.7] | `Stream.chunk_every/2`[`/3/4`](`Stream.chunk_every/4`) (v1.5)
`Stream.chunk/2`[`/3/4`](Stream.chunk/4) | [v1.7] | `Stream.chunk_every/2`[`/3/4`](`Stream.chunk_every/4`) (v1.5)
`Enum.partition/2` | [v1.6] | `Enum.split_with/2` (v1.4)
`Keyword.replace/3` | [v1.6] | `Keyword.fetch/2` + `Keyword.put/3` (v1.0)
`Macro.unescape_tokens/1` and `Macro.unescape_tokens/2` | [v1.6] | Use `Enum.map/2` to traverse over the arguments (v1.0)
@@ -150,4 +137,3 @@ Non-map as second argument in `URI.decode_query/2` | [v1.3] | Use a map (v1
[v1.5]: https://github.com/elixir-lang/elixir/blob/v1.5/CHANGELOG.md#4-deprecations
[v1.6]: https://github.com/elixir-lang/elixir/blob/v1.6/CHANGELOG.md#4-deprecations
[v1.7]: https://github.com/elixir-lang/elixir/blob/v1.7/CHANGELOG.md#4-hard-deprecations
[v1.8]: https://github.com/elixir-lang/elixir/blob/v1.8/CHANGELOG.md#4-hard-deprecations
+79 -39
View File
@@ -6,19 +6,61 @@ Not all expressions are allowed in guard clauses, but only a handful of them. Th
## List of allowed expressions
You can find the built-in list of guards [in the `Kernel` module](Kernel.html#guards). Here is an overview:
For reference, the following is a comprehensive list of all expressions allowed in guards:
* comparison operators ([`==`](`==/2`), [`!=`](`!=/2`), [`===`](`===/2`), [`!==`](`!==/2`),
[`>`](`>/2`), [`>=`](`>=/2`), [`<`](`</2`), [`<=`](`<=/2`))
* strictly boolean operators ([`and`](`and/2`), [`or`](`or/2`), [`not`](`not/1`)). Note [`&&`](`&&/2`), [`||`](`||/2`), and [`!`](`!/1`) sibling operators are **not allowed** as they're not *strictly* boolean - meaning they don't require arguments to be booleans
* arithmetic unary and binary operators ([`+`](`+/1`), [`-`](`-/1`), [`+`](`+/2`), [`-`](`-/2`), [`*`](`*/2`), [`/`](`//2`))
* [`in`](`in/2`) and [`not in`](`in/2`) operators (as long as the right-hand side is a list or a range)
* "type-check" functions ([`is_list/1`](`is_list/1`), [`is_number/1`](`is_number/1`), etc.)
* functions that work on built-in datatypes ([`abs/1`](`abs/1`), [`map_size/1`](`map_size/1`), etc.)
* comparison operators ([`==`](`Kernel.==/2`), [`!=`](`Kernel.!=/2`), [`===`](`Kernel.===/2`), [`!==`](`Kernel.!==/2`),
[`>`](`Kernel.>/2`), [`>=`](`Kernel.>=/2`), [`<`](`Kernel.</2`), [`<=`](`Kernel.<=/2`))
* strictly boolean operators ([`and`](`Kernel.and/2`), [`or`](`Kernel.or/2`), [`not`](`Kernel.not/1`))
- __NOTE__: [`&&`](`Kernel.&&/2`), [`||`](`Kernel.||/2`), and [`!`](`Kernel.!/1`) sibling operators are not allowed as they're not
*strictly* boolean - meaning they don't require both sides to be booleans
* arithmetic binary operators ([`+`](`Kernel.+/2`), [`-`](`Kernel.-/2`), [`*`](`Kernel.*/2`), [`/`](`Kernel.//2`))
* arithmetic unary operators ([`+`](`Kernel.+/1`), [`-`](`Kernel.-/1`))
* binary concatenation operator ([`<>`](`Kernel.<>/2`))
* [`in`](`Kernel.in/2`) and [`not in`](`Kernel.in/2`) operators (as long as the right-hand side is a list or a range)
* the following "type-check" functions (all documented in the `Kernel` module):
* `is_atom/1`
* `is_binary/1`
* `is_bitstring/1`
* `is_boolean/1`
* `is_float/1`
* `is_function/1`
* `is_function/2`
* `is_integer/1`
* `is_list/1`
* `is_map/1`
* `is_nil/1`
* `is_number/1`
* `is_pid/1`
* `is_port/1`
* `is_reference/1`
* `is_tuple/1`
* the following guard-friendly functions (all documented in the `Kernel` module):
* `abs/1`
* `binary_part/3`
* `bit_size/1`
* `byte_size/1`
* `div/2`
* `elem/2`
* `hd/1`
* `length/1`
* `map_size/1`
* `node/0`
* `node/1`
* `rem/2`
* `round/1`
* `self/0`
* `tl/1`
* `trunc/1`
* `tuple_size/1`
* the following handful of Erlang bitwise operations, if imported from the `Bitwise` module:
* [`band/2`](`Bitwise.band/2`) or the [`&&&`](`Bitwise.&&&/2`) operator
* [`bor/2`](`Bitwise.bor/2`) or the [`|||`](`Bitwise.|||/2`) operator
* [`bnot/1`](`Bitwise.bnot/1`) or the [`~~~`](`Bitwise.~~~/1`) operator
* [`bsl/2`](`Bitwise.bsl/2`) or the [`<<<`](`Bitwise.<<</2`) operator
* [`bsr/2`](`Bitwise.bsr/2`) or the [`>>>`](`Bitwise.>>>/2`) operator
* [`bxor/2`](`Bitwise.bxor/2`) or the [`^^^`](`Bitwise.^^^/2`) operator
The module `Bitwise` also includes a handful of [Erlang bitwise operations as guards](Bitwise.html#guards).
Macros constructed out of any combination of the above guards are also valid guards - for example, `Integer.is_even/1`. For more information, see the "Defining custom guard expressions" section shown below.
Macros constructed out of any combination of the above guards are also valid guards - for example, `Integer.is_even/1`. See the section "Defining custom guard expressions" below.
## Why guards
@@ -44,7 +86,7 @@ In the example above, we show how guards can be used in function clauses. There
def foo(term) when is_float(term), do: round(term)
```
* [`case`](`case/2`) expressions:
* [`case`](`Kernel.SpecialForms.case/2`) expressions:
```elixir
case x do
@@ -54,7 +96,7 @@ In the example above, we show how guards can be used in function clauses. There
end
```
* anonymous functions ([`fn`](`fn/1`)s):
* anonymous functions ([`fn`](`Kernel.SpecialForms.fn/1`)s):
```elixir
larger_than_two? = fn
@@ -63,10 +105,10 @@ In the example above, we show how guards can be used in function clauses. There
end
```
* custom guards can also be defined with `defguard/1` and `defguardp/1`.
* custom guards can also be defined with `Kernel.defguard/1` and `Kernel.defguardp/1`.
A custom guard is always defined based on existing guards.
Other constructs are [`for`](`for/1`), [`with`](`with/1`), [`try/rescue/catch/else`](`try/1`), and the `match?/2`.
Other constructs are [`for`](`Kernel.SpecialForms.for/1`), [`with`](`Kernel.SpecialForms.with/1`), [`try/rescue/catch/else`](`Kernel.SpecialForms.try/1`), and the `Kernel.match?/2`.
## Failing guards
@@ -162,34 +204,32 @@ def foo(_other) do
end
```
If each guard expression always returns a boolean, the two forms are equivalent. However, recall that if any function call in a guard raises an exception, the entire guard fails. So this function will not detect empty tuples:
For most cases, the two forms are exactly the same. However, there exists a subtle difference in the case of failing guards, as discussed in the section above.
In case of a boolean expression guard, a failed element means the whole guard fails. In case of multiple guards it means the next one will be evaluated.
The difference can be highlighted with an example:
```elixir
defmodule Check do
# If given a tuple, map_size/1 will raise, and tuple_size/1 will not be evaluated
def empty?(val) when map_size(val) == 0 or tuple_size(val) == 0, do: true
def empty?(_val), do: false
def multiguard(value)
when map_size(value) < 1
when tuple_size(value) < 1 do
:guard_passed
end
def multiguard(_value) do
:guard_failed
end
Check.empty?(%{}) #=> true
Check.empty?({}) #=> false # true was expected!
```
This could be corrected by ensuring that no exception is raised, either via type checks like `is_map(val) and map_size(val) == 0`, or by checking equality instead, like `val == %{}`.
It could also be corrected by using multiple guards, so that if an exception causes one guard to fail, the next one is evaluated.
```elixir
defmodule Check do
# If given a tuple, map_size/1 will raise, and the second guard will be evaluated
def empty?(val)
when map_size(val) == 0
when tuple_size(val) == 0,
do: true
def empty?(_val), do: false
def boolean(value) when map_size(value) < 1 or tuple_size(value) < 1 do
:guard_passed
end
def boolean(value) do
:guard_failed
end
Check.empty?(%{}) #=> true
Check.empty?({}) #=> true
multiguard(%{}) #=> :guard_passed
multiguard({}) #=> :guard_passed
boolean(%{}) #=> :guard_passed
boolean({}) #=> :guard_failed
```
For cases where guards do not rely on the failing guard behavior the two forms are exactly the same semantically but there are cases where multiple guard clauses may be more aesthetically pleasing.
+5 -5
View File
@@ -16,7 +16,7 @@ For more information on running your project, see the official [Mix & OTP guide]
### Applications with supervision tree
The `mix new` command also allows the `--sup` option to scaffold an application with a supervision tree out of the box. We talk about supervision trees later on when discussing one of the common anti-patterns when writing libraries.
The `mix new` command also allows the `--sup` flag to scaffold an application with a supervision tree out of the box. We talk about supervision trees later on when discussing one of the common anti-patterns when writing libraries.
## Publishing
@@ -70,7 +70,7 @@ iex> File.read(1)
** (FunctionClauseError) no function clause matching in IO.chardata_to_string/1
```
The usage of `:ok`/`:error` tuples is about the domain that the function works on, in this case, file system access. Bad arguments, logical errors, invalid options should raise regardless of the function name. If in doubt, prefer to return tuples instead of raising, as users of your library can always match on the results and raise if necessary.
The usage of `:ok`/`:error` tuples is about the domain that the function works on, in this case, filesystem access. Bad arguments, logical errors, invalid options should raise regardless of the function name. If in doubt, prefer to return tuples instead of raising, as users of your library can always match on the results and raise if necessary.
### Avoid working with invalid data
@@ -100,7 +100,7 @@ This advice does not only apply to libraries but to any Elixir code. Every time
### Avoid application configuration
You should avoid using the application environment (see `Application.get_env/2`) as the configuration mechanism for libraries. The application environment is **global** which means it becomes impossible for two dependencies to use your library in two different ways.
You should avoid using [the application environment](https://hexdocs.pm/elixir/Application.html#get_env/2) as the configuration mechanism for libraries. The application environment is **global** which means it becomes impossible for two dependencies to use your library in two different ways.
Let's see a simple example. Imagine that you implement a library that breaks a string in two parts based on the first occurrence of the dash `-` character:
@@ -192,7 +192,7 @@ Although the previous section could be summarized as "avoid macros", both topics
To quote [the official guide on Macros](https://elixir-lang.org/getting-started/meta/macros.html):
> Even though Elixir attempts its best to provide a safe environment for macros, the major responsibility of writing clean code with macros falls on developers. Macros are harder to write than ordinary Elixir functions and it's considered to be bad style to use them when they're not necessary. So write macros responsibly.
> Even though Elixir attempts its best to provide a safe environment for macros, the major responsibility of writing clean code with macros falls on developers. Macros are harder to write than ordinary Elixir functions and it’s considered to be bad style to use them when they’re not necessary. So write macros responsibly.
>
> Elixir already provides mechanisms to write your everyday code in a simple and readable fashion by using its data structures and functions. Macros should only be used as a last resort. Remember that **explicit is better than implicit**. **Clear code is better than concise code**.
@@ -202,7 +202,7 @@ When you absolutely have to use a macro, make sure that a macro is not the only
A developer must never use a process for code organization purposes. A process must be used to model runtime properties such as:
* Mutable state and access to shared resources (such as ETS, files, etc.)
* Mutable state and access to shared resources (such as ets, files, etc)
* Concurrency and distribution
* Initialization, shutdown and restart logic (as seen in supervisors)
* System messages such as timer messages and monitoring events
+2 -2
View File
@@ -4,7 +4,7 @@ This document covers some naming conventions in Elixir code, from casing to punc
## Casing
Elixir developers must use `snake_case` when defining variables, function names, module attributes, etc.:
Elixir developers must use `snake_case` when defining variables, function names, module attributes, etc:
some_map = %{this_is_a_key: "and a value"}
is_map(some_map)
@@ -71,7 +71,7 @@ More examples of paired functions: `Base.decode16/2` and `Base.decode16!/2`, `Fi
There are also some non-paired functions, with no non-bang variant. The bang still signifies that it will raise an exception on failure. Examples: `Mix.Config.validate!/1`, `Protocol.assert_protocol!/1`
In macro code, the bang on `Kernel.alias!/1` and `Kernel.var!/2` signifies that [macro hygiene](https://elixir-lang.org/getting-started/meta/macros.html#macros-hygiene) is set aside.
In macro code, the bang on `Kernel.alias!/1` and `Kernel.var!/2` signifies that [macro hygiene](http://elixir-lang.org/getting-started/meta/macros.html#macros-hygiene) is set aside.
## Trailing question mark (`foo?`)
+19 -20
View File
@@ -14,16 +14,15 @@ Operator
`*` `/` | Left to right
`+` `-` | Left to right
`++` `--` `..` `<>` | Right to left
`^^^` | Left to right
`in` `not in` | Left to right
`\|>` `<<<` `>>>` `<<~` `~>>` `<~` `~>` `<~>` `<\|>` | Left to right
`\|>` `<<<` `>>>` `~>>` `<<~` `~>` `<~` `<~>` `<\|>` | Left to right
`<` `>` `<=` `>=` | Left to right
`==` `!=` `=~` `===` `!==` | Left to right
`&&` `&&&` `and` | Left to right
`\|\|` `\|\|\|` `or` | Left to right
`=` | Right to left
`&` | Unary
`=>` (valid syntax only inside `%{}`) | Right to left
`=` | Right to left
`=>` | Right to left
`\|` | Right to left
`::` | Right to left
`when` | Right to left
@@ -33,16 +32,16 @@ Operator
Elixir provides the following built-in comparison operators:
* [`==`](`==/2`) - equality
* [`===`](`===/2`) - strict equality
* [`!=`](`!=/2`) - inequality
* [`!==`](`!==/2`) - strict inequality
* [`<`](`</2`) - less than
* [`>`](`>/2`) - greater than
* [`<=`](`<=/2`) - less than or equal
* [`>=`](`>=/2`) - greater than or equal
* [`==`](`Kernel.==/2`) - equality
* [`===`](`Kernel.===/2`) - strict equality
* [`!=`](`Kernel.!=/2`) - inequality
* [`!==`](`Kernel.!==/2`) - strict inequality
* [`>`](`Kernel.>/2`) - greater than
* [`<`](`Kernel.</2`) - less than
* [`>=`](`Kernel.>=/2`) - greater than or equal
* [`<=`](`Kernel.<=/2`) - less than or equal
The only difference between [`==`](`==/2`) and [`===`](`===/2`) is that [`===`](`===/2`) is strict when it comes to comparing integers and floats:
The only difference between [`==`](`Kernel.==/2`) and [`===`](`Kernel.===/2`) is that [`===`](`Kernel.===/2`) is stricter when it comes to comparing integers and floats:
```elixir
iex> 1 == 1.0
@@ -51,7 +50,7 @@ iex> 1 === 1.0
false
```
[`!=`](`!=/2`) and [`!==`](`!==/2`) act as the negation of [`==`](`==/2`) and [`===`](`===/2`), respectively.
[`!=`](`Kernel.!=/2`) and [`!==`](`Kernel.!==/2`) act as the negation of [`==`](`Kernel.==/2`) and [`===`](`Kernel.===/2`), respectively.
### Term ordering
@@ -62,18 +61,18 @@ iex> 1 < :an_atom
true
```
The reason we can compare different data types is pragmatism. Sorting algorithms don't need to worry about different data types in order to sort. For reference, the overall sorting order is defined below:
The reason we can compare different data types is pragmatism. Sorting algorithms don’t need to worry about different data types in order to sort. For reference, the overall sorting order is defined below:
```
number < atom < reference < function < port < pid < tuple < map < list < bitstring
```
When comparing two numbers of different types (a number being either an integer or a float), a conversion to the type with greater precision will always occur, unless the comparison operator used is either [`===`](`===/2`) or [`!==`](`!==/2`). A float will be considered more precise than an integer, unless the float is greater/less than +/-9007199254740992.0 respectively, at which point all the significant figures of the float are to the left of the decimal point. This behavior exists so that the comparison of large numbers remains transitive.
When comparing two numbers of different types (a number is either an integer or a float), a conversion to the type with greater precision will always occur, unless the comparison operator used is either `===` or `!==`. A float will be considered more precise than an integer, unless the float is greater/less than +/-9007199254740992.0, at which point all the significant figures of the float are to the left of the decimal point. This behavior exists so that the comparison of large numbers remains transitive.
The collection types are compared using the following rules:
* Tuples are compared by size, then element by element.
* Maps are compared by size, then by keys in ascending term order, then by values in key order. In the specific case of maps' key ordering, integers are always considered to be less than floats.
* Tuples are compared by size then element by element.
* Maps are compared by size then by keys in ascending term order then by values in key order. In the specific case of maps' key ordering, integers are always considered to be less than floats.
* Lists are compared element by element.
* Bitstrings are compared byte by byte, incomplete bytes are compared bit by bit.
@@ -112,10 +111,10 @@ The following is a table of all the operators that Elixir is capable of parsing,
* `&&&`
* `<<<`
* `>>>`
* `<<~`
* `~>>`
* `<~`
* `<<~`
* `~>`
* `<~`
* `<~>`
* `<|>`
* `^^^`
+9 -11
View File
@@ -17,17 +17,15 @@ These are the reserved words in the Elixir language. They are detailed throughou
### Numbers
Integers (`1234`) and floats (`123.4`) in Elixir are represented as a sequence of digits that may be separated by underscore for readability purposes, such as `1_000_000`. Integers never contain a dot (`.`) in their representation. Floats contain a dot and at least one other digit after the dot. Floats also support the scientific notation, such as `123.4e10` or `123.4E10`.
Integers (`1234`) and floats (`123.4`) in Elixir are represented as a sequence of digits that may be separated by underscore for readability purposes, such as `1_000_000`. Integers never contain a dot (`.`) in their representation. Floats contain a dot and at least one other digit after the dot. Floats also support the scientific format, such as `123.4e10` or `123.4E10`.
### Atoms
Unquoted atoms start with a colon (`:`) which must be inmediately followed by an underscore or a Unicode letter. The atom may continue using a sequence of Unicode letters, numbers, underscores, and `@`. Atoms may end in `!` or `?`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Valid unquoted atoms are: `:ok`, `:ISO8601`, and `:integer?`.
Atoms in Elixir start with a colon (`:`) which must be followed by non-combining Unicode characters and underscore. The atom may continue using a sequence of Unicode characters, including numbers, underscore and `@`. Atoms may end in `!` or `?`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
If the colon is immediately followed by a pair of double- or single-quotes surrounding the atom name, the atom is considered quoted. In contrast with an unquoted atom, this one can be made of any Unicode character (not only letters), such as `:'🌢 Elixir'`, `:"++olá++"`, and `:"123"`.
All operators in Elixir are also valid atoms. Valid examples are `:foo`, `:FOO`, `:foo_42`, `:foo@bar` and `:++`. Invalid examples are `:@foo` (`@` is not allowed at start), `:123` (numbers are not allowed at start) and `:(*)` (not a valid operator).
Quoted and unquoted atoms with the same name are considered equivalent, so `:atom`, `:"atom"`, and `:'atom'` represent the same atom. The only catch is that the compiler will warn when quotes are used in atoms that do not need to be quoted.
All operators in Elixir are also valid atoms. Valid examples are `:foo`, `:FOO`, `:foo_42`, `:foo@bar`, and `:++`. Invalid examples are `:@foo` (`@` is not allowed at start), `:123` (numbers are not allowed at start), and `:(*)` (not a valid operator).
If the colon is followed by a double- or single-quote, the atom can be made of any character, such as `:"++olá++"`.
`true`, `false`, and `nil` are reserved words that are represented by the atoms `:true`, `:false` and `:nil` respectively.
@@ -82,13 +80,13 @@ Structs built on the map syntax by passing the struct name between `%` and `{`.
### Variables
Variables in Elixir must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The variable may continue using a sequence of Unicode letters, numbers, and underscores. Variables may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification.
Variables in Elixir must start with underscore or a non-combining Unicode character that is not in uppercase or titlecase. The variable may continue using a sequence of Unicode characters, including numbers and underscore. Variables may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
[Elixir's naming conventions](naming-conventions.html) recommend variables to be in `snake_case` format.
### Non-qualified calls (local calls)
Non-qualified calls, such as `add(1, 2)`, must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The call may continue using a sequence of Unicode letters, numbers, and underscore. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification.
Non-qualified calls, such as `add(1, 2)`, must start with underscore or a non-combining Unicode character that is not in uppercase or titlecase. The call may continue using a sequence of Unicode characters, including numbers and underscore. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
Parentheses for non-qualified calls are optional, except for zero-arity calls, which would then be ambiguous with variables. If parentheses are used, they must immediately follow the function name *without spaces*. For example, `add (1, 2)` is a syntax error, since `(1, 2)` is treated as an invalid block which is attempted to be given as a single argument to `add`.
@@ -100,7 +98,7 @@ As many programming languages, Elixir also support operators as non-qualified ca
### Qualified calls (remote calls)
Qualified calls, such as `Math.add(1, 2)`, must start with an underscore or a Unicode letter that is not in uppercase or titlecase. The call may continue using a sequence of Unicode letters, numbers, and underscores. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification.
Qualified calls, such as `Math.add(1, 2)`, must start with underscore or a non-combining Unicode character that is not in uppercase or titlecase. The call may continue using a sequence of Unicode characters, including numbers and underscore. Calls may end in `?` or `!`. See [Unicode Syntax](unicode-syntax.html) for a formal specification. Unicode characters require Erlang/OTP 20.
[Elixir's naming conventions](naming-conventions.html) recommend calls to be in `snake_case` format.
@@ -120,7 +118,7 @@ Blocks are multiple Elixir expressions separated by newlines or semi-colons. A n
### Left to right arrow
The left to right arrow (`->`) is used to establish a relationship between left and right, commonly referred as clauses. The left side may have zero, one, or more arguments; the right side is zero, one, or more expressions separated by new line. The `->` may appear one or more times between one of the following terminators: `do`/`end`, `fn`/`end` or `(`/`)`. When `->` is used, only other clauses are allowed between those terminators. Mixing clauses and regular expressions is invalid syntax.
The left to right arrow (`->`) is used to establish a relationship between left and right. The left side may have zero, one or more arguments, the right side is zero, one or more expressions separated by new line. The `->` is always between one of the following terminators: `do`/`end`, `fn`/`end` or `(`/`)`.
It is seen on `case` and `cond` constructs between `do`/`end`:
@@ -439,7 +437,7 @@ However Elixir introduces a syntax sugar where the keywords above may be written
[foo: 1, bar: 2]
```
Atoms with foreign characters, such as whitespace, must be wrapped in quotes. This rule applies to keywords as well:
Atoms with foreign characters in their name, such as whitespace, must be wrapped in quotes. This rule applies to keywords as well:
```elixir
[{:"foo bar", 1}, {:"bar baz", 2}] == ["foo bar": 1, "bar baz": 2]
+3 -3
View File
@@ -68,7 +68,7 @@ The notation to represent the union of types is the pipe `|`. For example, the t
| nonempty_maybe_improper_list(type1, type2) # non-empty proper or improper list
| Literals # Described in section "Literals"
| BuiltIn # Described in section "Built-in types"
| Builtin # Described in section "Built-in types"
| Remotes # Described in section "Remote types"
| UserDefined # Described in section "User-defined types"
@@ -191,7 +191,7 @@ If you want to specify more than one variable, you separate them by a comma.
@spec function(arg1, arg2) :: {arg1, arg2} when arg1: atom, arg2: integer
Type variables with no restriction can also be defined using `var`.
Type variables with no restriction can also be defined.
@spec function(arg) :: [arg] when arg: var
@@ -260,4 +260,4 @@ Elixir's standard library contains a few frequently used behaviours such as `Gen
Elixir discourages the use of the `string()` type. The `string()` type refers to Erlang strings, which are known as "charlists" in Elixir. They do not refer to Elixir strings, which are UTF-8 encoded binaries. To avoid confusion, if you attempt to use the type `string()`, Elixir will emit a warning. You should use `charlist()`, `binary()` or `String.t()` accordingly.
Note that `String.t()` and `binary()` are equivalent to analysis tools. Although, for those reading the documentation, `String.t()` implies it is a UTF-8 encoded binary.
Note `String.t()` and `binary()` are equivalent to analysis tools. Although, for those reading the documentation, `String.t()` implies it is a UTF-8 encoded binary.
+20 -32
View File
@@ -17,7 +17,6 @@ Documentation in Elixir is usually attached to module attributes. Let's see an e
@moduledoc """
This is the Hello module.
"""
@moduledoc since: "1.0.0"
@doc """
Says hello to the given `name`.
@@ -30,13 +29,12 @@ Documentation in Elixir is usually attached to module attributes. Let's see an e
:ok
"""
@doc since: "1.3.0"
def world(name) do
IO.puts "hello #{name}"
end
end
The `@moduledoc` attribute is used to add documentation to the module. `@doc` is used before a function to provide documentation for it. Besides the attributes above, `@typedoc` can also be used to attach documentation to types defined as part of typespecs. Elixir also allows metadata to be attached to documentation, by passing a keyword list to `@doc` and friends.
The `@moduledoc` attribute is used to add documentation to the module. `@doc` is used before a function to provide documentation for it. Besides the attributes above, `@typedoc` can also be used to attach documentation to types defined as part of typespecs.
## Function Arguments
@@ -53,20 +51,6 @@ The compiler will infer this argument as `map`. Sometimes the inference will be
size
end
## Documentation metadata
Elixir allows developers to attach arbitrary metadata to the documentation. This is done by passing a keyword list to the relevant attribute (such as `@moduledoc`, `@typedoc`, and `@doc`). A commonly used metadata is `:since`, which annotates in which version that particular module, function, type, or callback was added, as shown in the example above.
Another common metadata is `:deprecated`, which emits a warning in the documentation, explaining that its usage is discouraged:
@doc deprecated: "Use Foo.bar/2 instead"
Note the `:deprecated` key does not warn when a developer invokes the functions. If you want the code to also emit a warning, you can use the `@deprecated` attribute:
@deprecated "Use Foo.bar/2 instead"
Metadata can have any key. Documentation tools often use metadata to provide more data to readers and to enrich the user experience.
## Recommendations
When writing documentation:
@@ -75,7 +59,7 @@ When writing documentation:
* Reference modules by their full name.
Markdown uses backticks (`` ` ``) to quote code. Elixir builds on top of that to automatically generate links when module or function names are referenced. For this reason, always use full module names. If you have a module called `MyApp.Hello`, always reference it as `` `MyApp.Hello` `` and never as `` `Hello` ``.
Markdown uses backticks (`` ` ``) to quote code. Elixir builds on top of that to automatically generate links when module or function names are referenced. For this reason, always use full module names. If you have a module called `MyApp.Hello`, always reference it as `` `MyApp.Hello` `` and never as `` `Hello` ``.
* Reference functions by name and arity if they are local, as in `` `world/1` ``, or by module, name and arity if pointing to an external module: `` `MyApp.Hello.world/1` ``.
@@ -86,8 +70,6 @@ When writing documentation:
* Start new sections with second level Markdown headers `##`. First level headers are reserved for module and function names.
* Place documentation before the first clause of multi-clause functions. Documentation is always per function and arity and not per clause.
* Use the `:since` key in the documentation metadata to annotate whenever new functions or modules are added to your API.
## Doctests
@@ -95,26 +77,19 @@ We recommend that developers include examples in their documentation, often unde
Notice doctests have limitations. When you cannot doctest a function, because it relies on state or side-effects, we recommend developers include examples directly without the `iex>` prompt.
## Documentation != Code comments
## Documentation != Comments
Elixir treats documentation and code comments as different concepts. Documentation is an explicit contract between you and users of your Application Programming Interface (API), be them third-party developers, co-workers, or your future self. Modules and functions must always be documented if they are part of your API.
Elixir treats documentation and code comments as different concepts. Documentation is for users of your Application Programming Interface (API), be it your co-worker or your future self. Modules and functions must always be documented if they are part of your API.
Code comments are aimed at developers reading the code. They are useful for marking improvements, leaving notes (for example, why you had to resort to a workaround due to a bug in a library), and so forth. They are tied to the source code: you can completely rewrite a function and remove all existing code comments, and it will continue to behave the same, with no change to either its behaviour or its documentation.
Code comments are for developers reading the code. They are useful to mark improvements, leave notes for developers reading the code (for example, you decided not to call a function due to a bug in a library) and so forth.
Because private functions cannot be accessed externally, Elixir will warn if a private function has a `@doc` attribute and will discard its content. However, you can add code comments to private functions, as with any other piece of code, and we recommend developers to do so whenever they believe it will add relevant information to the readers and maintainers of such code.
Finally, beware of redundant code comments, such as the ones describing the exact same that the code does:
# Total is the sum of the batch and individual entries
total = batch_sum + individual_sum
In summary, documentation is a contract with users of your API, who may not necessarily have access to the source code; whereas code comments are for those who interact directly with the source. You can learn and express different guarantees about your software by separating those two concepts.
In other words: documentation is required, code comments are optional.
## Hiding Internal Modules and Functions
Besides the modules and functions libraries provide as part of their public interface, libraries may also implement important functionality that is not part of their API. While these modules and functions can be accessed, they are meant to be internal to the library and thus should not have documentation for end users.
Conveniently, Elixir allows developers to hide modules and functions from the documentation, by setting `@doc false` to hide a particular function, or `@moduledoc false` to hide the whole module. If a module is hidden, you may even document the functions in the module, but the module itself won't be listed in the documentation:
Luckily, Elixir allows developers to hide modules and functions from the documentation. For example, one common practice for documenting internal behaviour is to set the `@moduledoc` attribute to `false` while documenting each function:
defmodule MyApp.Hidden do
@moduledoc false
@@ -127,12 +102,25 @@ Conveniently, Elixir allows developers to hide modules and functions from the do
end
end
Similarly, developers can add `@doc false` to functions they do not want to be publicly exposed:
defmodule MyApp.Sample do
@doc false
def add(a, b), do: a + b
end
However, keep in mind that adding `@doc false` does not make the function private. The function above can still be invoked as `MyApp.Sample.add(1, 2)`. Not only that, if `MyApp.Sample` is imported, the `add/2` function will also be imported into the caller. For those reasons, be cautious when adding `@doc false` to functions, instead use one of these two options:
* Move the undocumented function to a module with `@moduledoc false`, like `MyApp.Hidden`, ensuring the function won't be accidentally exposed or imported. Remember you can use `@moduledoc false` to hide a whole module and still document each function with `@doc`. Tools will still ignore the module.
* Start the function name with one or two underscores, for example, `__add__/2`, and add `@doc false`. The compiler does not import functions with leading underscores and they hint to anyone reading the code of their intended private usage.
## Documenting Private Functions
Elixir warns if a private function has a `@doc` attribute and discards its content, because `@doc` is intended to be used only for your public interface.
Private functions may still need internal documentation for maintainers, though. That can be accomplished with code comments.
## Code.fetch_docs/1
Elixir stores documentation inside pre-defined chunks in the bytecode. It can be accessed from Elixir by using the `Code.fetch_docs/1` function. This also means documentation is only accessed when required and not when modules are loaded by the Virtual Machine. The only downside is that modules defined in-memory, like the ones defined in IEx, cannot have their documentation accessed as they do not have their bytecode written to disk.
+1 -1
View File
@@ -5,5 +5,5 @@
{registered, [elixir_config, elixir_code_server]},
{applications, [kernel,stdlib,compiler]},
{mod, {elixir,[]}},
{env, [{ansi_enabled, false}, {time_zone_database, 'Elixir.Calendar.UTCOnlyTimeZoneDatabase'}]}
{env, [{ansi_enabled, false}]}
]}.
+17 -9
View File
@@ -4,7 +4,7 @@
-behaviour(application).
-export([start_cli/0,
string_to_tokens/4, tokens_to_quoted/3, 'string_to_quoted!'/4,
env_for_eval/1, env_for_eval/2, quoted_to_erl/2,
env_for_eval/1, env_for_eval/2, quoted_to_erl/2, quoted_to_erl/3,
eval/2, eval/3, eval_forms/3, eval_forms/4, eval_quoted/3]).
-include("elixir.hrl").
-define(system, 'Elixir.System').
@@ -25,7 +25,7 @@
-export([start/2, stop/1, config_change/3]).
start(_Type, _Args) ->
_ = parse_otp_release(),
OTPRelease = parse_otp_release(),
Encoding = file:native_name_encoding(),
preload_common_modules(),
@@ -33,8 +33,9 @@ start(_Type, _Args) ->
check_file_encoding(Encoding),
check_endianness(),
%% TODO: Remove OTPRelease check once we support OTP 20+.
Tokenizer = case code:ensure_loaded('Elixir.String.Tokenizer') of
{module, Mod} -> Mod;
{module, Mod} when OTPRelease >= 20 -> Mod;
_ -> elixir_tokenizer
end,
@@ -102,15 +103,21 @@ preload_common_modules() ->
%% the codebase we can avoid code:ensure_loaded/1 checks.
_ = code:ensure_loaded('Elixir.Kernel'),
_ = code:ensure_loaded('Elixir.Macro.Env'),
%% We need to make sure the re module is preloaded to make
%% function_exported checks inside Regex.version is fast.
%% TODO: Remove this once we support OTP 20+.
_ = code:ensure_loaded(re),
ok.
parse_otp_release() ->
%% Whenever we change this check, we should also change escript.build and Makefile.
case string:to_integer(erlang:system_info(otp_release)) of
{Num, _} when Num >= 20 ->
{Num, _} when Num >= 19 ->
Num;
_ ->
io:format(standard_error, "unsupported Erlang/OTP version, expected Erlang/OTP 20+~n", []),
io:format(standard_error, "unsupported Erlang/OTP version, expected Erlang/OTP 19+~n", []),
erlang:halt(1)
end.
@@ -233,7 +240,7 @@ eval(String, Binding, #{line := Line, file := File} = E) when
eval_quoted(Tree, Binding, Opts) when is_list(Opts) ->
eval_quoted(Tree, Binding, env_for_eval(Opts));
eval_quoted(Tree, Binding, #{line := Line} = E) ->
eval_forms(elixir_quote:linify(Line, line, Tree), Binding, E).
eval_forms(elixir_quote:linify(Line, Tree), Binding, E).
%% Handle forms evaluation. The main difference to
%% eval_quoted is that it does not linify the given
@@ -255,7 +262,7 @@ eval_forms(Tree, Binding, Env, Scope) ->
% Below must be all one line for locations to be the same
% when the stacktrace is extended to the full stacktrace.
{value, Value, NewBinding} =
try erl_eval:expr(Erl, ParsedBinding, none, none, none) catch ?WITH_STACKTRACE(Class, Exception, Stacktrace) erlang:raise(Class, Exception, get_stacktrace(Stacktrace)) end,
try erl_eval:expr(Erl, ParsedBinding, none, none, none) catch Class:Exception -> erlang:raise(Class, Exception, get_stacktrace(erlang:get_stacktrace())) end,
{Value, elixir_erl_var:dump_binding(NewBinding, NewScope), NewEnv, NewScope}
end.
@@ -266,9 +273,10 @@ get_stacktrace(Stacktrace) ->
try
throw(stack)
catch
?WITH_STACKTRACE(throw, stack, CurrentStack)
throw:stack ->
% Ignore stack item for current function.
merge_stacktrace(Stacktrace, tl(CurrentStack))
[_ | CurrentStack] = erlang:get_stacktrace(),
merge_stacktrace(Stacktrace, CurrentStack)
end.
% The stacktrace did not include the current stack, re-add it.
+1 -20
View File
@@ -3,7 +3,6 @@
-define(line(Opts), elixir_utils:get_line(Opts)).
-define(generated(Meta), [{generated, true} | Meta]).
-define(var_context, ?MODULE).
-define(remote(Ann, Module, Function, Args), {call, Ann, {remote, Ann, {atom, Ann, Module}, {atom, Ann, Function}}, Args}).
-record(elixir_erl, {
context=nil, %% can be match, guards or nil
@@ -24,6 +23,7 @@
aliases_hygiene=true,
imports_hygiene=true,
unquote=true,
unquoted=false,
generated=false
}).
@@ -39,22 +39,3 @@
mismatch_hints=[],
warn_on_unnecessary_quotes=true
}).
%% TODO: Remove this once we support Erlang/OTP 21+ exclusively.
-ifdef(OTP_RELEASE). %% defined on OTP 21+
-define(WITH_STACKTRACE(K, R, S), K:R:S ->).
-else.
-define(WITH_STACKTRACE(K, R, S), K:R -> S = erlang:get_stacktrace(),).
-endif.
%% TODO: Remove this once we support Erlang/OTP 22+ exclusively.
%% See https://github.com/erlang/otp/pull/1972
-ifdef(OTP_RELEASE).
-if(?OTP_RELEASE >= 22).
-define(NO_SPAWN_COMPILER_PROCESS, no_spawn_compiler_process).
-elif(?OTP_RELEASE >= 21).
-define(NO_SPAWN_COMPILER_PROCESS, dialyzer, no_spawn_compiler_process).
-endif.
-else.
-define(NO_SPAWN_COMPILER_PROCESS, dialyzer, no_spawn_compiler_process).
-endif.
+2 -2
View File
@@ -22,7 +22,7 @@ store_alias(New, Old, Aliases) ->
store_macro_alias(Meta, New, Old, Aliases) ->
case lists:keyfind(counter, 1, Meta) of
{counter, Counter} ->
{counter, Counter} when is_integer(Counter) ->
lists:keystore(New, 1, Aliases, {New, {Counter, Old}});
false ->
Aliases
@@ -33,7 +33,7 @@ remove_alias(Atom, Aliases) ->
remove_macro_alias(Meta, Atom, Aliases) ->
case lists:keyfind(counter, 1, Meta) of
{counter, _Counter} ->
{counter, Counter} when is_integer(Counter) ->
lists:keydelete(Atom, 1, Aliases);
false ->
Aliases
+31 -58
View File
@@ -7,7 +7,7 @@ expand(Meta, Args, E, RequireSize) ->
case ?key(E, context) of
match ->
{EArgs, Alignment, EE} =
expand(Meta, fun elixir_expand:expand/2, Args, [], E, E, 0, RequireSize),
expand(Meta, fun elixir_expand:expand/2, Args, [], E, 0, RequireSize),
case find_match(EArgs) of
false ->
@@ -16,14 +16,14 @@ expand(Meta, Args, E, RequireSize) ->
form_error(Meta, ?key(EE, file), ?MODULE, {nested_match, Match})
end;
_ ->
{EArgs, Alignment, {_EC, EV}} =
expand(Meta, fun elixir_expand:expand_arg/2, Args, [], {E, E}, E, 0, RequireSize),
{{'<<>>', [{alignment, Alignment} | Meta], EArgs}, EV}
{EArgs, Alignment, {EC, EV}} =
expand(Meta, fun elixir_expand:expand_arg/2, Args, [], {E, E}, 0, RequireSize),
{{'<<>>', [{alignment, Alignment} | Meta], EArgs}, elixir_env:mergea(EV, EC)}
end.
expand(_BitstrMeta, _Fun, [], Acc, E, _OriginalE, Alignment, _RequireSize) ->
expand(_BitstrMeta, _Fun, [], Acc, E, Alignment, _RequireSize) ->
{lists:reverse(Acc), Alignment, E};
expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, OriginalE, Alignment, RequireSize) ->
expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, Alignment, RequireSize) ->
{ELeft, EL} = expand_expr(Meta, Left, Fun, E),
%% Variables defined outside the binary can be accounted
@@ -38,7 +38,7 @@ expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, OriginalE, Al
end,
EType = expr_type(ELeft),
{ERight, EAlignment, ES} = expand_specs(EType, Meta, Right, EM, OriginalE, RequireSize or MatchSize),
{ERight, EAlignment, ES} = expand_specs(EType, Meta, Right, EM, RequireSize or MatchSize),
EE =
case EL of
@@ -65,15 +65,15 @@ expand(BitstrMeta, Fun, [{'::', Meta, [Left, Right]} | T], Acc, E, OriginalE, Al
prepend_unless_bitstring_in_match(EType, Meta, ELeft, ERight, Acc, E)
end,
expand(BitstrMeta, Fun, T, EAcc, EE, OriginalE, alignment(Alignment, EAlignment), RequireSize);
expand(BitstrMeta, Fun, [{_, Meta, _} = H | T], Acc, E, OriginalE, Alignment, RequireSize) ->
expand(BitstrMeta, Fun, T, EAcc, EE, alignment(Alignment, EAlignment), RequireSize);
expand(BitstrMeta, Fun, [{_, Meta, _} = H | T], Acc, E, Alignment, RequireSize) ->
{Expr, ES} = expand_expr(Meta, H, Fun, E),
{EAcc, EAlignment} = wrap_expr(Expr, Acc),
expand(BitstrMeta, Fun, T, EAcc, ES, OriginalE, alignment(Alignment, EAlignment), RequireSize);
expand(Meta, Fun, [H | T], Acc, E, OriginalE, Alignment, RequireSize) ->
expand(BitstrMeta, Fun, T, EAcc, ES, alignment(Alignment, EAlignment), RequireSize);
expand(Meta, Fun, [H | T], Acc, E, Alignment, RequireSize) ->
{Expr, ES} = expand_expr(Meta, H, Fun, E),
{EAcc, EAlignment} = wrap_expr(Expr, Acc),
expand(Meta, Fun, T, EAcc, ES, OriginalE, alignment(Alignment, EAlignment), RequireSize).
expand(Meta, Fun, T, EAcc, ES, alignment(Alignment, EAlignment), RequireSize).
prepend_unless_bitstring_in_match(Type, Meta, Left, Right, Acc, E) ->
Expr = {'::', Meta, [Left, Right]},
@@ -137,8 +137,7 @@ compute_alignment(_, _, _) -> unknown.
%% Expands the expression of a bitstring, that is, the LHS of :: or
%% an argument of the bitstring (such as "foo" in "<<foo>>").
expand_expr(_, {{'.', M1, [Mod, to_string]}, M2, [Arg]}, Fun, E)
when Mod == 'Elixir.Kernel'; Mod == 'Elixir.String.Chars' ->
expand_expr(_, {{'.', M1, ['Elixir.Kernel', to_string]}, M2, [Arg]}, Fun, E) ->
case Fun(Arg, E) of
{EBin, EE} when is_binary(EBin) -> {EBin, EE};
{EArg, EE} -> {{{'.', M1, ['Elixir.String.Chars', to_string]}, M2, [EArg]}, EE}
@@ -157,7 +156,7 @@ env_for_error(E) -> E.
%% Expands and normalizes types of a bitstring.
expand_specs(ExprType, Meta, Info, E, OriginalE, RequireSize) ->
expand_specs(ExprType, Meta, Info, E, RequireSize) ->
Default =
#{size => default,
unit => default,
@@ -165,7 +164,7 @@ expand_specs(ExprType, Meta, Info, E, OriginalE, RequireSize) ->
type => default,
endianness => default},
{#{size := Size, unit := Unit, type := Type, endianness := Endianness, sign := Sign}, ES} =
expand_each_spec(Meta, unpack_specs(Info, []), Default, E, OriginalE),
expand_each_spec(Meta, unpack_specs(Info, []), Default, E),
MergedType = type(Meta, ExprType, Type, E),
validate_size_required(Meta, RequireSize, ExprType, MergedType, Size, ES),
SizeAndUnit = size_and_unit(Meta, ExprType, Size, Unit, ES),
@@ -190,11 +189,11 @@ type(_, default, Type, _) ->
type(Meta, Other, Value, E) ->
form_error(Meta, ?key(E, file), ?MODULE, {bittype_mismatch, Value, Other, type}).
expand_each_spec(Meta, [{Expr, _, Args} = H | T], Map, E, OriginalE) when is_atom(Expr) ->
expand_each_spec(Meta, [{Expr, _, Args} = H | T], Map, E) when is_atom(Expr) ->
case validate_spec(Expr, Args) of
{Key, Arg} ->
{Value, EE} = expand_spec_arg(Arg, E),
validate_spec_arg(Meta, Key, Value, EE, OriginalE),
validate_spec_arg(Meta, Key, Value, EE),
case maps:get(Key, Map) of
default -> ok;
@@ -202,25 +201,25 @@ expand_each_spec(Meta, [{Expr, _, Args} = H | T], Map, E, OriginalE) when is_ato
Other -> form_error(Meta, ?key(E, file), ?MODULE, {bittype_mismatch, Value, Other, Key})
end,
expand_each_spec(Meta, T, maps:put(Key, Value, Map), EE, OriginalE);
expand_each_spec(Meta, T, maps:put(Key, Value, Map), EE);
none ->
case 'Elixir.Macro':expand(H, elixir_env:linify({?line(Meta), E})) of
H ->
form_error(Meta, ?key(E, file), ?MODULE, {undefined_bittype, H});
NewTypes ->
expand_each_spec(Meta, unpack_specs(NewTypes, []) ++ T, Map, E, OriginalE)
expand_each_spec(Meta, unpack_specs(NewTypes, []) ++ T, Map, E)
end
end;
expand_each_spec(Meta, [Expr | _], _Map, E, _OriginalE) ->
expand_each_spec(Meta, [Expr | _], _Map, E) ->
form_error(Meta, ?key(E, file), ?MODULE, {undefined_bittype, Expr});
expand_each_spec(_Meta, [], Map, E, _OriginalE) ->
expand_each_spec(_Meta, [], Map, E) ->
{Map, E}.
unpack_specs({'-', _, [H, T]}, Acc) ->
unpack_specs(H, unpack_specs(T, Acc));
unpack_specs({'*', _, [{'_', _, Atom}, Unit]}, Acc) when is_atom(Atom) ->
unpack_specs({'*', _, [{'_', _, Atom}, Unit]}, Acc) when is_atom(Atom) and is_integer(Unit) ->
[{unit, [], [Unit]} | Acc];
unpack_specs({'*', _, [Size, Unit]}, Acc) ->
unpack_specs({'*', _, [Size, Unit]}, Acc) when is_integer(Size) and is_integer(Unit) ->
[{size, [], [Size]}, {unit, [], [Unit]} | Acc];
unpack_specs(Size, Acc) when is_integer(Size) ->
[{size, [], [Size]} | Acc];
@@ -251,37 +250,17 @@ validate_spec(_, _) -> none.
expand_spec_arg(Expr, E) when is_atom(Expr); is_integer(Expr) -> {Expr, E};
expand_spec_arg(Expr, E) -> elixir_expand:expand(Expr, E).
validate_spec_arg(Meta, size, Value, E, OriginalE) ->
validate_spec_arg(Meta, size, Value, E) ->
case Value of
{Var, VarMeta, Context} when is_atom(Var) and is_atom(Context) ->
Tuple = {Var, elixir_utils:var_context(VarMeta, Context)},
case is_valid_spec_arg_var(Tuple, E, OriginalE) of
true -> ok;
false -> form_error(Meta, ?key(E, file), ?MODULE, {undefined_var_in_spec, Value})
end;
_ when is_integer(Value) ->
ok;
_ ->
form_error(Meta, ?key(E, file), ?MODULE, {bad_size_argument, Value})
{Var, _, Context} when is_atom(Var) and is_atom(Context) -> ok;
_ when is_integer(Value) -> ok;
_ -> form_error(Meta, ?key(E, file), ?MODULE, {bad_size_argument, Value})
end;
validate_spec_arg(Meta, unit, Value, E, _OriginalE) when not is_integer(Value) ->
validate_spec_arg(Meta, unit, Value, E) when not is_integer(Value) ->
form_error(Meta, ?key(E, file), ?MODULE, {bad_unit_argument, Value});
validate_spec_arg(_Meta, _Key, _Value, _E, _OriginalE) ->
validate_spec_arg(_Meta, _Key, _Value, _E) ->
ok.
is_valid_spec_arg_var(Var, E, #{context := match} = OriginalE) ->
case ?key(OriginalE, prematch_vars) of
#{Var := _} ->
true;
_ ->
maps:is_key(Var, ?key(E, current_vars)) andalso
not maps:is_key(Var, ?key(OriginalE, current_vars))
end;
is_valid_spec_arg_var(_Var, _E, _OriginalE) -> true.
validate_size_required(Meta, true, default, Type, default, E) when Type == binary; Type == bitstring ->
form_error(Meta, ?key(E, file), ?MODULE, unsized_binary);
validate_size_required(_, _, _, _, _, _) ->
@@ -352,7 +331,7 @@ format_error({unaligned_bitstring_in_match, Expr}) ->
Message =
"cannot verify size of binary expression in match. "
"If you are concatenating two binaries or nesting a binary inside a bitstring, "
"you need to make sure the size of all fields in the binary expression are known. "
"you need to make sure the size of all fieds in the binary expression are known. "
"The following examples are invalid:\n\n"
" \"foo\" <> <<field, rest::bits>>\n"
" <<\"foo\", <<field, rest::bitstring>>::binary>>\n\n"
@@ -395,10 +374,4 @@ format_error({nested_match, Expr}) ->
Message =
"cannot pattern match inside a bitstring "
"that is already in match, got: ~ts",
io_lib:format(Message, ['Elixir.Macro':to_string(Expr)]);
format_error({undefined_var_in_spec, Var}) ->
Message =
"undefined variable \"~ts\" in bitstring segment. If the size of the binary is a "
"variable, the variable must be defined prior to its use in the binary/bitstring match "
"itself, or outside the pattern match",
io_lib:format(Message, ['Elixir.Macro':to_string(Var)]).
io_lib:format(Message, ['Elixir.Macro':to_string(Expr)]).
+3 -5
View File
@@ -19,7 +19,7 @@
'MACRO-defmacrop'(Caller, Call, Expr) -> define(Caller, defmacrop, Call, Expr).
'MACRO-defmodule'(_Caller, Alias, [{do, Block}]) ->
Escaped = elixir_quote:escape(Block, default, false),
{Escaped, _} = elixir_quote:escape(Block, default, false),
Args = [Alias, Escaped, [], env()],
{{'.', [], [elixir_module, compile]}, [], Args}.
@@ -36,10 +36,8 @@
{defp, 2}].
define({Line, E}, Kind, Call, Expr) ->
UC = elixir_quote:has_unquotes(Call),
UE = elixir_quote:has_unquotes(Expr),
EscapedCall = elixir_quote:escape(Call, default, true),
EscapedExpr = elixir_quote:escape(Expr, default, true),
{EscapedCall, UC} = elixir_quote:escape(Call, default, true),
{EscapedExpr, UE} = elixir_quote:escape(Expr, default, true),
Args = [Kind, not(UC or UE), EscapedCall, EscapedExpr, elixir_locals:cache_env(E#{line := Line})],
{{'.', [], [elixir_def, store_definition]}, [], Args}.
+11 -26
View File
@@ -185,17 +185,10 @@ expand_with_else(Meta, Opts, E, HasMatch) ->
'try'(Meta, [], E) ->
form_error(Meta, ?key(E, file), elixir_expand, {missing_option, 'try', [do]});
'try'(Meta, [{do, _}], E) ->
form_error(Meta, ?key(E, file), elixir_expand, {missing_option, 'try', ['catch', 'rescue', 'after']});
form_error(Meta, ?key(E, file), elixir_expand, {missing_option, 'try', ['catch', 'rescue', 'after', 'else']});
'try'(Meta, Opts, E) when not is_list(Opts) ->
form_error(Meta, ?key(E, file), elixir_expand, {invalid_args, 'try'});
'try'(Meta, Opts, E) ->
% TODO: Make this an error in Elixir 2.0
case Opts of
[{do, _}, {else, _}] ->
form_warn(Meta, ?key(E, file), ?MODULE, {try_with_only_else_clause, origin(Meta, 'try')});
_ ->
ok
end,
RaiseError = fun(Key) ->
form_error(Meta, ?key(E, file), ?MODULE, {duplicated_clauses, 'try', Key})
end,
@@ -234,8 +227,7 @@ expand_catch(_Meta, [_] = Args, E) ->
expand_catch(_Meta, [_, _] = Args, E) ->
head(Args, E);
expand_catch(Meta, _, E) ->
Error = {wrong_number_of_args_for_clause, "one or two args", origin(Meta, 'try'), 'catch'},
form_error(Meta, ?key(E, file), ?MODULE, Error).
form_error(Meta, ?key(E, file), ?MODULE, {wrong_number_of_args_for_clause, "one or two args", 'try', 'catch'}).
expand_rescue(Meta, [Arg], E) ->
case expand_rescue(Arg, E) of
@@ -245,8 +237,7 @@ expand_rescue(Meta, [Arg], E) ->
form_error(Meta, ?key(E, file), ?MODULE, invalid_rescue_clause)
end;
expand_rescue(Meta, _, E) ->
Error = {wrong_number_of_args_for_clause, "one arg", origin(Meta, 'try'), 'rescue'},
form_error(Meta, ?key(E, file), ?MODULE, Error).
form_error(Meta, ?key(E, file), ?MODULE, {wrong_number_of_args_for_clause, "one arg", 'try', 'rescue'}).
%% rescue var
expand_rescue({Name, _, Atom} = Var, E) when is_atom(Name), is_atom(Atom) ->
@@ -295,7 +286,11 @@ expand_one(Meta, Kind, Key, Fun) ->
%% Expands all -> pairs in a given key but do not keep the overall vars.
expand_clauses(Meta, Kind, Fun, Clauses, E) ->
NewKind = origin(Meta, Kind),
NewKind =
case lists:keyfind(origin, 1, Meta) of
{origin, Origin} -> Origin;
_ -> Kind
end,
expand_clauses_origin(Meta, NewKind, Fun, Clauses, E).
expand_clauses_origin(Meta, Kind, Fun, {Key, Clauses}, E) when is_list(Clauses) ->
@@ -319,18 +314,12 @@ assert_at_most_once(Kind, [_ | Rest], Count, Fun) ->
warn_catch_before_rescue([], _, _, _) ->
ok;
warn_catch_before_rescue([{'rescue', _} | _], Meta, E, true) ->
form_warn(Meta, ?key(E, file), ?MODULE, {catch_before_rescue, origin(Meta, 'try')});
form_warn(Meta, ?key(E, file), ?MODULE, catch_before_rescue);
warn_catch_before_rescue([{'catch', _} | Rest], Meta, E, _) ->
warn_catch_before_rescue(Rest, Meta, E, true);
warn_catch_before_rescue([_ | Rest], Meta, E, Found) ->
warn_catch_before_rescue(Rest, Meta, E, Found).
origin(Meta, Default) ->
case lists:keyfind(origin, 1, Meta) of
{origin, Origin} -> Origin;
false -> Default
end.
format_error({bad_or_missing_clauses, {Kind, Key}}) ->
io_lib:format("expected -> clauses for :~ts in \"~ts\"", [Key, Kind]);
format_error({bad_or_missing_clauses, Kind}) ->
@@ -352,12 +341,8 @@ format_error(invalid_rescue_clause) ->
"invalid \"rescue\" clause. The clause should match on an alias, a variable "
"or be in the \"var in [alias]\" format";
format_error({catch_before_rescue, Origin}) ->
io_lib:format("\"catch\" should always come after \"rescue\" in ~ts", [Origin]);
format_error({try_with_only_else_clause, Origin}) ->
io_lib:format("\"else\" shouldn't be used as the only clause in \"~ts\", use \"case\" instead",
[Origin]);
format_error(catch_before_rescue) ->
"\"catch\" should always come after \"rescue\" in try";
format_error(unmatchable_else_in_with) ->
"\"else\" clauses will never match because all patterns in \"with\" will always match";
+9 -17
View File
@@ -52,28 +52,20 @@ eval_forms(Forms, Vars, E) ->
compile(Forms, Vars, E)
end.
compile(Quoted, Vars, E) ->
Args = list_to_tuple([V || {_, _, _, V} <- Vars]),
{Expanded, EE} = elixir_expand:expand(Quoted, E),
elixir_env:check_unused_vars(EE),
{Module, Fun, Purgeable} =
elixir_erl_compiler:spawn(fun spawned_compile/3, [Expanded, Vars, E]),
{dispatch(Module, Fun, Args, Purgeable), EE}.
spawned_compile(ExExprs, Vars, #{line := Line, file := File} = E) ->
compile(Forms, Vars, #{line := Line, file := File} = E) ->
Dict = [{{Name, Kind}, {0, Value}} || {Name, Kind, Value, _} <- Vars],
S = elixir_env:env_to_scope_with_vars(E, Dict),
{ErlExprs, _} = elixir_erl_pass:translate(ExExprs, S),
{Expr, EE, _S} = elixir:quoted_to_erl(Forms, E, S),
elixir_env:check_unused_vars(EE),
Module = retrieve_compiler_module(),
Fun = code_fun(?key(E, module)),
Forms = code_mod(Fun, ErlExprs, Line, File, Module, Vars),
Form = code_mod(Fun, Expr, Line, File, Module, Vars),
Args = list_to_tuple([V || {_, _, _, V} <- Vars]),
{Module, Binary} = elixir_erl_compiler:noenv_forms(Forms, File, [nowarn_nomatch]),
{Module, Binary} = elixir_erl_compiler:noenv_forms(Form, File, [nowarn_nomatch]),
code:load_binary(Module, "", Binary),
{Module, Fun, is_purgeable(Module, Binary)}.
{dispatch(Module, Fun, Args, is_purgeable(Module, Binary)), EE}.
dispatch(Module, Fun, Args, Purgeable) ->
Res = Module:Fun(Args),
@@ -131,8 +123,8 @@ bootstrap_file(File) ->
_ = [binary_to_path(X, "lib/elixir/ebin") || X <- Lists],
io:format("Compiled ~ts~n", [File])
catch
?WITH_STACKTRACE(Kind, Reason, Stacktrace)
io:format("~p: ~p~nstacktrace: ~p~n", [Kind, Reason, Stacktrace]),
Kind:Reason ->
io:format("~p: ~p~nstacktrace: ~p~n", [Kind, Reason, erlang:get_stacktrace()]),
erlang:halt(1)
end.
+2 -13
View File
@@ -1,6 +1,6 @@
-module(elixir_config).
-compile({no_auto_import, [get/1]}).
-export([new/1, delete/1, put/2, get/1, get/2, update/2, get_and_put/2, warn/2]).
-export([new/1, delete/1, put/2, get/1, safe_get/2, update/2, get_and_put/2]).
-export([start_link/0, init/1, handle_call/3, handle_cast/2,
handle_info/2, code_change/3, terminate/2]).
-behaviour(gen_server).
@@ -22,7 +22,7 @@ get(Key) ->
[{_, Value}] = ets:lookup(?MODULE, Key),
Value.
get(Key, Default) ->
safe_get(Key, Default) ->
try ets:lookup(?MODULE, Key) of
[{_, Value}] -> Value;
[] -> Default
@@ -39,17 +39,6 @@ get_and_put(Key, Value) ->
start_link() ->
gen_server:start_link({local, ?MODULE}, ?MODULE, ?MODULE, []).
%% Used to guarantee warnings are emitted only once per caller.
warn(Key, [{Mod, Fun, ArgsOrArity, _} | _]) ->
EtsKey = {warn, Key, Mod, Fun, to_arity(ArgsOrArity)},
ets:update_counter(?MODULE, EtsKey, {2, 1, 1, 1}, {EtsKey, -1}) =:= 0;
warn(_, _) ->
true.
to_arity(Args) when is_list(Args) -> length(Args);
to_arity(Arity) -> Arity.
%% gen_server api
init(Tab) ->
+25 -38
View File
@@ -61,22 +61,21 @@ fetch_definitions(File, Module) ->
{All, Private} = fetch_definition(Entries, File, Module, Set, Bag, [], []),
Unreachable = elixir_locals:warn_unused_local(File, Module, All, Private),
elixir_locals:ensure_no_undefined_local(File, Module, All),
elixir_locals:ensure_no_import_conflict(File, Module, All),
{All, Unreachable}.
fetch_definition([Tuple | T], File, Module, Set, Bag, All, Private) ->
[{_, Kind, Meta, _, Check, {MaxDefaults, _, Defaults}}] = ets:lookup(Set, {def, Tuple}),
[{_, Kind, Meta, _, Check, {Defaults, _, _}}] = ets:lookup(Set, {def, Tuple}),
try ets:lookup_element(Bag, {clauses, Tuple}, 2) of
Clauses ->
NewAll =
[{Tuple, Kind, add_defaults_to_meta(MaxDefaults, Meta), Clauses} | All],
[{Tuple, Kind, add_defaults_to_meta(Defaults, Meta), Clauses} | All],
NewPrivate =
case (Kind == defp) orelse (Kind == defmacrop) of
true ->
Metas = head_and_definition_meta(Check, Meta, MaxDefaults - Defaults, All),
[{Tuple, Kind, Metas, MaxDefaults} | Private];
WarnMeta = case Check of true -> Meta; false -> false end,
[{Tuple, Kind, WarnMeta, Defaults} | Private];
false ->
Private
end,
@@ -93,13 +92,6 @@ fetch_definition([], _File, _Module, _Set, _Bag, All, Private) ->
add_defaults_to_meta(0, Meta) -> Meta;
add_defaults_to_meta(Defaults, Meta) -> [{defaults, Defaults} | Meta].
head_and_definition_meta(true, Meta, 0, _All) ->
Meta;
head_and_definition_meta(true, _Meta, _HeadDefaults, [{_, _, HeadMeta, _} | _]) ->
HeadMeta;
head_and_definition_meta(false, _Meta, _HeadDefaults, _All) ->
false.
%% Section for storing definitions
store_definition(Kind, CheckClauses, Call, Body, Pos) ->
@@ -136,16 +128,16 @@ store_definition(Kind, CheckClauses, Call, Body, Pos) ->
%% Line and File will always point to the caller. __ENV__.line
%% will always point to the quoted one and __ENV__.file will
%% always point to the one at @file or the quoted one.
{Location, LinifyLine} =
{Location, Key} =
case elixir_utils:meta_keep(Meta) of
{_, _} = MetaFile -> {MetaFile, Line};
nil -> {nil, 0}
{_, _} = MetaFile -> {MetaFile, keep};
nil -> {nil, line}
end,
Arity = length(Args),
LinifyArgs = elixir_quote:linify(LinifyLine, keep, Args),
LinifyGuards = elixir_quote:linify(LinifyLine, keep, Guards),
LinifyBody = elixir_quote:linify(LinifyLine, keep, Body),
LinifyArgs = elixir_quote:linify(Line, Key, Args),
LinifyGuards = elixir_quote:linify(Line, Key, Guards),
LinifyBody = elixir_quote:linify(Line, Key, Body),
{File, DefMeta} =
case retrieve_location(Location, ?key(E, module)) of
@@ -172,7 +164,7 @@ store_definition(Meta, Kind, CheckClauses, Name, Arity, DefaultsArgs, Guards, Bo
Clause <- def_to_clauses(Kind, Meta, Args, Guards, Body, E)],
DefaultsLength = length(Defaults),
elixir_locals:record_defaults(Tuple, Kind, Module, DefaultsLength, Meta),
elixir_locals:record_defaults(Tuple, Kind, Module, DefaultsLength),
check_previous_defaults(Meta, Module, Name, Arity, Kind, DefaultsLength, E),
store_definition(CheckClauses, Kind, Meta, Name, Arity, File,
@@ -220,7 +212,7 @@ run_with_location_change(File, E, Callback) ->
end.
def_to_clauses(_Kind, Meta, Args, [], nil, E) ->
check_args_for_function_head(Meta, Args, E),
check_args_for_bodiless_clause(Meta, Args, E),
[];
def_to_clauses(_Kind, Meta, Args, Guards, [{do, Body}], _E) ->
[{Meta, Args, Guards, Body}];
@@ -250,23 +242,22 @@ store_definition(Check, Kind, Meta, Name, Arity, File, Module, Defaults, Clauses
ok
end,
{MaxDefaults, FirstMeta} =
MaxDefaults =
case ets:lookup(Set, {def, Tuple}) of
[{_, StoredKind, StoredMeta, StoredFile, StoredCheck, {StoredDefaults, LastHasBody, LastDefaults}}] ->
check_valid_kind(Meta, File, Name, Arity, Kind, StoredKind),
(Check and StoredCheck) andalso
check_valid_clause(Meta, File, Name, Arity, Kind, Set, StoredMeta, StoredFile),
check_valid_defaults(Meta, File, Name, Arity, Kind, Defaults, StoredDefaults, LastDefaults, HasBody, LastHasBody),
{max(Defaults, StoredDefaults), StoredMeta};
max(Defaults, StoredDefaults);
[] ->
ets:insert(Bag, {defs, Tuple}),
{Defaults, Meta}
Defaults
end,
Check andalso ets:insert(Set, {?last_def, Tuple}),
ets:insert(Bag, [{{clauses, Tuple}, Clause} || Clause <- Clauses]),
ets:insert(Set, {{def, Tuple}, Kind, FirstMeta, File, Check, {MaxDefaults, HasBody, Defaults}}).
ets:insert(Set, {{def, Tuple}, Kind, Meta, File, Check, {MaxDefaults, HasBody, Defaults}}).
%% Handling of defaults
@@ -348,12 +339,12 @@ warn_bodiless_function(Check, _Meta, _File, Module, _Kind, _Tuple)
when Check == false; Module == 'Elixir.Module' ->
ok;
warn_bodiless_function(_Check, Meta, File, _Module, Kind, Tuple) ->
elixir_errors:form_warn(Meta, File, ?MODULE, {function_head, Kind, Tuple}),
elixir_errors:form_warn(Meta, File, ?MODULE, {bodiless_clause, Kind, Tuple}),
ok.
check_args_for_function_head(Meta, Args, E) ->
check_args_for_bodiless_clause(Meta, Args, E) ->
[begin
elixir_errors:form_error(Meta, ?key(E, file), ?MODULE, invalid_args_for_function_head)
elixir_errors:form_error(Meta, ?key(E, file), ?MODULE, invalid_args_for_bodiless_clause)
end || Arg <- Args, invalid_arg(Arg)].
invalid_arg({Name, _, Kind}) when is_atom(Name), is_atom(Kind) -> false;
@@ -376,7 +367,7 @@ assert_no_aliases_name(Meta, '__aliases__', [Atom], #{file := File}) when is_ato
assert_no_aliases_name(_Meta, _Aliases, _Args, _S) ->
ok.
assert_valid_name(Meta, Kind, '__info__', [_], #{file := File}) ->
assert_valid_name(Meta, Kind, '__info__', [_], #{file := File, module := Module}) when Module /= 'Elixir.Module' ->
elixir_errors:form_error(Meta, File, ?MODULE, {'__info__', Kind});
assert_valid_name(Meta, Kind, 'module_info', [], #{file := File}) ->
elixir_errors:form_error(Meta, File, ?MODULE, {module_info, Kind, 0});
@@ -389,7 +380,7 @@ assert_valid_name(_Meta, _Kind, _Name, _Args, _S) ->
%% Format errors
format_error({function_head, Kind, {Name, Arity}}) ->
format_error({bodiless_clause, Kind, {Name, Arity}}) ->
io_lib:format("implementation not provided for predefined ~ts ~ts/~B", [Kind, Name, Arity]);
format_error({no_module, {Kind, Name, Arity}}) ->
@@ -450,16 +441,12 @@ format_error({no_alias, Atom}) ->
format_error({invalid_def, Kind, NameAndArgs}) ->
io_lib:format("invalid syntax in ~ts ~ts", [Kind, 'Elixir.Macro':to_string(NameAndArgs)]);
format_error(invalid_args_for_function_head) ->
"only variables and \\\\ are allowed as arguments in function head.\n"
format_error(invalid_args_for_bodiless_clause) ->
"only variables and \\\\ are allowed as arguments in definition header.\n"
"\n"
"If you did not intend to define a function head, make sure your function "
"If you did not intend to define a header, make sure your function "
"definition has the proper syntax by wrapping the arguments in parentheses "
"and using the do instruction accordingly:\n\n"
" def add(a, b), do: a + b\n\n"
" def add(a, b) do\n"
" a + b\n"
" end\n";
"and ensuring there is no space between the function name and arguments";
format_error({'__info__', Kind}) ->
io_lib:format("cannot define ~ts __info__/1 as it is automatically defined by Elixir", [Kind]);

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