Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
27fdc68ff4 | ||
|
|
2d4722a12f | ||
|
|
e002ac55b2 | ||
|
|
fb89d5548d | ||
|
|
8618d8effa | ||
|
|
bd1c3ab8d7 | ||
|
|
2110342661 | ||
|
|
8533df25a9 | ||
|
|
9e8ac51fb3 | ||
|
|
451b8eb9a3 | ||
|
|
23742f1237 | ||
|
|
3f9ffbeb82 | ||
|
|
0397a46bb7 | ||
|
|
b87e58e7e3 | ||
|
|
6cb09a77e6 | ||
|
|
12edab720c | ||
|
|
74f9a34015 | ||
|
|
49af97a800 | ||
|
|
b806ee8559 | ||
|
|
7d09c2b857 | ||
|
|
f38646781b | ||
|
|
b5777de582 | ||
|
|
67f77ec1cd | ||
|
|
8a91f648a8 | ||
|
|
7f61b0ff05 | ||
|
|
c830fde31e | ||
|
|
019e6b85e6 | ||
|
|
097fe87eb7 | ||
|
|
6ec1e7f7b4 | ||
|
|
f045705ac5 | ||
|
|
2b4f573092 | ||
|
|
7cf4369157 | ||
|
|
4135ab1c0d | ||
|
|
89f7dbc64d | ||
|
|
ec5afe2226 | ||
|
|
345ce9c592 | ||
|
|
9c734ac6ee | ||
|
|
9388198ca0 | ||
|
|
6ce366c7d4 | ||
|
|
10f9b78b4f | ||
|
|
eb8c734b96 | ||
|
|
c55cf5ac90 | ||
|
|
d28cc754b6 | ||
|
|
1819addc75 | ||
|
|
21e649a1f2 | ||
|
|
c599956de1 | ||
|
|
ca7f09a8b1 | ||
|
|
d32ad190ea | ||
|
|
4635631a56 | ||
|
|
2edf718f84 | ||
|
|
16a14c1f6d | ||
|
|
cfa6cf220e | ||
|
|
5e1b7d9470 | ||
|
|
38baa729da | ||
|
|
5fe53f7b7a | ||
|
|
276b0d3c72 | ||
|
|
abb8817a0a | ||
|
|
5309843d2b | ||
|
|
1a2c2dcda6 | ||
|
|
03b6c07215 | ||
|
|
d10b9d5b29 | ||
|
|
e38be075c3 | ||
|
|
28824e8171 | ||
|
|
3edc407713 |
@@ -1,18 +0,0 @@
|
||||
version: 1-{branch}+{build}
|
||||
|
||||
build_script:
|
||||
- cmd: C:\MinGW\msys\1.0\bin\make
|
||||
- cmd: rmdir /s /q .git
|
||||
before_test:
|
||||
- cmd: set PATH=%PATH%;C:\Program Files\erl8.3\erts-8.3\bin
|
||||
test_script:
|
||||
- cmd: C:\MinGW\msys\1.0\bin\make --keep-going test_windows
|
||||
|
||||
environment:
|
||||
ELIXIR_ASSERT_TIMEOUT: 2000
|
||||
|
||||
matrix:
|
||||
allow_failures:
|
||||
- platform: x86
|
||||
- platform: x64
|
||||
- platform: Any CPU
|
||||
@@ -1,21 +0,0 @@
|
||||
[
|
||||
inputs: [
|
||||
"lib/*/{lib,unicode,test}/**/*.{ex,exs}",
|
||||
"lib/*/mix.exs"
|
||||
],
|
||||
|
||||
locals_without_parens: [
|
||||
# Formatter tests
|
||||
assert_format: 2,
|
||||
assert_format: 3,
|
||||
assert_same: 1,
|
||||
assert_same: 2,
|
||||
|
||||
# Errors tests
|
||||
assert_eval_raise: 3,
|
||||
|
||||
# Mix tests
|
||||
in_fixture: 2,
|
||||
in_tmp: 2
|
||||
]
|
||||
]
|
||||
+9
-5
@@ -1,13 +1,17 @@
|
||||
/doc/
|
||||
/lib/*/ebin/
|
||||
/lib/*/_build/
|
||||
/lib/*/tmp/
|
||||
/doc
|
||||
/ebin
|
||||
/lib/*/ebin/*
|
||||
/lib/*/tmp
|
||||
/lib/elixir/src/*_lexer.erl
|
||||
/lib/elixir/src/*_parser.erl
|
||||
/lib/elixir/test/ebin/
|
||||
/lib/elixir/src/elixir.app.src
|
||||
/lib/elixir/test/ebin
|
||||
/man/elixir.1
|
||||
/man/iex.1
|
||||
/rel/elixir
|
||||
/Docs-v*.zip
|
||||
/Precompiled-v*.zip
|
||||
/.eunit
|
||||
/.release
|
||||
.elixir.plt
|
||||
erl_crash.dump
|
||||
|
||||
+13
-27
@@ -1,34 +1,20 @@
|
||||
language: erlang
|
||||
|
||||
otp_release:
|
||||
- 18.0
|
||||
- 18.1
|
||||
- 18.2
|
||||
- 18.3
|
||||
- 19.0
|
||||
- 19.1
|
||||
|
||||
sudo: false
|
||||
|
||||
matrix:
|
||||
include:
|
||||
- os: linux
|
||||
otp_release: 19.0
|
||||
- os: linux
|
||||
otp_release: 19.1
|
||||
- os: linux
|
||||
otp_release: 19.2
|
||||
- os: linux
|
||||
otp_release: 19.3
|
||||
- os: linux
|
||||
otp_release: 20.0
|
||||
- os: linux
|
||||
otp_release: 20.1
|
||||
|
||||
env:
|
||||
- ELIXIR_ASSERT_TIMEOUT=2000
|
||||
|
||||
script:
|
||||
- make compile
|
||||
- rm -rf .git
|
||||
- make test
|
||||
- bin/elixir bin/mix format --dry-run --check-formatted
|
||||
- dialyzer -pa lib/elixir/ebin --build_plt --output_plt elixir.plt --apps lib/elixir/ebin/elixir.beam lib/elixir/ebin/Elixir.Kernel.beam
|
||||
script: "make compile && rm -rf .git && make test"
|
||||
|
||||
notifications:
|
||||
irc: "irc.freenode.org#elixir-lang"
|
||||
recipients:
|
||||
- jose.valim@gmail.com
|
||||
- jose.valim@plataformatec.com.br
|
||||
- eric.meadows.jonsson@gmail.com
|
||||
- lexmag@me.com
|
||||
- an.leopardi@gmail.com
|
||||
|
||||
|
||||
+220
-313
@@ -1,385 +1,292 @@
|
||||
# Changelog for Elixir v1.6
|
||||
# Changelog for Elixir v1.4
|
||||
|
||||
## Code formatter
|
||||
Elixir v1.4 brings new features, enhancements and bug fixes into Elixir. The most notable changes are the addition of the `Registry` module and the `Task.async_stream/3` and `Task.async_stream/5` which aid developers in writing concurrent software. Those two features and a couple other improvements are described in detail below followed by the complete list of changes.
|
||||
|
||||
The big feature in Elixir v1.6 is the addition of a code formatter and an accompanying `mix format` task that adds automatic formatting to your projects.
|
||||
## Registry
|
||||
|
||||
The goal of the formatter is to automate the styling of codebases into a unique and consistent layout used across teams and the whole community. Code is now easier to write, as you no longer need to concern yourself with formatting rules. Code is also easier to read, as you no longer need to convert the styles of other developers in your mind.
|
||||
The registry is a local, decentralized and scalable key-value process storage:
|
||||
|
||||
The formatter also helps new developers to learn the language, by giving immediate feedback on code structure, and eases code reviews by allowing teams to focus on business rules and code quality, rather than code style.
|
||||
* Local because keys and values are only accessible to the current node (opposite to distributed)
|
||||
* Decentralized because there is no single entity responsible for managing the registry
|
||||
* Scalable because performance scales linearly with the addition of more cores upon partitioning
|
||||
|
||||
To automatically format your codebase, you can run the new `mix format` task. A `.formatter.exs` file may be added to your project root for rudimentary formatter configuration. The mix task also supports flags for CI integration. For instance, you can make your build or a Pull Request fail if the code is not formatted accordingly. We also recommend developers to check their favorite editor and see if they already provide key bindings for `mix format`, allowing a file or a code snippet to be formatted without ceremony.
|
||||
A registry is chosen upon start to have unique or duplicate keys. Every key-value pair is associated to the process registering the key. Keys are automatically removed once the owner process terminates.
|
||||
|
||||
The Elixir codebase itself has been already fully formatted and all further contributions are expected to contain formatted code. We recommend existing codebases to be formatted in steps. While the formatter will correctly handle long lines and complex expressions, refactoring the code by breaking those into variables or smaller functions as you format them will lead to overall cleaner and more readable codebases.
|
||||
iex> Registry.start_link(:unique, MyRegistry)
|
||||
iex> {:ok, _} = Registry.register(MyRegistry, "hello", 1)
|
||||
iex> Registry.lookup(MyRegistry, "hello")
|
||||
[{self(), 1}]
|
||||
|
||||
## Dynamic Supervisor
|
||||
With the registry, developers can provide dynamic process names, module-function dispatch or even a local pubsub system. See the `Registry` documentation for more information.
|
||||
|
||||
Supervisors in Elixir are responsible for starting, shutting down and restarting child process when things go wrong. Most of the interaction with supervisors happen with the Supervisor module and it contains three main strategies: `:one_for_one`, `:rest_for_one` and `:one_for_all`.
|
||||
## Syntax coloring
|
||||
|
||||
However, sometimes the children of a supervisor are not known upfront and are rather started dynamically. For example, if you are building a web server, you have each request being handled by a separate supervised process. Those cases were handled in the Supervisor module under a special strategy called `:simple_one_for_one`.
|
||||
Elixir v1.4 introduces the ability to syntax color inspected data structures:
|
||||
|
||||
Unfortunately, this special strategy changed the semantics of the supervisor in regards to initialization and shutdown. Plus some APIs expected different inputs or would be completely unavailable depending on the supervision strategy.
|
||||
iex> IO.puts inspect([hello: 1, world: "!"], syntax_colors: [atom: :cyan])
|
||||
[hello: 1, world: "!"]
|
||||
|
||||
Elixir v1.6 addresses this issue by introducing a new `DynamicSupervisor` module, which encapsulates the old `:simple_one_for_one` strategy and APIs in a proper module while allowing the documentation and API of the `Supervisor` module to focus on its main use cases. Having a separate `DynamicSupervisor` module also makes it simpler to add new features to the dynamic supervisor, such as the new `:max_children` option that limits the maximum number of children supervised dynamically.
|
||||
Coloring is done with ANSI colors as specified in the `IO.ANSI` module.
|
||||
|
||||
## `@deprecated` and `@since` attributes
|
||||
IEx automatically relies on this feature to provide syntax coloring for evaluated shell results. This behaviour can be configured via the `:syntax_colors` coloring option:
|
||||
|
||||
This release also introduces two new attributes associated to function definitions: `@deprecated` and `@since`. The former marks if a function or macro is deprecated, the latter annotates the version the API was introduced:
|
||||
IEx.configure [colors: [syntax_colors: [atom: :cyan, string: :green]]]
|
||||
|
||||
@doc "Breaks a collection into chunks"
|
||||
@since "1.0.0"
|
||||
@deprecated "Use chunk_every/2 instead"
|
||||
def chunk(collection, chunk_size) do
|
||||
chunk_every(collection, chunk_size)
|
||||
To disable coloring altogether, pass an empty list to `:syntax_colors`.
|
||||
|
||||
## Calendar
|
||||
|
||||
Elixir v1.3 introduced new calendar types. This release continues evolving the Calendar APIs by adding functions for comparing, adding and calculating the difference between types, retrieve the `day_of_week/1`, check if the current date is a `leap_year?/1` and more.
|
||||
|
||||
## Task.async_stream
|
||||
|
||||
When there is a need to traverse a collection of items concurrently, Elixir developers often resort to tasks:
|
||||
|
||||
collection
|
||||
|> Enum.map(&Task.async(SomeMod, :function, [&1]))
|
||||
|> Enum.map(&Task.await/1)
|
||||
|
||||
While the snippet above works fine in many occasions, for large collections it will spawn and run concurrently as many tasks as there are items in the collection.
|
||||
|
||||
`Task.async_stream/3` and `Task.async_stream/5` allows developers to process collections concurrently while controlling the maximum amount of concurrent tasks:
|
||||
|
||||
collection
|
||||
|> Task.async_stream(SomeMod, :function, [], max_concurrency: System.schedulers_online)
|
||||
|
||||
The `Task.async_stream` functions are also lazy, allowing developers to partially consume the stream until a condition is reached. Furthermore, `Task.Supervisor.async_stream/4` and `Task.Supervisor.async_stream/6` can be used to ensure the concurrent tasks are spawned under a given supervisor.
|
||||
|
||||
## Application inference
|
||||
|
||||
Mix v1.4 now automatically infers the list of applications that are required on runtime from your dependencies list.
|
||||
|
||||
In previous Mix versions, most of your dependencies had to be added both to your dependencies list and applications list. Here is how a `mix.exs` would look like:
|
||||
|
||||
def application do
|
||||
[applications: [:logger, :plug, :postgrex]]
|
||||
end
|
||||
|
||||
The `mix xref` task was also updated to warn if your project calls deprecated code. So if a definition is marked as `@deprecated` and a module invokes it, a warning will be emitted during compilation. This effectively provides libraries and frameworks a mechanism to deprecate code without causing multiple warnings to be printed in runtime and without impacting performance.
|
||||
|
||||
Note those attributes are not yet available to tools that generate documentation. Such functionality will be added in future releases as it requires changes to how Elixir stores documentation in BEAM files. We still recommend developers to properly annotate their APIs, as the information will then be already available when the tooling is updated.
|
||||
|
||||
## defguard and defguardp
|
||||
|
||||
Elixir provides the concepts of guards: expressions used alongside pattern matching to select a matching clause. Let's see an example straight from Elixir's home page:
|
||||
|
||||
def serve_drinks(%User{age: age}) when age >= 21 do
|
||||
# Code that serves drinks!
|
||||
def deps do
|
||||
[{:plug, "~> 1.2"},
|
||||
{:postgrex, "~> 1.0"}]
|
||||
end
|
||||
|
||||
`%User{age: age}` is matching on a `User` struct with an age field and `when age >= 21` is the guard.
|
||||
This was error prone as many developers would not list their dependencies in their applications list.
|
||||
|
||||
Since only a handful of constructs are [allowed in guards](https://hexdocs.pm/elixir/guards.html#content), if you were in a situation where you had to check the age to be more than or equal to 21 in multiple times, extracting the guard to a separate function would be [less than obvious and error prone](https://github.com/elixir-lang/elixir/issues/2469). To address those issues, this release introduces `defguard/1` and `defguardp/1`:
|
||||
Mix v1.4 now automatically infers your applications list as long as you leave the `:applications` key empty. The `mix.exs` above can be rewritten to:
|
||||
|
||||
defguard is_drinking_age(age) when age >= 21
|
||||
|
||||
def serve_drinks(%User{age: age}) when is_drinking_age(age) do
|
||||
# Code that serves drinks!
|
||||
def application do
|
||||
[extra_applications: [:logger]]
|
||||
end
|
||||
|
||||
## IEx improvements
|
||||
def deps do
|
||||
[{:plug, "~> 1.2"},
|
||||
{:postgrex, "~> 1.0"}]
|
||||
end
|
||||
|
||||
IEx also got its share of improvements. The new code formatter allows us to pretty print code snippets, types and specifications, improving the overall experience when exploring code through the terminal.
|
||||
With the above, Mix will automatically build your application list based on your dependencies. Applications that are part of Erlang or Elixir that are required at runtime, such as `:logger`, must be added to the `:extra_applications` list. All extra applications will be included in the application list.
|
||||
|
||||
The autocomplete mechanism also got smarter, being able to provide context autocompletion. For example, typing `t Enum.` and hitting TAB will autocomplete only the types in Enum (in contrast to all functions). Typing `b GenServer.` and hitting TAB will autocomplete only the behaviour callbacks.
|
||||
Finally, if there is a dependency you don't want to include in the application runtime list, you can do so by specifying the `runtime: false` option:
|
||||
|
||||
Finally, the breakpoint functionality added in Elixir v1.5 has been improved to support pattern matching and guards. For example, to pattern match on a function call when the first argument is the atom `:foo`, you may do:
|
||||
{:distillery, "> 0.0.0", runtime: false}
|
||||
|
||||
break! SomeFunction.call(:foo, _, _)
|
||||
We hope this feature provides a more streamlined workflow for developers who are building releases for their Elixir projects.
|
||||
|
||||
## mix xref
|
||||
## Mix install from SCM
|
||||
|
||||
`mix xref` is a task added in Elixir v1.3 which provides general information about how modules and files in an application depend on each other. This release brings many improvements to `xref`, extending the reach of the analysis and helping developers digest the vast amount of data it produces.
|
||||
Mix v1.4 can now install escripts and archives from both Git and Hex, providing you with even more options for distributing Elixir code.
|
||||
|
||||
One of such additions is the `--include-siblings` option that can be given to all `xref` commands inside umbrella projects. For example, to find all of the callers of a given module or function in an umbrella:
|
||||
This makes it possible to distribute CLI applications written in Elixir by publishing a package which builds an escript to Hex. [`ex_doc`](https://hex.pm/packages/ex_doc) has been updated to serve as an example of how to use this new functionality.
|
||||
|
||||
$ mix xref callers SomeModule --include-siblings
|
||||
Simply running:
|
||||
|
||||
The `graph` command in `mix xref` now can also output general statistics about the graph. In [the hexpm project](https://github.com/hexpm/hexpm), you would get:
|
||||
mix escript.install hex ex_doc
|
||||
|
||||
$ mix xref graph --format stats
|
||||
Tracked files: 129 (nodes)
|
||||
Compile dependencies: 256 (edges)
|
||||
Structs dependencies: 46 (edges)
|
||||
Runtime dependencies: 266 (edges)
|
||||
will fetch `ex_doc` and its dependencies, build them, and then install `ex_doc` to `~/.mix/escripts` (by default). After adding `~/.mix/escripts` to your `PATH`, running `ex_doc` is as simple as:
|
||||
|
||||
Top 10 files with most outgoing dependencies:
|
||||
* test/support/factory.ex (18)
|
||||
* lib/hexpm/accounts/user.ex (13)
|
||||
* lib/hexpm/accounts/audit_log.ex (12)
|
||||
* lib/hexpm/web/controllers/dashboard_controller.ex (12)
|
||||
* lib/hexpm/repository/package.ex (12)
|
||||
* lib/hexpm/repository/releases.ex (11)
|
||||
* lib/hexpm/repository/release.ex (10)
|
||||
* lib/hexpm/web/controllers/package_controller.ex (10)
|
||||
* lib/mix/tasks/hexpm.stats.ex (9)
|
||||
* lib/hexpm/repository/registry_builder.ex (9)
|
||||
ex_doc
|
||||
|
||||
Top 10 files with most incoming dependencies:
|
||||
* lib/hexpm/web/web.ex (84)
|
||||
* lib/hexpm/web/router.ex (29)
|
||||
* lib/hexpm/web/controllers/controller_helpers.ex (29)
|
||||
* lib/hexpm/web/controllers/auth_helpers.ex (28)
|
||||
* lib/hexpm/web/views/view_helpers.ex (27)
|
||||
* lib/hexpm/web/views/icons.ex (27)
|
||||
* lib/hexpm/web/endpoint.ex (23)
|
||||
* lib/hexpm/ecto/changeset.ex (22)
|
||||
* lib/hexpm/accounts/user.ex (19)
|
||||
* lib/hexpm/repo.ex (19)
|
||||
You can now also install archives from Hex in this way. Since they are fetched and built on the user's machine, they do not have the same limitations as pre-built archives. However, keep in mind archives run alongside every Mix project, which may lead to conflicts. For this reason, escripts is the preferred format.
|
||||
|
||||
`mix xref graph` also got the `--only-nodes` and `--label` options. The former asks Mix to only output file names (nodes) without the edges. The latter allows you to focus on certain relationships:
|
||||
It is also possible to install escripts and archives by providing a Git/GitHub repo. See `mix help escript.install` and `mix help archive.install` for more details.
|
||||
|
||||
# To get all files that depend on lib/foo.ex
|
||||
mix xref graph --sink lib/foo.ex --only-nodes
|
||||
|
||||
# To get all files that depend on lib/foo.ex at compile time
|
||||
mix xref graph --label compile --sink lib/foo.ex --only-nodes
|
||||
|
||||
# To get all files lib/foo.ex depends on
|
||||
mix xref graph --source lib/foo.ex --only-nodes
|
||||
|
||||
# To limit statistics only to compile time dependencies
|
||||
mix xref graph --format stats --label compile
|
||||
|
||||
Those improvements will help developers better understand the relationship between files and reveal potentially complex parts of their systems.
|
||||
|
||||
Other improvements in Mix include better compiler diagnostics for editor integration, support for the `--slowest N` flag in `mix test` that shows the slowest tests in your suite, and a new `mix profile.eprof` task that provides time based profiling, complementing the existing `mix profile.cprof` (count based) and `mix profile.fprof` (flame based).
|
||||
|
||||
## v1.6.6 (2018-06-20)
|
||||
|
||||
This release supports Erlang/OTP 21.0 by removing all warnings and by properly supporting the new Erlang logger module.
|
||||
## v1.4.2 (2017-02-16)
|
||||
|
||||
### 1. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Base] Do not raise when finding bad digits in `Base.decode32!` with `case: :mixed`
|
||||
* [Code] Preserve the user's choice when `fn` is followed by a newline and it has only a single clause
|
||||
* [DynamicSupervisor] Properly account for restarting children in the `:max_children` configuration
|
||||
* [String] Add performant impl for string upcase/downcase `:ascii` mode
|
||||
* [Task.Supervisor] Fix type spec for `start_child/4`
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Do not crash truncation when truncate is set to infinity
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix format] Match files starting with dot
|
||||
|
||||
## v1.6.5 (2018-05-07)
|
||||
|
||||
This release supports Erlang/OTP 21.0-rc by removing all warnings and by properly redirecting logger output. Note it is not guaranteed it will support Erlang/OTP 21.0 final.
|
||||
|
||||
### 1. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code] Preserve the user's choice in the formatter on parens call with next break fits
|
||||
* [Code] Preserve the user's choice in the formatter on calls without parens when we have one argument per line
|
||||
* [Code] Fix formatting when there is a tilde in the first element of a bitstring
|
||||
* [Kernel] Support specsdiff flag on `__info__` spec clauses
|
||||
* [Kernel] Do not exclude hygienic vars in `defguard`
|
||||
* [Kernel.SpecialForms] Mark `for` comprehensions as generated to avoid dialyzer warnings
|
||||
* [Macro] Make sure `Macro.to_string/2` emits valid quoted expressions
|
||||
* [Task] Support `:infinity` timeout on `Task.yield_many/2`
|
||||
* [Task.Supervisor] Do not crash spawning supervised tasks when the parent process is dead
|
||||
* [URI] Fix parsing of URIs with trailing `?`
|
||||
|
||||
## v1.6.4 (2018-03-16)
|
||||
|
||||
### 1. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code.Formatter] Do not double escape quoted keyword list identifiers
|
||||
* [Kernel] Properly support `into: binary` in Erlang/OTP 20.3
|
||||
|
||||
## v1.6.3 (2018-03-09)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code.Formatter] Support comments in the middle of pipelines, `when` and `|` expressions
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code.Formatter] Consider commas when breaking groups
|
||||
* [Code.Formatter] Ensure proper precedence between `&` and operators
|
||||
* [Code.Formatter] Consider `.formatter.exs` when formatting stdin
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger.Translator] Ensure logger doesn't crash when reporting named `DynamicSupervisor`
|
||||
|
||||
## v1.6.2 (2018-02-28)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix compile.erlang] Teach Mix erlang compiler alternative spelling for `-behavior` declaration
|
||||
* [mix format] Support the `:subdirectories` configuration that points to other directories with their own `.formatter.exs` file. This is useful in umbrella applications. `mix new --umbrella` has also been changed to use this new configuration by default
|
||||
* [mix format] Include the current environment for missing dependency errors
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code.Formatter] Ensure `->` does not exceed line length
|
||||
* [DynamicSupervisor] Properly tag error reports generated by dynamic supervisors so they can be properly translated by `Logger`
|
||||
* [DynamicSupervisor] Consider extra arguments during child restart
|
||||
* [Kernel] Ensure arguments given to a guard defined with `defguard` are evaluated in the correct order
|
||||
* [Module] Do not remove docs for previous function declaration when `@impl true` is used
|
||||
* [Supervisor] Ensure `use Supervisor` properly adds the `@behaviour Supervisor` annotation
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix.Shell] Bring back `Mix.Shell.cmd/2` - this arity was defined via a default argument that was accidentally removed
|
||||
|
||||
## v1.6.1 (2018-01-29)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [DynamicSupervisor] Implement `child_spec/1` for DynamicSupervisor
|
||||
* [Kernel] Raise better error messages on invalid map syntax
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Code.Formatter] Only rearrange `not in` operator if explicitly opted-in
|
||||
* [Code.Formatter] Ensure `do` blocks do not exceed line length on calls with a single argument
|
||||
* [Collectable] Support bitstrings in Collectable and for-comprehensions (regression in v1.6.0)
|
||||
* [GenServer] Do not override user own `@opts` attribute
|
||||
* [Enum] Reintroduce zipping of any enumerable of enumerables in `Enum.zip/1` (regression in v1.6.0)
|
||||
* [Macro] Reorder kw blocks in `Macro.to_string/1` to avoid warnings
|
||||
* [Protocol] Fix protocol consolidation when some chunks may be missing
|
||||
* [Stream] Reintroduce zipping of any enumerable of enumerables in `Stream.zip/1` (regression in v1.6.0)
|
||||
* [Supervisor] Do not override user own `@opts` attribute
|
||||
* [Supervisor] Add `@spec` to second clause of `start_link/2`
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.Case] Reintroduce `:case` in ExUnit setup/setup_all/test context
|
||||
|
||||
## v1.6.0 (2018-01-17)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### EEx
|
||||
|
||||
* [EEx] Allow markers `/` and `|` to be used in a custom EEx engine
|
||||
* [EEx] Support middle expressions on trim mode
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Calendar] Add truncate to `Time`, `DateTime` and `NaiveDateTime` to facilitate microsecond precision pruning
|
||||
* [Code] Add `format_string!/2` and `format_file!/2` for automatic code formatting
|
||||
* [Code] Support column annotations in quoted expressions with `columns: true` in `Code.string_to_quoted/2`
|
||||
* [DynamicSupervisor] Add `DynamicSupervisor` designed to manage children that are added and removed dynamically
|
||||
* [Exception] Make `Exception.blame/3` extensible by adding an optional `blame/2` callback to exceptions
|
||||
* [Exception] Improve the printing of guards on blamed exceptions
|
||||
* [Enumerable] Add `Enumerable.slice/1` and optimize many `Enum` operations with the new protocol. This allows data-structures with index-based random access to provide a non-linear implementation
|
||||
* [Inspect] Show UTF-8 BOM on inspected strings
|
||||
* [Inspect.Algebra] Add `:strict` and `:flex` breaks - this gives more control over the document fitting
|
||||
* [Inspect.Algebra] Allow a group to inherit the parent group break
|
||||
* [Inspect.Algebra] Add `force_unfit/1` and `next_break_fits/2` which give more control over document fitting
|
||||
* [Inspect.Algebra] Add `collapse_lines/1` for collapsing multiple lines to a maximum value
|
||||
* [Inspect.Algebra] Allow `nest/2` to be `:reset` or be set to the current `:cursor` position
|
||||
* [Kernel] Prefix variables with V when emitting Erlang code. This improves the integration with tools such as Erlang code formatters and the GUI debugger
|
||||
* [Kernel] Warn on the use of `length(x) == 0` in guards
|
||||
* [Kernel] Warn if `catch` comes before `rescue` in try
|
||||
* [Kernel] Warn if heredoc is outdented compared to its closing quotes
|
||||
* [Kernel] Add `defguard/1` and `defguardp/1` to make it easier to build guard-safe macros
|
||||
* [Kernel.ParallelCompiler] Add `compile/2`, `compile_to_path/3` and `require/2` which provide detailed information about warnings and errors
|
||||
* [Kernel.SpecialForms] Support the `uniq: true` flag in `for` comprehensions
|
||||
* [Module] Introduce `@deprecated` and `@since` attributes
|
||||
* [Module] Emit conflicting behaviour warnings if the same behaviour is given more than once
|
||||
* [List] Rearrange equals and inserts for shorter diff scripts in `List.myers_difference/2`
|
||||
* [Record] Allow `:macros` and `:includes` to be given to `Record.extract/2`
|
||||
* [Stream] Add `Stream.intersperse/2`
|
||||
* [String] Update to Unicode 10
|
||||
* [String] Allow passing empty string `match` to `String.replace/4`
|
||||
* [String] Support context and language sensitive operations in `String.upcase/2` and `String.downcase/2`. Currently only the `:greek` context is supported
|
||||
* [String] Support `:ascii` conversion in `String.upcase/2` and `String.downcase/2`
|
||||
* [Time] Add `Time.add/3`
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.Assertions] Perform inclusive checks in `assert_in_delta`
|
||||
* [ExUnit.Callbacks] Add `ExUnit.Callbacks.start_supervised!/2`
|
||||
* [ExUnit.Case] Generate a random seed per test based on the test suite seed
|
||||
* [Calendar] Correct typo on Calendar types
|
||||
* [Kernel] Ensure redefined functions point to the proper source
|
||||
* [OptionParser] Add `:allow_inexistent_atoms` to support unsafe behaviour prior to v1.4
|
||||
* [Stream] Allow consuming multiple items from suspended enumerable in `Stream.transform/3`
|
||||
* [String] Incorporate new grapheme rules in Unicode 9
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx.Autocomplete] Provide contextual autocompletion: `t Enum.` will autocomplete types, `b Enum` will autocomplete callbacks
|
||||
* [IEx.CLI] Provide hints for developers when a bad host name is given to `--remsh`
|
||||
* [IEx.Helpers] Automatically include specs when showing documentation for functions/macros
|
||||
* [IEx.Helpers] Improve formatting of behaviours and typespecs by using the formatter
|
||||
* [IEx.Helpers] Allow pattern matching and guard expressions when on `IEx.break!`
|
||||
|
||||
#### Logger
|
||||
|
||||
* [Logger] Add `:discard_threshold` to Logger to help with message queue overflow
|
||||
* [IEx.Autocomplete] Do not crash on aliases which are not known at compile time
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix app.start] Add `--preload-modules` to `mix app.start`
|
||||
* [mix archive.build] Allow `mix archive.build` to bundle dot files via an option
|
||||
* [mix compile] Define a behavior for Mix compiler tasks and return diagnostics from compiler tasks
|
||||
* [mix compile] Track struct dependencies between files and recompile them only if the struct changes
|
||||
* [mix deps] Support `:system_env` option when specifying dependencies
|
||||
* [mix format] Add a `mix format` task that formats the given files (or the files specified in a `.formatter.exs` file)
|
||||
* [mix profile.eprof] Add a new task for time-based profiling with eprof
|
||||
* [mix test] Run all functions in a describe block by giving the `file:line` the describe block starts
|
||||
* [mix test] Report the top N slowest tests with the `--slowest N` flag
|
||||
* [mix test] Report the number of doctests and tests separately
|
||||
* [mix xref] Support `--include-siblings` in reports for umbrella support
|
||||
* [mix xref] Add `mix xref graph --format stats`
|
||||
* [mix xref] Add `--only-nodes` and `--label` filters to mix xref graph
|
||||
* [mix xref] Add `mix xref deprecated` that shows the callsite of deprecated functions
|
||||
* [Mix.Umbrella] Ensure umbrella projects can depend on other umbrella projects
|
||||
* [Mix.Archive] Ensure previous archives with `.ez` extension are deleted
|
||||
|
||||
## v1.4.1 (2017-01-26)
|
||||
|
||||
### 1. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Kernel] Remove warning when making private functions overridable
|
||||
* [Path] Ensure `Path.join/1` returns strings for lists of one element
|
||||
* [Regex] Ensure `Regex.escape/1` also escapes `-`
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx] Disable ANSI detection for powershell to avoid false positives
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix.Make] Run `make clean` for `erlang.mk`
|
||||
* [Mix.Rebar] Support all of rebar3 dependency package declaration
|
||||
* [Mix.Rebar] Only pass overrides from parent to child in Rebar dep
|
||||
|
||||
## v1.4.0 (2017-01-05)
|
||||
|
||||
### 1. Enhancements
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Calendar] Add `Date.compare/2`, `Time.compare/2`, `NaiveDateTime.compare/2` and `DateTime.compare/2`
|
||||
* [Calendar] Support `NaiveDateTime.add/3` and `NaiveDateTime.diff/3` for adding seconds (up to microseconds) as well as the difference between two NaiveDateTimes in seconds (up to microseconds)
|
||||
* [Calendar] Add `Date.leap_year?/1` and `Date.day_of_week/1`
|
||||
* [Calendar] Ensure `Date`, `Time` and `NaiveDateTime` APIs work with any struct that provides the same set of fields as their respective struct. For example, a `NaiveDateTime` can be given to `Date` since it contains a superset of the fields in the `Date` struct
|
||||
* [Calendar] Add `Time.utc_now/0` and `NaiveDateTime.utc_now/0`
|
||||
* [Enum] Add `Enum.map_every/2` that invokes the given function with every nth item
|
||||
* [Enum] Add `min/2`, `max/2`, `min_max/2`, `min_by/3`, `max_by/3`, and `min_max_by/3` that allow a function specifying the default value when the enumerable is empty
|
||||
* [Enum] Introduce `Enum.zip/1` to zip multiple entries at once
|
||||
* [Float] Introduce `Float.ratio/1` that returns a tuple with the numerator and denominator as integers to retrieve the given float
|
||||
* [GenServer] Log warn on default `handle_info/2` implementation
|
||||
* [Inspect] Support syntax coloring via the `:syntax_color` option
|
||||
* [Integer] `Integer.digits/2` now accepts negative integers
|
||||
* [Integer] Add `Integer.mod/2` and `Integer.floor_div/2`
|
||||
* [IO] Add `:label` option to `IO.inspect/2` to help distinguish multiple `IO.inspect/2` calls.
|
||||
* [Kernel] Recognize merge conflict markers in source and provide a readable error message
|
||||
* [Kernel] Warn on unused module attributes
|
||||
* [Kernel] Improve compiler message on unexpected end of line
|
||||
* [Kernel] Raise `BadBooleanError` when a non-boolean is given on the left-hand side of `and`/`or`
|
||||
* [List] Add `List.pop_at/3`
|
||||
* [List] Add `List.myers_difference/2`
|
||||
* [OptionParser] Expand multi-letter aliases in `OptionParser`
|
||||
* [Process] Add `Process.send_after/4`
|
||||
* [Process] Improve error messages on `Process.register/2` errors
|
||||
* [Registry] Add a local, decentralized and scalable key-value process storage
|
||||
* [Stream] Add `Stream.map_every/2` that invokes the given function with every nth item
|
||||
* [Stream] Introduce `Stream.zip/1` to lazily zip multiple entries at once
|
||||
* [String] Update to Unicode 9.0.0
|
||||
* [Task] Add `Task.async_stream/3` and `Task.async_stream/5` as well as the supervised versions `Task.Supervisor.async_stream/4` and `Task.Supervisor.async_stream/6`
|
||||
* [URI] Allow 0 as URI scheme default port
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.Diff] Use red or green background for whitespace-only diffs
|
||||
* [ExUnit.Doctest] Allow inspected structures with multiples lines and unicode characters in the doctest result
|
||||
* [ExUnit.Formatter] Replace lhs/rhs with left/right in the formatter for clarity
|
||||
|
||||
#### IEx
|
||||
|
||||
* [IEx.Autocomplete] Stop appending a trailing dot when autocompleting modules in IEx
|
||||
* [IEx.Autocomplete] Support autocompletion for structs
|
||||
* [IEx.Autocomplete] Improve IEx autocomplete to support navigating map atom keys
|
||||
* [IEx.Helpers] `c/1` now compiles in memory by default to avoid common issue where `.beam` files remain at projects root directory
|
||||
* [IEx.Helpers] Add info about protocols in `i/1`
|
||||
* [IEx.Server] Support interrupting IEx evaluation through the Ctrl+G prompt
|
||||
|
||||
#### Mix
|
||||
|
||||
* [mix archive] Compress archive files built by `mix archive` as they are now unzipped during installation
|
||||
* [mix archive] Install from SCM
|
||||
* [mix compile] Automatically infer the list of applications for Mix projects
|
||||
* [mix cmd] Add the ability to specify one or more apps in `mix cmd`
|
||||
* [mix deps] Warn if there are non-applications in the `apps` directory for umbrella projects
|
||||
* [mix deps] Add warning for invalid paths on `mix deps.clean`
|
||||
* [mix deps] Add `Mix.Project.apps_paths` that returns the paths to children applications in umbrella projects
|
||||
* [mix deps] Add `MIX_REBAR` environment variable for overriding local rebar
|
||||
* [mix escript] Install from SCM
|
||||
* [mix new] Check directory existence in `mix new` and ask how to proceed if one exists
|
||||
* [mix new] Applications built with the `--sup` flag now have an individual module to work as application callback
|
||||
* [mix test] Add `--formatter` option to `mix test`
|
||||
* [mix xref] Provide "did you mean?" suggestions for `mix xref`
|
||||
|
||||
### 2. Bug fixes
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [CLI] Support path with spaces as argument to elixir.bat
|
||||
* [Inspect] Properly handle minus signal for non-decimal negative integers
|
||||
* [Integer] Do not raise on non-integer values in `is_odd`/`is_even`
|
||||
* [Kernel] Solve a precedence issue between `&` and `|`, such as `[&Foo.bar/1 | &Baz.bat/2]`
|
||||
* [Kernel] Do not load dynamic Elixir modules as `:in_memory` as this value is not officially supported by the code server. Instead, use an empty list, which is the same value used by Erlang.
|
||||
* [Kernel] Validate variable struct name is atom when used in pattern matching
|
||||
* [Kernel] No longer generate documentation for `defdelegate` functions automatically to avoid overriding previously specified `@doc`
|
||||
* [Macro] Fix `Macro.to_string/2` for tuple calls, such as `alias Foo.{Bar, Baz}`
|
||||
* [MapSet] Return valid MapSet when unioning a legacy MapSet
|
||||
* [Regex] Return a leading empty space when splitting on empty pattern. This makes the `split` operation consistent with the other operations in the `Regex` module
|
||||
* [Stream] Ensure `Stream.chunk_while/4` does not emit more elements than necessary when halted
|
||||
* [String] Return a leading empty space when splitting on empty string. This makes the `split` operation consistent with the other operations in the `String` module
|
||||
* [URI] Preserve empty fragments in `URI.parse/1`
|
||||
* [Access] Do not accept nils in `Access.key/1` and `Access.key/2` in favor of explicit default values (or Access.key!/1 if you expect the key to always be available)
|
||||
* [Float] Avoid multiple roundings in `Float.ceil/2`, `Float.floor/2` and `Float.round/2`
|
||||
* [Kernel] Don't crash in `macro_exported?/3` when dealing with Erlang modules
|
||||
* [Kernel] Ensure locals calls are rewritten when calling a local function or macro from inside a module
|
||||
* [Kernel] Annotate the context for variables as zero-arity funs in quotes
|
||||
* [Kernel.SpecialForms] Ensure comprehensions with guards and filters keep proper ordering,
|
||||
* [Kernel.SpecialForms] Produce meaningful warning when with's else clauses have no effect
|
||||
* [Macro] Wrap fn calls in parens in `Macro.to_string/2`
|
||||
* [Macro] Do not print aliases as keys inside keyword lists in `Macro.to_string/2`
|
||||
* [OptionParser] Support options in `OptionParser.to_argv/2` to ensure `:count` switches are correctly encoded
|
||||
* [Stream] Ensure `Stream.take/2` does not consume next element on `:suspend`
|
||||
* [String] Fix infinite recursion in `String.replace_leading/3` and `String.replace_trailing/3` when given an empty string
|
||||
* [Task] Fix `Task.shutdown/1,2` infinite block when task has no monitor
|
||||
* [Task] Ensure task cannot link after parents unlinks
|
||||
|
||||
#### Mix
|
||||
#### ExUnit
|
||||
|
||||
* [mix app.start] Improve the quality of reports if app fails to boot
|
||||
* [mix cmd] Allow `mix cmd` to be invoked multiple times without marking it as executed
|
||||
* [mix deps] Ensure optional dependencies in umbrella applications are loaded
|
||||
* [mix deps.update] Ensure transitive new non-Hex dependencies are also fetched when a repo is updated
|
||||
* [mix xref] Take compile dependencies with higher priority than runtime ones when building a graph
|
||||
* [mix xref] Handle external files for xref callers and warnings
|
||||
* [ExUnit] Fix a race condition in `assert_receive` where we would assert a message was not received but show it in the list of messages when the message is delivered right after the timeout value
|
||||
|
||||
### IEx
|
||||
|
||||
* [IEx.Helpers] Purge consolidated protocols before and after `recompile/0`
|
||||
|
||||
### Mix
|
||||
|
||||
* [Mix.Dep] Use `gmake` on FreeBSD instead of `make` when compiling make dependencies
|
||||
* [Mix.Project] Only copy files from source when they're newer than destination (for Windows machines)
|
||||
* [Mix.Task] Ensure non-recursive tasks inside umbrella are reenabled
|
||||
|
||||
### 3. Soft deprecations (no warnings emitted)
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [GenServer] Warn if `init/1` is not defined in `GenServer`. This brings GenServer closer to the implementation in OTP and aligns all behaviours to require the `init/1` callback
|
||||
* [Inspect.Algebra] `surround/3` and `surround_many/6` are deprecated in favor of `container_doc/6`
|
||||
* [Kernel] Specifying map types with variable keys without defining the type as required/optional is deprecated
|
||||
* [Kernel.ParallelCompiler] `files/2` and `files_to_path/3` are deprecated in favor of `compile/2` and `compile_to_path/3`
|
||||
* [Kernel.ParallelRequire] `files/2` is deprecated in favor of `Kernel.ParallelCompiler.require/2`
|
||||
* [Supervisor] The `:simple_one_for_one` strategy is deprecated in favor of `DynamicSupervisor`
|
||||
* [Supervisor] Passing a list of args to `Supervisor.start_child/2` is deprecated in favor of `DynamicSupervisor`
|
||||
* [Task.Supervisor] Passing `:restart` and `:shutdown` to `Task.Supervisor.start_link/2` is deprecated (it should be passed on start child instead)
|
||||
* [Enum] `Enum.partition/2` has been deprecated in favor of `Enum.split_with/2`
|
||||
* [System] Deprecate plural time units in favor of singular ones to align with future Erlang releases
|
||||
|
||||
#### ExUnit
|
||||
|
||||
* [ExUnit.Formatter] `:case_started` and `:case_finished` events are deprecated in favor of `:module_started` and `:module_finished`
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix.Compilers.Erlang] Returning `{:ok, val} | :error` from custom Erlang compilers is deprecated in favor of `{:ok, val, warnings} | {:error, errors, warnings}`
|
||||
* [ExUnit] Using GenEvent to implement ExUnit formatters is deprecated. Please use the new `GenServer` based formatters instead
|
||||
|
||||
### 4. Deprecations
|
||||
|
||||
#### Elixir
|
||||
|
||||
* [Enum] `Enum.partition/2` is deprecated in favor of `Enum.split_with/2`
|
||||
* [Keyword] `Keyword.replace/3` is deprecated in favor of `Keyword.fetch/2` and `Keyword.put/3`
|
||||
* [Map] `Map.replace/3` is deprecated in favor of `Map.fetch/2` and `Map.put/3`
|
||||
* [Macro] `Macro.unescape_tokens/1` and `Macro.unescape_tokens/2` are deprecated in favor of `Enum.map/2`
|
||||
* [Range] Deprecate `Range.range?/1` in favor of pattern matching on `_ .. _`
|
||||
* [Access] `Access.key/1` is deprecated due to erratic behaviour for missing keys, please use Access.key/2 instead with proper default values
|
||||
* [Behaviour] The `Behaviour` module is deprecated. Callbacks may now be defined directly via the `@callback` attribute
|
||||
* [Enum] Deprecate `Enum.uniq/2` in favor of `Enum.uniq_by/2`
|
||||
* [Float] `Float.to_char_list/2` and `Float.to_string/2` are deprecated (use the :erlang functions if such conversions are desired)
|
||||
* [Kernel] Deprecate support for making private functions overridable. Overridable functions must always be public as they must be contracts
|
||||
* [Kernel] Warn if variable is used as a function call
|
||||
* [OptionParser] Deprecate aliases with multiple letters, such as `-abc`
|
||||
* [Set] Deprecate the `Set` module
|
||||
* [Stream] Deprecate `Stream.uniq/2` in favor of `Stream.uniq_by/2`
|
||||
|
||||
## v1.5
|
||||
#### IEx
|
||||
|
||||
The CHANGELOG for v1.5 releases can be found [in the v1.5 branch](https://github.com/elixir-lang/elixir/blob/v1.5/CHANGELOG.md).
|
||||
* [IEx.Helpers] `import_file/2` is deprecated in favor of `import_file_if_available/1`
|
||||
|
||||
#### Mix
|
||||
|
||||
* [Mix.Utils] `underscore/1` and `camelize/1` are deprecated
|
||||
|
||||
## v1.3
|
||||
|
||||
The CHANGELOG for v1.3 releases can be found [in the v1.3 branch](https://github.com/elixir-lang/elixir/blob/v1.3/CHANGELOG.md).
|
||||
|
||||
+2
-2
@@ -7,8 +7,8 @@
|
||||
|
||||
### Environment
|
||||
|
||||
* Elixir & Erlang versions (elixir --version):
|
||||
* Operating system:
|
||||
* Elixir version (elixir -v):
|
||||
* Operating system:
|
||||
|
||||
### Current behavior
|
||||
|
||||
|
||||
@@ -1,201 +1,13 @@
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
Copyright 2012 Plataformatec
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
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
|
||||
|
||||
1. Definitions.
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction,
|
||||
and distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by
|
||||
the copyright owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all
|
||||
other entities that control, are controlled by, or are under common
|
||||
control with that entity. For the purposes of this definition,
|
||||
"control" means (i) the power, direct or indirect, to cause the
|
||||
direction or management of such entity, whether by contract or
|
||||
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity
|
||||
exercising permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications,
|
||||
including but not limited to software source code, documentation
|
||||
source, and configuration files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical
|
||||
transformation or translation of a Source form, including but
|
||||
not limited to compiled object code, generated documentation,
|
||||
and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or
|
||||
Object form, made available under the License, as indicated by a
|
||||
copyright notice that is included in or attached to the work
|
||||
(an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object
|
||||
form, that is based on (or derived from) the Work and for which the
|
||||
editorial revisions, annotations, elaborations, or other modifications
|
||||
represent, as a whole, an original work of authorship. For the purposes
|
||||
of this License, Derivative Works shall not include works that remain
|
||||
separable from, or merely link (or bind by name) to the interfaces of,
|
||||
the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including
|
||||
the original version of the Work and any modifications or additions
|
||||
to that Work or Derivative Works thereof, that is intentionally
|
||||
submitted to Licensor for inclusion in the Work by the copyright owner
|
||||
or by an individual or Legal Entity authorized to submit on behalf of
|
||||
the copyright owner. For the purposes of this definition, "submitted"
|
||||
means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems,
|
||||
and issue tracking systems that are managed by, or on behalf of, the
|
||||
Licensor for the purpose of discussing and improving the Work, but
|
||||
excluding communication that is conspicuously marked or otherwise
|
||||
designated in writing by the copyright owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity
|
||||
on behalf of whom a Contribution has been received by Licensor and
|
||||
subsequently incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the
|
||||
Work and such Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License. Subject to the terms and conditions of
|
||||
this License, each Contributor hereby grants to You a perpetual,
|
||||
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
||||
(except as stated in this section) patent license to make, have made,
|
||||
use, offer to sell, sell, import, and otherwise transfer the Work,
|
||||
where such license applies only to those patent claims licensable
|
||||
by such Contributor that are necessarily infringed by their
|
||||
Contribution(s) alone or by combination of their Contribution(s)
|
||||
with the Work to which such Contribution(s) was submitted. If You
|
||||
institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
||||
or a Contribution incorporated within the Work constitutes direct
|
||||
or contributory patent infringement, then any patent licenses
|
||||
granted to You under this License for that Work shall terminate
|
||||
as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution. You may reproduce and distribute copies of the
|
||||
Work or Derivative Works thereof in any medium, with or without
|
||||
modifications, and in Source or Object form, provided that You
|
||||
meet the following conditions:
|
||||
|
||||
(a) You must give any other recipients of the Work or
|
||||
Derivative Works a copy of this License; and
|
||||
|
||||
(b) You must cause any modified files to carry prominent notices
|
||||
stating that You changed the files; and
|
||||
|
||||
(c) You must retain, in the Source form of any Derivative Works
|
||||
that You distribute, all copyright, patent, trademark, and
|
||||
attribution notices from the Source form of the Work,
|
||||
excluding those notices that do not pertain to any part of
|
||||
the Derivative Works; and
|
||||
|
||||
(d) If the Work includes a "NOTICE" text file as part of its
|
||||
distribution, then any Derivative Works that You distribute must
|
||||
include a readable copy of the attribution notices contained
|
||||
within such NOTICE file, excluding those notices that do not
|
||||
pertain to any part of the Derivative Works, in at least one
|
||||
of the following places: within a NOTICE text file distributed
|
||||
as part of the Derivative Works; within the Source form or
|
||||
documentation, if provided along with the Derivative Works; or,
|
||||
within a display generated by the Derivative Works, if and
|
||||
wherever such third-party notices normally appear. The contents
|
||||
of the NOTICE file are for informational purposes only and
|
||||
do not modify the License. You may add Your own attribution
|
||||
notices within Derivative Works that You distribute, alongside
|
||||
or as an addendum to the NOTICE text from the Work, provided
|
||||
that such additional attribution notices cannot be construed
|
||||
as modifying the License.
|
||||
|
||||
You may add Your own copyright statement to Your modifications and
|
||||
may provide additional or different license terms and conditions
|
||||
for use, reproduction, or distribution of Your modifications, or
|
||||
for any such Derivative Works as a whole, provided Your use,
|
||||
reproduction, and distribution of the Work otherwise complies with
|
||||
the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions. Unless You explicitly state otherwise,
|
||||
any Contribution intentionally submitted for inclusion in the Work
|
||||
by You to the Licensor shall be under the terms and conditions of
|
||||
this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify
|
||||
the terms of any separate license agreement you may have executed
|
||||
with Licensor regarding such Contributions.
|
||||
|
||||
6. Trademarks. This License does not grant permission to use the trade
|
||||
names, trademarks, service marks, or product names of the Licensor,
|
||||
except as required for reasonable and customary use in describing the
|
||||
origin of the Work and reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty. Unless required by applicable law or
|
||||
agreed to in writing, Licensor provides the Work (and each
|
||||
Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
||||
implied, including, without limitation, any warranties or conditions
|
||||
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
||||
PARTICULAR PURPOSE. You are solely responsible for determining the
|
||||
appropriateness of using or redistributing the Work and assume any
|
||||
risks associated with Your exercise of permissions under this License.
|
||||
|
||||
8. Limitation of Liability. In no event and under no legal theory,
|
||||
whether in tort (including negligence), contract, or otherwise,
|
||||
unless required by applicable law (such as deliberate and grossly
|
||||
negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special,
|
||||
incidental, or consequential damages of any character arising as a
|
||||
result of this License or out of the use or inability to use the
|
||||
Work (including but not limited to damages for loss of goodwill,
|
||||
work stoppage, computer failure or malfunction, or any and all
|
||||
other commercial damages or losses), even if such Contributor
|
||||
has been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability. While redistributing
|
||||
the Work or Derivative Works thereof, You may choose to offer,
|
||||
and charge a fee for, acceptance of support, warranty, indemnity,
|
||||
or other liability obligations and/or rights consistent with this
|
||||
License. However, in accepting such obligations, You may act only
|
||||
on Your own behalf and on Your sole responsibility, not on behalf
|
||||
of any other Contributor, and only if You agree to indemnify,
|
||||
defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason
|
||||
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.
|
||||
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.
|
||||
@@ -1,7 +1,7 @@
|
||||
REBAR ?= "$(CURDIR)/rebar"
|
||||
PREFIX ?= /usr/local
|
||||
SHARE_PREFIX ?= $(PREFIX)/share
|
||||
CANONICAL := v1.6/
|
||||
CANONICAL :=
|
||||
ELIXIRC := bin/elixirc --verbose --ignore-module-conflict
|
||||
ERLC := erlc -I lib/elixir/include
|
||||
ERL := erl -I lib/elixir/include -noshell -pa lib/elixir/ebin
|
||||
@@ -16,17 +16,17 @@ INSTALL_PROGRAM = $(INSTALL) -m755
|
||||
GIT_REVISION = $(strip $(shell git rev-parse HEAD 2> /dev/null ))
|
||||
GIT_TAG = $(strip $(shell head="$(call GIT_REVISION)"; git tag --points-at $$head 2> /dev/null | tail -1) )
|
||||
|
||||
.PHONY: install compile erlang elixir build_plt clean_plt dialyze test clean clean_residual_files install_man clean_man docs Docs.zip Precompiled.zip zips
|
||||
.PHONY: install compile erlang elixir build_plt clean_plt dialyze test clean install_man clean_man docs Docs.zip Precompiled.zip zips
|
||||
.NOTPARALLEL: compile
|
||||
|
||||
#==> 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 >= 19)])' -s erlang halt | grep -q '^true'; \
|
||||
$(Q) erl -noshell -eval '{V,_} = string:to_integer(erlang:system_info(otp_release)), io:fwrite("~s", [is_integer(V) and (V >= 18)])' -s erlang halt | grep -q '^true'; \
|
||||
if [ $$? != 0 ]; then \
|
||||
echo "At least Erlang 19.0 is required to build Elixir"; \
|
||||
exit 1; \
|
||||
fi
|
||||
echo "At least Erlang 18.0 is required to build Elixir"; \
|
||||
exit 1; \
|
||||
fi;
|
||||
endef
|
||||
|
||||
define APP_TEMPLATE
|
||||
@@ -56,36 +56,40 @@ UNICODE:=lib/elixir/ebin/Elixir.String.Unicode.beam
|
||||
|
||||
default: compile
|
||||
|
||||
compile: erlang elixir
|
||||
compile: lib/elixir/src/elixir.app.src erlang elixir
|
||||
|
||||
lib/elixir/src/elixir.app.src: src/elixir.app.src
|
||||
$(Q) $(call CHECK_ERLANG_RELEASE)
|
||||
$(Q) rm -rf lib/elixir/src/elixir.app.src
|
||||
$(Q) echo "%% This file is automatically generated from <project_root>/src/elixir.app.src" \
|
||||
>lib/elixir/src/elixir.app.src
|
||||
$(Q) cat src/elixir.app.src >>lib/elixir/src/elixir.app.src
|
||||
|
||||
erlang:
|
||||
$(Q) cd lib/elixir && $(REBAR) compile
|
||||
|
||||
# Since Mix depends on EEx and EEx depends on Mix,
|
||||
# we first compile EEx without the .app file,
|
||||
# then mix and then compile EEx fully
|
||||
# Since Mix depends on EEx and EEx depends on
|
||||
# Mix, we first compile EEx without the .app
|
||||
# file, then mix and then compile EEx fully
|
||||
elixir: stdlib lib/eex/ebin/Elixir.EEx.beam mix ex_unit logger eex iex
|
||||
|
||||
stdlib: $(KERNEL) VERSION
|
||||
$(KERNEL): lib/elixir/lib/*.ex lib/elixir/lib/*/*.ex lib/elixir/lib/*/*/*.ex
|
||||
$(Q) if [ ! -f $(KERNEL) ]; then \
|
||||
$(call CHECK_ERLANG_RELEASE); \
|
||||
echo "==> bootstrap (compile)"; \
|
||||
$(ERL) -s elixir_compiler bootstrap -s erlang halt; \
|
||||
$(Q) if [ ! -f $(KERNEL) ]; then \
|
||||
echo "==> bootstrap (compile)"; \
|
||||
$(ERL) -s elixir_compiler core -s erlang halt; \
|
||||
fi
|
||||
@ echo "==> elixir (compile)";
|
||||
$(Q) cd lib/elixir && ../../$(ELIXIRC) "lib/kernel.ex" -o ebin;
|
||||
$(Q) cd lib/elixir && ../../$(ELIXIRC) "lib/**/*.ex" -o ebin;
|
||||
$(Q) $(MAKE) unicode
|
||||
$(Q) rm -f lib/elixir/ebin/elixir.app
|
||||
$(Q) rm -rf lib/elixir/ebin/elixir.app
|
||||
$(Q) cd lib/elixir && $(REBAR) compile
|
||||
|
||||
unicode: $(UNICODE)
|
||||
$(UNICODE): lib/elixir/unicode/*
|
||||
@ echo "==> unicode (compile)";
|
||||
$(Q) $(ELIXIRC) lib/elixir/unicode/unicode.ex -o lib/elixir/ebin;
|
||||
$(Q) $(ELIXIRC) lib/elixir/unicode/properties.ex -o lib/elixir/ebin;
|
||||
$(Q) $(ELIXIRC) lib/elixir/unicode/tokenizer.ex -o lib/elixir/ebin;
|
||||
$(Q) cd lib/elixir && ../../$(ELIXIRC) unicode/unicode.ex -o ebin;
|
||||
|
||||
$(eval $(call APP_TEMPLATE,ex_unit,ExUnit))
|
||||
$(eval $(call APP_TEMPLATE,logger,Logger))
|
||||
@@ -96,15 +100,15 @@ $(eval $(call APP_TEMPLATE,iex,IEx))
|
||||
install: compile
|
||||
@ echo "==> elixir (install)"
|
||||
$(Q) for dir in lib/*; do \
|
||||
rm -rf $(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/$$dir/ebin; \
|
||||
rm -Rf $(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/$$dir/ebin; \
|
||||
$(INSTALL_DIR) "$(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/$$dir/ebin"; \
|
||||
$(INSTALL_DATA) $$dir/ebin/* "$(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/$$dir/ebin"; \
|
||||
done
|
||||
$(Q) $(INSTALL_DIR) "$(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/bin"
|
||||
$(Q) $(INSTALL_PROGRAM) $(filter-out %.ps1, $(filter-out %.bat, $(wildcard bin/*))) "$(DESTDIR)$(PREFIX)/$(LIBDIR)/elixir/bin"
|
||||
$(Q) $(INSTALL_DIR) "$(DESTDIR)$(PREFIX)/$(BINDIR)"
|
||||
$(Q) for file in "$(DESTDIR)$(PREFIX)"/$(LIBDIR)/elixir/bin/*; do \
|
||||
ln -sf "../$(LIBDIR)/elixir/bin/$${file##*/}" "$(DESTDIR)$(PREFIX)/$(BINDIR)/"; \
|
||||
$(Q) for file in "$(DESTDIR)$(PREFIX)"/$(LIBDIR)/elixir/bin/* ; do \
|
||||
ln -sf "../$(LIBDIR)/elixir/bin/$${file##*/}" "$(DESTDIR)$(PREFIX)/$(BINDIR)/" ; \
|
||||
done
|
||||
$(MAKE) install_man
|
||||
|
||||
@@ -112,23 +116,18 @@ clean:
|
||||
cd lib/elixir && $(REBAR) clean
|
||||
rm -rf ebin
|
||||
rm -rf lib/*/ebin
|
||||
$(Q) $(MAKE) clean_residual_files
|
||||
rm -rf lib/elixir/test/ebin
|
||||
rm -rf lib/*/tmp
|
||||
rm -rf lib/mix/test/fixtures/git_repo
|
||||
rm -rf lib/mix/test/fixtures/deps_on_git_repo
|
||||
rm -rf lib/mix/test/fixtures/git_rebar
|
||||
rm -rf lib/elixir/src/elixir.app.src
|
||||
$(MAKE) clean_man
|
||||
|
||||
clean_elixir:
|
||||
clean_exbeam:
|
||||
$(Q) rm -f lib/*/ebin/Elixir.*.beam
|
||||
|
||||
clean_residual_files:
|
||||
rm -rf lib/*/_build/
|
||||
rm -rf lib/*/tmp/
|
||||
rm -rf lib/elixir/test/ebin/
|
||||
rm -rf lib/mix/test/fixtures/deps_on_git_repo/
|
||||
rm -rf lib/mix/test/fixtures/git_rebar/
|
||||
rm -rf lib/mix/test/fixtures/git_repo/
|
||||
rm -rf lib/mix/test/fixtures/git_sparse_repo/
|
||||
rm -f erl_crash.dump
|
||||
$(Q) $(MAKE) clean_man
|
||||
|
||||
#==> Documentation tasks
|
||||
#==> Create Documentation
|
||||
|
||||
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")
|
||||
@@ -140,7 +139,7 @@ docs: compile ../ex_doc/bin/ex_doc docs_elixir docs_eex docs_mix docs_iex docs_e
|
||||
docs_elixir: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (elixir)"
|
||||
$(Q) rm -rf doc/elixir
|
||||
$(call COMPILE_DOCS,Elixir,elixir,Kernel,-c lib/elixir/docs.exs)
|
||||
$(call COMPILE_DOCS,Elixir,elixir,Kernel,-e "lib/elixir/pages/Behaviours.md" -e "lib/elixir/pages/Guards.md" -e "lib/elixir/pages/Naming Conventions.md" -e "lib/elixir/pages/Operators.md" -e "lib/elixir/pages/Typespecs.md" -e "lib/elixir/pages/Writing Documentation.md")
|
||||
|
||||
docs_eex: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "==> ex_doc (eex)"
|
||||
@@ -171,30 +170,24 @@ docs_logger: compile ../ex_doc/bin/ex_doc
|
||||
@ echo "ex_doc is not found in ../ex_doc as expected. See README for more information."
|
||||
@ false
|
||||
|
||||
#==> Zip tasks
|
||||
#==> Zips
|
||||
|
||||
Docs.zip: docs
|
||||
rm -f Docs-v$(VERSION).zip
|
||||
rm -rf Docs-v$(VERSION).zip
|
||||
zip -9 -r Docs-v$(VERSION).zip CHANGELOG.md doc NOTICE LICENSE README.md
|
||||
@ echo "Docs file created $(CURDIR)/Docs-v$(VERSION).zip"
|
||||
|
||||
Precompiled.zip: build_man compile
|
||||
rm -f Precompiled-v$(VERSION).zip
|
||||
zip -9 -r Precompiled-v$(VERSION).zip bin CHANGELOG.md lib/*/ebin lib/*/lib LICENSE man NOTICE README.md VERSION
|
||||
rm -rf Precompiled-v$(VERSION).zip
|
||||
zip -9 -r Precompiled-v$(VERSION).zip bin CHANGELOG.md lib/*/ebin LICENSE man NOTICE README.md VERSION
|
||||
@ echo "Precompiled file created $(CURDIR)/Precompiled-v$(VERSION).zip"
|
||||
|
||||
zips: Precompiled.zip Docs.zip
|
||||
|
||||
#==> Test tasks
|
||||
#==> Tests tasks
|
||||
|
||||
test: test_erlang test_elixir
|
||||
|
||||
test_windows: test test_taskkill
|
||||
|
||||
test_taskkill:
|
||||
taskkill //IM erl.exe //F //T //FI "MEMUSAGE gt 0"
|
||||
taskkill //IM epmd.exe //F //T //FI "MEMUSAGE gt 0"
|
||||
|
||||
TEST_ERL = lib/elixir/test/erlang
|
||||
TEST_EBIN = lib/elixir/test/ebin
|
||||
TEST_ERLS = $(addprefix $(TEST_EBIN)/, $(addsuffix .beam, $(basename $(notdir $(wildcard $(TEST_ERL)/*.erl)))))
|
||||
@@ -243,21 +236,19 @@ build_man: man/iex.1 man/elixir.1
|
||||
|
||||
man/iex.1:
|
||||
$(Q) cp man/iex.1.in man/iex.1
|
||||
$(Q) sed -i.bak "/{COMMON}/r man/common" man/iex.1
|
||||
$(Q) sed -i.bak "/{COMMON}/r common" man/iex.1
|
||||
$(Q) sed -i.bak "/{COMMON}/d" man/iex.1
|
||||
$(Q) rm -f man/iex.1.bak
|
||||
$(Q) rm man/iex.1.bak
|
||||
|
||||
man/elixir.1:
|
||||
$(Q) cp man/elixir.1.in man/elixir.1
|
||||
$(Q) sed -i.bak "/{COMMON}/r man/common" man/elixir.1
|
||||
$(Q) sed -i.bak "/{COMMON}/r common" man/elixir.1
|
||||
$(Q) sed -i.bak "/{COMMON}/d" man/elixir.1
|
||||
$(Q) rm -f man/elixir.1.bak
|
||||
$(Q) rm man/elixir.1.bak
|
||||
|
||||
clean_man:
|
||||
rm -f man/elixir.1
|
||||
rm -f man/elixir.1.bak
|
||||
rm -f man/iex.1
|
||||
rm -f man/iex.1.bak
|
||||
|
||||
install_man: build_man
|
||||
$(Q) mkdir -p $(DESTDIR)$(SHARE_PREFIX)/man/man1
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||

|
||||
=========
|
||||
[](https://travis-ci.org/elixir-lang/elixir)
|
||||
|
||||
Elixir is a dynamic, functional language designed for building scalable and maintainable applications.
|
||||
|
||||
For more about Elixir, installation and documentation,
|
||||
[check Elixir's website](http://elixir-lang.org/).
|
||||
|
||||
@@ -30,10 +28,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 version
|
||||
(Elixir requires Erlang 19.0 or later). You can check your Erlang version
|
||||
(Elixir requires Erlang 18.0 or later). You can check your Erlang version
|
||||
by calling `erl` in the command line. You will see some information as follows:
|
||||
|
||||
Erlang/OTP 19 [erts-8.0] [smp:2:2] [async-threads:10] [kernel-poll:false]
|
||||
Erlang/OTP 18 [erts-7.0] [source] [smp:2:2] [async-threads:10] [hipe] [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.
|
||||
@@ -44,30 +42,11 @@ 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.
|
||||
|
||||
## Proposing new features
|
||||
|
||||
For proposing new features, please start a discussion in the
|
||||
[Elixir Core mailing list][3]. Keep in mind that it is your responsibility
|
||||
to argue and explain why a feature is useful and how it will impact the
|
||||
codebase and the community.
|
||||
|
||||
Once a proposal is accepted, it will be added to [the issues tracker][2].
|
||||
The issues tracker focuses on *actionable items* and it holds a list of
|
||||
upcoming enhancements and pending bugs. All entries in the tracker are
|
||||
tagged for clarity and to ease collaboration.
|
||||
|
||||
Features and bug fixes that have already been merged and will be included
|
||||
in the next release are marked as "closed" in the issues tracker and are
|
||||
added to the [CHANGELOG](CHANGELOG.md).
|
||||
|
||||
Finally, remember all interactions in our official spaces follow our
|
||||
[Code of Conduct][7].
|
||||
|
||||
## Contributing
|
||||
|
||||
We welcome everyone to contribute to Elixir. To do so, there are a few
|
||||
things you need to know about the code. First, Elixir code is divided
|
||||
in applications inside the `lib` folder:
|
||||
We welcome everyone to contribute to Elixir and help us tackle existing issues!
|
||||
To do so, there are a few things you need to know about the code. First, Elixir
|
||||
code is divided in applications inside the `lib` folder:
|
||||
|
||||
* `elixir` - Contains Elixir's kernel and stdlib
|
||||
|
||||
@@ -83,8 +62,7 @@ in applications inside the `lib` folder:
|
||||
|
||||
You can run all tests in the root directory with `make test` and you can
|
||||
also run tests for a specific framework `make test_#{NAME}`, for example,
|
||||
`make test_ex_unit`. If you just changed something in the Elixir's standard
|
||||
library, you can run only that portion through `make test_stdlib`.
|
||||
`make test_ex_unit`.
|
||||
|
||||
In case you are changing a single file, you can compile and run tests only
|
||||
for that particular file for fast development cycles. For example, if you
|
||||
@@ -95,27 +73,12 @@ bin/elixirc lib/elixir/lib/string.ex -o lib/elixir/ebin
|
||||
bin/elixir lib/elixir/test/elixir/string_test.exs
|
||||
```
|
||||
|
||||
To recompile (including Erlang modules):
|
||||
|
||||
```sh
|
||||
make compile
|
||||
```
|
||||
|
||||
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.
|
||||
`make test`.
|
||||
|
||||
If your contribution fails during the bootstrapping of the language,
|
||||
you can rebuild the language from scratch with:
|
||||
|
||||
```sh
|
||||
make clean_elixir compile
|
||||
```
|
||||
|
||||
Similarly, if you can't get Elixir to compile or the tests to pass after
|
||||
updating an existing checkout, run `make clean compile`. You can check
|
||||
[the official build status on Travis-CI](https://travis-ci.org/elixir-lang/elixir).
|
||||
More tasks can be found by reading the [Makefile](./Makefile).
|
||||
From time to time, your tests may fail in an existing Elixir checkout and
|
||||
may require a clean start by running `make clean compile`. You can always
|
||||
check [the official build status on Travis-CI](https://travis-ci.org/elixir-lang/elixir).
|
||||
|
||||
With tests running and passing, you are ready to contribute to Elixir and
|
||||
[send a pull request](https://help.github.com/articles/using-pull-requests/).
|
||||
@@ -126,28 +89,28 @@ case you are looking for some examples:
|
||||
* [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)
|
||||
|
||||
We usually keep a list of enhancements and bugs [in the issue tracker][2].
|
||||
For proposing new features, please start a discussion in the
|
||||
[Elixir Core mailing list][3]. Keep in mind that it is your responsibility
|
||||
to argue and explain why a feature is useful and how it will impact the
|
||||
codebase and the community. Finally, remember all interactions in our official
|
||||
spaces follow our [Code of Conduct][7].
|
||||
|
||||
### Reviewing changes
|
||||
|
||||
Once a pull request is sent, the Elixir team will review your changes.
|
||||
We outline our process below to clarify the roles of everyone involved.
|
||||
|
||||
All pull requests must be approved by two committers before being merged into
|
||||
the repository. If any changes are necessary, the team will leave appropriate
|
||||
comments requesting changes to the code. Unfortunately we cannot guarantee a
|
||||
pull request will be merged, even when modifications are requested, as the Elixir
|
||||
team will re-evaluate the contribution as it changes.
|
||||
|
||||
Committers may also push style changes directly to your branch. If you would
|
||||
rather manage all changes yourself, you can disable "Allow edits from maintainers"
|
||||
feature when submitting your pull request.
|
||||
the repository. In case any changes are necessary, the team will leave
|
||||
appropriate comments requesting changes to the code.
|
||||
|
||||
The Elixir team may optionally assign someone to review a pull request.
|
||||
In case someone is assigned, they must explicitly approve the code before
|
||||
another team member can merge it.
|
||||
|
||||
When the review finishes, your pull request will be squashed and merged
|
||||
into the repository. If you have carefully organized your commits and
|
||||
believe they should be merged without squashing, leave a comment.
|
||||
When review is completed, your pull request will be squashed and merged
|
||||
into the repository.
|
||||
|
||||
## Building documentation
|
||||
|
||||
@@ -161,20 +124,20 @@ cd ex_doc && ../elixir/bin/mix do deps.get, compile
|
||||
cd ../elixir && make docs
|
||||
```
|
||||
|
||||
This will produce documentation sets for `elixir`, `mix`, etc. under
|
||||
This will produce documentation sets for `elixir`, `mix`, etc., under
|
||||
the `doc` directory. If you are planning to contribute documentation,
|
||||
[please check our best practices for writing documentation](https://hexdocs.pm/elixir/writing-documentation.html).
|
||||
[please check our best practices for writing documentation](http://elixir-lang.org/docs/stable/elixir/writing-documentation.html).
|
||||
|
||||
## Development links
|
||||
|
||||
* [Elixir Getting Started guide][1]
|
||||
* [Elixir Website][1]
|
||||
* [Elixir Documentation][6]
|
||||
* [Elixir Core Mailing list (development)][3]
|
||||
* [Issues tracker][2]
|
||||
* [Code of Conduct][7]
|
||||
* **[#elixir-lang][4]** on [Freenode][5] IRC
|
||||
|
||||
[1]: https://elixir-lang.org/getting-started/introduction.html
|
||||
[1]: http://elixir-lang.org
|
||||
[2]: https://github.com/elixir-lang/elixir/issues
|
||||
[3]: https://groups.google.com/group/elixir-lang-core
|
||||
[4]: https://webchat.freenode.net/?channels=#elixir-lang
|
||||
|
||||
+19
-13
@@ -10,28 +10,34 @@ This document simply outlines the release process:
|
||||
|
||||
3. Ensure CHANGELOG is updated and add current date
|
||||
|
||||
4. Update "Compatibility and Deprecations" if a new OTP version is supported. If a new `vMAJOR.MINOR`, replace "master" with "vVERSION" in the "Deprecations" section
|
||||
4. Commit changes above with title "Release vVERSION" and generate new tag
|
||||
|
||||
5. If a new `vMAJOR.MINOR`, create a new branch "vMAJOR.MINOR" and set `CANONICAL=` in Makefile
|
||||
5. Run `make clean test` to ensure all tests pass from scratch and the CI is green
|
||||
|
||||
6. Add an entry for the new version to the OTP compatibility table in the "Compatibility and Deprecations" page
|
||||
6. Recompile an existing project (for example, Ecto) to ensure manifests can be upgraded
|
||||
|
||||
7. Commit changes above with title "Release vVERSION" and generate new tag
|
||||
7. Push branch and the new tag
|
||||
|
||||
8. Run `make clean test` to ensure all tests pass from scratch and the CI is green
|
||||
8. If a new `vMAJOR.MINOR`, create a new branch "vMAJOR.MINOR" and set `CANONICAL=` in Makefile before building docs
|
||||
|
||||
9. Recompile an existing project (for example, Ecto) to ensure manifests can be upgraded
|
||||
9. Publish new zips with `make zips`, upload `Precompiled.zip` and `Docs.zip` to GitHub Releases
|
||||
|
||||
10. Push branch and the new tag
|
||||
10. Add the release to `elixir.csv` and `_data/elixir-versions.yml` files in `elixir-lang/elixir-lang.github.com`
|
||||
|
||||
11. Publish new zips with `make zips`, upload `Precompiled.zip` and `Docs.zip` to GitHub Releases
|
||||
|
||||
12. Add the release to `elixir.csv` and `_data/elixir-versions.yml` files in `elixir-lang/elixir-lang.github.com`
|
||||
|
||||
13. After a new `vMAJOR.MINOR`, move back to master, bump versions, start new CHANGELOG, add `-dev` back and commit "Start vMAJOR.MINOR+1"
|
||||
11. After a new `vMAJOR.MINOR`, move back to master, bump versions, start new CHANGELOG, add `-dev` back and commit "Start vMAJOR.MINOR+1"
|
||||
|
||||
## Places where version is mentioned
|
||||
|
||||
* VERSION
|
||||
* CHANGELOG.md
|
||||
* lib/elixir/src/elixir.app.src
|
||||
* src/elixir.app.src (not lib/elixir/src/elixir.app.src)
|
||||
|
||||
## Deprecation policy
|
||||
|
||||
Elixir deprecations happens in 3 steps:
|
||||
|
||||
1. The feature is soft-deprecated. It means both CHANGELOG and documentation must list the feature as deprecated but no warning is effectively emitted by running the code. There is no requirement to soft-deprecate a feature.
|
||||
|
||||
2. The feature is effectively deprecated by emitting warnings on usage. In order to deprecate a feature, the proposed alternative MUST exist for AT LEAST two versions. For example, `Enum.uniq/2` was soft-deprecated in favor of `Enum.uniq_by/2` in Elixir v1.1. This means a deprecation warning may only be emitted by Elixir v1.3 or later.
|
||||
|
||||
3. The feature is removed. This can only happen on major releases. This means deprecated features in Elixir v1.x shall only be removed by Elixir v2.x.
|
||||
|
||||
+3
-4
@@ -2,6 +2,7 @@
|
||||
if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
||||
echo "Usage: `basename $0` [options] [.exs file] [data]
|
||||
|
||||
-v Prints version and exits
|
||||
-e COMMAND Evaluates the given command (*)
|
||||
-r FILE Requires the given files/patterns (*)
|
||||
-S SCRIPT Finds and executes the given script in PATH
|
||||
@@ -13,14 +14,12 @@ if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
||||
--cookie COOKIE Sets a cookie for this distributed node
|
||||
--detached Starts the Erlang VM detached from console
|
||||
--erl SWITCHES Switches to be passed down to Erlang (*)
|
||||
--help, -h Prints this message and exits
|
||||
--hidden Makes a hidden node
|
||||
--logger-otp-reports BOOL Enables or disables OTP reporting
|
||||
--logger-sasl-reports BOOL Enables or disables SASL reporting
|
||||
--name NAME Makes and assigns a name to the distributed node
|
||||
--no-halt Does not halt the Erlang VM after execution
|
||||
--sname NAME Makes and assigns a short name to the distributed node
|
||||
--version, -v Prints Elixir version and exits
|
||||
--werl Uses Erlang's Windows shell GUI (Windows only)
|
||||
|
||||
** Options marked with (*) can be given more than once
|
||||
@@ -75,14 +74,14 @@ while [ $I -le $# ]; do
|
||||
--logger-otp-reports)
|
||||
I=$(expr $I + 1)
|
||||
eval "VAL=\${$I}"
|
||||
if [ "$VAL" = 'true' ] || [ "$VAL" = 'false' ]; then
|
||||
if [ "$VAL" == 'true' ] || [ "$VAL" == 'false' ]; then
|
||||
ERL="$ERL -logger handle_otp_reports "$VAL""
|
||||
fi
|
||||
;;
|
||||
--logger-sasl-reports)
|
||||
I=$(expr $I + 1)
|
||||
eval "VAL=\${$I}"
|
||||
if [ "$VAL" = 'true' ] || [ "$VAL" = 'false' ]; then
|
||||
if [ "$VAL" == 'true' ] || [ "$VAL" == 'false' ]; then
|
||||
ERL="$ERL -logger handle_sasl_reports "$VAL""
|
||||
fi
|
||||
;;
|
||||
|
||||
+2
-3
@@ -10,6 +10,7 @@ goto parseopts
|
||||
:documentation
|
||||
echo Usage: %~nx0 [options] [.exs file] [data]
|
||||
echo.
|
||||
echo -v Prints version and exits
|
||||
echo -e COMMAND Evaluates the given command (*)
|
||||
echo -r FILE Requires the given files/patterns (*)
|
||||
echo -S SCRIPT Finds and executes the given script in PATH
|
||||
@@ -21,14 +22,12 @@ echo --app APP Starts the given app and its dependencies (*)
|
||||
echo --cookie COOKIE Sets a cookie for this distributed node
|
||||
echo --detached Starts the Erlang VM detached from console
|
||||
echo --erl SWITCHES Switches to be passed down to Erlang (*)
|
||||
echo --help, -h Prints this message and exits
|
||||
echo --hidden Makes a hidden node
|
||||
echo --logger-otp-reports BOOL Enables or disables OTP reporting
|
||||
echo --logger-sasl-reports BOOL Enables or disables SASL reporting
|
||||
echo --name NAME Makes and assigns a name to the distributed node
|
||||
echo --no-halt Does not halt the Erlang VM after execution
|
||||
echo --sname NAME Makes and assigns a short name to the distributed node
|
||||
echo --version, -v Prints Elixir version and exits
|
||||
echo --werl Uses Erlang's Windows shell GUI
|
||||
echo.
|
||||
echo ** Options marked with (*) can be given more than once
|
||||
@@ -88,7 +87,7 @@ if """"=="%par:--sname=%" (set parsErlang=%parsErlang% -sname %1 &
|
||||
if """"=="%par:--name=%" (set parsErlang=%parsErlang% -name %1 && shift)
|
||||
if """"=="%par:--logger-otp-reports=%" (set parsErlang=%parsErlang% -logger handle_otp_reports %1 && shift)
|
||||
if """"=="%par:--logger-sasl-reports=%" (set parsErlang=%parsErlang% -logger handle_sasl_reports %1 && shift)
|
||||
if """"=="%par:--erl=%" (set "beforeExtra=%beforeExtra% %~1" && shift)
|
||||
if """"=="%par:--erl=%" (set beforeExtra=%beforeExtra% %~1 && shift)
|
||||
goto:startloop
|
||||
|
||||
rem ******* assume all pre-params are parsed ********************
|
||||
|
||||
+6
-9
@@ -2,15 +2,12 @@
|
||||
if [ $# -eq 0 ] || [ "$1" = "--help" ] || [ "$1" = "-h" ]; then
|
||||
echo "Usage: `basename $0` [elixir switches] [compiler switches] [.ex files]
|
||||
|
||||
-o The directory to output compiled files
|
||||
|
||||
--help, -h Prints this message and exits
|
||||
--ignore-module-conflict Does not emit warnings if a module was previously defined
|
||||
--no-debug-info Does not attach debug info to compiled modules
|
||||
--no-docs Does not attach documentation to compiled modules
|
||||
--verbose Prints compilation status
|
||||
--version, -v Prints Elixir version and exits
|
||||
--warnings-as-errors Treats warnings as errors and return non-zero exit code
|
||||
-o The directory to output compiled files
|
||||
--no-docs Do not attach documentation to compiled modules
|
||||
--no-debug-info Do not attach debug info to compiled modules
|
||||
--verbose Print compilation status
|
||||
--warnings-as-errors Treat warnings as errors and return non-zero exit code
|
||||
--ignore-module-conflict
|
||||
|
||||
** Options given after -- are passed down to the executed code
|
||||
** Options can be passed to the Erlang runtime using ELIXIR_ERL_OPTIONS
|
||||
|
||||
+6
-9
@@ -14,15 +14,12 @@ goto run
|
||||
:documentation
|
||||
echo Usage: %~nx0 [elixir switches] [compiler switches] [.ex files]
|
||||
echo.
|
||||
echo -o The directory to output compiled files
|
||||
echo.
|
||||
echo --help, -h Prints this message and exits
|
||||
echo --ignore-module-conflict Does not emit warnings if a module was previously defined
|
||||
echo --no-debug-info Does not attach debug info to compiled modules
|
||||
echo --no-docs Does not attach documentation to compiled modules
|
||||
echo --verbose Prints compilation status
|
||||
echo --version, -v Prints Elixir version and exits
|
||||
echo --warnings-as-errors Treats warnings as errors and returns non-zero exit code
|
||||
echo -o The directory to output compiled files
|
||||
echo --no-docs Do not attach documentation to compiled modules
|
||||
echo --no-debug-info Do not attach debug info to compiled modules
|
||||
echo --verbose Print compilation status
|
||||
echo --warnings-as-errors Treat warnings as errors and return non-zero exit code
|
||||
echo --ignore-module-conflict
|
||||
echo.
|
||||
echo ** Options given after -- are passed down to the executed code
|
||||
echo ** Options can be passed to the Erlang runtime using ELIXIR_ERL_OPTIONS
|
||||
|
||||
@@ -2,6 +2,7 @@
|
||||
if [ $# -gt 0 ] && ([ "$1" = "--help" ] || [ "$1" = "-h" ]); then
|
||||
echo "Usage: `basename $0` [options] [.exs file] [data]
|
||||
|
||||
-v Prints version and exits
|
||||
-e COMMAND Evaluates the given command (*)
|
||||
-r FILE Requires the given files/patterns (*)
|
||||
-S SCRIPT Finds and executes the given script in PATH
|
||||
@@ -13,14 +14,12 @@ if [ $# -gt 0 ] && ([ "$1" = "--help" ] || [ "$1" = "-h" ]); then
|
||||
--cookie COOKIE Sets a cookie for this distributed node
|
||||
--detached Starts the Erlang VM detached from console
|
||||
--erl SWITCHES Switches to be passed down to Erlang (*)
|
||||
--help, -h Prints this message and exits
|
||||
--hidden Makes a hidden node
|
||||
--logger-otp-reports BOOL Enables or disables OTP reporting
|
||||
--logger-sasl-reports BOOL Enables or disables SASL reporting
|
||||
--name NAME Makes and assigns a name to the distributed node
|
||||
--no-halt Does not halt the Erlang VM after execution
|
||||
--sname NAME Makes and assigns a short name to the distributed node
|
||||
--version, -v Prints IEx version and exits
|
||||
--werl Uses Erlang's Windows shell GUI (Windows only)
|
||||
|
||||
--dot-iex PATH Overrides default .iex.exs file and uses path instead;
|
||||
@@ -45,4 +44,4 @@ readlink_f () {
|
||||
|
||||
SELF=$(readlink_f "$0")
|
||||
SCRIPT_PATH=$(dirname "$SELF")
|
||||
exec "$SCRIPT_PATH"/elixir --no-halt --erl "-noshell -user Elixir.IEx.CLI" +iex "$@"
|
||||
exec "$SCRIPT_PATH"/elixir --no-halt --erl "-user Elixir.IEx.CLI" +iex "$@"
|
||||
|
||||
+22
-23
@@ -9,30 +9,29 @@ goto run
|
||||
:documentation
|
||||
echo Usage: %~nx0 [options] [.exs file] [data]
|
||||
echo.
|
||||
echo -e COMMAND Evaluates the given command (*)
|
||||
echo -r FILE Requires the given files/patterns (*)
|
||||
echo -S SCRIPT Finds and executes the given script in PATH
|
||||
echo -pr FILE Requires the given files/patterns in parallel (*)
|
||||
echo -pa PATH Prepends the given path to Erlang code path (*)
|
||||
echo -pz PATH Appends the given path to Erlang code path (*)
|
||||
echo -v Prints version and exits
|
||||
echo -e COMMAND Evaluates the given command (*)
|
||||
echo -r FILE Requires the given files/patterns (*)
|
||||
echo -S SCRIPT Finds and executes the given script in PATH
|
||||
echo -pr FILE Requires the given files/patterns in parallel (*)
|
||||
echo -pa PATH Prepends the given path to Erlang code path (*)
|
||||
echo -pz PATH Appends the given path to Erlang code path (*)
|
||||
echo.
|
||||
echo --app APP Starts the given app and its dependencies (*)
|
||||
echo --cookie COOKIE Sets a cookie for this distributed node
|
||||
echo --detached Starts the Erlang VM detached from console
|
||||
echo --erl SWITCHES Switches to be passed down to Erlang (*)
|
||||
echo --help, -h Prints this message and exits
|
||||
echo --hidden Makes a hidden node
|
||||
echo --logger-otp-reports BOOL Enables or disables OTP reporting
|
||||
echo --logger-sasl-reports BOOL Enables or disables SASL reporting
|
||||
echo --name NAME Makes and assigns a name to the distributed node
|
||||
echo --no-halt Does not halt the Erlang VM after execution
|
||||
echo --sname NAME Makes and assigns a short name to the distributed node
|
||||
echo --version, -v Prints IEx version and exits
|
||||
echo --werl Uses Erlang's Windows shell GUI (Windows only)
|
||||
echo --app APP Starts the given app and its dependencies (*)
|
||||
echo --cookie COOKIE Sets a cookie for this distributed node
|
||||
echo --detached Starts the Erlang VM detached from console
|
||||
echo --erl SWITCHES Switches to be passed down to Erlang (*)
|
||||
echo --hidden Makes a hidden node
|
||||
echo --logger-otp-reports BOOL Enables or disables OTP reporting
|
||||
echo --logger-sasl-reports BOOL Enables or disables SASL reporting
|
||||
echo --name NAME Makes and assigns a name to the distributed node
|
||||
echo --no-halt Does not halt the Erlang VM after execution
|
||||
echo --sname NAME Makes and assigns a short name to the distributed node
|
||||
echo --werl Uses Erlang's Windows shell GUI (Windows only)
|
||||
echo.
|
||||
echo --dot-iex PATH Overrides default .iex.exs file and uses path instead;
|
||||
echo path can be empty, then no file will be loaded
|
||||
echo --remsh NAME Connects to a node using a remote shell
|
||||
echo --dot-iex PATH Overrides default .iex.exs file and uses path instead;
|
||||
echo path can be empty, then no file will be loaded
|
||||
echo --remsh NAME Connects to a node using a remote shell
|
||||
echo.
|
||||
echo ** Options marked with (*) can be given more than once
|
||||
echo ** Options given after the .exs file or -- are passed down to the executed code
|
||||
@@ -41,6 +40,6 @@ goto end
|
||||
|
||||
:run
|
||||
@if defined IEX_WITH_WERL (@set __ELIXIR_IEX_FLAGS=--werl) else (set __ELIXIR_IEX_FLAGS=)
|
||||
call "%~dp0\elixir.bat" --no-halt --erl "-noshell -user Elixir.IEx.CLI" +iex %__ELIXIR_IEX_FLAGS% %*
|
||||
call "%~dp0\elixir.bat" +iex --erl "-user Elixir.IEx.CLI" --no-halt %__ELIXIR_IEX_FLAGS% %*
|
||||
:end
|
||||
endlocal
|
||||
|
||||
+14
-14
@@ -112,13 +112,13 @@ defmodule EEx do
|
||||
"""
|
||||
defmacro function_from_string(kind, name, source, args \\ [], options \\ []) do
|
||||
quote bind_quoted: binding() do
|
||||
info = Keyword.merge([file: __ENV__.file, line: __ENV__.line], options)
|
||||
args = Enum.map(args, fn arg -> {arg, [line: info[:line]], nil} end)
|
||||
info = Keyword.merge [file: __ENV__.file, line: __ENV__.line], options
|
||||
args = Enum.map args, fn arg -> {arg, [line: info[:line]], nil} end
|
||||
compiled = EEx.compile_string(source, info)
|
||||
|
||||
case kind do
|
||||
:def -> def unquote(name)(unquote_splicing(args)), do: unquote(compiled)
|
||||
:defp -> defp unquote(name)(unquote_splicing(args)), do: unquote(compiled)
|
||||
:def -> def(unquote(name)(unquote_splicing(args)), do: unquote(compiled))
|
||||
:defp -> defp(unquote(name)(unquote_splicing(args)), do: unquote(compiled))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -149,15 +149,15 @@ defmodule EEx do
|
||||
"""
|
||||
defmacro function_from_file(kind, name, file, args \\ [], options \\ []) do
|
||||
quote bind_quoted: binding() do
|
||||
info = Keyword.merge(options, file: file, line: 1)
|
||||
args = Enum.map(args, fn arg -> {arg, [line: 1], nil} end)
|
||||
info = Keyword.merge options, [file: file, line: 1]
|
||||
args = Enum.map args, fn arg -> {arg, [line: 1], nil} end
|
||||
compiled = EEx.compile_file(file, info)
|
||||
|
||||
@external_resource file
|
||||
@file file
|
||||
case kind do
|
||||
:def -> def unquote(name)(unquote_splicing(args)), do: unquote(compiled)
|
||||
:defp -> defp unquote(name)(unquote_splicing(args)), do: unquote(compiled)
|
||||
:def -> def(unquote(name)(unquote_splicing(args)), do: unquote(compiled))
|
||||
:defp -> defp(unquote(name)(unquote_splicing(args)), do: unquote(compiled))
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -166,7 +166,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() | no_return
|
||||
@spec compile_string(String.t, Keyword.t) :: Macro.t | no_return
|
||||
def compile_string(source, options \\ []) when is_binary(source) and is_list(options) do
|
||||
EEx.Compiler.compile(source, options)
|
||||
end
|
||||
@@ -175,9 +175,9 @@ 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() | no_return
|
||||
@spec compile_file(String.t, Keyword.t) :: 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)
|
||||
options = Keyword.merge options, [file: filename, line: 1]
|
||||
compile_string(File.read!(filename), options)
|
||||
end
|
||||
|
||||
@@ -190,7 +190,7 @@ defmodule EEx do
|
||||
"foo baz"
|
||||
|
||||
"""
|
||||
@spec eval_string(String.t(), keyword, keyword) :: any
|
||||
@spec eval_string(String.t, Keyword.t, Keyword.t) :: any
|
||||
def eval_string(source, bindings \\ [], options \\ [])
|
||||
when is_binary(source) and is_list(bindings) and is_list(options) do
|
||||
compiled = compile_string(source, options)
|
||||
@@ -209,10 +209,10 @@ defmodule EEx do
|
||||
EEx.eval_file "sample.eex", [bar: "baz"] #=> "foo baz"
|
||||
|
||||
"""
|
||||
@spec eval_file(String.t(), keyword, keyword) :: any
|
||||
@spec eval_file(String.t, Keyword.t, Keyword.t) :: any
|
||||
def eval_file(filename, bindings \\ [], options \\ [])
|
||||
when is_binary(filename) and is_list(bindings) and is_list(options) do
|
||||
options = Keyword.put(options, :file, filename)
|
||||
options = Keyword.put options, :file, filename
|
||||
compiled = compile_file(filename, options)
|
||||
do_eval(compiled, bindings, options)
|
||||
end
|
||||
|
||||
+36
-100
@@ -9,25 +9,16 @@ 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() | no_return
|
||||
@spec compile(String.t, Keyword.t) :: 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
|
||||
trim = opts[:trim] || false
|
||||
|
||||
file = opts[:file] || "nofile"
|
||||
line = opts[:line] || 1
|
||||
trim = opts[:trim] || false
|
||||
case EEx.Tokenizer.tokenize(source, line, trim: trim) do
|
||||
{:ok, tokens} ->
|
||||
state = %{
|
||||
engine: opts[:engine] || @default_engine,
|
||||
file: file,
|
||||
line: line,
|
||||
quoted: [],
|
||||
start_line: nil
|
||||
}
|
||||
|
||||
init = state.engine.init(opts)
|
||||
generate_buffer(tokens, init, [], state)
|
||||
|
||||
state = %{engine: opts[:engine] || @default_engine,
|
||||
file: file, line: line, quoted: [], start_line: nil}
|
||||
generate_buffer(tokens, state.engine.init(opts), [], state)
|
||||
{:error, line, message} ->
|
||||
raise EEx.SyntaxError, line: line, file: file, message: message
|
||||
end
|
||||
@@ -36,84 +27,39 @@ defmodule EEx.Compiler do
|
||||
# Generates the buffers by handling each expression from the tokenizer.
|
||||
# It returns Macro.t/0 or it raises.
|
||||
|
||||
defp generate_buffer([{:text, chars} | rest], buffer, scope, state) do
|
||||
defp generate_buffer([{:text, chars} | t], buffer, scope, state) do
|
||||
buffer = state.engine.handle_text(buffer, IO.chardata_to_string(chars))
|
||||
generate_buffer(rest, buffer, scope, state)
|
||||
generate_buffer(t, buffer, scope, state)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:expr, line, mark, chars} | rest], buffer, scope, state) do
|
||||
expr = Code.string_to_quoted!(chars, line: line, file: state.file)
|
||||
defp generate_buffer([{:expr, line, mark, chars} | t], buffer, scope, state) do
|
||||
expr = Code.string_to_quoted!(chars, [line: line, file: state.file])
|
||||
buffer = state.engine.handle_expr(buffer, IO.chardata_to_string(mark), expr)
|
||||
generate_buffer(rest, buffer, scope, state)
|
||||
generate_buffer(t, buffer, scope, state)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:start_expr, start_line, mark, chars} | rest], buffer, scope, state) do
|
||||
{contents, line, rest} = look_ahead_text(rest, start_line, chars)
|
||||
|
||||
{contents, rest} =
|
||||
generate_buffer(rest, state.engine.handle_begin(buffer), [contents | scope], %{
|
||||
state
|
||||
| quoted: [],
|
||||
line: line,
|
||||
start_line: start_line
|
||||
})
|
||||
|
||||
defp generate_buffer([{:start_expr, start_line, mark, chars} | t], buffer, scope, state) do
|
||||
{contents, line, t} = look_ahead_text(t, start_line, chars)
|
||||
{contents, t} = generate_buffer(t, "", [contents | scope],
|
||||
%{state | quoted: [], line: line, start_line: start_line})
|
||||
buffer = state.engine.handle_expr(buffer, IO.chardata_to_string(mark), contents)
|
||||
generate_buffer(rest, buffer, scope, state)
|
||||
generate_buffer(t, buffer, scope, state)
|
||||
end
|
||||
|
||||
defp generate_buffer([{:middle_expr, line, '', chars} | rest], buffer, [current | scope], state) do
|
||||
defp generate_buffer([{:middle_expr, line, _, chars} | t], buffer, [current | scope], state) do
|
||||
{wrapped, state} = wrap_expr(current, line, buffer, chars, state)
|
||||
state = %{state | line: line}
|
||||
generate_buffer(rest, state.engine.handle_begin(buffer), [wrapped | scope], state)
|
||||
generate_buffer(t, "", [wrapped | scope], %{state | line: line})
|
||||
end
|
||||
|
||||
defp generate_buffer(
|
||||
[{:middle_expr, line, modifier, chars} | t],
|
||||
buffer,
|
||||
[_ | _] = scope,
|
||||
state
|
||||
) do
|
||||
message =
|
||||
"unexpected beginning of EEx tag \"<%#{modifier}\" on \"<%#{modifier}#{chars}%>\", " <>
|
||||
"please remove \"#{modifier}\" accordingly"
|
||||
|
||||
:elixir_errors.warn(line, state.file, message)
|
||||
generate_buffer([{:middle_expr, line, '', chars} | t], buffer, scope, state)
|
||||
# TODO: Make this an error on Elixir v2.0 since it accidentally worked previously.
|
||||
# raise EEx.SyntaxError, message: message, file: state.file, line: line
|
||||
end
|
||||
|
||||
defp generate_buffer([{:middle_expr, line, _, chars} | _], _buffer, [], state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected middle of expression <%#{chars}%>",
|
||||
file: state.file,
|
||||
line: line
|
||||
end
|
||||
|
||||
defp generate_buffer([{:end_expr, line, '', chars} | rest], buffer, [current | _], state) do
|
||||
defp generate_buffer([{:end_expr, line, _, chars} | t], buffer, [current | _], state) do
|
||||
{wrapped, state} = wrap_expr(current, line, buffer, chars, state)
|
||||
tuples = Code.string_to_quoted!(wrapped, line: state.start_line, file: state.file)
|
||||
tuples = Code.string_to_quoted!(wrapped, [line: state.start_line, file: state.file])
|
||||
buffer = insert_quoted(tuples, state.quoted)
|
||||
{buffer, rest}
|
||||
end
|
||||
|
||||
defp generate_buffer([{:end_expr, line, modifier, chars} | t], buffer, [_ | _] = scope, state) do
|
||||
message =
|
||||
"unexpected beginning of EEx tag \"<%#{modifier}\" on end of " <>
|
||||
"expression \"<%#{modifier}#{chars}%>\", please remove \"#{modifier}\" accordingly"
|
||||
|
||||
:elixir_errors.warn(line, state.file, message)
|
||||
generate_buffer([{:end_expr, line, '', chars} | t], buffer, scope, state)
|
||||
# TODO: Make this an error on Elixir v2.0 since it accidentally worked previously.
|
||||
# raise EEx.SyntaxError, message: message, file: state.file, line: line
|
||||
{buffer, t}
|
||||
end
|
||||
|
||||
defp generate_buffer([{:end_expr, line, _, chars} | _], _buffer, [], state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected end of expression <%#{chars}%>",
|
||||
file: state.file,
|
||||
line: line
|
||||
raise EEx.SyntaxError, message: "unexpected token #{inspect chars}", file: state.file, line: line
|
||||
end
|
||||
|
||||
defp generate_buffer([], buffer, [], state) do
|
||||
@@ -121,10 +67,8 @@ defmodule EEx.Compiler do
|
||||
end
|
||||
|
||||
defp generate_buffer([], _buffer, _scope, state) do
|
||||
raise EEx.SyntaxError,
|
||||
message: "unexpected end of string, expected a closing '<% end %>'",
|
||||
file: state.file,
|
||||
line: state.line
|
||||
raise EEx.SyntaxError, message: "unexpected end of string, expected a closing '<% end %>'",
|
||||
file: state.file, line: state.line
|
||||
end
|
||||
|
||||
# Creates a placeholder and wrap it inside the expression block
|
||||
@@ -133,32 +77,24 @@ defmodule EEx.Compiler do
|
||||
new_lines = List.duplicate(?\n, line - state.line)
|
||||
key = length(state.quoted)
|
||||
placeholder = '__EEX__(' ++ Integer.to_charlist(key) ++ ');'
|
||||
count = current ++ placeholder ++ new_lines ++ chars
|
||||
new_state = %{state | quoted: [{key, state.engine.handle_end(buffer)} | state.quoted]}
|
||||
|
||||
{count, new_state}
|
||||
{current ++ placeholder ++ new_lines ++ chars,
|
||||
%{state | quoted: [{key, buffer} | state.quoted]}}
|
||||
end
|
||||
|
||||
# Look text ahead on expressions
|
||||
|
||||
defp look_ahead_text(
|
||||
[{:text, text}, {:middle_expr, line, _, chars} | rest] = tokens,
|
||||
start,
|
||||
contents
|
||||
) do
|
||||
defp look_ahead_text([{:text, text}, {:middle_expr, line, _, chars} | t]=list, start, contents) do
|
||||
if only_spaces?(text) do
|
||||
{contents ++ text ++ chars, line, rest}
|
||||
{contents ++ text ++ chars, line, t}
|
||||
else
|
||||
{contents, start, tokens}
|
||||
{contents, start, list}
|
||||
end
|
||||
end
|
||||
|
||||
defp look_ahead_text([{:middle_expr, line, _, chars} | rest], _start, contents) do
|
||||
{contents ++ chars, line, rest}
|
||||
defp look_ahead_text([{:middle_expr, line, _, chars} | t], _start, contents) do
|
||||
{contents ++ chars, line, t}
|
||||
end
|
||||
|
||||
defp look_ahead_text(tokens, start, contents) do
|
||||
{contents, start, tokens}
|
||||
defp look_ahead_text(t, start, contents) do
|
||||
{contents, start, t}
|
||||
end
|
||||
|
||||
defp only_spaces?(chars) do
|
||||
@@ -168,7 +104,7 @@ defmodule EEx.Compiler do
|
||||
# Changes placeholder to real expression
|
||||
|
||||
defp insert_quoted({:__EEX__, _, [key]}, quoted) do
|
||||
{^key, value} = List.keyfind(quoted, key, 0)
|
||||
{^key, value} = List.keyfind quoted, key, 0
|
||||
value
|
||||
end
|
||||
|
||||
@@ -181,7 +117,7 @@ defmodule EEx.Compiler do
|
||||
end
|
||||
|
||||
defp insert_quoted(list, quoted) when is_list(list) do
|
||||
Enum.map(list, &insert_quoted(&1, quoted))
|
||||
Enum.map list, &insert_quoted(&1, quoted)
|
||||
end
|
||||
|
||||
defp insert_quoted(other, _quoted) do
|
||||
|
||||
+21
-80
@@ -2,43 +2,23 @@ defmodule EEx.Engine do
|
||||
@moduledoc ~S"""
|
||||
Basic EEx engine that ships with Elixir.
|
||||
|
||||
An engine needs to implement six functions:
|
||||
An engine needs to implement four functions:
|
||||
|
||||
* `init(opts)` - called at the beginning of every text
|
||||
and it must return the initial state.
|
||||
* `init(opts)` - returns the initial buffer
|
||||
|
||||
* `handle_body(state)` - receives the state of the document
|
||||
and it must return a quoted expression.
|
||||
* `handle_body(quoted)` - receives the final built quoted
|
||||
expression, should do final post-processing and return a
|
||||
quoted expression.
|
||||
|
||||
* `handle_text(state, text)` - it receives the state,
|
||||
* `handle_text(buffer, text)` - it receives the buffer,
|
||||
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
|
||||
* `handle_expr(buffer, marker, expr)` - it receives the buffer,
|
||||
the marker, the expr and must return a new 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.
|
||||
as marker. The allowed markers so far are: `""` and `"="`.
|
||||
|
||||
Read `handle_expr/3` below for more information about the markers
|
||||
implemented by default by this engine.
|
||||
@@ -47,14 +27,10 @@ defmodule EEx.Engine do
|
||||
default implementations for the functions above.
|
||||
"""
|
||||
|
||||
@type state :: term
|
||||
|
||||
@callback init(opts :: keyword) :: state
|
||||
@callback handle_body(state) :: Macro.t()
|
||||
@callback handle_text(state, text :: String.t()) :: state
|
||||
@callback handle_expr(state, marker :: String.t(), expr :: Macro.t()) :: state
|
||||
@callback handle_begin(state) :: state
|
||||
@callback handle_end(state) :: Macro.t()
|
||||
@callback init(opts :: Keyword.t) :: Macro.t
|
||||
@callback handle_body(quoted :: Macro.t) :: Macro.t
|
||||
@callback handle_text(buffer :: Macro.t, text :: String.t) :: Macro.t
|
||||
@callback handle_expr(buffer :: Macro.t, marker :: String.t, expr :: Macro.t) :: Macro.t
|
||||
|
||||
@doc false
|
||||
defmacro __using__(_) do
|
||||
@@ -69,14 +45,6 @@ defmodule EEx.Engine do
|
||||
EEx.Engine.handle_body(quoted)
|
||||
end
|
||||
|
||||
def handle_begin(quoted) do
|
||||
EEx.Engine.handle_begin(quoted)
|
||||
end
|
||||
|
||||
def handle_end(quoted) do
|
||||
EEx.Engine.handle_end(quoted)
|
||||
end
|
||||
|
||||
def handle_text(buffer, text) do
|
||||
EEx.Engine.handle_text(buffer, text)
|
||||
end
|
||||
@@ -85,7 +53,7 @@ defmodule EEx.Engine do
|
||||
EEx.Engine.handle_expr(buffer, marker, expr)
|
||||
end
|
||||
|
||||
defoverridable EEx.Engine
|
||||
defoverridable [handle_body: 1, handle_expr: 3, handle_text: 2, init: 1]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -104,33 +72,27 @@ defmodule EEx.Engine do
|
||||
end
|
||||
|
||||
"""
|
||||
@spec handle_assign(Macro.t()) :: Macro.t()
|
||||
@spec handle_assign(Macro.t) :: Macro.t
|
||||
def handle_assign({:@, meta, [{name, _, atom}]}) when is_atom(name) and is_atom(atom) do
|
||||
line = meta[:line] || 0
|
||||
quote(line: line, do: EEx.Engine.fetch_assign!(var!(assigns), unquote(name)))
|
||||
quote line: line, do: EEx.Engine.fetch_assign!(var!(assigns), unquote(name))
|
||||
end
|
||||
|
||||
def handle_assign(arg) do
|
||||
arg
|
||||
end
|
||||
|
||||
@doc false
|
||||
# TODO: Raise on 2.0
|
||||
@spec fetch_assign!(Access.t(), Access.key()) :: term | nil
|
||||
@spec fetch_assign!(map, Map.key) :: term | nil
|
||||
def fetch_assign!(assigns, key) do
|
||||
case Access.fetch(assigns, key) do
|
||||
{:ok, val} ->
|
||||
val
|
||||
|
||||
:error ->
|
||||
keys = Enum.map(assigns, &elem(&1, 0))
|
||||
|
||||
IO.warn(
|
||||
"assign @#{key} not available in EEx template. " <>
|
||||
"Please ensure all assigns are given as options. " <>
|
||||
"Available assigns: #{inspect(keys)}"
|
||||
)
|
||||
|
||||
IO.warn "assign @#{key} not available in EEx template. " <>
|
||||
"Please ensure all assigns are given as options. " <>
|
||||
"Available assigns: #{inspect keys}"
|
||||
nil
|
||||
end
|
||||
end
|
||||
@@ -142,20 +104,6 @@ defmodule EEx.Engine do
|
||||
""
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns an empty string as the new buffer.
|
||||
"""
|
||||
def handle_begin(_previous) do
|
||||
""
|
||||
end
|
||||
|
||||
@doc """
|
||||
End of the new buffer.
|
||||
"""
|
||||
def handle_end(quoted) do
|
||||
quoted
|
||||
end
|
||||
|
||||
@doc """
|
||||
The default implementation simply returns the given expression.
|
||||
"""
|
||||
@@ -167,7 +115,7 @@ defmodule EEx.Engine do
|
||||
The default implementation simply concatenates text to the buffer.
|
||||
"""
|
||||
def handle_text(buffer, text) do
|
||||
quote(do: unquote(buffer) <> unquote(text))
|
||||
quote do: unquote(buffer) <> unquote(text)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -175,8 +123,6 @@ defmodule EEx.Engine do
|
||||
|
||||
<% 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 %>
|
||||
|
||||
All other markers are not implemented by this engine.
|
||||
"""
|
||||
@@ -194,9 +140,4 @@ defmodule EEx.Engine do
|
||||
tmp2
|
||||
end
|
||||
end
|
||||
|
||||
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
|
||||
end
|
||||
|
||||
@@ -1,12 +1,10 @@
|
||||
defmodule EEx.Tokenizer do
|
||||
@moduledoc false
|
||||
|
||||
@type content :: IO.chardata()
|
||||
@type content :: IO.chardata
|
||||
@type line :: non_neg_integer
|
||||
@type marker :: '=' | '/' | '|' | ''
|
||||
@type token ::
|
||||
{:text, content}
|
||||
| {:expr | :start_expr | :middle_expr | :end_expr, line, marker, content}
|
||||
@type token :: {:text, content} |
|
||||
{:expr | :start_expr | :middle_expr | :end_expr, line, '=' | '', content}
|
||||
|
||||
@doc """
|
||||
Tokenizes the given charlist or binary.
|
||||
@@ -21,7 +19,7 @@ defmodule EEx.Tokenizer do
|
||||
|
||||
Or `{:error, line, error}` in case of errors.
|
||||
"""
|
||||
@spec tokenize(binary | charlist, line, keyword) :: {:ok, [token]} | {:error, line, String.t()}
|
||||
@spec tokenize(binary | charlist, line, Keyword.t) :: {:ok, [token]} | {:error, line, String.t}
|
||||
def tokenize(bin, line, opts \\ [])
|
||||
|
||||
def tokenize(bin, line, opts)
|
||||
@@ -35,17 +33,15 @@ defmodule EEx.Tokenizer do
|
||||
end
|
||||
|
||||
defp tokenize('<%%' ++ t, line, opts, buffer, acc) do
|
||||
tokenize(t, line, opts, [?%, ?< | buffer], acc)
|
||||
tokenize t, line, opts, [?%, ?< | buffer], acc
|
||||
end
|
||||
|
||||
defp tokenize('<%#' ++ t, line, opts, buffer, acc) do
|
||||
case expr(t, line, []) do
|
||||
{:error, _, _} = error ->
|
||||
error
|
||||
|
||||
{:error, _, _} = error -> error
|
||||
{:ok, _, new_line, rest} ->
|
||||
{rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
|
||||
tokenize(rest, new_line, opts, buffer, acc)
|
||||
tokenize rest, new_line, opts, buffer, acc
|
||||
end
|
||||
end
|
||||
|
||||
@@ -53,24 +49,22 @@ defmodule EEx.Tokenizer do
|
||||
{marker, t} = retrieve_marker(t)
|
||||
|
||||
case expr(t, line, []) do
|
||||
{:error, _, _} = error ->
|
||||
error
|
||||
|
||||
{:error, _, _} = error -> error
|
||||
{:ok, expr, new_line, rest} ->
|
||||
token = token_name(expr)
|
||||
{rest, new_line, buffer} = trim_if_needed(rest, new_line, opts, buffer, acc)
|
||||
acc = tokenize_text(buffer, acc)
|
||||
acc = tokenize_text(buffer, acc)
|
||||
final = {token, line, marker, Enum.reverse(expr)}
|
||||
tokenize(rest, new_line, opts, [], [final | acc])
|
||||
tokenize rest, new_line, opts, [], [final | acc]
|
||||
end
|
||||
end
|
||||
|
||||
defp tokenize('\n' ++ t, line, opts, buffer, acc) do
|
||||
tokenize(t, line + 1, opts, [?\n | buffer], acc)
|
||||
tokenize t, line + 1, opts, [?\n | buffer], acc
|
||||
end
|
||||
|
||||
defp tokenize([h | t], line, opts, buffer, acc) do
|
||||
tokenize(t, line, opts, [h | buffer], acc)
|
||||
tokenize t, line, opts, [h | buffer], acc
|
||||
end
|
||||
|
||||
defp tokenize([], _line, _opts, buffer, acc) do
|
||||
@@ -79,8 +73,8 @@ defmodule EEx.Tokenizer do
|
||||
|
||||
# Retrieve marker for <%
|
||||
|
||||
defp retrieve_marker([marker | t]) when marker in [?=, ?/, ?|] do
|
||||
{[marker], t}
|
||||
defp retrieve_marker('=' ++ t) do
|
||||
{'=', t}
|
||||
end
|
||||
|
||||
defp retrieve_marker(t) do
|
||||
@@ -94,11 +88,11 @@ defmodule EEx.Tokenizer do
|
||||
end
|
||||
|
||||
defp expr('\n' ++ t, line, buffer) do
|
||||
expr(t, line + 1, [?\n | buffer])
|
||||
expr t, line + 1, [?\n | buffer]
|
||||
end
|
||||
|
||||
defp expr([h | t], line, buffer) do
|
||||
expr(t, line, [h | buffer])
|
||||
expr t, line, [h | buffer]
|
||||
end
|
||||
|
||||
defp expr([], line, _buffer) do
|
||||
@@ -129,8 +123,8 @@ defmodule EEx.Tokenizer do
|
||||
# token and, if so, it is not followed by an "end"
|
||||
# token. If this is the case, we are on a start expr.
|
||||
case :elixir_tokenizer.tokenize(rest, 1, file: "eex", check_terminators: false) do
|
||||
{:ok, tokens} ->
|
||||
tokens = Enum.reverse(tokens)
|
||||
{:ok, _line, _column, tokens} ->
|
||||
tokens = Enum.reverse(tokens)
|
||||
fn_index = fn_index(tokens)
|
||||
|
||||
if fn_index && end_index(tokens) > fn_index do
|
||||
@@ -138,28 +132,27 @@ defmodule EEx.Tokenizer do
|
||||
else
|
||||
:middle_expr
|
||||
end
|
||||
|
||||
_error ->
|
||||
:middle_expr
|
||||
end
|
||||
end
|
||||
|
||||
defp token_name('esle' ++ t), do: check_spaces(t, :middle_expr)
|
||||
defp token_name('retfa' ++ t), do: check_spaces(t, :middle_expr)
|
||||
defp token_name('hctac' ++ t), do: check_spaces(t, :middle_expr)
|
||||
defp token_name('esle' ++ t), do: check_spaces(t, :middle_expr)
|
||||
defp token_name('retfa' ++ t), do: check_spaces(t, :middle_expr)
|
||||
defp token_name('hctac' ++ t), do: check_spaces(t, :middle_expr)
|
||||
defp token_name('eucser' ++ t), do: check_spaces(t, :middle_expr)
|
||||
defp token_name('dne' ++ t), do: check_spaces(t, :end_expr)
|
||||
defp token_name('dne' ++ t), do: check_spaces(t, :end_expr)
|
||||
|
||||
defp token_name(_) do
|
||||
:expr
|
||||
end
|
||||
|
||||
defp fn_index(tokens) do
|
||||
Enum.find_index(tokens, fn
|
||||
Enum.find_index tokens, fn
|
||||
{:fn_paren, _} -> true
|
||||
{:fn, _} -> true
|
||||
_ -> false
|
||||
end)
|
||||
{:fn, _} -> true
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp end_index(tokens) do
|
||||
@@ -190,12 +183,10 @@ defmodule EEx.Tokenizer do
|
||||
# including the line break following it if there is one.
|
||||
defp trim_if_needed(rest, line, opts, buffer, acc) do
|
||||
original = {rest, line, buffer}
|
||||
|
||||
if opts[:trim] do
|
||||
case {trim_left(buffer, acc), trim_right(rest, line)} do
|
||||
{{true, new_buffer}, {true, new_rest, new_line}} ->
|
||||
{new_rest, new_line, new_buffer}
|
||||
|
||||
_ ->
|
||||
original
|
||||
end
|
||||
|
||||
+4
-6
@@ -1,11 +1,9 @@
|
||||
defmodule EEx.MixProject do
|
||||
defmodule EEx.Mixfile do
|
||||
use Mix.Project
|
||||
|
||||
def project do
|
||||
[
|
||||
app: :eex,
|
||||
version: System.version(),
|
||||
build_per_environment: false
|
||||
]
|
||||
[app: :eex,
|
||||
version: System.version,
|
||||
build_per_environment: false]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,48 +1,45 @@
|
||||
Code.require_file("../test_helper.exs", __DIR__)
|
||||
Code.require_file "../test_helper.exs", __DIR__
|
||||
|
||||
defmodule EEx.SmartEngineTest do
|
||||
# TODO: Make this async: true once capture_io is removed
|
||||
use ExUnit.Case
|
||||
use ExUnit.Case, async: true
|
||||
|
||||
import ExUnit.CaptureIO
|
||||
|
||||
test "evaluates simple string" do
|
||||
assert_eval("foo bar", "foo bar")
|
||||
assert_eval "foo bar", "foo bar"
|
||||
end
|
||||
|
||||
test "evaluates with assigns as keywords" do
|
||||
assert_eval("1", "<%= @foo %>", assigns: [foo: 1])
|
||||
assert_eval "1", "<%= @foo %>", assigns: [foo: 1]
|
||||
end
|
||||
|
||||
test "evaluates with assigns as a map" do
|
||||
assert_eval("1", "<%= @foo %>", assigns: %{foo: 1})
|
||||
assert_eval "1", "<%= @foo %>", assigns: %{foo: 1}
|
||||
end
|
||||
|
||||
test "error with missing assigns" do
|
||||
stderr =
|
||||
ExUnit.CaptureIO.capture_io(:stderr, fn ->
|
||||
assert_eval("", "<%= @foo %>", assigns: %{})
|
||||
end)
|
||||
|
||||
stderr = capture_io(:stderr, fn ->
|
||||
assert_eval "", "<%= @foo %>", assigns: %{}
|
||||
end)
|
||||
assert stderr =~ "assign @foo not available in EEx template"
|
||||
end
|
||||
|
||||
test "evaluates with loops" do
|
||||
assert_eval("1\n2\n3\n", "<%= for x <- [1, 2, 3] do %><%= x %>\n<% end %>")
|
||||
assert_eval "1\n2\n3\n", "<%= for x <- [1, 2, 3] do %><%= x %>\n<% end %>"
|
||||
end
|
||||
|
||||
test "preserves line numbers" do
|
||||
test "compiled preserved line numbers" do
|
||||
result = EEx.compile_string("<%= @hello %>", engine: EEx.SmartEngine)
|
||||
|
||||
Macro.prewalk(result, fn
|
||||
{_left, meta, _right} ->
|
||||
assert Keyword.get(meta, :line, 0) in [0, 1]
|
||||
|
||||
_ ->
|
||||
:ok
|
||||
end)
|
||||
end
|
||||
|
||||
defp assert_eval(expected, actual, binding \\ []) do
|
||||
result = EEx.eval_string(actual, binding, file: __ENV__.file, engine: EEx.SmartEngine)
|
||||
result = EEx.eval_string(actual, binding, file: __ENV__.file)
|
||||
assert result == expected
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
Code.require_file("../test_helper.exs", __DIR__)
|
||||
Code.require_file "../test_helper.exs", __DIR__
|
||||
|
||||
defmodule EEx.TokenizerTest do
|
||||
use ExUnit.Case, async: true
|
||||
@@ -13,102 +13,86 @@ defmodule EEx.TokenizerTest do
|
||||
end
|
||||
|
||||
test "strings with embedded code" do
|
||||
assert T.tokenize('foo <% bar %>', 1) == {:ok, [{:text, 'foo '}, {:expr, 1, '', ' bar '}]}
|
||||
assert T.tokenize('foo <% bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '', ' bar '}]}
|
||||
end
|
||||
|
||||
test "strings with embedded equals code" do
|
||||
assert T.tokenize('foo <%= bar %>', 1) == {:ok, [{:text, 'foo '}, {:expr, 1, '=', ' bar '}]}
|
||||
end
|
||||
|
||||
test "strings with embedded slash code" do
|
||||
assert T.tokenize('foo <%/ bar %>', 1) == {:ok, [{:text, 'foo '}, {:expr, 1, '/', ' bar '}]}
|
||||
end
|
||||
|
||||
test "strings with embedded pipe code" do
|
||||
assert T.tokenize('foo <%| bar %>', 1) == {:ok, [{:text, 'foo '}, {:expr, 1, '|', ' bar '}]}
|
||||
assert T.tokenize('foo <%= bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo '}, {:expr, 1, '=', ' bar '}]}
|
||||
end
|
||||
|
||||
test "strings with more than one line" do
|
||||
assert T.tokenize('foo\n<%= bar %>', 1) == {:ok, [{:text, 'foo\n'}, {:expr, 2, '=', ' bar '}]}
|
||||
assert T.tokenize('foo\n<%= bar %>', 1) ==
|
||||
{:ok, [{:text, 'foo\n'}, {:expr, 2, '=', ' bar '}]}
|
||||
end
|
||||
|
||||
test "strings with more than one line and expression with more than one line" do
|
||||
string = '''
|
||||
foo <%= bar
|
||||
foo <%= bar
|
||||
|
||||
baz %>
|
||||
<% foo %>
|
||||
'''
|
||||
baz %>
|
||||
<% foo %>
|
||||
'''
|
||||
|
||||
exprs = [
|
||||
assert T.tokenize(string, 1) == {:ok, [
|
||||
{:text, 'foo '},
|
||||
{:expr, 1, '=', ' bar\n\nbaz '},
|
||||
{:text, '\n'},
|
||||
{:expr, 4, '', ' foo '},
|
||||
{:text, '\n'}
|
||||
]
|
||||
|
||||
assert T.tokenize(string, 1) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "quotation" do
|
||||
assert T.tokenize('foo <%% true %>', 1) == {:ok, [{:text, 'foo <% true %>'}]}
|
||||
assert T.tokenize('foo <%% true %>', 1) == {:ok, [
|
||||
{:text, 'foo <% true %>'}
|
||||
]}
|
||||
end
|
||||
|
||||
test "quotation with do/end" do
|
||||
assert T.tokenize('foo <%% true do %>bar<%% end %>', 1) ==
|
||||
{:ok, [{:text, 'foo <% true do %>bar<% end %>'}]}
|
||||
assert T.tokenize('foo <%% true do %>bar<%% end %>', 1) == {:ok, [
|
||||
{:text, 'foo <% true do %>bar<% end %>'}
|
||||
]}
|
||||
end
|
||||
|
||||
test "quotation with interpolation" do
|
||||
exprs = [
|
||||
assert T.tokenize('a <%% b <%= c %> <%= d %> e %> f', 1) == {:ok, [
|
||||
{:text, 'a <% b '},
|
||||
{:expr, 1, '=', ' c '},
|
||||
{:text, ' '},
|
||||
{:expr, 1, '=', ' d '},
|
||||
{:text, ' e %> f'}
|
||||
]
|
||||
]}
|
||||
|
||||
assert T.tokenize('a <%% b <%= c %> <%= d %> e %> f', 1) == {:ok, exprs}
|
||||
end
|
||||
|
||||
test "improperly formatted quotation with interpolation" do
|
||||
exprs = [
|
||||
assert T.tokenize('<%%% a <%%= b %> c %>', 1) == {:ok, [
|
||||
{:text, '<%% a <%= b %> c %>'}
|
||||
]
|
||||
|
||||
assert T.tokenize('<%%% a <%%= b %> c %>', 1) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "comments" do
|
||||
exprs = [
|
||||
assert T.tokenize('foo <%# true %>', 1) == {:ok, [
|
||||
{:text, 'foo '}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <%# true %>', 1) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "comments with do/end" do
|
||||
exprs = [
|
||||
assert T.tokenize('foo <%# true do %>bar<%# end %>', 1) == {:ok, [
|
||||
{:text, 'foo bar'}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <%# true do %>bar<%# end %>', 1) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "strings with embedded do end" do
|
||||
exprs = [
|
||||
assert T.tokenize('foo <% if true do %>bar<% end %>', 1) == {:ok, [
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, '', ' if true do '},
|
||||
{:text, 'bar'},
|
||||
{:end_expr, 1, '', ' end '}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <% if true do %>bar<% end %>', 1) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "strings with embedded -> end" do
|
||||
exprs = [
|
||||
assert T.tokenize('foo <% cond do %><% false -> %>bar<% true -> %>baz<% end %>', 1) == {:ok, [
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, '', ' cond do '},
|
||||
{:middle_expr, 1, '', ' false -> '},
|
||||
@@ -116,65 +100,51 @@ defmodule EEx.TokenizerTest do
|
||||
{:middle_expr, 1, '', ' true -> '},
|
||||
{:text, 'baz'},
|
||||
{:end_expr, 1, '', ' end '}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <% cond do %><% false -> %>bar<% true -> %>baz<% end %>', 1) ==
|
||||
{:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "strings with embedded keywords blocks" do
|
||||
exprs = [
|
||||
assert T.tokenize('foo <% if true do %>bar<% else %>baz<% end %>', 1) == {:ok, [
|
||||
{:text, 'foo '},
|
||||
{:start_expr, 1, '', ' if true do '},
|
||||
{:text, 'bar'},
|
||||
{:middle_expr, 1, '', ' else '},
|
||||
{:text, 'baz'},
|
||||
{:end_expr, 1, '', ' end '}
|
||||
]
|
||||
|
||||
assert T.tokenize('foo <% if true do %>bar<% else %>baz<% end %>', 1) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "trim mode" do
|
||||
template = '\t<%= if true do %> \n TRUE \n <% else %>\n FALSE \n <% end %> '
|
||||
|
||||
exprs = [
|
||||
assert T.tokenize(template, 1, trim: true) == {:ok, [
|
||||
{:start_expr, 1, '=', ' if true do '},
|
||||
{:text, ' TRUE \n'},
|
||||
{:middle_expr, 3, '', ' else '},
|
||||
{:text, ' FALSE \n'},
|
||||
{:end_expr, 5, '', ' end '}
|
||||
]
|
||||
|
||||
assert T.tokenize(template, 1, trim: true) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "trim mode with comment" do
|
||||
exprs = [
|
||||
assert T.tokenize(' <%# comment %> \n123', 1, trim: true) == {:ok, [
|
||||
{:text, '123'}
|
||||
]
|
||||
|
||||
assert T.tokenize(' <%# comment %> \n123', 1, trim: true) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "trim mode with CRLF" do
|
||||
exprs = [
|
||||
assert T.tokenize('0\r\n <%= 12 %> \r\n34', 1, trim: true) == {:ok, [
|
||||
{:text, '0\r\n'},
|
||||
{:expr, 2, '=', ' 12 '},
|
||||
{:text, '34'}
|
||||
]
|
||||
|
||||
assert T.tokenize('0\r\n <%= 12 %> \r\n34', 1, trim: true) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "trim mode set to false" do
|
||||
exprs = [
|
||||
assert T.tokenize(' <%= 12 %> \n', 1, trim: false) == {:ok, [
|
||||
{:text, ' '},
|
||||
{:expr, 1, '=', ' 12 '},
|
||||
{:text, ' \n'}
|
||||
]
|
||||
|
||||
assert T.tokenize(' <%= 12 %> \n', 1, trim: false) == {:ok, exprs}
|
||||
]}
|
||||
end
|
||||
|
||||
test "trim mode no false positives" do
|
||||
|
||||
+327
-422
@@ -1,39 +1,39 @@
|
||||
Code.require_file("test_helper.exs", __DIR__)
|
||||
Code.require_file "test_helper.exs", __DIR__
|
||||
|
||||
require EEx
|
||||
|
||||
defmodule EExTest.Compiled do
|
||||
def before_compile do
|
||||
fill_in_stacktrace()
|
||||
{__ENV__.line, hd(tl(System.stacktrace()))}
|
||||
{__ENV__.line, hd(tl(System.stacktrace))}
|
||||
end
|
||||
|
||||
EEx.function_from_string(:def, :string_sample, "<%= a + b %>", [:a, :b])
|
||||
EEx.function_from_string :def, :string_sample, "<%= a + b %>", [:a, :b]
|
||||
|
||||
filename = Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")
|
||||
EEx.function_from_file(:defp, :private_file_sample, filename, [:bar])
|
||||
EEx.function_from_file :defp, :private_file_sample, filename, [:bar]
|
||||
|
||||
filename = Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")
|
||||
EEx.function_from_file(:def, :public_file_sample, filename, [:bar])
|
||||
EEx.function_from_file :def, :public_file_sample, filename, [:bar]
|
||||
|
||||
def file_sample(arg), do: private_file_sample(arg)
|
||||
|
||||
def after_compile do
|
||||
fill_in_stacktrace()
|
||||
{__ENV__.line, hd(tl(System.stacktrace()))}
|
||||
{__ENV__.line, hd(tl(System.stacktrace))}
|
||||
end
|
||||
|
||||
@file "unknown"
|
||||
def unknown do
|
||||
fill_in_stacktrace()
|
||||
{__ENV__.line, hd(tl(System.stacktrace()))}
|
||||
{__ENV__.line, hd(tl(System.stacktrace))}
|
||||
end
|
||||
|
||||
defp fill_in_stacktrace do
|
||||
try do
|
||||
:erlang.error("failed")
|
||||
:erlang.error "failed"
|
||||
catch
|
||||
:error, _ -> System.stacktrace()
|
||||
:error, _ -> System.stacktrace
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -53,439 +53,372 @@ defmodule EExTest do
|
||||
doctest EEx.Engine
|
||||
doctest EEx.SmartEngine
|
||||
|
||||
describe "evaluates" do
|
||||
test "simple string" do
|
||||
assert_eval("foo bar", "foo bar")
|
||||
end
|
||||
test "evaluates simple string" do
|
||||
assert_eval "foo bar", "foo bar"
|
||||
end
|
||||
|
||||
test "Unicode" do
|
||||
template = """
|
||||
• <%= "•" %> •
|
||||
<%= "Jößé Vâlìm" %> Jößé Vâlìm
|
||||
"""
|
||||
test "evaluates with embedded" do
|
||||
assert_eval "foo bar", "foo <%= :bar %>"
|
||||
end
|
||||
|
||||
assert_eval(" • • •\n Jößé Vâlìm Jößé Vâlìm\n", template)
|
||||
end
|
||||
test "evaluates with embedded and the binding" do
|
||||
assert EEx.eval_string("foo <%= bar %>", [bar: 1]) == "foo 1"
|
||||
end
|
||||
|
||||
test "trim mode" do
|
||||
string = "<%= 123 %> \n456\n <%= 789 %>"
|
||||
expected = "123456\n789"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
end
|
||||
test "evaluates with embedded do end" do
|
||||
assert_eval "foo bar", "foo <%= if true do %>bar<% end %>"
|
||||
end
|
||||
|
||||
test "trim mode with middle expression" do
|
||||
string = """
|
||||
<%= cond do %>
|
||||
<% false -> %>
|
||||
this
|
||||
<% true -> %>
|
||||
that
|
||||
<% end %>
|
||||
"""
|
||||
test "evaluates with embedded do end and eval the expression" do
|
||||
assert_eval "foo ", "foo <%= if false do %>bar<% end %>"
|
||||
end
|
||||
|
||||
expected = " that\n"
|
||||
assert_eval(expected, string, [], trim: true)
|
||||
end
|
||||
test "evaluates with embedded do end and nested print expression" do
|
||||
assert_eval "foo bar", "foo <%= if true do %><%= :bar %><% end %>"
|
||||
end
|
||||
|
||||
test "embedded code" do
|
||||
assert_eval("foo bar", "foo <%= :bar %>")
|
||||
end
|
||||
test "evaluates with embedded do end and nested expressions" do
|
||||
assert_eval "foo bar baz", "foo <%= if true do %>bar <% Process.put(:eex_text, 1) %><%= :baz %><% end %>"
|
||||
assert Process.get(:eex_text) == 1
|
||||
end
|
||||
|
||||
test "embedded code with binding" do
|
||||
assert EEx.eval_string("foo <%= bar %>", bar: 1) == "foo 1"
|
||||
end
|
||||
test "evaluates with embedded middle expression" do
|
||||
assert_eval "foo bar", "foo <%= if true do %>bar<% else %>baz<% end %>"
|
||||
end
|
||||
|
||||
test "embedded code with do end when true" do
|
||||
assert_eval("foo bar", "foo <%= if true do %>bar<% end %>")
|
||||
end
|
||||
test "evaluates with embedded middle expression and eval the expression" do
|
||||
assert_eval "foo baz", "foo <%= if false do %>bar<% else %>baz<% end %>"
|
||||
end
|
||||
|
||||
test "embedded code with do end when false" do
|
||||
assert_eval("foo ", "foo <%= if false do %>bar<% end %>")
|
||||
end
|
||||
test "evaluates with nested start expression" do
|
||||
assert_eval "foo bar", "foo <%= if true do %><%= if true do %>bar<% end %><% end %>"
|
||||
end
|
||||
|
||||
test "embedded code with do end and expression" do
|
||||
assert_eval("foo bar", "foo <%= if true do %><%= :bar %><% end %>")
|
||||
end
|
||||
test "evaluates with nested middle expression" do
|
||||
assert_eval "foo baz", "foo <%= if true do %><%= if false do %>bar<% else %>baz<% end %><% end %>"
|
||||
end
|
||||
|
||||
test "embedded code with do end and multiple expressions" do
|
||||
assert_eval(
|
||||
"foo bar baz",
|
||||
"foo <%= if true do %>bar <% Process.put(:eex_text, 1) %><%= :baz %><% end %>"
|
||||
)
|
||||
test "evaluates with parentheses after end in end token" do
|
||||
assert_eval " 101 102 103 ", "<%= Enum.map([1, 2, 3], (fn x -> %> <%= 100 + x %> <% end) ) %>"
|
||||
end
|
||||
|
||||
assert Process.get(:eex_text) == 1
|
||||
end
|
||||
test "evaluates with defined variable" do
|
||||
assert_eval "foo 1", "foo <% bar = 1 %><%= bar %>"
|
||||
end
|
||||
|
||||
test "embedded code with middle expression" do
|
||||
assert_eval("foo bar", "foo <%= if true do %>bar<% else %>baz<% end %>")
|
||||
end
|
||||
test "evaluates with require code" do
|
||||
assert_eval "foo 1,2,3", "foo <% require Enum, as: E %><%= E.join [1, 2, 3], \",\" %>"
|
||||
end
|
||||
|
||||
test "embedded code with evaluated middle expression" do
|
||||
assert_eval("foo baz", "foo <%= if false do %>bar<% else %>baz<% end %>")
|
||||
end
|
||||
test "evaluates with end of token" do
|
||||
assert_eval "foo bar %>", "foo bar %>"
|
||||
end
|
||||
|
||||
test "embedded code with nested do end" do
|
||||
assert_eval("foo bar", "foo <%= if true do %><%= if true do %>bar<% end %><% end %>")
|
||||
end
|
||||
|
||||
test "embedded code with nested do end with middle expression" do
|
||||
assert_eval(
|
||||
"foo baz",
|
||||
"foo <%= if true do %><%= if false do %>bar<% else %>baz<% end %><% end %>"
|
||||
)
|
||||
end
|
||||
|
||||
test "embedded code with parentheses after end in end token" do
|
||||
assert_eval(
|
||||
" 101 102 103 ",
|
||||
"<%= Enum.map([1, 2, 3], (fn x -> %> <%= 100 + x %> <% end) ) %>"
|
||||
)
|
||||
end
|
||||
|
||||
test "embedded code with variable definition" do
|
||||
assert_eval("foo 1", "foo <% bar = 1 %><%= bar %>")
|
||||
end
|
||||
|
||||
test "embedded code with require" do
|
||||
assert_eval("foo 1,2,3", "foo <% require Enum, as: E %><%= E.join [1, 2, 3], \",\" %>")
|
||||
end
|
||||
|
||||
test "with end of token" do
|
||||
assert_eval("foo bar %>", "foo bar %>")
|
||||
test "raises a syntax error when the token is invalid" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1: missing token '%>'", fn ->
|
||||
EEx.compile_string "foo <%= bar"
|
||||
end
|
||||
end
|
||||
|
||||
describe "raises syntax errors" do
|
||||
test "when the token is invalid" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1: missing token '%>'", fn ->
|
||||
EEx.compile_string("foo <%= bar")
|
||||
end
|
||||
end
|
||||
|
||||
test "when middle expression is found without a start expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1: unexpected middle of expression <% else %>", fn ->
|
||||
EEx.compile_string("<% if true %> foo<% else %>bar<% end %>")
|
||||
end
|
||||
end
|
||||
|
||||
test "when end expression is found without a start expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1: unexpected end of expression <% end %>", fn ->
|
||||
EEx.compile_string("foo <% end %>")
|
||||
end
|
||||
end
|
||||
|
||||
test "when start expression is found without an end expression" do
|
||||
msg = "nofile:2: unexpected end of string, expected a closing '<% end %>'"
|
||||
|
||||
assert_raise EEx.SyntaxError, msg, fn ->
|
||||
EEx.compile_string("foo\n<% if true do %>")
|
||||
end
|
||||
end
|
||||
|
||||
test "when nested end expression is found without a start expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1: unexpected end of expression <% end %>", fn ->
|
||||
EEx.compile_string("foo <% if true do %><% end %><% end %>")
|
||||
end
|
||||
end
|
||||
|
||||
test "when middle expression has a modifier" do
|
||||
assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
|
||||
EEx.compile_string("foo <%= if true do %>true<%= else %>false<% end %>")
|
||||
end) =~ ~s[unexpected beginning of EEx tag \"<%=\" on \"<%= else %>\"]
|
||||
end
|
||||
|
||||
test "when end expression has a modifier" do
|
||||
assert ExUnit.CaptureIO.capture_io(:stderr, fn ->
|
||||
EEx.compile_string("foo <%= if true do %>true<% else %>false<%= end %>")
|
||||
end) =~
|
||||
~s[unexpected beginning of EEx tag \"<%=\" on end of expression \"<%= end %>\"]
|
||||
end
|
||||
|
||||
test "when trying to use marker '/' without implementation" do
|
||||
msg =
|
||||
~r/unsupported EEx syntax <%\/ %> \(the syntax is valid but not supported by the current EEx engine\)/
|
||||
|
||||
assert_raise EEx.SyntaxError, msg, fn ->
|
||||
EEx.compile_string("<%/ true %>")
|
||||
end
|
||||
end
|
||||
|
||||
test "when trying to use marker '|' without implementation" do
|
||||
msg =
|
||||
~r/unsupported EEx syntax <%| %> \(the syntax is valid but not supported by the current EEx engine\)/
|
||||
|
||||
assert_raise EEx.SyntaxError, msg, fn ->
|
||||
EEx.compile_string("<%| true %>")
|
||||
end
|
||||
test "raises a syntax error when end expression is found without a start expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1: unexpected token ' end '", fn ->
|
||||
EEx.compile_string "foo <% end %>"
|
||||
end
|
||||
end
|
||||
|
||||
describe "environment" do
|
||||
test "respects line numbers" do
|
||||
expected = """
|
||||
foo
|
||||
2
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval(expected, string)
|
||||
end
|
||||
|
||||
test "respects line numbers inside nested expressions" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
3
|
||||
|
||||
5
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= if true do %>
|
||||
<%= __ENV__.line %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval(expected, string)
|
||||
end
|
||||
|
||||
test "respects line numbers inside start expression" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
true
|
||||
|
||||
5
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= if __ENV__.line == 2 do %>
|
||||
<%= true %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval(expected, string)
|
||||
end
|
||||
|
||||
test "respects line numbers inside middle expression with ->" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
true
|
||||
|
||||
7
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= cond do %>
|
||||
<% false -> %> false
|
||||
<% __ENV__.line == 4 -> %>
|
||||
<%= true %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval(expected, string)
|
||||
end
|
||||
|
||||
test "respects line number inside middle expressions with keywords" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
5
|
||||
|
||||
7
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= if false do %>
|
||||
<%= __ENV__.line %>
|
||||
<% else %>
|
||||
<%= __ENV__.line %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval(expected, string)
|
||||
end
|
||||
|
||||
test "respects files" do
|
||||
assert_eval("sample.ex", "<%= __ENV__.file %>", [], file: "sample.ex")
|
||||
test "raises a syntax error when start expression is found without an end expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:2: unexpected end of string, expected a closing '<% end %>'", fn ->
|
||||
EEx.compile_string "foo\n<% if true do %>"
|
||||
end
|
||||
end
|
||||
|
||||
describe "clauses" do
|
||||
test "inside functions" do
|
||||
expected = """
|
||||
|
||||
Number 1
|
||||
|
||||
Number 2
|
||||
|
||||
Number 3
|
||||
|
||||
"""
|
||||
|
||||
string = """
|
||||
<%= Enum.map [1, 2, 3], fn x -> %>
|
||||
Number <%= x %>
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
assert_eval(expected, string)
|
||||
end
|
||||
|
||||
test "inside cond" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
true
|
||||
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= cond do %>
|
||||
<% false -> %> false
|
||||
<% fn -> 1 end -> %>
|
||||
<%= true %>
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
assert_eval(expected, string)
|
||||
end
|
||||
|
||||
test "inside cond with do end" do
|
||||
string = """
|
||||
<% y = ["a", "b", "c"] %>
|
||||
<%= cond do %>
|
||||
<% "a" in y -> %>
|
||||
Good
|
||||
<% true -> %>
|
||||
<% if true do %>true<% else %>false<% end %>
|
||||
Bad
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
assert_eval("\n\n Good\n \n", string)
|
||||
test "raises a syntax error when nested end expression is found without a start expression" do
|
||||
assert_raise EEx.SyntaxError, "nofile:1: unexpected token ' end '", fn ->
|
||||
EEx.compile_string "foo <% if true do %><% end %><% end %>"
|
||||
end
|
||||
end
|
||||
|
||||
describe "buffers" do
|
||||
test "unused buffers are kept out" do
|
||||
string = """
|
||||
<%= 123 %>
|
||||
<% if true do %>
|
||||
<%= 456 %>
|
||||
<% end %>
|
||||
<%= 789 %>
|
||||
"""
|
||||
test "respects line numbers" do
|
||||
expected = """
|
||||
foo
|
||||
2
|
||||
"""
|
||||
|
||||
assert_eval("123\n\n789\n", string)
|
||||
end
|
||||
string = """
|
||||
foo
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
test "inside comprehensions" do
|
||||
string = """
|
||||
<%= for _name <- packages || [] do %>
|
||||
<% end %>
|
||||
<%= all || :done %>
|
||||
"""
|
||||
assert_eval expected, string
|
||||
end
|
||||
|
||||
assert_eval("\ndone\n", string, packages: nil, all: nil)
|
||||
test "respects line numbers inside nested expressions" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
3
|
||||
|
||||
5
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= if true do %>
|
||||
<%= __ENV__.line %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval expected, string
|
||||
end
|
||||
|
||||
test "respects line numbers inside start expression" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
true
|
||||
|
||||
5
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= if __ENV__.line == 2 do %>
|
||||
<%= true %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval expected, string
|
||||
end
|
||||
|
||||
test "respects line numbers inside middle expression with ->" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
true
|
||||
|
||||
7
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= cond do %>
|
||||
<% false -> %> false
|
||||
<% __ENV__.line == 4 -> %>
|
||||
<%= true %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval expected, string
|
||||
end
|
||||
|
||||
test "respects line number inside middle expressions with keywords" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
5
|
||||
|
||||
7
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= if false do %>
|
||||
<%= __ENV__.line %>
|
||||
<% else %>
|
||||
<%= __ENV__.line %>
|
||||
<% end %>
|
||||
<%= __ENV__.line %>
|
||||
"""
|
||||
|
||||
assert_eval expected, string
|
||||
end
|
||||
|
||||
test "respects files" do
|
||||
assert_eval "sample.ex", "<%= __ENV__.file %>", [], file: "sample.ex"
|
||||
end
|
||||
|
||||
test "properly handle functions" do
|
||||
expected = """
|
||||
|
||||
Number 1
|
||||
|
||||
Number 2
|
||||
|
||||
Number 3
|
||||
|
||||
"""
|
||||
|
||||
string = """
|
||||
<%= Enum.map [1, 2, 3], fn x -> %>
|
||||
Number <%= x %>
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
assert_eval expected, string
|
||||
end
|
||||
|
||||
test "properly handle functions on the left side of clauses" do
|
||||
expected = """
|
||||
foo
|
||||
|
||||
true
|
||||
|
||||
"""
|
||||
|
||||
string = """
|
||||
foo
|
||||
<%= cond do %>
|
||||
<% false -> %> false
|
||||
<% fn -> 1 end -> %>
|
||||
<%= true %>
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
assert_eval expected, string
|
||||
end
|
||||
|
||||
test "evaluates nested do expressions" do
|
||||
string = """
|
||||
<% y = ["a", "b", "c"] %>
|
||||
<%= cond do %>
|
||||
<% "a" in y -> %>
|
||||
Good
|
||||
<% true -> %>
|
||||
<% if true do %>true<% else %>false<% end %>
|
||||
Bad
|
||||
<% end %>
|
||||
"""
|
||||
|
||||
assert_eval "\n\n Good\n \n", string
|
||||
end
|
||||
|
||||
test "evaluates expressions with buffers" do
|
||||
string = """
|
||||
<%= 123 %>
|
||||
<% if true do %>
|
||||
<%= 456 %>
|
||||
<% end %>
|
||||
<%= 789 %>
|
||||
"""
|
||||
|
||||
assert_eval "123\n\n789\n", string
|
||||
end
|
||||
|
||||
test "for comprehensions" do
|
||||
string = """
|
||||
<%= for _name <- packages || [] do %>
|
||||
<% end %>
|
||||
<%= all || :done %>
|
||||
"""
|
||||
assert_eval "\ndone\n", string, packages: nil, all: nil
|
||||
end
|
||||
|
||||
test "Unicode" do
|
||||
template = """
|
||||
• <%= "•" %> •
|
||||
<%= "Jößé Vâlìm" %> Jößé Vâlìm
|
||||
"""
|
||||
result = EEx.eval_string(template)
|
||||
assert result == " • • •\n Jößé Vâlìm Jößé Vâlìm\n"
|
||||
end
|
||||
|
||||
test "trim mode" do
|
||||
string = "<%= 123 %> \n456\n <%= 789 %>"
|
||||
expected = "123456\n789"
|
||||
assert_eval expected, string, [], trim: true
|
||||
end
|
||||
|
||||
test "trim mode with middle expression" do
|
||||
string = """
|
||||
<%= cond do %>
|
||||
<% false -> %>
|
||||
this
|
||||
<% true -> %>
|
||||
that
|
||||
<% end %>
|
||||
"""
|
||||
expected = " that\n"
|
||||
assert_eval expected, string, [], trim: true
|
||||
end
|
||||
|
||||
test "evaluates the source from a given file" do
|
||||
filename = Path.join(__DIR__, "fixtures/eex_template.eex")
|
||||
result = EEx.eval_file(filename)
|
||||
assert result == "foo bar.\n"
|
||||
end
|
||||
|
||||
test "evaluates the source from a given file with bindings" do
|
||||
filename = Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")
|
||||
result = EEx.eval_file(filename, [bar: 1])
|
||||
assert result == "foo 1\n"
|
||||
end
|
||||
|
||||
test "raises an Exception when there's an error with the given file" do
|
||||
assert_raise File.Error, "could not read file \"non-existent.eex\": no such file or directory", fn ->
|
||||
filename = "non-existent.eex"
|
||||
EEx.compile_file(filename)
|
||||
end
|
||||
end
|
||||
|
||||
describe "from file" do
|
||||
test "evaluates the source" do
|
||||
filename = Path.join(__DIR__, "fixtures/eex_template.eex")
|
||||
result = EEx.eval_file(filename)
|
||||
assert_normalized_newline_equal("foo bar.\n", result)
|
||||
end
|
||||
|
||||
test "evaluates the source with bindings" do
|
||||
filename = Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")
|
||||
result = EEx.eval_file(filename, bar: 1)
|
||||
assert_normalized_newline_equal("foo 1\n", result)
|
||||
end
|
||||
|
||||
test "raises an Exception when file is missing" do
|
||||
msg = "could not read file \"non-existent.eex\": no such file or directory"
|
||||
|
||||
assert_raise File.Error, msg, fn ->
|
||||
filename = "non-existent.eex"
|
||||
EEx.compile_file(filename)
|
||||
end
|
||||
end
|
||||
|
||||
test "sets external resource attribute" do
|
||||
assert EExTest.Compiled.__info__(:attributes)[:external_resource] ==
|
||||
[Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")]
|
||||
end
|
||||
test "sets external resource attribute" do
|
||||
assert EExTest.Compiled.__info__(:attributes)[:external_resource] ==
|
||||
[Path.join(__DIR__, "fixtures/eex_template_with_bindings.eex")]
|
||||
end
|
||||
|
||||
describe "precompiled" do
|
||||
test "from string" do
|
||||
assert EExTest.Compiled.string_sample(1, 2) == "3"
|
||||
end
|
||||
test "defined from string" do
|
||||
assert EExTest.Compiled.string_sample(1, 2) == "3"
|
||||
end
|
||||
|
||||
test "from file" do
|
||||
assert_normalized_newline_equal("foo 1\n", EExTest.Compiled.file_sample(1))
|
||||
assert_normalized_newline_equal("foo 1\n", EExTest.Compiled.public_file_sample(1))
|
||||
end
|
||||
test "defined from file" do
|
||||
assert EExTest.Compiled.file_sample(1) == "foo 1\n"
|
||||
assert EExTest.Compiled.public_file_sample(1) == "foo 1\n"
|
||||
end
|
||||
|
||||
test "from file does not affect backtrace" do
|
||||
file = to_charlist(Path.relative_to_cwd(__ENV__.file))
|
||||
test "defined from file do not affect backtrace" do
|
||||
assert EExTest.Compiled.before_compile ==
|
||||
{8,
|
||||
{EExTest.Compiled,
|
||||
:before_compile,
|
||||
0,
|
||||
[file: to_charlist(Path.relative_to_cwd(__ENV__.file)), line: 7]
|
||||
}
|
||||
}
|
||||
|
||||
assert EExTest.Compiled.before_compile() ==
|
||||
{8, {EExTest.Compiled, :before_compile, 0, [file: file, line: 7]}}
|
||||
assert EExTest.Compiled.after_compile ==
|
||||
{23,
|
||||
{EExTest.Compiled,
|
||||
:after_compile,
|
||||
0,
|
||||
[file: to_charlist(Path.relative_to_cwd(__ENV__.file)), line: 22]
|
||||
}
|
||||
}
|
||||
|
||||
assert EExTest.Compiled.after_compile() ==
|
||||
{23, {EExTest.Compiled, :after_compile, 0, [file: file, line: 22]}}
|
||||
|
||||
assert EExTest.Compiled.unknown() ==
|
||||
{29, {EExTest.Compiled, :unknown, 0, [file: 'unknown', line: 28]}}
|
||||
end
|
||||
assert EExTest.Compiled.unknown ==
|
||||
{29,
|
||||
{EExTest.Compiled,
|
||||
:unknown,
|
||||
0,
|
||||
[file: 'unknown', line: 28]
|
||||
}
|
||||
}
|
||||
end
|
||||
|
||||
defmodule TestEngine do
|
||||
@behaviour EEx.Engine
|
||||
|
||||
def init(_opts) do
|
||||
"INIT"
|
||||
""
|
||||
end
|
||||
|
||||
def handle_body(body) do
|
||||
"BODY(#{body})"
|
||||
end
|
||||
|
||||
def handle_begin(_) do
|
||||
"BEGIN"
|
||||
end
|
||||
|
||||
def handle_end(buffer) do
|
||||
buffer <> ":END"
|
||||
{:wrapped, body}
|
||||
end
|
||||
|
||||
def handle_text(buffer, text) do
|
||||
buffer <> ":TEXT(#{String.trim(text)})"
|
||||
end
|
||||
|
||||
def handle_expr(buffer, "/", expr) do
|
||||
buffer <> ":DIV(#{Macro.to_string(expr)})"
|
||||
end
|
||||
|
||||
def handle_expr(buffer, "=", expr) do
|
||||
buffer <> ":EQUAL(#{Macro.to_string(expr)})"
|
||||
EEx.Engine.handle_text(buffer, text)
|
||||
end
|
||||
|
||||
def handle_expr(buffer, mark, expr) do
|
||||
@@ -493,41 +426,13 @@ defmodule EExTest do
|
||||
end
|
||||
end
|
||||
|
||||
describe "custom engines" do
|
||||
test "text" do
|
||||
assert_eval("BODY(INIT:TEXT(foo))", "foo", [], engine: TestEngine)
|
||||
end
|
||||
|
||||
test "custom marker" do
|
||||
assert_eval("BODY(INIT:TEXT(foo):DIV(:bar))", "foo <%/ :bar %>", [], engine: TestEngine)
|
||||
end
|
||||
|
||||
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))],
|
||||
"foo <%= if do %>this<% else %>that<% end %>",
|
||||
[],
|
||||
engine: TestEngine
|
||||
)
|
||||
end
|
||||
|
||||
test "not implemented custom marker" do
|
||||
msg =
|
||||
~r/unsupported EEx syntax <%| %> \(the syntax is valid but not supported by the current EEx engine\)/
|
||||
|
||||
assert_raise EEx.SyntaxError, msg, fn ->
|
||||
assert_eval({:wrapped, "foo baz"}, "foo <%| :bar %>", [], engine: TestEngine)
|
||||
end
|
||||
end
|
||||
test "calls handle_body" do
|
||||
assert {:wrapped, "foo"} = EEx.eval_string("foo", [], engine: TestEngine)
|
||||
end
|
||||
|
||||
defp assert_eval(expected, actual, binding \\ [], opts \\ []) do
|
||||
opts = Enum.into([file: __ENV__.file, engine: opts[:engine] || EEx.Engine], opts)
|
||||
opts = Enum.into [file: __ENV__.file, engine: EEx.Engine], opts
|
||||
result = EEx.eval_string(actual, binding, opts)
|
||||
assert result == expected
|
||||
end
|
||||
|
||||
defp assert_normalized_newline_equal(expected, actual) do
|
||||
assert String.replace(expected, "\r\n", "\n") == String.replace(actual, "\r\n", "\n")
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1 +1 @@
|
||||
ExUnit.start(trace: "--trace" in System.argv())
|
||||
ExUnit.start [trace: "--trace" in System.argv]
|
||||
|
||||
@@ -1,96 +0,0 @@
|
||||
# Returns config for Elixir docs
|
||||
[
|
||||
extras: Path.wildcard("lib/elixir/pages/*.md"),
|
||||
groups_for_modules: [
|
||||
# [Kernel, Kernel.SpecialForms],
|
||||
|
||||
"Basic Types": [
|
||||
Atom,
|
||||
Base,
|
||||
Bitwise,
|
||||
Calendar,
|
||||
Calendar.ISO,
|
||||
Date,
|
||||
DateTime,
|
||||
Exception,
|
||||
Float,
|
||||
Integer,
|
||||
NaiveDateTime,
|
||||
Record,
|
||||
Regex,
|
||||
String,
|
||||
Time,
|
||||
Tuple,
|
||||
URI,
|
||||
Version,
|
||||
],
|
||||
|
||||
"Collections & Enumerables": [
|
||||
Access,
|
||||
Date.Range,
|
||||
Enum,
|
||||
Keyword,
|
||||
List,
|
||||
Map,
|
||||
MapSet,
|
||||
Range,
|
||||
Stream,
|
||||
],
|
||||
|
||||
"IO & System": [
|
||||
File,
|
||||
File.Stat,
|
||||
File.Stream,
|
||||
IO,
|
||||
IO.ANSI,
|
||||
IO.Stream,
|
||||
OptionParser,
|
||||
Path,
|
||||
Port,
|
||||
StringIO,
|
||||
System,
|
||||
],
|
||||
|
||||
"Modules & Code": [
|
||||
Code,
|
||||
Kernel.ParallelCompiler,
|
||||
Macro,
|
||||
Macro.Env,
|
||||
Module,
|
||||
],
|
||||
|
||||
"Processes & Applications": [
|
||||
Agent,
|
||||
Application,
|
||||
DynamicSupervisor,
|
||||
GenServer,
|
||||
Node,
|
||||
Process,
|
||||
Registry,
|
||||
Supervisor,
|
||||
Task,
|
||||
Task.Supervisor,
|
||||
],
|
||||
|
||||
"Protocols": [
|
||||
Collectable,
|
||||
Enumerable,
|
||||
Inspect,
|
||||
Inspect.Algebra,
|
||||
Inspect.Opts,
|
||||
List.Chars,
|
||||
Protocol,
|
||||
String.Chars,
|
||||
],
|
||||
|
||||
"Deprecated": [
|
||||
Behaviour,
|
||||
Dict,
|
||||
GenEvent,
|
||||
HashDict,
|
||||
HashSet,
|
||||
Set,
|
||||
Supervisor.Spec
|
||||
],
|
||||
]
|
||||
]
|
||||
+111
-252
@@ -60,7 +60,7 @@ defmodule Access do
|
||||
|
||||
## Static lookups
|
||||
|
||||
The `Access` syntax (`data[key]`) cannot be used to access fields in
|
||||
The `Access` syntax (`foo[bar]`) cannot be used to access fields in
|
||||
structs, since structs do not implement the `Access` behaviour by
|
||||
default. It is also a design decision: the dynamic access lookup
|
||||
is meant to be used for dynamic key-value structures, like maps
|
||||
@@ -73,7 +73,8 @@ defmodule Access do
|
||||
|
||||
user = %User{name: "John"}
|
||||
user[:name]
|
||||
# ** (UndefinedFunctionError) undefined function User.fetch/2 (User does not implement the Access behaviour)
|
||||
# ** (UndefinedFunctionError) undefined function User.fetch/2
|
||||
# (User does not implement the Access behaviour)
|
||||
|
||||
Structs instead use the `user.name` syntax to access fields:
|
||||
|
||||
@@ -81,7 +82,7 @@ defmodule Access do
|
||||
#=> "John"
|
||||
|
||||
The same `user.name` syntax can also be used by `Kernel.put_in/2`
|
||||
for updating structs fields:
|
||||
to for updating structs fields:
|
||||
|
||||
put_in user.name, "Mary"
|
||||
#=> %User{name: "Mary"}
|
||||
@@ -106,14 +107,12 @@ defmodule Access do
|
||||
functions for traversing other structures, like tuples and lists,
|
||||
to be used alongside `Kernel.put_in/2` in others.
|
||||
|
||||
For instance, given a user map with `:name` and `:languages` keys, here is how
|
||||
to deeply traverse the map and convert all language names to uppercase:
|
||||
For instance, given a user with a list of languages, here is how to
|
||||
deeply traverse the map and convert all language names to uppercase:
|
||||
|
||||
iex> languages = [
|
||||
...> %{name: "elixir", type: :functional},
|
||||
...> %{name: "c", type: :procedural},
|
||||
...> ]
|
||||
iex> user = %{name: "john", languages: languages}
|
||||
iex> user = %{name: "john",
|
||||
...> languages: [%{name: "elixir", type: :functional},
|
||||
...> %{name: "c", type: :procedural}]}
|
||||
iex> update_in user, [:languages, Access.all(), :name], &String.upcase/1
|
||||
%{name: "john",
|
||||
languages: [%{name: "ELIXIR", type: :functional},
|
||||
@@ -124,7 +123,7 @@ defmodule Access do
|
||||
|
||||
## Implementing the Access behaviour for custom data structures
|
||||
|
||||
In order to be able to use the `Access` behaviour with custom data structures
|
||||
In order to be able to use the `Access` protocol with custom data structures
|
||||
(which have to be structs), such structures have to implement the `Access`
|
||||
behaviour. For example, for a `User` struct, this would have to be done:
|
||||
|
||||
@@ -137,30 +136,15 @@ defmodule Access do
|
||||
|
||||
"""
|
||||
|
||||
@type container :: keyword | struct | map
|
||||
@type nil_container :: nil
|
||||
@type any_container :: any
|
||||
@type t :: container | nil_container | any_container
|
||||
@type t :: list | map | nil | any
|
||||
@type key :: any
|
||||
@type value :: any
|
||||
|
||||
@type get_fun(data, get_value) ::
|
||||
(:get, data, (term -> term) ->
|
||||
{get_value, new_data :: container})
|
||||
|
||||
@type get_and_update_fun(data, get_value) ::
|
||||
(:get_and_update, data, (term -> term) ->
|
||||
{get_value, new_data :: container} | :pop)
|
||||
|
||||
@type access_fun(data, get_value) ::
|
||||
get_fun(data, get_value) | get_and_update_fun(data, get_value)
|
||||
|
||||
@doc """
|
||||
Invoked in order to access the value stored under `key` in the given term `term`.
|
||||
|
||||
This function should return `{:ok, value}` where `value` is the value under
|
||||
`key` if the key exists in the term, or `:error` if the key does not exist in
|
||||
the term.
|
||||
`key` if it succeeded, or `:error` if the key does not exist in the structure.
|
||||
|
||||
Many of the functions defined in the `Access` module internally call this
|
||||
function. This function is also used when the square-brackets access syntax
|
||||
@@ -169,6 +153,7 @@ defmodule Access do
|
||||
value}` then `value` is returned, or if it returns `:error` then `nil` is
|
||||
returned.
|
||||
|
||||
|
||||
See the `Map.fetch/2` and `Keyword.fetch/2` implementations for examples of
|
||||
how to implement this callback.
|
||||
"""
|
||||
@@ -178,7 +163,7 @@ defmodule Access do
|
||||
Invoked in order to access the value stored under `key` in the given term `term`,
|
||||
defaulting to `default` if not present.
|
||||
|
||||
This function should return the value under `key` in `term` if there's
|
||||
This function should return the value under the key `key` in `term` if there's
|
||||
such key, otherwise `default`.
|
||||
|
||||
For most data structures, this can be implemented using `fetch/2` internally;
|
||||
@@ -191,101 +176,84 @@ defmodule Access do
|
||||
end
|
||||
end
|
||||
|
||||
See the `Map.get/3` and `Keyword.get/3` implementations for examples of
|
||||
how to implement this callback.
|
||||
See the `Map.get/3` and `Keyword.get/3` implementations for more examples.
|
||||
"""
|
||||
@callback get(term :: t, key, default :: value) :: value
|
||||
|
||||
@doc """
|
||||
Invoked in order to access the value under `key` and update it at the same time.
|
||||
|
||||
The implementation of this callback should invoke `fun` with the value under
|
||||
`key` in the passed structure `data`, or with `nil` if `key` is not present in it.
|
||||
This function must return either `{get_value, update_value}` or `:pop`.
|
||||
The implementation of this callback should invoke the passed function with the
|
||||
value under key `key` in the passed structure, or `nil` if the key is not
|
||||
present. This function should return either `{value_to_return, new_value}` or
|
||||
`:pop`.
|
||||
|
||||
If the passed function returns `{get_value, update_value}`,
|
||||
the return value of this callback should be `{get_value, new_data}`, where:
|
||||
- `get_value` is the retrieved value (which can be operated on before being returned)
|
||||
- `update_value` is the new value to be stored under `key`
|
||||
- `new_data` is `data` after updating the value of `key` with `update_value`.
|
||||
If it returns `{value_to_return, new_value}`, the return value of this
|
||||
callback should be `{value_to_return, new_term}` where `new_term` is `term`
|
||||
after updating the value of `key` with `new_value`.
|
||||
|
||||
If the passed function returns `:pop`, the return value of this callback
|
||||
must be `{value, new_data}` where `value` is the value under `key`
|
||||
(or `nil` if not present) and `new_data` is `data` without `key`.
|
||||
If it returns `:pop`, the return value of this callback should be `{value,
|
||||
new_term}` where `value` is the value under `key` or `nil` if not present, and
|
||||
`new_term` is `term` without the key `key`.
|
||||
|
||||
See the implementations of `Map.get_and_update/3` or `Keyword.get_and_update/3`
|
||||
for more examples.
|
||||
"""
|
||||
@callback get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data}
|
||||
when get_value: var, data: container | any_container
|
||||
@callback get_and_update(term :: t, key, (value -> {value, value} | :pop)) :: {value, t}
|
||||
|
||||
@doc """
|
||||
Invoked to "pop" the value under `key` out of the given data structure.
|
||||
Invoked to "pop" the value under `key` out of the given term.
|
||||
|
||||
When `key` exists in the given structure `data`, the implementation should
|
||||
return a `{value, new_data}` tuple where `value` is the value that was under
|
||||
`key` and `new_data` is `term` without `key`.
|
||||
When the key `key` exists in the given `term`, the implementation should
|
||||
return a `{value, new_term}` tuple where `value` is the value that was under
|
||||
`key` and `new_term` is `term` without `key`.
|
||||
|
||||
When `key` is not present in the given structure, a tuple `{value, data}`
|
||||
When the key `key` is not present in the given `term`, a tuple `{value, term}`
|
||||
should be returned, where `value` is implementation-defined.
|
||||
|
||||
See the implementations for `Map.pop/3` or `Keyword.pop/3` for more examples.
|
||||
"""
|
||||
@callback pop(data, key) :: {value, data} when data: container | any_container
|
||||
@callback pop(term :: t, key) :: {value, t}
|
||||
|
||||
defmacrop raise_undefined_behaviour(exception, module, top) do
|
||||
defmacrop raise_undefined_behaviour(e, struct, top) do
|
||||
quote do
|
||||
stacktrace = System.stacktrace()
|
||||
|
||||
exception =
|
||||
stacktrace = System.stacktrace
|
||||
e =
|
||||
case stacktrace do
|
||||
[unquote(top) | _] ->
|
||||
reason = "#{inspect(unquote(module))} does not implement the Access behaviour"
|
||||
%{unquote(exception) | reason: reason}
|
||||
|
||||
%{unquote(e) | reason: "#{inspect unquote(struct)} does not implement the Access behaviour"}
|
||||
_ ->
|
||||
unquote(exception)
|
||||
unquote(e)
|
||||
end
|
||||
|
||||
reraise exception, stacktrace
|
||||
reraise e, stacktrace
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Fetches the value for the given key in a container (a map, keyword
|
||||
list, or struct that implements the `Access` behaviour).
|
||||
|
||||
Returns `{:ok, value}` where `value` is the value under `key` if there is such
|
||||
a key, or `:error` if `key` is not found.
|
||||
"""
|
||||
@spec fetch(container, term) :: {:ok, term} | :error
|
||||
@spec fetch(nil_container, any) :: :error
|
||||
@spec fetch(t, term) :: {:ok, term} | :error
|
||||
def fetch(container, key)
|
||||
|
||||
def fetch(%module{} = container, key) do
|
||||
module.fetch(container, key)
|
||||
def fetch(%{__struct__: struct} = container, key) do
|
||||
struct.fetch(container, key)
|
||||
rescue
|
||||
exception in UndefinedFunctionError ->
|
||||
raise_undefined_behaviour(exception, module, {^module, :fetch, [^container, ^key], _})
|
||||
e in UndefinedFunctionError ->
|
||||
raise_undefined_behaviour e, struct, {^struct, :fetch, [^container, ^key], _}
|
||||
end
|
||||
|
||||
def fetch(map, key) when is_map(map) do
|
||||
case map do
|
||||
%{^key => value} -> {:ok, value}
|
||||
_ -> :error
|
||||
end
|
||||
Map.fetch(map, key)
|
||||
end
|
||||
|
||||
def fetch(list, key) when is_list(list) and is_atom(key) do
|
||||
case :lists.keyfind(key, 1, list) do
|
||||
{_, value} -> {:ok, value}
|
||||
false -> :error
|
||||
end
|
||||
Keyword.fetch(list, key)
|
||||
end
|
||||
|
||||
def fetch(list, key) when is_list(list) do
|
||||
raise ArgumentError,
|
||||
"the Access calls for keywords expect the key to be an atom, got: " <> inspect(key)
|
||||
"the Access calls for keywords expect the key to be an atom, got: " <> inspect(key)
|
||||
end
|
||||
|
||||
def fetch(nil, _key) do
|
||||
@@ -295,76 +263,38 @@ defmodule Access do
|
||||
@doc """
|
||||
Gets the value for the given key in a container (a map, keyword
|
||||
list, or struct that implements the `Access` behaviour).
|
||||
|
||||
Returns the value under `key` if there is such a key, or `default` if `key` is
|
||||
not found.
|
||||
"""
|
||||
@spec get(container, term, term) :: term
|
||||
@spec get(nil_container, any, default) :: default when default: var
|
||||
def get(container, key, default \\ nil)
|
||||
|
||||
def get(%module{} = container, key, default) do
|
||||
try do
|
||||
module.fetch(container, key)
|
||||
rescue
|
||||
exception in UndefinedFunctionError ->
|
||||
raise_undefined_behaviour(exception, module, {^module, :fetch, [^container, ^key], _})
|
||||
else
|
||||
@spec get(t, term, term) :: term
|
||||
def get(container, key, default \\ nil) do
|
||||
case fetch(container, key) do
|
||||
{:ok, value} -> value
|
||||
:error -> default
|
||||
end
|
||||
end
|
||||
|
||||
def get(map, key, default) when is_map(map) do
|
||||
case map do
|
||||
%{^key => value} -> value
|
||||
_ -> default
|
||||
end
|
||||
end
|
||||
|
||||
def get(list, key, default) when is_list(list) and is_atom(key) do
|
||||
case :lists.keyfind(key, 1, list) do
|
||||
{_, value} -> value
|
||||
false -> default
|
||||
end
|
||||
end
|
||||
|
||||
def get(list, key, _default) when is_list(list) do
|
||||
raise ArgumentError,
|
||||
"the Access calls for keywords expect the key to be an atom, got: " <> inspect(key)
|
||||
end
|
||||
|
||||
def get(nil, _key, default) do
|
||||
default
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets and updates the given key in a `container` (a map, a keyword list,
|
||||
a struct that implements the `Access` behaviour).
|
||||
Gets and updates the given key in a container (a map, keyword
|
||||
list, or struct that implements the `Access` behaviour).
|
||||
|
||||
The `fun` argument receives the value of `key` (or `nil` if `key` is not
|
||||
present in `container`) and must return a two-element tuple `{get_value, update_value}`:
|
||||
the "get" value `get_value` (the retrieved value, which can be operated on before
|
||||
being returned) and the new value to be stored under `key` (`update_value`).
|
||||
`fun` may also return `:pop`, which means the current value
|
||||
should be removed from the container and returned.
|
||||
This `fun` argument receives the value of `key` (or `nil` if `key`
|
||||
is not present) and must return a two-element tuple: the "get" value
|
||||
(the retrieved value, which can be operated on before being returned)
|
||||
and the new value to be stored under `key`. The `fun` may also
|
||||
return `:pop`, implying the current value shall be removed
|
||||
from the container and returned.
|
||||
|
||||
The returned value is a two-element tuple with the "get" value returned by
|
||||
`fun` and a new container with the updated value under `key`.
|
||||
"""
|
||||
@spec get_and_update(data, key, (value -> {get_value, value} | :pop)) :: {get_value, data}
|
||||
when get_value: var, data: container
|
||||
@spec get_and_update(container :: t, key, (value -> {get_value, update_value} | :pop)) ::
|
||||
{get_value, container :: t} when get_value: var, update_value: value
|
||||
def get_and_update(container, key, fun)
|
||||
|
||||
def get_and_update(%module{} = container, key, fun) do
|
||||
module.get_and_update(container, key, fun)
|
||||
def get_and_update(%{__struct__: struct} = container, key, fun) do
|
||||
struct.get_and_update(container, key, fun)
|
||||
rescue
|
||||
exception in UndefinedFunctionError ->
|
||||
raise_undefined_behaviour(
|
||||
exception,
|
||||
module,
|
||||
{^module, :get_and_update, [^container, ^key, ^fun], _}
|
||||
)
|
||||
e in UndefinedFunctionError ->
|
||||
raise_undefined_behaviour e, struct, {^struct, :get_and_update, [^container, ^key, ^fun], _}
|
||||
end
|
||||
|
||||
def get_and_update(map, key, fun) when is_map(map) do
|
||||
@@ -376,7 +306,8 @@ defmodule Access do
|
||||
end
|
||||
|
||||
def get_and_update(nil, key, _fun) do
|
||||
raise ArgumentError, "could not put/update key #{inspect(key)} on a nil value"
|
||||
raise ArgumentError,
|
||||
"could not put/update key #{inspect key} on a nil value"
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -405,12 +336,11 @@ defmodule Access do
|
||||
{nil, %{creator: "Valim", name: "Elixir"}}
|
||||
|
||||
"""
|
||||
@spec pop(data, key) :: {value, data} when data: container
|
||||
def pop(%module{} = container, key) do
|
||||
module.pop(container, key)
|
||||
def pop(%{__struct__: struct} = container, key) do
|
||||
struct.pop(container, key)
|
||||
rescue
|
||||
exception in UndefinedFunctionError ->
|
||||
raise_undefined_behaviour(exception, module, {^module, :pop, [^container, ^key], _})
|
||||
e in UndefinedFunctionError ->
|
||||
raise_undefined_behaviour e, struct, {^struct, :pop, [^container, ^key], _}
|
||||
end
|
||||
|
||||
def pop(map, key) when is_map(map) do
|
||||
@@ -422,11 +352,34 @@ defmodule Access do
|
||||
end
|
||||
|
||||
def pop(nil, key) do
|
||||
raise ArgumentError, "could not pop key #{inspect(key)} on a nil value"
|
||||
raise ArgumentError,
|
||||
"could not pop key #{inspect key} on a nil value"
|
||||
end
|
||||
|
||||
## Accessors
|
||||
|
||||
@doc false
|
||||
def key(key) do
|
||||
IO.warn "Access.key/1 is deprecated due to erratic behaviour for missing keys, " <>
|
||||
"please use Access.key/2 instead with proper default values " <>
|
||||
"(or Access.key!/1 if you expect the key to always be available)"
|
||||
|
||||
fn
|
||||
:get, data, next ->
|
||||
next.(Map.get(to_map(data), key))
|
||||
:get_and_update, data, next ->
|
||||
value = Map.get(to_map(data), key)
|
||||
case next.(value) do
|
||||
{get, update} -> {get, Map.put(data, key, update)}
|
||||
:pop -> {value, Map.delete(data, key)}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp to_map(nil), do: %{}
|
||||
defp to_map(%{} = map), do: map
|
||||
defp to_map(data), do: raise "Access.key/1 expected a map/struct or nil, got: #{inspect data}"
|
||||
|
||||
@doc """
|
||||
Returns a function that accesses the given key in a map/struct.
|
||||
|
||||
@@ -436,13 +389,13 @@ defmodule Access do
|
||||
The returned function uses the default value if the key does not exist.
|
||||
This can be used to specify defaults and safely traverse missing keys:
|
||||
|
||||
iex> get_in(%{}, [Access.key(:user, %{}), Access.key(:name)])
|
||||
iex> get_in(%{}, [Access.key(:user, %{}), Access.key(:name, nil)])
|
||||
nil
|
||||
|
||||
Such is also useful when using update functions, allowing us to introduce
|
||||
values as we traverse the data structure for updates:
|
||||
values as we traverse the data-structure for updates:
|
||||
|
||||
iex> put_in(%{}, [Access.key(:user, %{}), Access.key(:name)], "Mary")
|
||||
iex> put_in(%{}, [Access.key(:user, %{}), Access.key(:name, nil)], "Mary")
|
||||
%{user: %{name: "Mary"}}
|
||||
|
||||
## Examples
|
||||
@@ -450,31 +403,28 @@ defmodule Access do
|
||||
iex> map = %{user: %{name: "john"}}
|
||||
iex> get_in(map, [Access.key(:unknown, %{}), Access.key(:name, "john")])
|
||||
"john"
|
||||
iex> get_and_update_in(map, [Access.key(:user), Access.key(:name)], fn
|
||||
iex> get_and_update_in(map, [Access.key!(:user), Access.key!(:name)], fn
|
||||
...> prev -> {prev, String.upcase(prev)}
|
||||
...> end)
|
||||
{"john", %{user: %{name: "JOHN"}}}
|
||||
iex> pop_in(map, [Access.key(:user), Access.key(:name)])
|
||||
iex> pop_in(map, [Access.key!(:user), Access.key!(:name)])
|
||||
{"john", %{user: %{}}}
|
||||
|
||||
An error is raised if the accessed structure is not a map or a struct:
|
||||
|
||||
iex> get_in(nil, [Access.key(:foo)])
|
||||
iex> get_in(nil, [Access.key(:foo, nil)])
|
||||
** (BadMapError) expected a map, got: nil
|
||||
|
||||
iex> get_in([], [Access.key(:foo)])
|
||||
iex> get_in([], [Access.key(:foo, nil)])
|
||||
** (BadMapError) expected a map, got: []
|
||||
|
||||
"""
|
||||
@spec key(key, term) :: access_fun(data :: struct | map, get_value :: term)
|
||||
def key(key, default \\ nil) do
|
||||
def key(key, default) do
|
||||
fn
|
||||
:get, data, next ->
|
||||
next.(Map.get(data, key, default))
|
||||
|
||||
:get_and_update, data, next ->
|
||||
value = Map.get(data, key, default)
|
||||
|
||||
case next.(value) do
|
||||
{get, update} -> {get, Map.put(data, key, update)}
|
||||
:pop -> {value, Map.delete(data, key)}
|
||||
@@ -488,7 +438,7 @@ defmodule Access do
|
||||
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
|
||||
`Kernel.get_and_update_in/3`, and friends.
|
||||
|
||||
The returned function raises if the key does not exist.
|
||||
Raises if the key does not exist.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -510,22 +460,18 @@ defmodule Access do
|
||||
** (RuntimeError) Access.key!/1 expected a map/struct, got: []
|
||||
|
||||
"""
|
||||
@spec key!(key) :: access_fun(data :: struct | map, get_value :: term)
|
||||
def key!(key) do
|
||||
fn
|
||||
:get, %{} = data, next ->
|
||||
next.(Map.fetch!(data, key))
|
||||
|
||||
:get_and_update, %{} = data, next ->
|
||||
value = Map.fetch!(data, key)
|
||||
|
||||
case next.(value) do
|
||||
{get, update} -> {get, Map.put(data, key, update)}
|
||||
:pop -> {value, Map.delete(data, key)}
|
||||
end
|
||||
|
||||
_op, data, _next ->
|
||||
raise "Access.key!/1 expected a map/struct, got: #{inspect(data)}"
|
||||
raise "Access.key!/1 expected a map/struct, got: #{inspect data}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -535,7 +481,7 @@ defmodule Access do
|
||||
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
|
||||
`Kernel.get_and_update_in/3`, and friends.
|
||||
|
||||
The returned function raises if `index` is out of bounds.
|
||||
Raises if the index is out of bounds.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -555,24 +501,20 @@ defmodule Access do
|
||||
** (RuntimeError) Access.elem/1 expected a tuple, got: %{}
|
||||
|
||||
"""
|
||||
@spec elem(non_neg_integer) :: access_fun(data :: tuple, get_value :: term)
|
||||
def elem(index) when is_integer(index) do
|
||||
pos = index + 1
|
||||
|
||||
fn
|
||||
:get, data, next when is_tuple(data) ->
|
||||
next.(:erlang.element(pos, data))
|
||||
|
||||
:get_and_update, data, next when is_tuple(data) ->
|
||||
value = :erlang.element(pos, data)
|
||||
|
||||
case next.(value) do
|
||||
{get, update} -> {get, :erlang.setelement(pos, data, update)}
|
||||
:pop -> raise "cannot pop data from a tuple"
|
||||
end
|
||||
|
||||
_op, data, _next ->
|
||||
raise "Access.elem/1 expected a tuple, got: #{inspect(data)}"
|
||||
raise "Access.elem/1 expected a tuple, got: #{inspect data}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -595,7 +537,7 @@ defmodule Access do
|
||||
{["john", "mary"], [%{}, %{}]}
|
||||
|
||||
Here is an example that traverses the list dropping even
|
||||
numbers and multiplying odd numbers by 2:
|
||||
numbers and multipling odd numbers by 2:
|
||||
|
||||
iex> require Integer
|
||||
iex> get_and_update_in([1, 2, 3, 4, 5], [Access.all], fn
|
||||
@@ -609,7 +551,6 @@ defmodule Access do
|
||||
** (RuntimeError) Access.all/0 expected a list, got: %{}
|
||||
|
||||
"""
|
||||
@spec all() :: access_fun(data :: list, get_value :: list)
|
||||
def all() do
|
||||
&all/3
|
||||
end
|
||||
@@ -619,11 +560,11 @@ defmodule Access do
|
||||
end
|
||||
|
||||
defp all(:get_and_update, data, next) when is_list(data) do
|
||||
all(data, next, _gets = [], _updates = [])
|
||||
all(data, next, [], [])
|
||||
end
|
||||
|
||||
defp all(_op, data, _next) do
|
||||
raise "Access.all/0 expected a list, got: #{inspect(data)}"
|
||||
raise "Access.all/0 expected a list, got: #{inspect data}"
|
||||
end
|
||||
|
||||
defp all([head | rest], next, gets, updates) do
|
||||
@@ -681,11 +622,9 @@ defmodule Access do
|
||||
|
||||
iex> get_in(%{}, [Access.at(1)])
|
||||
** (RuntimeError) Access.at/1 expected a list, got: %{}
|
||||
|
||||
"""
|
||||
@spec at(non_neg_integer) :: access_fun(data :: list, get_value :: term)
|
||||
def at(index) when is_integer(index) and index >= 0 do
|
||||
fn op, data, next -> at(op, data, index, next) end
|
||||
def at(index) when index >= 0 do
|
||||
fn(op, data, next) -> at(op, data, index, next) end
|
||||
end
|
||||
|
||||
defp at(:get, data, index, next) when is_list(data) do
|
||||
@@ -697,7 +636,7 @@ defmodule Access do
|
||||
end
|
||||
|
||||
defp at(_op, data, _index, _next) do
|
||||
raise "Access.at/1 expected a list, got: #{inspect(data)}"
|
||||
raise "Access.at/1 expected a list, got: #{inspect data}"
|
||||
end
|
||||
|
||||
defp get_and_update_at([head | rest], 0, next, updates) do
|
||||
@@ -714,84 +653,4 @@ defmodule Access do
|
||||
defp get_and_update_at([], _index, _next, updates) do
|
||||
{nil, :lists.reverse(updates)}
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Returns a function that accesses all elements of a list that match the provided predicate.
|
||||
|
||||
The returned function is typically passed as an accessor to `Kernel.get_in/2`,
|
||||
`Kernel.get_and_update_in/3`, and friends.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]
|
||||
iex> get_in(list, [Access.filter(&(&1.salary > 20)), :name])
|
||||
["francine"]
|
||||
iex> get_and_update_in(list, [Access.filter(&(&1.salary <= 20)), :name], fn
|
||||
...> prev -> {prev, String.upcase(prev)}
|
||||
...> end)
|
||||
{["john"], [%{name: "JOHN", salary: 10}, %{name: "francine", salary: 30}]}
|
||||
|
||||
`filter/1` can also be used to pop elements out of a list or
|
||||
a key inside of a list:
|
||||
|
||||
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]
|
||||
iex> pop_in(list, [Access.filter(&(&1.salary >= 20))])
|
||||
{[%{name: "francine", salary: 30}], [%{name: "john", salary: 10}]}
|
||||
iex> pop_in(list, [Access.filter(&(&1.salary >= 20)), :name])
|
||||
{["francine"], [%{name: "john", salary: 10}, %{salary: 30}]}
|
||||
|
||||
When no match is found, an empty list is returned and the update function is never called
|
||||
|
||||
iex> list = [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]
|
||||
iex> get_in(list, [Access.filter(&(&1.salary >= 50)), :name])
|
||||
[]
|
||||
iex> get_and_update_in(list, [Access.filter(&(&1.salary >= 50)), :name], fn
|
||||
...> prev -> {prev, String.upcase(prev)}
|
||||
...> end)
|
||||
{[], [%{name: "john", salary: 10}, %{name: "francine", salary: 30}]}
|
||||
|
||||
An error is raised if the predicate is not a function or is of the incorrect arity:
|
||||
|
||||
iex> get_in([], [Access.filter(5)])
|
||||
** (FunctionClauseError) no function clause matching in Access.filter/1
|
||||
|
||||
An error is raised if the accessed structure is not a list:
|
||||
|
||||
iex> get_in(%{}, [Access.filter(fn a -> a == 10 end)])
|
||||
** (RuntimeError) Access.filter/1 expected a list, got: %{}
|
||||
"""
|
||||
@spec filter((term -> boolean)) :: access_fun(data :: list, get_value :: list)
|
||||
def filter(func) when is_function(func) do
|
||||
fn op, data, next -> filter(op, data, func, next) end
|
||||
end
|
||||
|
||||
defp filter(:get, data, func, next) when is_list(data) do
|
||||
data |> Enum.filter(func) |> Enum.map(next)
|
||||
end
|
||||
|
||||
defp filter(:get_and_update, data, func, next) when is_list(data) do
|
||||
get_and_update_filter(data, func, next, [], [])
|
||||
end
|
||||
|
||||
defp filter(_op, data, _func, _next) do
|
||||
raise "Access.filter/1 expected a list, got: #{inspect(data)}"
|
||||
end
|
||||
|
||||
defp get_and_update_filter([head | rest], func, next, updates, gets) do
|
||||
if func.(head) do
|
||||
case next.(head) do
|
||||
{get, update} ->
|
||||
get_and_update_filter(rest, func, next, [update | updates], [get | gets])
|
||||
|
||||
:pop ->
|
||||
get_and_update_filter(rest, func, next, updates, [head | gets])
|
||||
end
|
||||
else
|
||||
get_and_update_filter(rest, func, next, [head | updates], gets)
|
||||
end
|
||||
end
|
||||
|
||||
defp get_and_update_filter([], _func, _next, updates, gets) do
|
||||
{:lists.reverse(gets), :lists.reverse(updates)}
|
||||
end
|
||||
end
|
||||
|
||||
+64
-184
@@ -6,19 +6,17 @@ defmodule Agent do
|
||||
must be accessed from different processes or by the same process
|
||||
at different points in time.
|
||||
|
||||
The `Agent` module provides a basic server implementation that
|
||||
The Agent module provides a basic server implementation that
|
||||
allows state to be retrieved and updated via a simple API.
|
||||
|
||||
## Examples
|
||||
|
||||
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:
|
||||
this set is shared, we can implement it with an Agent:
|
||||
|
||||
defmodule Mix.TasksServer do
|
||||
use Agent
|
||||
|
||||
def start_link(_) do
|
||||
def start_link do
|
||||
Agent.start_link(fn -> MapSet.new end, name: __MODULE__)
|
||||
end
|
||||
|
||||
@@ -44,11 +42,12 @@ defmodule Agent do
|
||||
end
|
||||
end
|
||||
|
||||
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.
|
||||
Note that agents still provide a segregation between the
|
||||
client and server APIs, as seen in GenServers. In particular,
|
||||
all code inside the function passed to the agent is executed
|
||||
by the agent. This distinction is important because you may
|
||||
want to avoid expensive operations inside the agent, as it will
|
||||
effectively block the agent until the request is fulfilled.
|
||||
|
||||
Consider these two examples:
|
||||
|
||||
@@ -62,36 +61,16 @@ defmodule Agent do
|
||||
Agent.get(agent, &(&1)) |> do_something_expensive()
|
||||
end
|
||||
|
||||
The first function blocks the agent. The second function copies all the state
|
||||
to the client and then executes the operation in the client. One aspect to
|
||||
consider is whether the data is large enough to require processing in the server,
|
||||
at least initially, or small enough to be sent to the client cheaply. Another
|
||||
factor is whether the data needs to be processed atomically: getting the
|
||||
state and calling `do_something_expensive(state)` outside of the agent means
|
||||
that the agent's state can be updated in the meantime. This is specially
|
||||
important in case of updates as computing the new state in the client rather
|
||||
than in the server can lead to race conditions if multiple clients are trying
|
||||
to update the same state to different values.
|
||||
The first function blocks the agent. The second function copies
|
||||
all the state to the client and then executes the operation in the
|
||||
client. The difference is whether the data is large enough to require
|
||||
processing in the server, at least initially, or small enough to be
|
||||
sent to the client cheaply.
|
||||
|
||||
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:
|
||||
## Name Registration
|
||||
|
||||
* `:id` - the child specification id, 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
|
||||
|
||||
For example:
|
||||
|
||||
use Agent, restart: :transient, shutdown: 10_000
|
||||
|
||||
See the `Supervisor` docs for more information.
|
||||
|
||||
## Name registration
|
||||
|
||||
An agent is bound to the same name registration rules as GenServers.
|
||||
Read more about it in the `GenServer` documentation.
|
||||
An Agent is bound to the same name registration rules as GenServers.
|
||||
Read more about it in the `GenServer` docs.
|
||||
|
||||
## A word on distributed agents
|
||||
|
||||
@@ -116,15 +95,14 @@ defmodule Agent do
|
||||
## Hot code swapping
|
||||
|
||||
An agent can have its code hot swapped live by simply passing a module,
|
||||
function, and arguments tuple to the update instruction. For example, imagine
|
||||
function, and args tuple to the update instruction. For example, imagine
|
||||
you have an agent named `:sample` and you want to convert its inner state
|
||||
from a keyword list to a map. It can be done with the following
|
||||
from some dict structure to a map. It can be done with the following
|
||||
instruction:
|
||||
|
||||
{:update, :sample, {:advanced, {Enum, :into, [%{}]}}}
|
||||
|
||||
The agent's state will be added to the given list of arguments (`[%{}]`) as
|
||||
the first argument.
|
||||
The agent's state will be added to the given list as the first argument.
|
||||
"""
|
||||
|
||||
@typedoc "Return values of `start*` functions"
|
||||
@@ -139,47 +117,13 @@ defmodule Agent do
|
||||
@typedoc "The agent state"
|
||||
@type state :: term
|
||||
|
||||
@doc """
|
||||
Returns a specification to start an agent under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
@since "1.5.0"
|
||||
def child_spec(arg) do
|
||||
%{
|
||||
id: Agent,
|
||||
start: {Agent, :start_link, [arg]}
|
||||
}
|
||||
end
|
||||
|
||||
@doc false
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
def child_spec(arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
start: {__MODULE__, :start_link, [arg]}
|
||||
}
|
||||
|
||||
Supervisor.child_spec(default, unquote(Macro.escape(opts)))
|
||||
end
|
||||
|
||||
defoverridable child_spec: 1
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts an agent linked to the current process with the given function.
|
||||
|
||||
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 and its return
|
||||
value is used as the agent state. Note that `start_link/2` does not return
|
||||
Once the agent is spawned, the given function is invoked and its return
|
||||
value is used as the agent state. Note that `start_link` does not return
|
||||
until the given function has returned.
|
||||
|
||||
## Options
|
||||
@@ -204,32 +148,22 @@ defmodule Agent do
|
||||
specified name already exists, the function returns
|
||||
`{:error, {:already_started, pid}}` with the PID of that process.
|
||||
|
||||
If the given function callback fails, the function returns `{:error, reason}`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
42
|
||||
|
||||
iex> {:error, {exception, _stacktrace}} = Agent.start(fn -> raise "oops" end)
|
||||
iex> exception
|
||||
%RuntimeError{message: "oops"}
|
||||
|
||||
If the given function callback fails with `reason`, the function returns
|
||||
`{:error, reason}`.
|
||||
"""
|
||||
@spec start_link((() -> term), GenServer.options()) :: on_start
|
||||
@spec start_link((() -> term), GenServer.options) :: on_start
|
||||
def start_link(fun, options \\ []) when is_function(fun, 0) do
|
||||
GenServer.start_link(Agent.Server, fun, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts an agent linked to the current process.
|
||||
Starts an agent linked to the current process with the given module
|
||||
function and arguments.
|
||||
|
||||
Same as `start_link/2` but a module, function, and arguments are expected
|
||||
instead of an anonymous function; `fun` in `module` will be called with the
|
||||
given arguments `args` to initialize the state.
|
||||
Same as `start_link/2` but a module, function and args are expected
|
||||
instead of an anonymous function.
|
||||
"""
|
||||
@spec start_link(module, atom, [any], GenServer.options()) :: on_start
|
||||
@spec start_link(module, atom, [any], GenServer.options) :: on_start
|
||||
def start_link(module, fun, args, options \\ []) do
|
||||
GenServer.start_link(Agent.Server, {module, fun, args}, options)
|
||||
end
|
||||
@@ -238,48 +172,31 @@ defmodule Agent do
|
||||
Starts an agent process without links (outside of a supervision tree).
|
||||
|
||||
See `start_link/2` for more information.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start(fn -> 42 end)
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
42
|
||||
|
||||
"""
|
||||
@spec start((() -> term), GenServer.options()) :: on_start
|
||||
@spec start((() -> term), GenServer.options) :: on_start
|
||||
def start(fun, options \\ []) when is_function(fun, 0) do
|
||||
GenServer.start(Agent.Server, fun, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts an agent without links with the given module, function, and arguments.
|
||||
Starts an agent with the given module function and arguments.
|
||||
|
||||
See `start_link/4` for more information.
|
||||
Similar to `start/2` but a module, function and args are expected
|
||||
instead of an anonymous function.
|
||||
"""
|
||||
@spec start(module, atom, [any], GenServer.options()) :: on_start
|
||||
@spec start(module, atom, [any], GenServer.options) :: on_start
|
||||
def start(module, fun, args, options \\ []) do
|
||||
GenServer.start(Agent.Server, {module, fun, args}, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets an agent value via the given anonymous function.
|
||||
Gets an agent value via the given function.
|
||||
|
||||
The function `fun` is sent to the `agent` which invokes the function
|
||||
passing the agent state. The result of the function invocation is
|
||||
returned from this function.
|
||||
|
||||
`timeout` is an integer greater than zero which specifies how many
|
||||
milliseconds are allowed before the agent executes the function and returns
|
||||
the result value, or the atom `:infinity` to wait indefinitely. If no result
|
||||
is received within the specified time, the function call fails and the caller
|
||||
exits.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
42
|
||||
returned.
|
||||
|
||||
A timeout can also be specified (it has a default value of 5000).
|
||||
"""
|
||||
@spec get(agent, (state -> a), timeout) :: a when a: var
|
||||
def get(agent, fun, timeout \\ 5000) when is_function(fun, 1) do
|
||||
@@ -289,9 +206,9 @@ defmodule Agent do
|
||||
@doc """
|
||||
Gets an agent value via the given function.
|
||||
|
||||
Same as `get/3` but a module, function, and arguments are expected
|
||||
Same as `get/3` but a module, function and args are expected
|
||||
instead of an anonymous function. The state is added as first
|
||||
argument to the given list of arguments.
|
||||
argument to the given list of args.
|
||||
"""
|
||||
@spec get(agent, module, atom, [term], timeout) :: any
|
||||
def get(agent, module, fun, args, timeout \\ 5000) do
|
||||
@@ -299,28 +216,14 @@ defmodule Agent do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets and updates the agent state in one operation via the given anonymous
|
||||
function.
|
||||
Gets and updates the agent state in one operation.
|
||||
|
||||
The function `fun` is sent to the `agent` which invokes the function
|
||||
passing the agent state. The function must return a tuple with two
|
||||
elements, the first being the value to return (that is, the "get" value)
|
||||
and the second one being the new state of the agent.
|
||||
|
||||
`timeout` is an integer greater than zero which specifies how many
|
||||
milliseconds are allowed before the agent executes the function and returns
|
||||
the result value, or the atom `:infinity` to wait indefinitely. If no result
|
||||
is received within the specified time, the function call fails and the caller
|
||||
exits.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.get_and_update(pid, fn state -> {state, state + 1} end)
|
||||
42
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
43
|
||||
elements, the first being the value to return (i.e. the `get` value)
|
||||
and the second one is the new state.
|
||||
|
||||
A timeout can also be specified (it has a default value of 5000).
|
||||
"""
|
||||
@spec get_and_update(agent, (state -> {a, state}), timeout) :: a when a: var
|
||||
def get_and_update(agent, fun, timeout \\ 5000) when is_function(fun, 1) do
|
||||
@@ -328,11 +231,11 @@ defmodule Agent do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Gets and updates the agent state in one operation via the given function.
|
||||
Gets and updates the agent state in one operation.
|
||||
|
||||
Same as `get_and_update/3` but a module, function, and arguments are expected
|
||||
Same as `get_and_update/3` but a module, function and args are expected
|
||||
instead of an anonymous function. The state is added as first
|
||||
argument to the given list of arguments.
|
||||
argument to the given list of args.
|
||||
"""
|
||||
@spec get_and_update(agent, module, atom, [term], timeout) :: any
|
||||
def get_and_update(agent, module, fun, args, timeout \\ 5000) do
|
||||
@@ -340,28 +243,13 @@ defmodule Agent do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the agent state via the given anonymous function.
|
||||
Updates the agent state.
|
||||
|
||||
The function `fun` is sent to the `agent` which invokes the function
|
||||
passing the agent state. The return value of `fun` becomes the new
|
||||
state of the agent.
|
||||
passing the agent state. The function must return the new state.
|
||||
|
||||
A timeout can also be specified (it has a default value of 5000).
|
||||
This function always returns `:ok`.
|
||||
|
||||
`timeout` is an integer greater than zero which specifies how many
|
||||
milliseconds are allowed before the agent executes the function and returns
|
||||
the result value, or the atom `:infinity` to wait indefinitely. If no result
|
||||
is received within the specified time, the function call fails and the caller
|
||||
exits.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.update(pid, fn state -> state + 1 end)
|
||||
:ok
|
||||
iex> Agent.get(pid, fn state -> state end)
|
||||
43
|
||||
|
||||
"""
|
||||
@spec update(agent, (state -> state), timeout) :: :ok
|
||||
def update(agent, fun, timeout \\ 5000) when is_function(fun, 1) do
|
||||
@@ -369,11 +257,11 @@ defmodule Agent do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Updates the agent state via the given function.
|
||||
Updates the agent state.
|
||||
|
||||
Same as `update/3` but a module, function, and arguments are expected
|
||||
Same as `update/3` but a module, function and args are expected
|
||||
instead of an anonymous function. The state is added as first
|
||||
argument to the given list of arguments.
|
||||
argument to the given list of args.
|
||||
"""
|
||||
@spec update(agent, module, atom, [term], timeout) :: :ok
|
||||
def update(agent, module, fun, args, timeout \\ 5000) do
|
||||
@@ -381,14 +269,13 @@ defmodule Agent do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Performs a cast (*fire and forget*) operation on the agent state.
|
||||
Performs a cast (fire and forget) operation on the agent state.
|
||||
|
||||
The function `fun` is sent to the `agent` which invokes the function
|
||||
passing the agent state. The return value of `fun` becomes the new
|
||||
state of the agent.
|
||||
passing the agent state. The function must return the new state.
|
||||
|
||||
Note that `cast` returns `:ok` immediately, regardless of whether `agent` (or
|
||||
the node it should live on) exists.
|
||||
Note that `cast` returns `:ok` immediately, regardless of whether the
|
||||
destination node or agent exists.
|
||||
"""
|
||||
@spec cast(agent, (state -> state)) :: :ok
|
||||
def cast(agent, fun) when is_function(fun, 1) do
|
||||
@@ -396,11 +283,11 @@ defmodule Agent do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Performs a cast (*fire and forget*) operation on the agent state.
|
||||
Performs a cast (fire and forget) operation on the agent state.
|
||||
|
||||
Same as `cast/2` but a module, function, and arguments are expected
|
||||
Same as `cast/2` but a module, function and args are expected
|
||||
instead of an anonymous function. The state is added as first
|
||||
argument to the given list of arguments.
|
||||
argument to the given list of args.
|
||||
"""
|
||||
@spec cast(agent, module, atom, [term]) :: :ok
|
||||
def cast(agent, module, fun, args) do
|
||||
@@ -408,25 +295,18 @@ defmodule Agent do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Synchronously stops the agent with the given `reason`.
|
||||
Stops the agent with the given `reason`.
|
||||
|
||||
It returns `:ok` if the agent terminates with the given
|
||||
reason. If the agent terminates with another reason, the call will
|
||||
It returns `:ok` if the server terminates with the given
|
||||
reason, if it terminates with another reason, the call will
|
||||
exit.
|
||||
|
||||
This function keeps OTP semantics regarding error reporting.
|
||||
If the reason is any other than `:normal`, `:shutdown` or
|
||||
`{:shutdown, _}`, an error report will be logged.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, pid} = Agent.start_link(fn -> 42 end)
|
||||
iex> Agent.stop(pid)
|
||||
:ok
|
||||
|
||||
"""
|
||||
@spec stop(agent, reason :: term, timeout) :: :ok
|
||||
def stop(agent, reason \\ :normal, timeout \\ :infinity) do
|
||||
GenServer.stop(agent, reason, timeout)
|
||||
:gen.stop(agent, reason, timeout)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -15,7 +15,7 @@ defmodule Agent.Server do
|
||||
def handle_call({:get_and_update, fun}, _from, state) do
|
||||
case run(fun, [state]) do
|
||||
{reply, state} -> {:reply, reply, state}
|
||||
other -> {:stop, {:bad_return_value, other}, state}
|
||||
other -> {:stop, {:bad_return_value, other}, state}
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
+85
-200
@@ -9,114 +9,17 @@ defmodule Application do
|
||||
Applications are defined with an application file named `APP.app` where
|
||||
`APP` is the application name, usually in `underscore_case`. The application
|
||||
file must reside in the same `ebin` directory as the compiled modules of the
|
||||
application. In Elixir, the Mix build tool is responsible for compiling your
|
||||
source code and generating your application `.app` file. You can learn more
|
||||
about the generation of `.app` files by typing `mix help compile.app`.
|
||||
application.
|
||||
|
||||
Once your application is compiled, running your system is a matter of starting
|
||||
your current application and its dependencies. Differently from other languages,
|
||||
Elixir does not have a `main` procedure that is responsible for starting your
|
||||
system. Instead, you start one or more applications, each with their own
|
||||
initialization and termination logic.
|
||||
In Elixir, Mix is responsible for compiling your source code and
|
||||
generating your application `.app` file. Furthermore, Mix is also
|
||||
responsible for configuring, starting and stopping your application
|
||||
and its dependencies. For this reason, this documentation will focus
|
||||
on the remaining aspects of your application: the application environment
|
||||
and the application callback module.
|
||||
|
||||
Applications also provide an "application environment", which provides one
|
||||
mechanism for configuring long running applications. We will learn more about
|
||||
the tooling, start and shutdown and the application environment in the next
|
||||
sections.
|
||||
|
||||
## Start and shutdown
|
||||
|
||||
Starting an application is done via the "application module callback", which
|
||||
is a module that defines the `start/2` function. The `start/2` function should
|
||||
then start a supervisor, which is often called as the top-level supervisor, since
|
||||
it sits at the root of a potentially long supervision tree. When the system is
|
||||
shutting down, all applications shut down their top-level supervisor, which
|
||||
terminates children in the opposite order they are started.
|
||||
|
||||
Shutting down a live system cleanly can be done by calling `System.stop/1`.
|
||||
It will shut down all applications in the opposite order they are started.
|
||||
Each application will then shutdown its top-level supervisor, if one is
|
||||
available, [which then shuts down its children](Supervisor.html#module-start-and-shutdown).
|
||||
|
||||
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.
|
||||
|
||||
### Application module callback
|
||||
|
||||
An application may start and stop a supervision tree when it boots via
|
||||
the application module callback.
|
||||
|
||||
The first step is to pass the module callback in the application definition
|
||||
in the `mix.exs` file:
|
||||
|
||||
def application do
|
||||
[mod: {MyApp, []}]
|
||||
end
|
||||
|
||||
Our application now requires the `MyApp` module to provide an application
|
||||
callback. This can be done by invoking `use Application` in that module and
|
||||
defining a `start/2` callback, for example:
|
||||
|
||||
defmodule MyApp do
|
||||
use Application
|
||||
|
||||
def start(_type, _args) do
|
||||
children = []
|
||||
Supervisor.start_link(children, strategy: :one_for_one)
|
||||
end
|
||||
end
|
||||
|
||||
`start/2` typically returns `{:ok, pid}` or `{:ok, pid, state}` where
|
||||
`pid` identifies the supervision tree and `state` is the application state.
|
||||
`args` is the second element of the tuple given to the `:mod` option.
|
||||
|
||||
The `type` argument passed to `start/2` is usually `:normal` unless in a
|
||||
distributed setup where application takeovers and failovers are configured.
|
||||
Distributed applications is beyond the scope of this documentation. For those
|
||||
interested on the topic, please access the OTP documentation:
|
||||
|
||||
* [`:application` module](http://www.erlang.org/doc/man/application.html)
|
||||
* [Applications – OTP Design Principles](http://www.erlang.org/doc/design_principles/applications.html)
|
||||
|
||||
When an application is shutting down, its `c:stop/1` callback is called after
|
||||
the supervision tree has been stopped by the runtime. This callback allows the
|
||||
application to do any final cleanup. The argument is the state returned by
|
||||
`c:start/2`, if it did, or `[]` otherwise. The return value of `c:stop/1` is
|
||||
ignored.
|
||||
|
||||
By using `Application`, modules get a default implementation of `c:stop/1`
|
||||
that ignores its argument and returns `:ok`, but it can be overridden.
|
||||
|
||||
Application callback modules may also implement the optional callback
|
||||
`c:prep_stop/1`. If present, `c:prep_stop/1` is invoked before the supervision
|
||||
tree is terminated. Its argument is the state returned by `c:start/2`, if it did,
|
||||
or `[]` otherwise, and its return value is passed to `c:stop/1`.
|
||||
|
||||
An application without a supervision tree doesn't define an application
|
||||
module callback in the application definition in `mix.exs` file. Even though
|
||||
there is no module with application callbacks such as `start/2` and
|
||||
`stop/1`, the application can be started and stopped the same way as an
|
||||
application with a supervision tree.
|
||||
|
||||
## Tooling
|
||||
|
||||
The Mix build tool can also be used to start your applications. For example,
|
||||
`mix test` automatically starts your application dependencies and your application
|
||||
itself before your test runs. `mix run --no-halt` boots your current project and
|
||||
can be used to start a long running system. See `mix help run`.
|
||||
|
||||
Developers can also use tools like [Distillery](https://github.com/bitwalker/distillery)
|
||||
that build **releases**. Releases are able to package all of your source code
|
||||
as well as the Erlang VM into a single directory. Releases also give you explicit
|
||||
control over how each application is started and in which order. They also provide
|
||||
a more streamlined mechanism for starting and stopping systems, debugging, logging,
|
||||
as well as system monitoring.
|
||||
|
||||
Finally, Elixir provides tools such as escripts and archives, which are
|
||||
different mechanisms for packaging your application. Those are typically used
|
||||
when tools must be shared between developers and not as deployment options.
|
||||
See `mix help archive.build` and `mix help escript.build` for more detail.
|
||||
You can learn more about Mix generation of `.app` files by typing
|
||||
`mix help compile.app`.
|
||||
|
||||
## Application environment
|
||||
|
||||
@@ -137,28 +40,60 @@ defmodule Application do
|
||||
Application.get_env(:APP_NAME, :hello)
|
||||
#=> :world
|
||||
|
||||
Applications and dependencies in Mix projects are typically configured
|
||||
via the `config/config.exs` file. For example, someone using your
|
||||
application can configure the `:hello` key as follows:
|
||||
|
||||
config :APP_NAME, hello: :brand_new_world
|
||||
|
||||
Keep in mind configuration files are only useful to configure static
|
||||
values. For example, if you need to configure your applications based
|
||||
on the system environment, the file system or on database entries,
|
||||
then those configurations are better placed at runtime. For example,
|
||||
one may configure applications dynamically via `put_env/3`.
|
||||
It is also possible to put and delete values from the application value,
|
||||
including new values that are not defined in the environment file (although
|
||||
this should be avoided).
|
||||
|
||||
Keep in mind that each application is responsible for its environment.
|
||||
Do not use the functions in this module for directly accessing or modifying
|
||||
the environment of other applications (as it may lead to inconsistent
|
||||
data in the application environment).
|
||||
|
||||
## Application module callback
|
||||
|
||||
Often times, an application defines a supervision tree that must be started
|
||||
and stopped when the application starts and stops. For such, we need to
|
||||
define an application module callback. The first step is to define the
|
||||
module callback in the application definition in the `mix.exs` file:
|
||||
|
||||
def application do
|
||||
[mod: {MyApp, []}]
|
||||
end
|
||||
|
||||
Our application now requires the `MyApp` module to provide an application
|
||||
callback. This can be done by invoking `use Application` in that module and
|
||||
defining a `start/2` callback, for example:
|
||||
|
||||
defmodule MyApp do
|
||||
use Application
|
||||
|
||||
def start(_type, _args) do
|
||||
MyApp.Supervisor.start_link()
|
||||
end
|
||||
end
|
||||
|
||||
`start/2` typically returns `{:ok, pid}` or `{:ok, pid, state}` where
|
||||
`pid` identifies the supervision tree and `state` is the application state.
|
||||
`args` is the second element of the tuple given to the `:mod` option.
|
||||
|
||||
The `type` argument passed to `start/2` is usually `:normal` unless in a
|
||||
distributed setup where application takeovers and failovers are configured.
|
||||
This particular aspect of applications is explained in more detail in the
|
||||
OTP documentation:
|
||||
|
||||
* [`:application` module](http://www.erlang.org/doc/man/application.html)
|
||||
* [Applications – OTP Design Principles](http://www.erlang.org/doc/design_principles/applications.html)
|
||||
|
||||
A developer may also implement the `stop/1` callback (automatically defined
|
||||
by `use Application`) which does any application cleanup. It receives the
|
||||
application state and can return any value. Note that shutting down the
|
||||
supervisor is automatically handled by the VM.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Called when an application is started.
|
||||
|
||||
This function is called when an application is started using
|
||||
This function is called when an the application is started using
|
||||
`Application.start/2` (and functions on top of that, such as
|
||||
`Application.ensure_started/2`). This function should start the top-level
|
||||
process of the application (which should be the top supervisor of the
|
||||
@@ -169,7 +104,7 @@ defmodule Application do
|
||||
|
||||
* `:normal` - used if the startup is a normal startup or if the application
|
||||
is distributed and is started on the current node because of a failover
|
||||
from another node and the application specification key `:start_phases`
|
||||
from another mode and the application specification key `:start_phases`
|
||||
is `:undefined`.
|
||||
* `{:takeover, node}` - used if the application is distributed and is
|
||||
started on the current node because of a failover on the node `node`.
|
||||
@@ -190,49 +125,26 @@ defmodule Application do
|
||||
callback.
|
||||
"""
|
||||
@callback start(start_type, start_args :: term) ::
|
||||
{:ok, pid}
|
||||
| {:ok, pid, state}
|
||||
| {:error, reason :: term}
|
||||
{:ok, pid} |
|
||||
{:ok, pid, state} |
|
||||
{:error, reason :: term}
|
||||
|
||||
@doc """
|
||||
Called before stopping the application.
|
||||
Called when an application is stopped.
|
||||
|
||||
This function is called before the top-level supervisor is terminated. It
|
||||
receives the state returned by `c:start/2`, if it did, or `[]` otherwise.
|
||||
The return value is later passed to `c:stop/1`.
|
||||
"""
|
||||
@callback prep_stop(state) :: state
|
||||
|
||||
@doc """
|
||||
Called after an application has been stopped.
|
||||
|
||||
This function is called after an application has been stopped, i.e., after its
|
||||
This function is called when an application has stopped, i.e., when its
|
||||
supervision tree has been stopped. It should do the opposite of what the
|
||||
`c:start/2` callback did, and should perform any necessary cleanup. The return
|
||||
`start/2` callback did, and should perform any necessary cleanup. The return
|
||||
value of this callback is ignored.
|
||||
|
||||
`state` is the state returned by `c:start/2`, if it did, or `[]` otherwise.
|
||||
If the optional callback `c:prep_stop/1` is present, `state` is its return
|
||||
value instead.
|
||||
`state` is the return value of the `start/2` callback or the return value of
|
||||
the `prep_stop/1` function if the application module defines such a function.
|
||||
|
||||
`use Application` defines a default implementation of this function which does
|
||||
nothing and just returns `:ok`.
|
||||
"""
|
||||
@callback stop(state) :: term
|
||||
|
||||
@doc """
|
||||
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
|
||||
defined in the application's (and any included applications') specification,
|
||||
in the order they are listed in.
|
||||
"""
|
||||
@callback start_phase(phase :: term, start_type, phase_args :: term) ::
|
||||
:ok | {:error, reason :: term}
|
||||
|
||||
@optional_callbacks start_phase: 3, prep_stop: 1
|
||||
|
||||
@doc false
|
||||
defmacro __using__(_) do
|
||||
quote location: :keep do
|
||||
@@ -243,7 +155,7 @@ defmodule Application do
|
||||
:ok
|
||||
end
|
||||
|
||||
defoverridable Application
|
||||
defoverridable [stop: 1]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -253,26 +165,15 @@ defmodule Application do
|
||||
@type state :: term
|
||||
@type start_type :: :permanent | :transient | :temporary
|
||||
|
||||
@application_keys [
|
||||
:description,
|
||||
:id,
|
||||
:vsn,
|
||||
:modules,
|
||||
:maxP,
|
||||
:maxT,
|
||||
:registered,
|
||||
:included_applications,
|
||||
:applications,
|
||||
:mod,
|
||||
:start_phases
|
||||
]
|
||||
@application_keys [:description, :id, :vsn, :modules, :maxP, :maxT, :registered,
|
||||
:included_applications, :applications, :mod, :start_phases]
|
||||
|
||||
@doc """
|
||||
Returns the spec for `app`.
|
||||
|
||||
The following keys are returned:
|
||||
|
||||
* #{Enum.map_join(@application_keys, "\n * ", &"`#{inspect(&1)}`")}
|
||||
* #{Enum.map_join @application_keys, "\n * ", &inspect/1}
|
||||
|
||||
Note the environment is not returned as it can be accessed via
|
||||
`fetch_env/2`. Returns `nil` if the application is not loaded.
|
||||
@@ -281,7 +182,7 @@ defmodule Application do
|
||||
def spec(app) do
|
||||
case :application.get_all_key(app) do
|
||||
{:ok, info} -> :lists.keydelete(:env, 1, info)
|
||||
:undefined -> nil
|
||||
:undefined -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@@ -355,27 +256,11 @@ defmodule Application do
|
||||
@spec fetch_env!(app, key) :: value | no_return
|
||||
def fetch_env!(app, key) do
|
||||
case fetch_env(app, key) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:ok, value} -> value
|
||||
:error ->
|
||||
vsn = :application.get_key(app, :vsn)
|
||||
app = inspect(app)
|
||||
key = inspect(key)
|
||||
|
||||
case vsn do
|
||||
{:ok, _} ->
|
||||
raise ArgumentError,
|
||||
"could not fetch application environment #{key} for application #{app} " <>
|
||||
"because configuration #{key} was not set"
|
||||
|
||||
:undefined ->
|
||||
raise ArgumentError,
|
||||
"could not fetch application environment #{key} for application #{app} " <>
|
||||
"because the application was not loaded/started. If your application " <>
|
||||
"depends on #{app} at runtime, make sure to load/start it or list it " <>
|
||||
"under :extra_applications in your mix.exs file"
|
||||
end
|
||||
raise ArgumentError,
|
||||
"application #{inspect app} is not loaded, " <>
|
||||
"or the configuration parameter #{inspect key} is not set"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -384,7 +269,7 @@ defmodule Application do
|
||||
|
||||
## Options
|
||||
|
||||
* `:timeout` - the timeout for the change (defaults to `5_000` milliseconds)
|
||||
* `:timeout` - the timeout for the change (defaults to 5000ms)
|
||||
* `:persistent` - persists the given value on application load and reloads
|
||||
|
||||
If `put_env/4` is called before the application is loaded, the application
|
||||
@@ -396,7 +281,7 @@ defmodule Application do
|
||||
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
|
||||
@spec put_env(app, key, value, [timeout: timeout, persistent: boolean]) :: :ok
|
||||
def put_env(app, key, value, opts \\ []) do
|
||||
:application.set_env(app, key, value, opts)
|
||||
end
|
||||
@@ -406,7 +291,7 @@ defmodule Application do
|
||||
|
||||
See `put_env/4` for a description of the options.
|
||||
"""
|
||||
@spec delete_env(app, key, timeout: timeout, persistent: boolean) :: :ok
|
||||
@spec delete_env(app, key, [timeout: timeout, persistent: boolean]) :: :ok
|
||||
def delete_env(app, key, opts \\ []) do
|
||||
:application.unset_env(app, key, opts)
|
||||
end
|
||||
@@ -449,7 +334,7 @@ defmodule Application do
|
||||
started before this application is. If not, `{:error, {:not_started, app}}` is
|
||||
returned, where `app` is the name of the missing application.
|
||||
|
||||
In case you want to automatically load **and start** all of `app`'s dependencies,
|
||||
In case you want to automatically load **and start** all of `app`'s dependencies,
|
||||
see `ensure_all_started/2`.
|
||||
|
||||
The `type` argument specifies the type of the application:
|
||||
@@ -534,24 +419,23 @@ defmodule Application do
|
||||
#=> "bar-123"
|
||||
|
||||
For more information on code paths, check the `Code` module in
|
||||
Elixir and also Erlang's [`:code` module](http://www.erlang.org/doc/man/code.html).
|
||||
Elixir and also Erlang's `:code` module.
|
||||
"""
|
||||
@spec app_dir(app) :: String.t()
|
||||
@spec app_dir(app) :: String.t
|
||||
def app_dir(app) when is_atom(app) do
|
||||
case :code.lib_dir(app) do
|
||||
lib when is_list(lib) -> IO.chardata_to_string(lib)
|
||||
{:error, :bad_name} -> raise ArgumentError, "unknown application: #{inspect(app)}"
|
||||
{:error, :bad_name} -> raise ArgumentError, "unknown application: #{inspect app}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the given path inside `app_dir/1`.
|
||||
"""
|
||||
@spec app_dir(app, String.t() | [String.t()]) :: String.t()
|
||||
@spec app_dir(app, String.t | [String.t]) :: String.t
|
||||
def app_dir(app, path) when is_binary(path) do
|
||||
Path.join(app_dir(app), path)
|
||||
end
|
||||
|
||||
def app_dir(app, path) when is_list(path) do
|
||||
Path.join([app_dir(app) | path])
|
||||
end
|
||||
@@ -569,7 +453,7 @@ defmodule Application do
|
||||
"""
|
||||
@spec loaded_applications :: [tuple]
|
||||
def loaded_applications do
|
||||
:application.loaded_applications()
|
||||
:application.loaded_applications
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -577,7 +461,7 @@ defmodule Application do
|
||||
`ensure_started/2`, `stop/1`, `load/1` and `unload/1`,
|
||||
returns a string.
|
||||
"""
|
||||
@spec format_error(any) :: String.t()
|
||||
@spec format_error(any) :: String.t
|
||||
def format_error(reason) do
|
||||
try do
|
||||
do_format_error(reason)
|
||||
@@ -596,8 +480,8 @@ defmodule Application do
|
||||
|
||||
# {:error, reason} return value
|
||||
defp do_format_error({reason, {mod, :start, args}}) do
|
||||
Exception.format_mfa(mod, :start, args) <>
|
||||
" returned an error: " <> Exception.format_exit(reason)
|
||||
Exception.format_mfa(mod, :start, args) <> " returned an error: " <>
|
||||
Exception.format_exit(reason)
|
||||
end
|
||||
|
||||
# error or exit(reason) call, use exit reason as reason.
|
||||
@@ -607,7 +491,8 @@ defmodule Application do
|
||||
|
||||
# bad return value
|
||||
defp do_format_error({:bad_return, {{mod, :start, args}, return}}) do
|
||||
Exception.format_mfa(mod, :start, args) <> " returned a bad value: " <> inspect(return)
|
||||
Exception.format_mfa(mod, :start, args) <>
|
||||
" returned a bad value: " <> inspect(return)
|
||||
end
|
||||
|
||||
defp do_format_error({:already_started, app}) when is_atom(app) do
|
||||
|
||||
@@ -16,7 +16,7 @@ defmodule Atom do
|
||||
"foo"
|
||||
|
||||
"""
|
||||
@spec to_string(atom) :: String.t()
|
||||
@spec to_string(atom) :: String.t
|
||||
def to_string(atom) do
|
||||
:erlang.atom_to_binary(atom, :utf8)
|
||||
end
|
||||
@@ -37,8 +37,7 @@ defmodule Atom do
|
||||
:erlang.atom_to_list(atom)
|
||||
end
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
# TODO: Deprecate by v1.5
|
||||
@doc false
|
||||
@spec to_char_list(atom) :: charlist
|
||||
def to_char_list(atom), do: Atom.to_charlist(atom)
|
||||
|
||||
+295
-638
File diff suppressed because it is too large
Load Diff
@@ -1,6 +1,6 @@
|
||||
defmodule Behaviour do
|
||||
@moduledoc """
|
||||
WARNING: this module is deprecated.
|
||||
This module has been deprecated.
|
||||
|
||||
Instead of `defcallback/1` and `defmacrocallback/1`, the `@callback` and
|
||||
`@macrocallback` module attributes can be used (respectively). See the
|
||||
@@ -21,7 +21,7 @@ defmodule Behaviour do
|
||||
Defines a macro callback according to the given type specification.
|
||||
"""
|
||||
defmacro defmacrocallback(spec) do
|
||||
do_defcallback(:defmacro, split_spec(spec, quote(do: Macro.t())))
|
||||
do_defcallback(:defmacro, split_spec(spec, quote(do: Macro.t)))
|
||||
end
|
||||
|
||||
defp split_spec({:when, _, [{:::, _, [spec, return]}, guard]}, _default) do
|
||||
@@ -44,25 +44,21 @@ defmodule Behaviour do
|
||||
case Macro.decompose_call(spec) do
|
||||
{name, args} ->
|
||||
do_callback(kind, name, args, return, guards)
|
||||
|
||||
_ ->
|
||||
raise ArgumentError, "invalid syntax in #{kind}callback #{Macro.to_string(spec)}"
|
||||
end
|
||||
end
|
||||
|
||||
defp do_callback(kind, name, args, return, guards) do
|
||||
fun = fn
|
||||
:lists.foreach fn
|
||||
{:::, _, [left, right]} ->
|
||||
ensure_not_default(left)
|
||||
ensure_not_default(right)
|
||||
left
|
||||
|
||||
other ->
|
||||
ensure_not_default(other)
|
||||
other
|
||||
end
|
||||
|
||||
:lists.foreach(fun, args)
|
||||
end, args
|
||||
|
||||
spec =
|
||||
quote do
|
||||
@@ -70,8 +66,8 @@ defmodule Behaviour do
|
||||
end
|
||||
|
||||
case kind do
|
||||
:def -> quote(do: @callback(unquote(spec)))
|
||||
:defmacro -> quote(do: @macrocallback(unquote(spec)))
|
||||
:def -> quote(do: @callback unquote(spec))
|
||||
:defmacro -> quote(do: @macrocallback unquote(spec))
|
||||
end
|
||||
end
|
||||
|
||||
@@ -86,9 +82,8 @@ defmodule Behaviour do
|
||||
quote do
|
||||
warning =
|
||||
"the Behaviour module is deprecated. Instead of using this module, " <>
|
||||
"use the @callback and @macrocallback module attributes. See the " <>
|
||||
"documentation for Module for more information on these attributes"
|
||||
|
||||
"use the @callback and @macrocallback module attributes. See the " <>
|
||||
"documentation for Module for more information on these attributes"
|
||||
IO.warn(warning)
|
||||
|
||||
@doc false
|
||||
|
||||
+20
-23
@@ -37,17 +37,14 @@ defmodule Bitwise do
|
||||
|
||||
@doc false
|
||||
defmacro __using__(options) do
|
||||
except =
|
||||
cond do
|
||||
Keyword.get(options, :only_operators) ->
|
||||
[bnot: 1, band: 2, bor: 2, bxor: 2, bsl: 2, bsr: 2]
|
||||
|
||||
Keyword.get(options, :skip_operators) ->
|
||||
[~~~: 1, &&&: 2, |||: 2, ^^^: 2, <<<: 2, >>>: 2]
|
||||
|
||||
true ->
|
||||
[]
|
||||
end
|
||||
except = cond do
|
||||
Keyword.get(options, :only_operators) ->
|
||||
[bnot: 1, band: 2, bor: 2, bxor: 2, bsl: 2, bsr: 2]
|
||||
Keyword.get(options, :skip_operators) ->
|
||||
[~~~: 1, &&&: 2, |||: 2, ^^^: 2, <<<: 2, >>>: 2]
|
||||
true ->
|
||||
[]
|
||||
end
|
||||
|
||||
quote do
|
||||
import Bitwise, except: unquote(except)
|
||||
@@ -64,7 +61,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro bnot(expr) do
|
||||
quote(do: :erlang.bnot(unquote(expr)))
|
||||
quote do: :erlang.bnot(unquote(expr))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -77,7 +74,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro ~~~expr do
|
||||
quote(do: :erlang.bnot(unquote(expr)))
|
||||
quote do: :erlang.bnot(unquote(expr))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -88,7 +85,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro band(left, right) do
|
||||
quote(do: :erlang.band(unquote(left), unquote(right)))
|
||||
quote do: :erlang.band(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -99,7 +96,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro left &&& right do
|
||||
quote(do: :erlang.band(unquote(left), unquote(right)))
|
||||
quote do: :erlang.band(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -110,7 +107,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro bor(left, right) do
|
||||
quote(do: :erlang.bor(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bor(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -121,7 +118,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro left ||| right do
|
||||
quote(do: :erlang.bor(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bor(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -132,7 +129,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro bxor(left, right) do
|
||||
quote(do: :erlang.bxor(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bxor(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -143,7 +140,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro left ^^^ right do
|
||||
quote(do: :erlang.bxor(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bxor(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -160,7 +157,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro bsl(left, right) do
|
||||
quote(do: :erlang.bsl(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bsl(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -177,7 +174,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro left <<< right do
|
||||
quote(do: :erlang.bsl(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bsl(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -194,7 +191,7 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro bsr(left, right) do
|
||||
quote(do: :erlang.bsr(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bsr(unquote(left), unquote(right))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -211,6 +208,6 @@ defmodule Bitwise do
|
||||
|
||||
"""
|
||||
defmacro left >>> right do
|
||||
quote(do: :erlang.bsr(unquote(left), unquote(right)))
|
||||
quote do: :erlang.bsr(unquote(left), unquote(right))
|
||||
end
|
||||
end
|
||||
|
||||
+1711
-167
File diff suppressed because it is too large
Load Diff
@@ -1,613 +0,0 @@
|
||||
defmodule Date do
|
||||
@moduledoc """
|
||||
A Date struct and functions.
|
||||
|
||||
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`
|
||||
sigil:
|
||||
|
||||
iex> ~D[2000-01-01]
|
||||
~D[2000-01-01]
|
||||
|
||||
Both `new/3` and sigil return a struct where the date fields can
|
||||
be accessed directly:
|
||||
|
||||
iex> date = ~D[2000-01-01]
|
||||
iex> date.year
|
||||
2000
|
||||
iex> date.month
|
||||
1
|
||||
|
||||
The functions on this module work with the `Date` struct as well
|
||||
as any struct that contains the same fields as the `Date` struct,
|
||||
such as `NaiveDateTime` and `DateTime`. Such functions expect
|
||||
`t:Calendar.date/0` in their typespecs (instead of `t:t/0`).
|
||||
|
||||
Developers should avoid creating the Date structs directly
|
||||
and instead rely on the functions provided by this module as well
|
||||
as the ones in 3rd party calendar libraries.
|
||||
|
||||
## Comparing dates
|
||||
|
||||
Comparisons in Elixir using `==`, `>`, `<` and similar are structural
|
||||
and based on the `Date` struct fields. For proper comparison between
|
||||
dates, use the `compare/2` function.
|
||||
|
||||
## Using epochs
|
||||
|
||||
The `add/2` and `diff/2` functions can be used for computing dates
|
||||
or retrieving the number of days between instants. For example, if there
|
||||
is an interest in computing the number of days from the Unix epoch
|
||||
(1970-01-01):
|
||||
|
||||
iex> Date.diff(~D[2010-04-17], ~D[1970-01-01])
|
||||
14716
|
||||
|
||||
iex> Date.add(~D[1970-01-01], 14716)
|
||||
~D[2010-04-17]
|
||||
|
||||
Those functions are optimized to deal with common epochs, such
|
||||
as the Unix Epoch above or the Gregorian Epoch (0000-01-01).
|
||||
"""
|
||||
|
||||
@enforce_keys [:year, :month, :day]
|
||||
defstruct [:year, :month, :day, calendar: Calendar.ISO]
|
||||
|
||||
@type t :: %Date{
|
||||
year: Calendar.year(),
|
||||
month: Calendar.month(),
|
||||
day: Calendar.day(),
|
||||
calendar: Calendar.calendar()
|
||||
}
|
||||
|
||||
@doc """
|
||||
Returns a range of dates.
|
||||
|
||||
A range of dates represents a discrete number of dates where
|
||||
the first and last values are dates with matching calendars.
|
||||
|
||||
Ranges of dates can be either increasing (`first <= last`) or
|
||||
decreasing (`first > last`). They are also always inclusive.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.range(~D[1999-01-01], ~D[2000-01-01])
|
||||
#DateRange<~D[1999-01-01], ~D[2000-01-01]>
|
||||
|
||||
A range of dates implements the `Enumerable` protocol, which means
|
||||
functions in the `Enum` module can be used to work with
|
||||
ranges:
|
||||
|
||||
iex> range = Date.range(~D[2001-01-01], ~D[2002-01-01])
|
||||
iex> Enum.count(range)
|
||||
366
|
||||
iex> Enum.member?(range, ~D[2001-02-01])
|
||||
true
|
||||
iex> Enum.reduce(range, 0, fn _date, acc -> acc - 1 end)
|
||||
-366
|
||||
"""
|
||||
|
||||
@spec range(Date.t(), Date.t()) :: Date.Range.t()
|
||||
def range(%Date{calendar: calendar} = first, %Date{calendar: calendar} = last) do
|
||||
{first_days, _} = to_iso_days(first)
|
||||
{last_days, _} = to_iso_days(last)
|
||||
|
||||
%Date.Range{
|
||||
first: first,
|
||||
last: last,
|
||||
first_in_iso_days: first_days,
|
||||
last_in_iso_days: last_days
|
||||
}
|
||||
end
|
||||
|
||||
def range(%Date{}, %Date{}) do
|
||||
raise ArgumentError, "both dates must have matching calendars"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the current date in UTC.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> date = Date.utc_today()
|
||||
iex> date.year >= 2016
|
||||
true
|
||||
|
||||
"""
|
||||
@spec utc_today(Calendar.calendar()) :: t
|
||||
def utc_today(calendar \\ Calendar.ISO)
|
||||
|
||||
def utc_today(Calendar.ISO) do
|
||||
{:ok, {year, month, day}, _, _} = Calendar.ISO.from_unix(System.os_time(), :native)
|
||||
%Date{year: year, month: month, day: day}
|
||||
end
|
||||
|
||||
def utc_today(calendar) do
|
||||
calendar
|
||||
|> DateTime.utc_now()
|
||||
|> DateTime.to_date()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns true if the year in the given `date` is a leap year.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.leap_year?(~D[2000-01-01])
|
||||
true
|
||||
iex> Date.leap_year?(~D[2001-01-01])
|
||||
false
|
||||
iex> Date.leap_year?(~D[2004-01-01])
|
||||
true
|
||||
iex> Date.leap_year?(~D[1900-01-01])
|
||||
false
|
||||
iex> Date.leap_year?(~N[2004-01-01 01:23:45])
|
||||
true
|
||||
|
||||
"""
|
||||
@spec leap_year?(Calendar.date()) :: boolean()
|
||||
def leap_year?(date)
|
||||
|
||||
def leap_year?(%{calendar: calendar, year: year}) do
|
||||
calendar.leap_year?(year)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the number of days in the given `date` month.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.days_in_month(~D[1900-01-13])
|
||||
31
|
||||
iex> Date.days_in_month(~D[1900-02-09])
|
||||
28
|
||||
iex> Date.days_in_month(~N[2000-02-20 01:23:45])
|
||||
29
|
||||
|
||||
"""
|
||||
@spec days_in_month(Calendar.date()) :: Calendar.day()
|
||||
def days_in_month(date)
|
||||
|
||||
def days_in_month(%{calendar: calendar, year: year, month: month}) do
|
||||
calendar.days_in_month(year, month)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a new ISO date.
|
||||
|
||||
Expects all values to be integers. Returns `{:ok, date}` if each
|
||||
entry fits its appropriate range, returns `{:error, reason}` otherwise.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.new(2000, 1, 1)
|
||||
{:ok, ~D[2000-01-01]}
|
||||
iex> Date.new(2000, 13, 1)
|
||||
{:error, :invalid_date}
|
||||
iex> Date.new(2000, 2, 29)
|
||||
{:ok, ~D[2000-02-29]}
|
||||
|
||||
iex> Date.new(2000, 2, 30)
|
||||
{:error, :invalid_date}
|
||||
iex> Date.new(2001, 2, 29)
|
||||
{:error, :invalid_date}
|
||||
|
||||
"""
|
||||
@spec new(Calendar.year(), Calendar.month(), Calendar.day(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, atom}
|
||||
def new(year, month, day, calendar \\ Calendar.ISO) do
|
||||
if calendar.valid_date?(year, month, day) do
|
||||
{:ok, %Date{year: year, month: month, day: day, calendar: calendar}}
|
||||
else
|
||||
{:error, :invalid_date}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given date to a string according to its calendar.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> Date.to_string(~D[2000-02-28])
|
||||
"2000-02-28"
|
||||
iex> Date.to_string(~N[2000-02-28 01:23:45])
|
||||
"2000-02-28"
|
||||
|
||||
"""
|
||||
@spec to_string(Calendar.date()) :: String.t()
|
||||
def to_string(date)
|
||||
|
||||
def to_string(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.date_to_string(year, month, day)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Dates" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.from_iso8601("2015-01-23")
|
||||
{:ok, ~D[2015-01-23]}
|
||||
|
||||
iex> Date.from_iso8601("2015:01:23")
|
||||
{:error, :invalid_format}
|
||||
|
||||
iex> Date.from_iso8601("2015-01-32")
|
||||
{:error, :invalid_date}
|
||||
|
||||
"""
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes>>, calendar) do
|
||||
with {year, ""} <- Integer.parse(year),
|
||||
{month, ""} <- Integer.parse(month),
|
||||
{day, ""} <- Integer.parse(day) do
|
||||
with {:ok, date} <- new(year, month, day, Calendar.ISO), do: convert(date, calendar)
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
def from_iso8601(<<_::binary>>, _calendar) do
|
||||
{:error, :invalid_format}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Dates" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Raises if the format is invalid.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.from_iso8601!("2015-01-23")
|
||||
~D[2015-01-23]
|
||||
iex> Date.from_iso8601!("2015:01:23")
|
||||
** (ArgumentError) cannot parse "2015:01:23" as date, reason: :invalid_format
|
||||
"""
|
||||
@spec from_iso8601!(String.t(), Calendar.calendar()) :: t
|
||||
def from_iso8601!(string, calendar \\ Calendar.ISO) do
|
||||
case from_iso8601(string, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError, "cannot parse #{inspect(string)} as date, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `date` to
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
By default, `Date.to_iso8601/2` returns dates formatted in the "extended"
|
||||
format, for human readability. It also supports the "basic" format through passing the `:basic` option.
|
||||
|
||||
Only supports converting dates which are in the ISO calendar,
|
||||
or other calendars in which the days also start at midnight.
|
||||
Attempting to convert dates from other calendars will raise an `ArgumentError`.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> Date.to_iso8601(~D[2000-02-28])
|
||||
"2000-02-28"
|
||||
|
||||
iex> Date.to_iso8601(~D[2000-02-28], :basic)
|
||||
"20000228"
|
||||
|
||||
iex> Date.to_iso8601(~N[2000-02-28 00:00:00])
|
||||
"2000-02-28"
|
||||
|
||||
"""
|
||||
@spec to_iso8601(Calendar.date(), :extended | :basic) :: String.t()
|
||||
def to_iso8601(date, format \\ :extended) when format in [:basic, :extended] do
|
||||
%{year: year, month: month, day: day} = convert!(date, Calendar.ISO)
|
||||
Calendar.ISO.date_to_iso8601(year, month, day, format)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `date` to an Erlang date tuple.
|
||||
|
||||
Only supports converting dates which are in the ISO calendar,
|
||||
or other calendars in which the days also start at midnight.
|
||||
Attempting to convert dates from other calendars will raise.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.to_erl(~D[2000-01-01])
|
||||
{2000, 1, 1}
|
||||
|
||||
iex> Date.to_erl(~N[2000-01-01 00:00:00])
|
||||
{2000, 1, 1}
|
||||
|
||||
"""
|
||||
@spec to_erl(Calendar.date()) :: :calendar.date()
|
||||
def to_erl(date) do
|
||||
%{year: year, month: month, day: day} = convert!(date, Calendar.ISO)
|
||||
{year, month, day}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts an Erlang date tuple to a `Date` struct.
|
||||
|
||||
Only supports converting dates which are in the ISO calendar,
|
||||
or other calendars in which the days also start at midnight.
|
||||
Attempting to convert dates from other calendars will return an error tuple.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.from_erl({2000, 1, 1})
|
||||
{:ok, ~D[2000-01-01]}
|
||||
iex> Date.from_erl({2000, 13, 1})
|
||||
{:error, :invalid_date}
|
||||
|
||||
"""
|
||||
@spec from_erl(:calendar.date(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_erl(tuple, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_erl({year, month, day}, calendar) do
|
||||
with {:ok, date} <- new(year, month, day, Calendar.ISO), do: convert(date, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts an Erlang date tuple but raises for invalid dates.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.from_erl!({2000, 1, 1})
|
||||
~D[2000-01-01]
|
||||
iex> Date.from_erl!({2000, 13, 1})
|
||||
** (ArgumentError) cannot convert {2000, 13, 1} to date, reason: :invalid_date
|
||||
|
||||
"""
|
||||
@spec from_erl!(:calendar.date(), Calendar.calendar()) :: t
|
||||
def from_erl!(tuple, calendar \\ Calendar.ISO) do
|
||||
case from_erl(tuple, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(tuple)} to date, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares two date structs.
|
||||
|
||||
Returns `:gt` if first date is later than the second
|
||||
and `:lt` for vice versa. If the two dates are equal
|
||||
`:eq` is returned.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.compare(~D[2016-04-16], ~D[2016-04-28])
|
||||
:lt
|
||||
|
||||
This function can also be used to compare across more
|
||||
complex calendar types by considering only the date fields:
|
||||
|
||||
iex> Date.compare(~D[2016-04-16], ~N[2016-04-28 01:23:45])
|
||||
:lt
|
||||
iex> Date.compare(~D[2016-04-16], ~N[2016-04-16 01:23:45])
|
||||
:eq
|
||||
iex> Date.compare(~N[2016-04-16 12:34:56], ~N[2016-04-16 01:23:45])
|
||||
:eq
|
||||
|
||||
"""
|
||||
@spec compare(Calendar.date(), Calendar.date()) :: :lt | :eq | :gt
|
||||
def compare(%{calendar: calendar} = date1, %{calendar: calendar} = date2) do
|
||||
%{year: year1, month: month1, day: day1} = date1
|
||||
%{year: year2, month: month2, day: day2} = date2
|
||||
|
||||
case {{year1, month1, day1}, {year2, month2, day2}} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
_ -> :eq
|
||||
end
|
||||
end
|
||||
|
||||
def compare(date1, date2) do
|
||||
if Calendar.compatible_calendars?(date1.calendar, date2.calendar) do
|
||||
case {to_iso_days(date1), to_iso_days(date2)} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
_ -> :eq
|
||||
end
|
||||
else
|
||||
raise ArgumentError, """
|
||||
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`s) to resolve this ambiguity
|
||||
"""
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `date` from its calendar to the given `calendar`.
|
||||
|
||||
Returns `{:ok, date}` if the calendars are compatible,
|
||||
or `{:error, :incompatible_calendars}` if they are not.
|
||||
|
||||
See also `Calendar.compatible_calendars?/2`.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> Date.convert(~D[2000-01-01], Calendar.Holocene)
|
||||
{:ok, %Date{calendar: Calendar.Holocene, year: 12000, month: 1, day: 1}}
|
||||
|
||||
"""
|
||||
@spec convert(Calendar.date(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, :incompatible_calendars}
|
||||
def convert(%{calendar: calendar, year: year, month: month, day: day}, calendar) do
|
||||
{:ok, %Date{calendar: calendar, year: year, month: month, day: day}}
|
||||
end
|
||||
|
||||
def convert(%{calendar: calendar} = date, target_calendar) do
|
||||
if Calendar.compatible_calendars?(calendar, target_calendar) do
|
||||
result_date =
|
||||
date
|
||||
|> to_iso_days()
|
||||
|> from_iso_days(target_calendar)
|
||||
|
||||
{:ok, result_date}
|
||||
else
|
||||
{:error, :incompatible_calendars}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Similar to `Date.convert/2`, but raises an `ArgumentError`
|
||||
if the conversion between the two calendars is not possible.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> Date.convert!(~D[2000-01-01], Calendar.Holocene)
|
||||
%Date{calendar: Calendar.Holocene, year: 12000, month: 1, day: 1}
|
||||
|
||||
"""
|
||||
@spec convert!(Calendar.date(), Calendar.calendar()) :: t
|
||||
def convert!(date, calendar) do
|
||||
case convert(date, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(date)} to target calendar #{inspect(calendar)}, " <>
|
||||
"reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds the number of days to the given `date`.
|
||||
|
||||
The days are counted as Gregorian days. The date is returned in the same
|
||||
calendar as it was given in.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.add(~D[2000-01-03], -2)
|
||||
~D[2000-01-01]
|
||||
iex> Date.add(~D[2000-01-01], 2)
|
||||
~D[2000-01-03]
|
||||
|
||||
iex> Date.add(~N[2000-01-01 09:00:00], 2)
|
||||
~D[2000-01-03]
|
||||
|
||||
"""
|
||||
@spec add(Calendar.date(), integer()) :: t
|
||||
def add(%{calendar: calendar} = date, days) do
|
||||
{iso_days, fraction} = to_iso_days(date)
|
||||
from_iso_days({iso_days + days, fraction}, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the difference between two dates, in a full number of days.
|
||||
|
||||
It returns the number of Gregorian days between the dates. Only `Date`
|
||||
structs that follow the same or compatible calendars can be compared
|
||||
this way. If two calendars are not compatible, it will raise.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.diff(~D[2000-01-03], ~D[2000-01-01])
|
||||
2
|
||||
iex> Date.diff(~D[2000-01-01], ~D[2000-01-03])
|
||||
-2
|
||||
|
||||
iex> Date.diff(~D[2000-01-01], ~N[2000-01-03 09:00:00])
|
||||
-2
|
||||
|
||||
"""
|
||||
@spec diff(Calendar.date(), Calendar.date()) :: integer
|
||||
def diff(%{calendar: Calendar.ISO} = date1, %{calendar: Calendar.ISO} = date2) do
|
||||
%{year: year1, month: month1, day: day1} = date1
|
||||
%{year: year2, month: month2, day: day2} = date2
|
||||
|
||||
Calendar.ISO.date_to_iso_days(year1, month1, day1) -
|
||||
Calendar.ISO.date_to_iso_days(year2, month2, day2)
|
||||
end
|
||||
|
||||
def diff(%{calendar: calendar1} = date1, %{calendar: calendar2} = date2) do
|
||||
if Calendar.compatible_calendars?(calendar1, calendar2) do
|
||||
{days1, _} = to_iso_days(date1)
|
||||
{days2, _} = to_iso_days(date2)
|
||||
days1 - days2
|
||||
else
|
||||
raise ArgumentError,
|
||||
"cannot calculate the difference between #{inspect(date1)} and #{inspect(date2)} because their calendars are not compatible and thus the result would be ambiguous"
|
||||
end
|
||||
end
|
||||
|
||||
defp to_iso_days(%{calendar: Calendar.ISO, year: year, month: month, day: day}) do
|
||||
{Calendar.ISO.date_to_iso_days(year, month, day), {0, 86_400_000_000}}
|
||||
end
|
||||
|
||||
defp to_iso_days(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.naive_datetime_to_iso_days(year, month, day, 0, 0, 0, {0, 0})
|
||||
end
|
||||
|
||||
defp from_iso_days({days, _}, Calendar.ISO) do
|
||||
{year, month, day} = Calendar.ISO.date_from_iso_days(days)
|
||||
%Date{year: year, month: month, day: day, calendar: Calendar.ISO}
|
||||
end
|
||||
|
||||
defp from_iso_days(iso_days, target_calendar) do
|
||||
{year, month, day, _, _, _, _} = target_calendar.naive_datetime_from_iso_days(iso_days)
|
||||
%Date{year: year, month: month, day: day, calendar: target_calendar}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Calculates the day of the week of a given `date`.
|
||||
|
||||
Returns the day of the week as an integer. For the ISO 8601
|
||||
calendar (the default), it is an integer from 1 to 7, where
|
||||
1 is Monday and 7 is Sunday.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Date.day_of_week(~D[2016-10-31])
|
||||
1
|
||||
iex> Date.day_of_week(~D[2016-11-01])
|
||||
2
|
||||
iex> Date.day_of_week(~N[2016-11-01 01:23:45])
|
||||
2
|
||||
|
||||
"""
|
||||
@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
|
||||
|
||||
## Helpers
|
||||
|
||||
defimpl String.Chars do
|
||||
def to_string(%{calendar: calendar, year: year, month: month, day: day}) do
|
||||
calendar.date_to_string(year, month, day)
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(%{calendar: Calendar.ISO, year: year, month: month, day: day}, _) do
|
||||
"~D[" <> Calendar.ISO.date_to_string(year, month, day) <> "]"
|
||||
end
|
||||
|
||||
def inspect(date, opts) do
|
||||
Inspect.Any.inspect(date, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,130 +0,0 @@
|
||||
defmodule Date.Range do
|
||||
@moduledoc """
|
||||
Returns an inclusive range between dates.
|
||||
|
||||
Ranges must be created with the `Date.range/2` function.
|
||||
|
||||
The following fields are public:
|
||||
|
||||
* `:first` - the initial date on the range
|
||||
* `:last` - the last date on the range
|
||||
|
||||
The remaining fields are private and should not be accessed.
|
||||
"""
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
first: Date.t(),
|
||||
last: Date.t(),
|
||||
first_in_iso_days: Calendar.iso_days(),
|
||||
last_in_iso_days: Calendar.iso_days()
|
||||
}
|
||||
|
||||
defstruct [:first, :last, :first_in_iso_days, :last_in_iso_days]
|
||||
|
||||
defimpl Enumerable do
|
||||
def member?(%{first: %{calendar: calendar}} = range, %Date{calendar: calendar} = date) do
|
||||
%{
|
||||
first: first,
|
||||
last: last,
|
||||
first_in_iso_days: first_in_iso_days,
|
||||
last_in_iso_days: last_in_iso_days
|
||||
} = range
|
||||
|
||||
%{year: first_year, month: first_month, day: first_day} = first
|
||||
%{year: last_year, month: last_month, day: last_day} = last
|
||||
%{year: year, month: month, day: day} = date
|
||||
first = {first_year, first_month, first_day}
|
||||
last = {last_year, last_month, last_day}
|
||||
date = {year, month, day}
|
||||
|
||||
if first_in_iso_days <= last_in_iso_days do
|
||||
{:ok, date >= first and date <= last}
|
||||
else
|
||||
{:ok, date >= last and date <= first}
|
||||
end
|
||||
end
|
||||
|
||||
def member?(_, _) do
|
||||
{:ok, false}
|
||||
end
|
||||
|
||||
def count(%{first_in_iso_days: first, last_in_iso_days: last}) do
|
||||
{:ok, abs(first - last) + 1}
|
||||
end
|
||||
|
||||
def slice(range) do
|
||||
%{
|
||||
first_in_iso_days: first,
|
||||
last_in_iso_days: last,
|
||||
first: %{calendar: calendar}
|
||||
} = range
|
||||
|
||||
if first <= last do
|
||||
{:ok, last - first + 1, &slice_asc(first + &1, &2, calendar)}
|
||||
else
|
||||
{:ok, first - last + 1, &slice_desc(first - &1, &2, calendar)}
|
||||
end
|
||||
end
|
||||
|
||||
defp slice_asc(current, 1, calendar), do: [date_from_iso_days(current, calendar)]
|
||||
|
||||
defp slice_asc(current, remaining, calendar) do
|
||||
[date_from_iso_days(current, calendar) | slice_asc(current + 1, remaining - 1, calendar)]
|
||||
end
|
||||
|
||||
defp slice_desc(current, 1, calendar), do: [date_from_iso_days(current, calendar)]
|
||||
|
||||
defp slice_desc(current, remaining, calendar) do
|
||||
[date_from_iso_days(current, calendar) | slice_desc(current - 1, remaining - 1, calendar)]
|
||||
end
|
||||
|
||||
def reduce(range, acc, fun) do
|
||||
%{
|
||||
first_in_iso_days: first_in_iso_days,
|
||||
last_in_iso_days: last_in_iso_days,
|
||||
first: %{calendar: calendar}
|
||||
} = range
|
||||
|
||||
up? = first_in_iso_days <= last_in_iso_days
|
||||
reduce(first_in_iso_days, last_in_iso_days, acc, fun, calendar, up?)
|
||||
end
|
||||
|
||||
defp reduce(_x, _y, {:halt, acc}, _fun, _calendar, _up?) do
|
||||
{:halted, acc}
|
||||
end
|
||||
|
||||
defp reduce(x, y, {:suspend, acc}, fun, calendar, up?) do
|
||||
{:suspended, acc, &reduce(x, y, &1, fun, calendar, up?)}
|
||||
end
|
||||
|
||||
defp reduce(x, y, {:cont, acc}, fun, calendar, up? = true) when x <= y do
|
||||
reduce(x + 1, y, fun.(date_from_iso_days(x, calendar), acc), fun, calendar, up?)
|
||||
end
|
||||
|
||||
defp reduce(x, y, {:cont, acc}, fun, calendar, up? = false) when x >= y do
|
||||
reduce(x - 1, y, fun.(date_from_iso_days(x, calendar), acc), fun, calendar, up?)
|
||||
end
|
||||
|
||||
defp reduce(_, _, {:cont, acc}, _fun, _calendar, _up) do
|
||||
{:done, acc}
|
||||
end
|
||||
|
||||
defp date_from_iso_days(days, Calendar.ISO) do
|
||||
{year, month, day} = Calendar.ISO.date_from_iso_days(days)
|
||||
%Date{year: year, month: month, day: day, calendar: Calendar.ISO}
|
||||
end
|
||||
|
||||
defp date_from_iso_days(days, calendar) do
|
||||
{year, month, day, _, _, _, _} =
|
||||
calendar.naive_datetime_from_iso_days({days, {0, 86_400_000_000}})
|
||||
|
||||
%Date{year: year, month: month, day: day, calendar: calendar}
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(%Date.Range{first: first, last: last}, _) do
|
||||
"#DateRange<" <> inspect(first) <> ", " <> inspect(last) <> ">"
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,949 +0,0 @@
|
||||
defmodule DateTime do
|
||||
@moduledoc """
|
||||
A datetime implementation with a time zone.
|
||||
|
||||
This datetime can be seen as an ephemeral snapshot
|
||||
of a datetime at a given time zone. For such purposes,
|
||||
it also includes both UTC and Standard offsets, as
|
||||
well as the zone abbreviation field used exclusively
|
||||
for formatting purposes.
|
||||
|
||||
Remember, comparisons in Elixir using `==`, `>`, `<` and friends
|
||||
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 3rd party calendar libraries.
|
||||
|
||||
## Where are my functions?
|
||||
|
||||
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
|
||||
TimeZone database which currently is not provided as part
|
||||
of Elixir.
|
||||
|
||||
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] ++
|
||||
[:time_zone, :zone_abbr, :utc_offset, :std_offset]
|
||||
|
||||
defstruct [
|
||||
:year,
|
||||
:month,
|
||||
:day,
|
||||
:hour,
|
||||
:minute,
|
||||
:second,
|
||||
:time_zone,
|
||||
:zone_abbr,
|
||||
:utc_offset,
|
||||
:std_offset,
|
||||
microsecond: {0, 0},
|
||||
calendar: Calendar.ISO
|
||||
]
|
||||
|
||||
@type t :: %__MODULE__{
|
||||
year: Calendar.year(),
|
||||
month: Calendar.month(),
|
||||
day: Calendar.day(),
|
||||
calendar: Calendar.calendar(),
|
||||
hour: Calendar.hour(),
|
||||
minute: Calendar.minute(),
|
||||
second: Calendar.second(),
|
||||
microsecond: Calendar.microsecond(),
|
||||
time_zone: Calendar.time_zone(),
|
||||
zone_abbr: Calendar.zone_abbr(),
|
||||
utc_offset: Calendar.utc_offset(),
|
||||
std_offset: Calendar.std_offset()
|
||||
}
|
||||
|
||||
@unix_days :calendar.date_to_gregorian_days({1970, 1, 1})
|
||||
|
||||
@doc """
|
||||
Returns the current datetime in UTC.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> datetime = DateTime.utc_now()
|
||||
iex> datetime.time_zone
|
||||
"Etc/UTC"
|
||||
|
||||
"""
|
||||
@spec utc_now(Calendar.calendar()) :: t
|
||||
def utc_now(calendar \\ Calendar.ISO) do
|
||||
System.os_time() |> from_unix!(:native, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given Unix time to `DateTime`.
|
||||
|
||||
The integer can be given in different unit
|
||||
according to `System.convert_time_unit/3` and it will
|
||||
be converted to microseconds internally.
|
||||
|
||||
Unix times are always in UTC and therefore the DateTime
|
||||
will be returned in UTC.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_unix(1464096368)
|
||||
iex> datetime
|
||||
#DateTime<2016-05-24 13:26:08Z>
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_unix(1432560368868569, :microsecond)
|
||||
iex> datetime
|
||||
#DateTime<2015-05-25 13:26:08.868569Z>
|
||||
|
||||
The unit can also be an integer as in `t:System.time_unit/0`:
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_unix(143256036886856, 1024)
|
||||
iex> datetime
|
||||
#DateTime<6403-03-17 07:05:22.320Z>
|
||||
|
||||
Negative Unix times are supported, up to -62167219200 seconds,
|
||||
which is equivalent to "0000-01-01T00:00:00Z" or 0 Gregorian seconds.
|
||||
"""
|
||||
@spec from_unix(integer, :native | System.time_unit(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, atom}
|
||||
def from_unix(integer, unit \\ :second, calendar \\ Calendar.ISO) when is_integer(integer) do
|
||||
case Calendar.ISO.from_unix(integer, unit) do
|
||||
{:ok, {year, month, day}, {hour, minute, second}, microsecond} ->
|
||||
iso_datetime = %DateTime{
|
||||
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"
|
||||
}
|
||||
|
||||
convert(iso_datetime, calendar)
|
||||
|
||||
{:error, _} = error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given Unix time to `DateTime`.
|
||||
|
||||
The integer can be given in different unit
|
||||
according to `System.convert_time_unit/3` and it will
|
||||
be converted to microseconds internally.
|
||||
|
||||
Unix times are always in UTC and therefore the DateTime
|
||||
will be returned in UTC.
|
||||
|
||||
## Examples
|
||||
|
||||
# An easy way to get the Unix epoch is passing 0 to this function
|
||||
iex> DateTime.from_unix!(0)
|
||||
#DateTime<1970-01-01 00:00:00Z>
|
||||
|
||||
iex> DateTime.from_unix!(1464096368)
|
||||
#DateTime<2016-05-24 13:26:08Z>
|
||||
|
||||
iex> DateTime.from_unix!(1432560368868569, :microsecond)
|
||||
#DateTime<2015-05-25 13:26:08.868569Z>
|
||||
|
||||
"""
|
||||
@spec from_unix!(integer, :native | System.time_unit(), Calendar.calendar()) :: t
|
||||
def from_unix!(integer, unit \\ :second, calendar \\ Calendar.ISO) when is_atom(unit) do
|
||||
case from_unix(integer, unit, calendar) do
|
||||
{:ok, datetime} ->
|
||||
datetime
|
||||
|
||||
{:error, :invalid_unix_time} ->
|
||||
raise ArgumentError, "invalid Unix time #{integer}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `NaiveDateTime` to `DateTime`.
|
||||
|
||||
It expects a time zone to put the NaiveDateTime in.
|
||||
Currently it only supports "Etc/UTC" as time zone.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> {:ok, datetime} = DateTime.from_naive(~N[2016-05-24 13:26:08.003], "Etc/UTC")
|
||||
iex> datetime
|
||||
#DateTime<2016-05-24 13:26:08.003Z>
|
||||
|
||||
"""
|
||||
@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,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day
|
||||
} = naive_datetime
|
||||
|
||||
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}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `NaiveDateTime` to `DateTime`.
|
||||
|
||||
It expects a time zone to put the NaiveDateTime in.
|
||||
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>
|
||||
|
||||
"""
|
||||
@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
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot parse #{inspect(naive_datetime)} to datetime, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `datetime` to Unix time.
|
||||
|
||||
The `datetime` is expected to be using the ISO calendar
|
||||
with a year greater than or equal to 0.
|
||||
|
||||
It will return the integer with the given unit,
|
||||
according to `System.convert_time_unit/3`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> 1464096368 |> DateTime.from_unix!() |> DateTime.to_unix()
|
||||
1464096368
|
||||
|
||||
iex> dt = %DateTime{calendar: Calendar.ISO, day: 20, hour: 18, microsecond: {273806, 6},
|
||||
...> minute: 58, month: 11, second: 19, time_zone: "America/Montevideo",
|
||||
...> utc_offset: -10800, std_offset: 3600, year: 2014, zone_abbr: "UYST"}
|
||||
iex> DateTime.to_unix(dt)
|
||||
1416517099
|
||||
|
||||
iex> flamel = %DateTime{calendar: Calendar.ISO, day: 22, hour: 8, microsecond: {527771, 6},
|
||||
...> minute: 2, month: 3, second: 25, std_offset: 0, time_zone: "Etc/UTC",
|
||||
...> utc_offset: 0, year: 1418, zone_abbr: "UTC"}
|
||||
iex> DateTime.to_unix(flamel)
|
||||
-17412508655
|
||||
|
||||
"""
|
||||
@spec to_unix(Calendar.datetime(), System.time_unit()) :: integer
|
||||
def to_unix(datetime, unit \\ :second)
|
||||
|
||||
def to_unix(%{utc_offset: utc_offset, std_offset: std_offset} = datetime, unit) do
|
||||
{days, fraction} = to_iso_days(datetime)
|
||||
unix_units = Calendar.ISO.iso_days_to_unit({days - @unix_days, fraction}, unit)
|
||||
offset_units = System.convert_time_unit(utc_offset + std_offset, :second, unit)
|
||||
unix_units - offset_units
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `datetime` into a `NaiveDateTime`.
|
||||
|
||||
Because `NaiveDateTime` does not hold time zone information,
|
||||
any time zone related data will be lost during the conversion.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "CET",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 1},
|
||||
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Warsaw"}
|
||||
iex> DateTime.to_naive(dt)
|
||||
~N[2000-02-29 23:00:07.0]
|
||||
|
||||
"""
|
||||
@spec to_naive(t) :: NaiveDateTime.t()
|
||||
def to_naive(%DateTime{} = datetime) do
|
||||
%DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
} = datetime
|
||||
|
||||
%NaiveDateTime{
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
calendar: calendar,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `DateTime` into a `Date`.
|
||||
|
||||
Because `Date` does not hold time nor time zone information,
|
||||
data will be lost during the conversion.
|
||||
|
||||
## Examples
|
||||
|
||||
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> DateTime.to_date(dt)
|
||||
~D[2000-02-29]
|
||||
|
||||
"""
|
||||
@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
|
||||
|
||||
@doc """
|
||||
Converts a `DateTime` into `Time`.
|
||||
|
||||
Because `Time` does not hold date nor time zone information,
|
||||
data will be lost during the conversion.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "CET",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 1},
|
||||
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Warsaw"}
|
||||
iex> DateTime.to_time(dt)
|
||||
~T[23:00:07.0]
|
||||
|
||||
"""
|
||||
@spec to_time(t) :: Time.t()
|
||||
def to_time(%DateTime{} = datetime) do
|
||||
%{hour: hour, minute: minute, second: second, microsecond: microsecond, calendar: calendar} =
|
||||
datetime
|
||||
|
||||
%Time{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given datetime to
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601) format.
|
||||
|
||||
By default, `DateTime.to_iso8601/2` returns datetimes formatted in the "extended"
|
||||
format, for human readability. It also supports the "basic" format through passing the `:basic` option.
|
||||
|
||||
Only supports converting datetimes which are in the ISO calendar,
|
||||
attempting to convert datetimes from other calendars will raise.
|
||||
|
||||
WARNING: the ISO 8601 datetime format does not contain the time zone nor
|
||||
its abbreviation, which means information is lost when converting to such
|
||||
format.
|
||||
|
||||
### Examples
|
||||
|
||||
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> DateTime.to_iso8601(dt)
|
||||
"2000-02-29T23:00:07+01:00"
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "UTC",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: 0, std_offset: 0, time_zone: "Etc/UTC"}
|
||||
iex> DateTime.to_iso8601(dt)
|
||||
"2000-02-29T23:00:07Z"
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
|
||||
iex> DateTime.to_iso8601(dt, :extended)
|
||||
"2000-02-29T23:00:07-04:00"
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
|
||||
iex> DateTime.to_iso8601(dt, :basic)
|
||||
"20000229T230007-0400"
|
||||
|
||||
"""
|
||||
@spec to_iso8601(Calendar.datetime(), :extended | :basic) :: String.t()
|
||||
def to_iso8601(datetime, format \\ :extended)
|
||||
|
||||
def to_iso8601(_, format) when format not in [:extended, :basic] do
|
||||
raise ArgumentError,
|
||||
"DateTime.to_iso8601/2 expects format to be :extended or :basic, got: #{inspect(format)}"
|
||||
end
|
||||
|
||||
def to_iso8601(%{calendar: Calendar.ISO} = datetime, format) do
|
||||
%{
|
||||
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
|
||||
} = datetime
|
||||
|
||||
Calendar.ISO.datetime_to_iso8601(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
time_zone,
|
||||
zone_abbr,
|
||||
utc_offset,
|
||||
std_offset,
|
||||
format
|
||||
)
|
||||
end
|
||||
|
||||
def to_iso8601(%{calendar: _} = datetime, format) do
|
||||
datetime
|
||||
|> convert!(Calendar.ISO)
|
||||
|> to_iso8601(format)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Date and time of day" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Since ISO 8601 does not include the proper time zone, the given
|
||||
string will be converted to UTC and its offset in seconds will be
|
||||
returned as part of this function. Therefore offset information
|
||||
must be present in the string.
|
||||
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
desired as there is no ambiguity within this function.
|
||||
|
||||
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
|
||||
|
||||
iex> {:ok, datetime, 0} = DateTime.from_iso8601("2015-01-23T23:50:07Z")
|
||||
iex> datetime
|
||||
#DateTime<2015-01-23 23:50:07Z>
|
||||
|
||||
iex> {:ok, datetime, 9000} = DateTime.from_iso8601("2015-01-23T23:50:07.123+02:30")
|
||||
iex> datetime
|
||||
#DateTime<2015-01-23 21:20:07.123Z>
|
||||
|
||||
iex> {:ok, datetime, 9000} = DateTime.from_iso8601("2015-01-23T23:50:07,123+02:30")
|
||||
iex> datetime
|
||||
#DateTime<2015-01-23 21:20:07.123Z>
|
||||
|
||||
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}
|
||||
|
||||
"""
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) ::
|
||||
{:ok, t, Calendar.utc_offset()} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO) when is_binary(string) do
|
||||
with <<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, rest::binary>> <- string,
|
||||
true <- sep in [?\s, ?T],
|
||||
<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>> <- rest,
|
||||
{year, ""} <- Integer.parse(year),
|
||||
{month, ""} <- Integer.parse(month),
|
||||
{day, ""} <- Integer.parse(day),
|
||||
{hour, ""} <- Integer.parse(hour),
|
||||
{minute, ""} <- Integer.parse(min),
|
||||
{second, ""} <- Integer.parse(sec),
|
||||
{microsecond, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{:ok, date} <- Date.new(year, month, day),
|
||||
{:ok, time} <- Time.new(hour, minute, second, microsecond),
|
||||
{:ok, offset} <- parse_offset(rest) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
%{hour: hour, minute: minute, second: second, microsecond: microsecond} = time
|
||||
{_, precision} = microsecond
|
||||
|
||||
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)
|
||||
|
||||
{:ok, %{datetime | microsecond: microsecond}, offset}
|
||||
else
|
||||
{:error, reason} -> {:error, reason}
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
defp parse_offset(rest) do
|
||||
case Calendar.ISO.parse_offset(rest) do
|
||||
{offset, ""} when is_integer(offset) -> {:ok, offset}
|
||||
{nil, ""} -> {:error, :missing_offset}
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `datetime` to a string according to its calendar.
|
||||
|
||||
### Examples
|
||||
|
||||
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> DateTime.to_string(dt)
|
||||
"2000-02-29 23:00:07+01:00 CET Europe/Warsaw"
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "UTC",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: 0, std_offset: 0, time_zone: "Etc/UTC"}
|
||||
iex> DateTime.to_string(dt)
|
||||
"2000-02-29 23:00:07Z"
|
||||
|
||||
iex> dt = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
|
||||
iex> DateTime.to_string(dt)
|
||||
"2000-02-29 23:00:07-04:00 AMT America/Manaus"
|
||||
|
||||
"""
|
||||
@spec to_string(Calendar.datetime()) :: String.t()
|
||||
def to_string(%{calendar: calendar} = datetime) do
|
||||
%{
|
||||
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
|
||||
} = datetime
|
||||
|
||||
calendar.datetime_to_string(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
time_zone,
|
||||
zone_abbr,
|
||||
utc_offset,
|
||||
std_offset
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares two datetime structs.
|
||||
|
||||
Returns `:gt` if the first datetime is later than the second
|
||||
and `:lt` for vice versa. If the two datetimes are equal
|
||||
`:eq` is returned.
|
||||
|
||||
Note that both UTC and Standard offsets will be taken into
|
||||
account when comparison is done.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> dt1 = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
|
||||
iex> dt2 = %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> DateTime.compare(dt1, dt2)
|
||||
:gt
|
||||
|
||||
"""
|
||||
@spec compare(Calendar.datetime(), Calendar.datetime()) :: :lt | :eq | :gt
|
||||
def compare(
|
||||
%{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
|
||||
|> to_iso_days()
|
||||
|> apply_tz_offset(utc_offset1 + std_offset1)
|
||||
|
||||
{days2, {parts2, ppd2}} =
|
||||
datetime2
|
||||
|> to_iso_days()
|
||||
|> apply_tz_offset(utc_offset2 + std_offset2)
|
||||
|
||||
# Ensure fraction tuples have same denominator.
|
||||
iso_days1 = {days1, parts1 * ppd2}
|
||||
iso_days2 = {days2, parts2 * ppd1}
|
||||
|
||||
case {iso_days1, iso_days2} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
_ -> :eq
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Subtracts `datetime2` from `datetime1`.
|
||||
|
||||
The answer can be returned in any `unit` available from `t:System.time_unit/0`.
|
||||
|
||||
This function returns the difference in seconds where seconds are measured
|
||||
according to `Calendar.ISO`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> dt1 = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
|
||||
iex> dt2 = %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> DateTime.diff(dt1, dt2)
|
||||
18000
|
||||
iex> DateTime.diff(dt2, dt1)
|
||||
-18000
|
||||
|
||||
"""
|
||||
@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,
|
||||
unit \\ :second
|
||||
) do
|
||||
naive_diff =
|
||||
(datetime1 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(unit)) -
|
||||
(datetime2 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(unit))
|
||||
|
||||
offset_diff = utc_offset2 + std_offset2 - (utc_offset1 + std_offset1)
|
||||
naive_diff + System.convert_time_unit(offset_diff, :second, unit)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the given datetime with the microsecond field truncated to the given
|
||||
precision (`:microsecond`, `millisecond` or `:second`).
|
||||
|
||||
## Examples
|
||||
|
||||
iex> dt1 = %DateTime{year: 2017, month: 11, day: 7, zone_abbr: "CET",
|
||||
...> hour: 11, minute: 45, second: 18, microsecond: {123456, 6},
|
||||
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Paris"}
|
||||
iex> DateTime.truncate(dt1, :microsecond)
|
||||
#DateTime<2017-11-07 11:45:18.123456+01:00 CET Europe/Paris>
|
||||
|
||||
iex> dt2 = %DateTime{year: 2017, month: 11, day: 7, zone_abbr: "CET",
|
||||
...> hour: 11, minute: 45, second: 18, microsecond: {123456, 6},
|
||||
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Paris"}
|
||||
iex> DateTime.truncate(dt2, :millisecond)
|
||||
#DateTime<2017-11-07 11:45:18.123+01:00 CET Europe/Paris>
|
||||
|
||||
iex> dt3 = %DateTime{year: 2017, month: 11, day: 7, zone_abbr: "CET",
|
||||
...> hour: 11, minute: 45, second: 18, microsecond: {123456, 6},
|
||||
...> utc_offset: 3600, std_offset: 0, time_zone: "Europe/Paris"}
|
||||
iex> DateTime.truncate(dt3, :second)
|
||||
#DateTime<2017-11-07 11:45:18+01:00 CET Europe/Paris>
|
||||
|
||||
"""
|
||||
@spec truncate(t(), :microsecond | :millisecond | :second) :: t()
|
||||
def truncate(%DateTime{microsecond: microsecond} = datetime, precision) do
|
||||
%{datetime | microsecond: Calendar.truncate(microsecond, precision)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a given `datetime` from one calendar to another.
|
||||
|
||||
If it is not possible to convert unambiguously between the calendars
|
||||
(see `Calendar.compatible_calendars?/2`), an `{:error, :incompatible_calendars}` tuple
|
||||
is returned.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> dt1 = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
|
||||
iex> DateTime.convert(dt1, Calendar.Holocene)
|
||||
{:ok, %DateTime{calendar: Calendar.Holocene, day: 29, hour: 23,
|
||||
microsecond: {0, 0}, minute: 0, month: 2, second: 7, std_offset: 0,
|
||||
time_zone: "America/Manaus", utc_offset: -14400, year: 12000,
|
||||
zone_abbr: "AMT"}}
|
||||
|
||||
"""
|
||||
@spec convert(Calendar.datetime(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, :incompatible_calendars}
|
||||
|
||||
# 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
|
||||
}
|
||||
|
||||
{:ok, datetime}
|
||||
end
|
||||
|
||||
def convert(%{calendar: dt_calendar, microsecond: {_, precision}} = datetime, calendar) do
|
||||
if Calendar.compatible_calendars?(dt_calendar, calendar) do
|
||||
result_datetime =
|
||||
datetime
|
||||
|> to_iso_days
|
||||
|> from_iso_days(datetime, calendar, precision)
|
||||
|
||||
{:ok, result_datetime}
|
||||
else
|
||||
{:error, :incompatible_calendars}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a given `datetime` from one calendar to another.
|
||||
|
||||
If it is not possible to convert unambiguously between the calendars
|
||||
(see `Calendar.compatible_calendars?/2`), an ArgumentError is raised.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> dt1 = %DateTime{year: 2000, month: 2, day: 29, zone_abbr: "AMT",
|
||||
...> hour: 23, minute: 0, second: 7, microsecond: {0, 0},
|
||||
...> utc_offset: -14400, std_offset: 0, time_zone: "America/Manaus"}
|
||||
iex> DateTime.convert!(dt1, Calendar.Holocene)
|
||||
%DateTime{calendar: Calendar.Holocene, day: 29, hour: 23,
|
||||
microsecond: {0, 0}, minute: 0, month: 2, second: 7, std_offset: 0,
|
||||
time_zone: "America/Manaus", utc_offset: -14400, year: 12000,
|
||||
zone_abbr: "AMT"}
|
||||
|
||||
"""
|
||||
@spec convert!(Calendar.datetime(), Calendar.calendar()) :: t | no_return
|
||||
def convert!(datetime, calendar) do
|
||||
case convert(datetime, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, :incompatible_calendars} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(datetime)} to target calendar #{inspect(calendar)}, " <>
|
||||
"reason: #{inspect(datetime.calendar)} and #{inspect(calendar)} have different " <>
|
||||
"day rollover moments, making this conversion ambiguous"
|
||||
end
|
||||
end
|
||||
|
||||
# Keep it multiline for proper function clause errors.
|
||||
defp to_iso_days(%{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}) do
|
||||
calendar.naive_datetime_to_iso_days(year, month, day, hour, minute, second, microsecond)
|
||||
end
|
||||
|
||||
defp from_iso_days(iso_days, datetime, calendar, precision) 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)
|
||||
|
||||
%DateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {microsecond, precision},
|
||||
time_zone: time_zone,
|
||||
zone_abbr: zone_abbr,
|
||||
utc_offset: utc_offset,
|
||||
std_offset: std_offset
|
||||
}
|
||||
end
|
||||
|
||||
defp apply_tz_offset(iso_days, offset) do
|
||||
Calendar.ISO.add_day_fraction_to_iso_days(iso_days, -offset, 86400)
|
||||
end
|
||||
|
||||
defimpl String.Chars do
|
||||
def to_string(datetime) do
|
||||
%{
|
||||
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
|
||||
} = datetime
|
||||
|
||||
calendar.datetime_to_string(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
time_zone,
|
||||
zone_abbr,
|
||||
utc_offset,
|
||||
std_offset
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(%{calendar: Calendar.ISO} = datetime, _) do
|
||||
%{
|
||||
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
|
||||
} = datetime
|
||||
|
||||
"#DateTime<" <>
|
||||
Calendar.ISO.datetime_to_string(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
time_zone,
|
||||
zone_abbr,
|
||||
utc_offset,
|
||||
std_offset
|
||||
) <> ">"
|
||||
end
|
||||
|
||||
def inspect(datetime, opts) do
|
||||
Inspect.Any.inspect(datetime, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
+68
-465
@@ -1,180 +1,20 @@
|
||||
defmodule Calendar.ISO do
|
||||
@moduledoc """
|
||||
A calendar implementation that follows to ISO 8601.
|
||||
A calendar implementation that follows to ISO8601.
|
||||
|
||||
This calendar implements the proleptic Gregorian calendar and
|
||||
is therefore compatible with the calendar used in most countries
|
||||
today. The proleptic means the Gregorian rules for leap years are
|
||||
applied for all time, consequently the dates give different results
|
||||
before the year 1583 from when the Gregorian calendar was adopted.
|
||||
|
||||
Note that while ISO 8601 allows times and datetimes to specify
|
||||
24:00:00 as the zero hour of the next day, this notation is not
|
||||
supported by Elixir.
|
||||
"""
|
||||
|
||||
@behaviour Calendar
|
||||
@unix_epoch :calendar.datetime_to_gregorian_seconds {{1970, 1, 1}, {0, 0, 0}}
|
||||
|
||||
@unix_epoch 62_167_219_200
|
||||
@unix_start 1_000_000 * -@unix_epoch
|
||||
@unix_end 315_569_519_999_999_999 - @unix_epoch * 1_000_000
|
||||
@unix_range_microseconds @unix_start..@unix_end
|
||||
|
||||
@type year :: 0..9999
|
||||
@type year :: 0..9999
|
||||
@type month :: 1..12
|
||||
@type day :: 1..31
|
||||
|
||||
@seconds_per_minute 60
|
||||
@seconds_per_hour 60 * 60
|
||||
# Note that this does _not_ handle leap seconds.
|
||||
@seconds_per_day 24 * 60 * 60
|
||||
@microseconds_per_second 1_000_000
|
||||
@parts_per_day @seconds_per_day * @microseconds_per_second
|
||||
|
||||
@days_per_nonleap_year 365
|
||||
@days_per_leap_year 366
|
||||
|
||||
@doc """
|
||||
Returns the `t:Calendar.iso_days` format of the specified date.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.naive_datetime_to_iso_days(0, 1, 1, 0, 0, 0, {0, 6})
|
||||
{0, {0, 86400000000}}
|
||||
iex> Calendar.ISO.naive_datetime_to_iso_days(2000, 1, 1, 12, 0, 0, {0, 6})
|
||||
{730485, {43200000000, 86400000000}}
|
||||
iex> Calendar.ISO.naive_datetime_to_iso_days(2000, 1, 1, 13, 0, 0, {0, 6})
|
||||
{730485, {46800000000, 86400000000}}
|
||||
|
||||
"""
|
||||
@impl true
|
||||
@spec naive_datetime_to_iso_days(
|
||||
Calendar.year(),
|
||||
Calendar.month(),
|
||||
Calendar.day(),
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond()
|
||||
) :: Calendar.iso_days()
|
||||
def naive_datetime_to_iso_days(year, month, day, hour, minute, second, microsecond) do
|
||||
{date_to_iso_days(year, month, day), time_to_day_fraction(hour, minute, second, microsecond)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the `t:Calendar.iso_days` format to the datetime format specified by this calendar.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.naive_datetime_from_iso_days({0, {0, 86400}})
|
||||
{0, 1, 1, 0, 0, 0, {0, 6}}
|
||||
iex> Calendar.ISO.naive_datetime_from_iso_days({730485, {0, 86400}})
|
||||
{2000, 1, 1, 0, 0, 0, {0, 6}}
|
||||
iex> Calendar.ISO.naive_datetime_from_iso_days({730485, {43200, 86400}})
|
||||
{2000, 1, 1, 12, 0, 0, {0, 6}}
|
||||
|
||||
"""
|
||||
@spec naive_datetime_from_iso_days(Calendar.iso_days()) :: {
|
||||
Calendar.year(),
|
||||
Calendar.month(),
|
||||
Calendar.day(),
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond()
|
||||
}
|
||||
@impl true
|
||||
def naive_datetime_from_iso_days({days, day_fraction}) do
|
||||
{year, month, day} = date_from_iso_days(days)
|
||||
{hour, minute, second, microsecond} = time_from_day_fraction(day_fraction)
|
||||
{year, month, day, hour, minute, second, microsecond}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the normalized day fraction of the specified time.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.time_to_day_fraction(0, 0, 0, {0, 6})
|
||||
{0, 86400000000}
|
||||
iex> Calendar.ISO.time_to_day_fraction(12, 34, 56, {123, 6})
|
||||
{45296000123, 86400000000}
|
||||
|
||||
"""
|
||||
@impl true
|
||||
@spec time_to_day_fraction(
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond()
|
||||
) :: Calendar.day_fraction()
|
||||
def time_to_day_fraction(0, 0, 0, {0, _}) do
|
||||
{0, @parts_per_day}
|
||||
end
|
||||
|
||||
def time_to_day_fraction(hour, minute, second, {microsecond, _}) do
|
||||
combined_seconds = hour * @seconds_per_hour + minute * @seconds_per_minute + second
|
||||
{combined_seconds * @microseconds_per_second + microsecond, @parts_per_day}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a day fraction to this Calendar's representation of time.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Calendar.ISO.time_from_day_fraction({1,2})
|
||||
{12, 0, 0, {0, 6}}
|
||||
iex> Calendar.ISO.time_from_day_fraction({13,24})
|
||||
{13, 0, 0, {0, 6}}
|
||||
|
||||
"""
|
||||
@impl true
|
||||
@spec time_from_day_fraction(Calendar.day_fraction()) ::
|
||||
{Calendar.hour(), Calendar.minute(), Calendar.second(), Calendar.microsecond()}
|
||||
def time_from_day_fraction({parts_in_day, parts_per_day}) do
|
||||
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)
|
||||
|
||||
{minutes, rest_microseconds2} =
|
||||
div_mod(rest_microseconds1, @seconds_per_minute * @microseconds_per_second)
|
||||
|
||||
{seconds, microseconds} = div_mod(rest_microseconds2, @microseconds_per_second)
|
||||
{hours, minutes, seconds, {microseconds, 6}}
|
||||
end
|
||||
|
||||
# Converts year, month, day to count of days since 0000-01-01.
|
||||
@doc false
|
||||
def date_to_iso_days(0, 1, 1) do
|
||||
0
|
||||
end
|
||||
|
||||
def date_to_iso_days(1970, 1, 1) do
|
||||
719_528
|
||||
end
|
||||
|
||||
def date_to_iso_days(year, month, day) when year in 0..9999 do
|
||||
true = day <= days_in_month(year, month)
|
||||
|
||||
days_in_previous_years(year) + days_before_month(month) + leap_day_offset(year, month) + day -
|
||||
1
|
||||
end
|
||||
|
||||
# Converts count of days since 0000-01-01 to {year, month, day} tuple.
|
||||
@doc false
|
||||
def date_from_iso_days(days) when days in 0..3_652_424 do
|
||||
{year, day_of_year} = days_to_year(days)
|
||||
extra_day = if leap_year?(year), do: 1, else: 0
|
||||
{month, day_in_month} = year_day_to_year_date(extra_day, day_of_year)
|
||||
{year, month, day_in_month + 1}
|
||||
end
|
||||
|
||||
defp div_mod(int1, int2) do
|
||||
div = div(int1, int2)
|
||||
mod = int1 - div * int2
|
||||
{div, mod}
|
||||
end
|
||||
@type day :: 1..31
|
||||
|
||||
@doc """
|
||||
Returns how many days there are in the given year-month.
|
||||
@@ -196,13 +36,11 @@ defmodule Calendar.ISO do
|
||||
|
||||
"""
|
||||
@spec days_in_month(year, month) :: 28..31
|
||||
@impl true
|
||||
def days_in_month(year, month)
|
||||
|
||||
def days_in_month(year, 2) do
|
||||
if leap_year?(year), do: 29, else: 28
|
||||
end
|
||||
|
||||
def days_in_month(_, month) when month in [4, 6, 9, 11], do: 30
|
||||
def days_in_month(_, month) when month in 1..12, do: 31
|
||||
|
||||
@@ -222,7 +60,6 @@ defmodule Calendar.ISO do
|
||||
|
||||
"""
|
||||
@spec leap_year?(year) :: boolean()
|
||||
@impl true
|
||||
def leap_year?(year) when is_integer(year) and year >= 0 do
|
||||
rem(year, 4) === 0 and (rem(year, 100) > 0 or rem(year, 400) === 0)
|
||||
end
|
||||
@@ -250,57 +87,21 @@ defmodule Calendar.ISO do
|
||||
7
|
||||
"""
|
||||
@spec day_of_week(year, month, day) :: 1..7
|
||||
@impl true
|
||||
def day_of_week(year, month, day)
|
||||
when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
Integer.mod(date_to_iso_days(year, month, day) + 5, 7) + 1
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given time into a string.
|
||||
"""
|
||||
@impl true
|
||||
def time_to_string(hour, minute, second, microsecond) do
|
||||
time_to_string(hour, minute, second, microsecond, :extended)
|
||||
end
|
||||
|
||||
def time_to_string(hour, minute, second, {_, 0}, format) do
|
||||
time_to_string_format(hour, minute, second, format)
|
||||
end
|
||||
|
||||
def time_to_string(hour, minute, second, {microsecond, precision}, format) do
|
||||
time_to_string_format(hour, minute, second, format) <>
|
||||
"." <> (microsecond |> zero_pad(6) |> binary_part(0, precision))
|
||||
end
|
||||
|
||||
defp time_to_string_format(hour, minute, second, :extended) do
|
||||
zero_pad(hour, 2) <> ":" <> zero_pad(minute, 2) <> ":" <> zero_pad(second, 2)
|
||||
end
|
||||
|
||||
defp time_to_string_format(hour, minute, second, :basic) do
|
||||
zero_pad(hour, 2) <> zero_pad(minute, 2) <> zero_pad(second, 2)
|
||||
:calendar.day_of_the_week(year, month, day)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given date into a string.
|
||||
"""
|
||||
@impl true
|
||||
def date_to_string(year, month, day) do
|
||||
date_to_string(year, month, day, :extended)
|
||||
end
|
||||
|
||||
defp date_to_string(year, month, day, :extended) do
|
||||
zero_pad(year, 4) <> "-" <> zero_pad(month, 2) <> "-" <> zero_pad(day, 2)
|
||||
end
|
||||
|
||||
defp date_to_string(year, month, day, :basic) do
|
||||
zero_pad(year, 4) <> zero_pad(month, 2) <> zero_pad(day, 2)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the datetime (without time zone) into a string.
|
||||
"""
|
||||
@impl true
|
||||
def naive_datetime_to_string(year, month, day, hour, minute, second, microsecond) do
|
||||
date_to_string(year, month, day) <> " " <> time_to_string(hour, minute, second, microsecond)
|
||||
end
|
||||
@@ -308,62 +109,23 @@ defmodule Calendar.ISO do
|
||||
@doc """
|
||||
Convers the datetime (with time zone) into a string.
|
||||
"""
|
||||
@impl true
|
||||
def datetime_to_string(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
time_zone,
|
||||
zone_abbr,
|
||||
utc_offset,
|
||||
std_offset
|
||||
) do
|
||||
date_to_string(year, month, day) <>
|
||||
" " <>
|
||||
def datetime_to_string(year, month, day, hour, minute, second, microsecond,
|
||||
time_zone, zone_abbr, utc_offset, std_offset) do
|
||||
date_to_string(year, month, day) <> " " <>
|
||||
time_to_string(hour, minute, second, microsecond) <>
|
||||
offset_to_string(utc_offset, std_offset, time_zone) <>
|
||||
zone_to_string(utc_offset, std_offset, zone_abbr, time_zone)
|
||||
end
|
||||
|
||||
@impl true
|
||||
def valid_date?(year, month, day) do
|
||||
month in 1..12 and year in 0..9999 and day in 1..days_in_month(year, month)
|
||||
end
|
||||
|
||||
@impl true
|
||||
def valid_time?(hour, minute, second, {microsecond, precision}) do
|
||||
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
|
||||
|
||||
@impl true
|
||||
def day_rollover_relative_to_midnight_utc() do
|
||||
{0, 1}
|
||||
end
|
||||
|
||||
defp offset_to_string(utc, std, zone, format \\ :extended)
|
||||
defp offset_to_string(0, 0, "Etc/UTC", _format), do: "Z"
|
||||
|
||||
defp offset_to_string(utc, std, _zone, format) do
|
||||
total = utc + std
|
||||
defp offset_to_string(0, 0, "Etc/UTC"), do: "Z"
|
||||
defp offset_to_string(utc, std, _zone) do
|
||||
total = utc + std
|
||||
second = abs(total)
|
||||
minute = second |> rem(3600) |> div(60)
|
||||
hour = div(second, 3600)
|
||||
format_offset(total, hour, minute, format)
|
||||
end
|
||||
|
||||
defp format_offset(total, hour, minute, :extended) do
|
||||
hour = second |> div(3600)
|
||||
sign(total) <> zero_pad(hour, 2) <> ":" <> zero_pad(minute, 2)
|
||||
end
|
||||
|
||||
defp format_offset(total, hour, minute, :basic) do
|
||||
sign(total) <> zero_pad(hour, 2) <> zero_pad(minute, 2)
|
||||
end
|
||||
|
||||
defp zone_to_string(0, 0, _abbr, "Etc/UTC"), do: ""
|
||||
defp zone_to_string(_, _, abbr, zone), do: " " <> abbr <> " " <> zone
|
||||
|
||||
@@ -377,76 +139,73 @@ defmodule Calendar.ISO do
|
||||
|
||||
## Helpers
|
||||
|
||||
@doc false
|
||||
def time_to_string(hour, minute, second, {_, 0}) do
|
||||
time_to_string(hour, minute, second)
|
||||
end
|
||||
def time_to_string(hour, minute, second, {microsecond, precision}) do
|
||||
time_to_string(hour, minute, second) <> "." <>
|
||||
(microsecond |> zero_pad(6) |> binary_part(0, precision))
|
||||
end
|
||||
defp time_to_string(hour, minute, second) do
|
||||
zero_pad(hour, 2) <> ":" <> zero_pad(minute, 2) <> ":" <> zero_pad(second, 2)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def date(year, month, day) when is_integer(year) and is_integer(month) and is_integer(day) do
|
||||
if :calendar.valid_date(year, month, day) and year <= 9999 do
|
||||
{:ok, %Date{year: year, month: month, day: day}}
|
||||
else
|
||||
{:error, :invalid_date}
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def from_unix(integer, unit) when is_integer(integer) do
|
||||
total = System.convert_time_unit(integer, unit, :microsecond)
|
||||
|
||||
if total in @unix_range_microseconds do
|
||||
microseconds = Integer.mod(total, @microseconds_per_second)
|
||||
seconds = @unix_epoch + Integer.floor_div(total, @microseconds_per_second)
|
||||
precision = precision_for_unit(unit)
|
||||
{date, time} = iso_seconds_to_datetime(seconds)
|
||||
{:ok, date, time, {microseconds, precision}}
|
||||
else
|
||||
if total < -@unix_epoch * 1_000_000 do
|
||||
{:error, :invalid_unix_time}
|
||||
else
|
||||
microsecond = rem(total, 1_000_000)
|
||||
precision = precision_for_unit(unit)
|
||||
{date, time} = :calendar.gregorian_seconds_to_datetime(@unix_epoch + div(total, 1_000_000))
|
||||
{:ok, date, time, {microsecond, precision}}
|
||||
end
|
||||
end
|
||||
|
||||
defp precision_for_unit(unit) do
|
||||
subsecond = div(System.convert_time_unit(1, :second, unit), 10)
|
||||
subsecond = div System.convert_time_unit(1, :second, unit), 10
|
||||
precision_for_unit(subsecond, 0)
|
||||
end
|
||||
|
||||
defp precision_for_unit(0, precision), do: precision
|
||||
defp precision_for_unit(_, 6), do: 6
|
||||
|
||||
defp precision_for_unit(0, precision),
|
||||
do: precision
|
||||
defp precision_for_unit(_, 6),
|
||||
do: 6
|
||||
defp precision_for_unit(number, precision),
|
||||
do: precision_for_unit(div(number, 10), precision + 1)
|
||||
|
||||
@doc false
|
||||
def date_to_iso8601(year, month, day, format \\ :extended) do
|
||||
date_to_string(year, month, day, format)
|
||||
def date_to_iso8601(year, month, day) do
|
||||
date_to_string(year, month, day)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def time_to_iso8601(hour, minute, second, microsecond, format \\ :extended) do
|
||||
time_to_string(hour, minute, second, microsecond, format)
|
||||
def time_to_iso8601(hour, minute, second, microsecond) do
|
||||
time_to_string(hour, minute, second, microsecond)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def naive_datetime_to_iso8601(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
format \\ :extended
|
||||
) do
|
||||
date_to_string(year, month, day, format) <>
|
||||
"T" <> time_to_string(hour, minute, second, microsecond, format)
|
||||
def naive_datetime_to_iso8601(year, month, day, hour, minute, second, microsecond) do
|
||||
date_to_string(year, month, day) <> "T" <> time_to_string(hour, minute, second, microsecond)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def datetime_to_iso8601(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
time_zone,
|
||||
_zone_abbr,
|
||||
utc_offset,
|
||||
std_offset,
|
||||
format \\ :extended
|
||||
) do
|
||||
date_to_string(year, month, day, format) <>
|
||||
"T" <>
|
||||
time_to_string(hour, minute, second, microsecond, format) <>
|
||||
offset_to_string(utc_offset, std_offset, time_zone, format)
|
||||
def datetime_to_iso8601(year, month, day, hour, minute, second, microsecond,
|
||||
time_zone, _zone_abbr, utc_offset, std_offset) do
|
||||
date_to_string(year, month, day) <> "T" <>
|
||||
time_to_string(hour, minute, second, microsecond) <>
|
||||
offset_to_string(utc_offset, std_offset, time_zone)
|
||||
end
|
||||
|
||||
@doc false
|
||||
@@ -454,198 +213,42 @@ defmodule Calendar.ISO do
|
||||
case parse_microsecond(rest, 0, "") do
|
||||
{"", 0, _} ->
|
||||
:error
|
||||
|
||||
{microsecond, precision, rest} when precision in 1..6 ->
|
||||
pad = String.duplicate("0", 6 - byte_size(microsecond))
|
||||
{{String.to_integer(microsecond <> pad), precision}, rest}
|
||||
|
||||
{microsecond, _precision, rest} ->
|
||||
{{String.to_integer(binary_part(microsecond, 0, 6)), 6}, rest}
|
||||
end
|
||||
end
|
||||
|
||||
def parse_microsecond("," <> rest) do
|
||||
parse_microsecond("." <> rest)
|
||||
end
|
||||
|
||||
def parse_microsecond(rest) do
|
||||
{{0, 0}, rest}
|
||||
end
|
||||
|
||||
defp parse_microsecond(<<head, tail::binary>>, precision, acc) when head in ?0..?9,
|
||||
do: parse_microsecond(tail, precision + 1, <<acc::binary, head>>)
|
||||
|
||||
defp parse_microsecond(rest, precision, acc), do: {acc, precision, rest}
|
||||
defp parse_microsecond(<<h, t::binary>>, precision, acc) when h in ?0..?9,
|
||||
do: parse_microsecond(t, precision + 1, <<acc::binary, h>>)
|
||||
defp parse_microsecond(rest, precision, acc),
|
||||
do: {acc, precision, rest}
|
||||
|
||||
@doc false
|
||||
def parse_offset(""), do: {nil, ""}
|
||||
def parse_offset("Z"), do: {0, ""}
|
||||
def parse_offset("-00:00"), do: :error
|
||||
|
||||
def parse_offset(""),
|
||||
do: {nil, ""}
|
||||
def parse_offset("Z"),
|
||||
do: {0, ""}
|
||||
def parse_offset("-00:00"),
|
||||
do: :error
|
||||
def parse_offset(<<?+, hour::2-bytes, ?:, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(1, hour, min, rest)
|
||||
|
||||
def parse_offset(<<?-, hour::2-bytes, ?:, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(-1, hour, min, rest)
|
||||
|
||||
def parse_offset(<<?+, hour::2-bytes, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(1, hour, min, rest)
|
||||
|
||||
def parse_offset(<<?-, hour::2-bytes, min::2-bytes, rest::binary>>),
|
||||
do: parse_offset(-1, hour, min, rest)
|
||||
|
||||
def parse_offset(<<?+, hour::2-bytes, rest::binary>>), do: parse_offset(1, hour, "00", rest)
|
||||
def parse_offset(<<?-, hour::2-bytes, rest::binary>>), do: parse_offset(-1, hour, "00", rest)
|
||||
def parse_offset(_), do: :error
|
||||
def parse_offset(_),
|
||||
do: :error
|
||||
|
||||
defp parse_offset(sign, hour, min, rest) do
|
||||
with {hour, ""} when hour < 24 <- Integer.parse(hour),
|
||||
{min, ""} when min < 60 <- Integer.parse(min) do
|
||||
{(hour * 60 + min) * 60 * sign, rest}
|
||||
{((hour * 60) + min) * 60 * sign, rest}
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def iso_days_to_unit({days, {parts, ppd}}, unit) do
|
||||
day_microseconds = days * @parts_per_day
|
||||
microseconds = div(parts * @parts_per_day, ppd)
|
||||
System.convert_time_unit(day_microseconds + microseconds, :microsecond, unit)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def add_day_fraction_to_iso_days({days, {parts, ppd}}, add, ppd) do
|
||||
normalize_iso_days(days, parts + add, ppd)
|
||||
end
|
||||
|
||||
def add_day_fraction_to_iso_days({days, {parts, ppd}}, add, add_ppd) do
|
||||
parts = parts * add_ppd
|
||||
add = add * ppd
|
||||
gcd = Integer.gcd(ppd, add_ppd)
|
||||
result_parts = div(parts + add, gcd)
|
||||
result_ppd = div(ppd * add_ppd, gcd)
|
||||
normalize_iso_days(days, result_parts, result_ppd)
|
||||
end
|
||||
|
||||
defp normalize_iso_days(days, parts, ppd) do
|
||||
days_offset = div(parts, ppd)
|
||||
parts = rem(parts, ppd)
|
||||
|
||||
if parts < 0 do
|
||||
{days + days_offset - 1, {parts + ppd, ppd}}
|
||||
else
|
||||
{days + days_offset, {parts, ppd}}
|
||||
end
|
||||
end
|
||||
|
||||
# Note that this function does not add the extra leap day for a leap year.
|
||||
# If you want to add that leap day when appropriate,
|
||||
# add the result of leap_day_offset/2 to the result of days_before_month/1.
|
||||
defp days_before_month(1), do: 0
|
||||
defp days_before_month(2), do: 31
|
||||
defp days_before_month(3), do: 59
|
||||
defp days_before_month(4), do: 90
|
||||
defp days_before_month(5), do: 120
|
||||
defp days_before_month(6), do: 151
|
||||
defp days_before_month(7), do: 181
|
||||
defp days_before_month(8), do: 212
|
||||
defp days_before_month(9), do: 243
|
||||
defp days_before_month(10), do: 273
|
||||
defp days_before_month(11), do: 304
|
||||
defp days_before_month(12), do: 334
|
||||
|
||||
defp leap_day_offset(_year, month) when month < 3, do: 0
|
||||
|
||||
defp leap_day_offset(year, _month) do
|
||||
if leap_year?(year), do: 1, else: 0
|
||||
end
|
||||
|
||||
defp days_to_year(days) do
|
||||
year = Integer.floor_div(days, @days_per_nonleap_year)
|
||||
{year, days_before_year} = days_to_year(year, days, days_in_previous_years(year))
|
||||
{year, days - days_before_year}
|
||||
end
|
||||
|
||||
defp days_to_year(year, days1, days2) when days1 < days2 do
|
||||
days_to_year(year - 1, days1, days_in_previous_years(year - 1))
|
||||
end
|
||||
|
||||
defp days_to_year(year, _days1, days2) do
|
||||
{year, days2}
|
||||
end
|
||||
|
||||
defp days_in_previous_years(0), do: 0
|
||||
|
||||
defp days_in_previous_years(year) do
|
||||
previous_year = year - 1
|
||||
|
||||
Integer.floor_div(previous_year, 4) - Integer.floor_div(previous_year, 100) +
|
||||
Integer.floor_div(previous_year, 400) + previous_year * @days_per_nonleap_year +
|
||||
@days_per_leap_year
|
||||
end
|
||||
|
||||
# Note that 0 is the first day of the month.
|
||||
defp year_day_to_year_date(_extra_day, day_of_year) when day_of_year < 31 do
|
||||
{1, day_of_year}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 59 + extra_day do
|
||||
{2, day_of_year - 31}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 90 + extra_day do
|
||||
{3, day_of_year - (59 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 120 + extra_day do
|
||||
{4, day_of_year - (90 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 151 + extra_day do
|
||||
{5, day_of_year - (120 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 181 + extra_day do
|
||||
{6, day_of_year - (151 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 212 + extra_day do
|
||||
{7, day_of_year - (181 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 243 + extra_day do
|
||||
{8, day_of_year - (212 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 273 + extra_day do
|
||||
{9, day_of_year - (243 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 304 + extra_day do
|
||||
{10, day_of_year - (273 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) when day_of_year < 334 + extra_day do
|
||||
{11, day_of_year - (304 + extra_day)}
|
||||
end
|
||||
|
||||
defp year_day_to_year_date(extra_day, day_of_year) do
|
||||
{12, day_of_year - (334 + extra_day)}
|
||||
end
|
||||
|
||||
defp iso_seconds_to_datetime(seconds) do
|
||||
{days, rest_seconds} = div_mod(seconds, @seconds_per_day)
|
||||
|
||||
date = date_from_iso_days(days)
|
||||
time = seconds_to_time(rest_seconds)
|
||||
{date, time}
|
||||
end
|
||||
|
||||
defp seconds_to_time(seconds) when seconds in 0..(@seconds_per_day - 1) do
|
||||
{hour, rest_seconds} = div_mod(seconds, @seconds_per_hour)
|
||||
{minute, second} = div_mod(rest_seconds, @seconds_per_minute)
|
||||
|
||||
{hour, minute, second}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,869 +0,0 @@
|
||||
defmodule NaiveDateTime do
|
||||
@moduledoc """
|
||||
A NaiveDateTime struct (without a time zone) and functions.
|
||||
|
||||
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/7` functions or using the `~N` sigil:
|
||||
|
||||
iex> ~N[2000-01-01 23:00:07]
|
||||
~N[2000-01-01 23:00:07]
|
||||
|
||||
The date and time fields in the struct can be accessed directly:
|
||||
|
||||
iex> naive = ~N[2000-01-01 23:00:07]
|
||||
iex> naive.year
|
||||
2000
|
||||
iex> naive.second
|
||||
7
|
||||
|
||||
We call them "naive" because this datetime representation does not
|
||||
have a time zone. This means the datetime may not actually exist in
|
||||
certain areas in the world even though it is valid.
|
||||
|
||||
For example, when daylight saving changes are applied by a region,
|
||||
the clock typically moves forward or backward by one hour. This means
|
||||
certain datetimes never occur or may occur more than once. Since
|
||||
`NaiveDateTime` is not validated against a time zone, such errors
|
||||
would go unnoticed.
|
||||
|
||||
The functions on 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 3rd party calendar libraries.
|
||||
|
||||
## Comparing naive date times
|
||||
|
||||
Comparisons in Elixir using `==`, `>`, `<` and similar are structural
|
||||
and based on the `NaiveDateTime` struct fields. For proper comparison
|
||||
between naive datetimes, use the `compare/2` function.
|
||||
|
||||
## Using epochs
|
||||
|
||||
The `add/3` and `diff/3` functions can be used for computing with
|
||||
date times or retrieving the number of seconds between instants.
|
||||
For example, if there is an interest in computing the number of
|
||||
seconds from the Unix epoch (1970-01-01 00:00:00):
|
||||
|
||||
iex> NaiveDateTime.diff(~N[2010-04-17 14:00:00], ~N[1970-01-01 00:00:00])
|
||||
1271512800
|
||||
|
||||
iex> NaiveDateTime.add(~N[1970-01-01 00:00:00], 1271512800)
|
||||
~N[2010-04-17 14:00:00]
|
||||
|
||||
Those functions are optimized to deal with common epochs, such
|
||||
as the Unix Epoch above or the Gregorian Epoch (0000-01-01 00:00:00).
|
||||
"""
|
||||
|
||||
@enforce_keys [:year, :month, :day, :hour, :minute, :second]
|
||||
defstruct [
|
||||
:year,
|
||||
:month,
|
||||
:day,
|
||||
:hour,
|
||||
:minute,
|
||||
:second,
|
||||
microsecond: {0, 0},
|
||||
calendar: Calendar.ISO
|
||||
]
|
||||
|
||||
@type t :: %NaiveDateTime{
|
||||
year: Calendar.year(),
|
||||
month: Calendar.month(),
|
||||
day: Calendar.day(),
|
||||
calendar: Calendar.calendar(),
|
||||
hour: Calendar.hour(),
|
||||
minute: Calendar.minute(),
|
||||
second: Calendar.second(),
|
||||
microsecond: Calendar.microsecond()
|
||||
}
|
||||
|
||||
@doc """
|
||||
Returns the current naive datetime in UTC.
|
||||
|
||||
Prefer using `DateTime.utc_now/0` when possible as, opposite
|
||||
to `NaiveDateTime`, it will keep the time zone information.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> naive_datetime = NaiveDateTime.utc_now()
|
||||
iex> naive_datetime.year >= 2016
|
||||
true
|
||||
|
||||
"""
|
||||
@spec utc_now(Calendar.calendar()) :: t
|
||||
def utc_now(calendar \\ Calendar.ISO)
|
||||
|
||||
def utc_now(Calendar.ISO) do
|
||||
{:ok, {year, month, day}, {hour, minute, second}, microsecond} =
|
||||
Calendar.ISO.from_unix(:os.system_time(), :native)
|
||||
|
||||
%NaiveDateTime{
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: Calendar.ISO
|
||||
}
|
||||
end
|
||||
|
||||
def utc_now(calendar) do
|
||||
calendar
|
||||
|> DateTime.utc_now()
|
||||
|> DateTime.to_naive()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a new ISO naive datetime.
|
||||
|
||||
Expects all values to be integers. Returns `{:ok, naive_datetime}`
|
||||
if each entry fits its appropriate range, returns `{:error, reason}`
|
||||
otherwise.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 0, 0, 0)
|
||||
{:ok, ~N[2000-01-01 00:00:00]}
|
||||
iex> NaiveDateTime.new(2000, 13, 1, 0, 0, 0)
|
||||
{:error, :invalid_date}
|
||||
iex> NaiveDateTime.new(2000, 2, 29, 0, 0, 0)
|
||||
{:ok, ~N[2000-02-29 00:00:00]}
|
||||
iex> NaiveDateTime.new(2000, 2, 30, 0, 0, 0)
|
||||
{:error, :invalid_date}
|
||||
iex> NaiveDateTime.new(2001, 2, 29, 0, 0, 0)
|
||||
{:error, :invalid_date}
|
||||
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 59, {0, 1})
|
||||
{: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, 61, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> NaiveDateTime.new(2000, 1, 1, 23, 59, 59, 1_000_000)
|
||||
{:error, :invalid_time}
|
||||
|
||||
"""
|
||||
@spec new(
|
||||
Calendar.year(),
|
||||
Calendar.month(),
|
||||
Calendar.day(),
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond(),
|
||||
Calendar.calendar()
|
||||
) :: {:ok, t} | {:error, atom}
|
||||
def new(year, month, day, hour, minute, second, microsecond \\ {0, 0}, calendar \\ Calendar.ISO) do
|
||||
with {:ok, date} <- Date.new(year, month, day, calendar),
|
||||
{:ok, time} <- Time.new(hour, minute, second, microsecond, calendar),
|
||||
do: new(date, time)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a naive datetime from date and time structs.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.new(~D[2010-01-13], ~T[23:00:07.005])
|
||||
{:ok, ~N[2010-01-13 23:00:07.005]}
|
||||
|
||||
"""
|
||||
@spec new(Date.t(), Time.t()) :: {:ok, t}
|
||||
def new(date, time)
|
||||
|
||||
def new(%Date{calendar: calendar} = date, %Time{calendar: calendar} = time) do
|
||||
%{year: year, month: month, day: day} = date
|
||||
%{hour: hour, minute: minute, second: second, microsecond: microsecond} = time
|
||||
|
||||
naive_datetime = %NaiveDateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}
|
||||
|
||||
{:ok, naive_datetime}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds a specified amount of time to a `NaiveDateTime`.
|
||||
|
||||
Accepts an `integer` in any `unit` available from `t:System.time_unit/0`.
|
||||
Negative values will be move backwards in time.
|
||||
|
||||
This operation is only possible if both calendars are convertible to `Calendar.ISO`.
|
||||
|
||||
## Examples
|
||||
|
||||
# adds seconds by default
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], 2)
|
||||
~N[2014-10-02 00:29:12]
|
||||
|
||||
# accepts negative offsets
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], -2)
|
||||
~N[2014-10-02 00:29:08]
|
||||
|
||||
# can work with other units
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10], 2_000, :millisecond)
|
||||
~N[2014-10-02 00:29:12]
|
||||
|
||||
# keeps the same precision
|
||||
iex> NaiveDateTime.add(~N[2014-10-02 00:29:10.021], 21, :second)
|
||||
~N[2014-10-02 00:29:31.021]
|
||||
|
||||
# changes below the precision will not be visible
|
||||
iex> hidden = NaiveDateTime.add(~N[2014-10-02 00:29:10], 21, :millisecond)
|
||||
iex> hidden.microsecond # ~N[2014-10-02 00:29:10]
|
||||
{21000, 0}
|
||||
|
||||
# from Gregorian seconds
|
||||
iex> NaiveDateTime.add(~N[0000-01-01 00:00:00], 63579428950)
|
||||
~N[2014-10-02 00:29:10]
|
||||
|
||||
"""
|
||||
@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(integer, ppd)
|
||||
|> from_iso_days(calendar, precision)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Subtracts `naive_datetime2` from `naive_datetime1`.
|
||||
|
||||
The answer can be returned in any `unit` available from `t:System.time_unit/0`.
|
||||
|
||||
This function returns the difference in seconds where seconds are measured
|
||||
according to `Calendar.ISO`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:12], ~N[2014-10-02 00:29:10])
|
||||
2
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:12], ~N[2014-10-02 00:29:10], :microsecond)
|
||||
2_000_000
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:10.042], ~N[2014-10-02 00:29:10.021], :millisecond)
|
||||
21
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:10], ~N[2014-10-02 00:29:12])
|
||||
-2
|
||||
|
||||
# to Gregorian seconds
|
||||
iex> NaiveDateTime.diff(~N[2014-10-02 00:29:10], ~N[0000-01-01 00:00:00])
|
||||
63579428950
|
||||
|
||||
"""
|
||||
@spec diff(t, t, System.time_unit()) :: integer
|
||||
def diff(%NaiveDateTime{} = ndatetime1, %NaiveDateTime{} = ndatetime2, unit \\ :second) do
|
||||
if not Calendar.compatible_calendars?(ndatetime1.calendar, ndatetime2.calendar) do
|
||||
raise ArgumentError,
|
||||
"cannot calculate the difference between #{inspect(ndatetime1)} and " <>
|
||||
"#{inspect(ndatetime2)} because their calendars are not compatible " <>
|
||||
"and thus the result would be ambiguous"
|
||||
end
|
||||
|
||||
units1 = ndatetime1 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(unit)
|
||||
units2 = ndatetime2 |> to_iso_days() |> Calendar.ISO.iso_days_to_unit(unit)
|
||||
units1 - units2
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the given naive datetime with the microsecond field truncated to the
|
||||
given precision (`:microsecond`, `millisecond` or `:second`).
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :microsecond)
|
||||
~N[2017-11-06 00:23:51.123456]
|
||||
|
||||
iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :millisecond)
|
||||
~N[2017-11-06 00:23:51.123]
|
||||
|
||||
iex> NaiveDateTime.truncate(~N[2017-11-06 00:23:51.123456], :second)
|
||||
~N[2017-11-06 00:23:51]
|
||||
|
||||
"""
|
||||
@spec truncate(t(), :microsecond | :millisecond | :second) :: t()
|
||||
def truncate(%NaiveDateTime{microsecond: microsecond} = ndatetime, precision) do
|
||||
%{ndatetime | microsecond: Calendar.truncate(microsecond, precision)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `NaiveDateTime` into a `Date`.
|
||||
|
||||
Because `Date` does not hold time information,
|
||||
data will be lost during the conversion.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.to_date(~N[2002-01-13 23:00:07])
|
||||
~D[2002-01-13]
|
||||
|
||||
"""
|
||||
@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
|
||||
|
||||
@doc """
|
||||
Converts a `NaiveDateTime` into `Time`.
|
||||
|
||||
Because `Time` does not hold date information,
|
||||
data will be lost during the conversion.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.to_time(~N[2002-01-13 23:00:07])
|
||||
~T[23:00:07]
|
||||
|
||||
"""
|
||||
@spec to_time(t) :: Time.t()
|
||||
def to_time(%NaiveDateTime{} = naive_datetime) do
|
||||
%{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
} = naive_datetime
|
||||
|
||||
%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.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> NaiveDateTime.to_string(~N[2000-02-28 23:00:13])
|
||||
"2000-02-28 23:00:13"
|
||||
iex> NaiveDateTime.to_string(~N[2000-02-28 23:00:13.001])
|
||||
"2000-02-28 23:00:13.001"
|
||||
|
||||
This function can also be used to convert a DateTime to a string without
|
||||
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.to_string(dt)
|
||||
"2000-02-29 23:00:07"
|
||||
|
||||
"""
|
||||
@spec to_string(Calendar.naive_datetime()) :: String.t()
|
||||
def to_string(%{calendar: calendar} = naive_datetime) do
|
||||
%{
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
} = naive_datetime
|
||||
|
||||
calendar.naive_datetime_to_string(year, month, day, hour, minute, second, microsecond)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Date and time of day" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Timezone offset may be included in the string but they will be
|
||||
simply discarded as such information is not included in naive date
|
||||
times.
|
||||
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
desired as there is no ambiguity within this function.
|
||||
|
||||
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
|
||||
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07")
|
||||
{:ok, ~N[2015-01-23 23:50:07]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07")
|
||||
{:ok, ~N[2015-01-23 23:50:07]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07Z")
|
||||
{:ok, ~N[2015-01-23 23:50:07]}
|
||||
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07.0")
|
||||
{:ok, ~N[2015-01-23 23:50:07.0]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07,0123456")
|
||||
{:ok, ~N[2015-01-23 23:50:07.012345]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07.0123456")
|
||||
{:ok, ~N[2015-01-23 23:50:07.012345]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07.123Z")
|
||||
{:ok, ~N[2015-01-23 23:50:07.123]}
|
||||
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23P23:50:07")
|
||||
{:error, :invalid_format}
|
||||
iex> NaiveDateTime.from_iso8601("2015:01:23 23-50-07")
|
||||
{:error, :invalid_format}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:07A")
|
||||
{:error, :invalid_format}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23 23:50:61")
|
||||
{:error, :invalid_time}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-32 23:50:07")
|
||||
{:error, :invalid_date}
|
||||
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07.123+02:30")
|
||||
{:ok, ~N[2015-01-23 23:50:07.123]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07.123+00:00")
|
||||
{:ok, ~N[2015-01-23 23:50:07.123]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07.123-02:30")
|
||||
{:ok, ~N[2015-01-23 23:50:07.123]}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07.123-00:00")
|
||||
{:error, :invalid_format}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07.123-00:60")
|
||||
{:error, :invalid_format}
|
||||
iex> NaiveDateTime.from_iso8601("2015-01-23T23:50:07.123-24:00")
|
||||
{:error, :invalid_format}
|
||||
|
||||
"""
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO) when is_binary(string) do
|
||||
with <<year::4-bytes, ?-, month::2-bytes, ?-, day::2-bytes, sep, rest::binary>> <- string,
|
||||
true <- sep in [?\s, ?T],
|
||||
<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>> <- rest,
|
||||
{year, ""} <- Integer.parse(year),
|
||||
{month, ""} <- Integer.parse(month),
|
||||
{day, ""} <- Integer.parse(day),
|
||||
{hour, ""} <- Integer.parse(hour),
|
||||
{min, ""} <- Integer.parse(min),
|
||||
{sec, ""} <- Integer.parse(sec),
|
||||
{microsec, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{_offset, ""} <- Calendar.ISO.parse_offset(rest) do
|
||||
with {:ok, utc_date} <- new(year, month, day, hour, min, sec, microsec, Calendar.ISO),
|
||||
do: convert(utc_date, calendar)
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Date and time of day" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Raises if the format is invalid.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.from_iso8601!("2015-01-23T23:50:07.123Z")
|
||||
~N[2015-01-23 23:50:07.123]
|
||||
iex> NaiveDateTime.from_iso8601!("2015-01-23T23:50:07,123Z")
|
||||
~N[2015-01-23 23:50:07.123]
|
||||
iex> NaiveDateTime.from_iso8601!("2015-01-23P23:50:07")
|
||||
** (ArgumentError) cannot parse "2015-01-23P23:50:07" as naive datetime, reason: :invalid_format
|
||||
|
||||
"""
|
||||
@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} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot parse #{inspect(string)} as naive datetime, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given naive datetime to
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
By default, `NaiveDateTime.to_iso8601/2` returns naive datetimes formatted in the "extended"
|
||||
format, for human readability. It also supports the "basic" format through passing the `:basic` option.
|
||||
|
||||
Only supports converting naive datetimes which are in the ISO calendar,
|
||||
attempting to convert naive datetimes from other calendars will raise.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> NaiveDateTime.to_iso8601(~N[2000-02-28 23:00:13])
|
||||
"2000-02-28T23:00:13"
|
||||
|
||||
iex> NaiveDateTime.to_iso8601(~N[2000-02-28 23:00:13.001])
|
||||
"2000-02-28T23:00:13.001"
|
||||
|
||||
iex> NaiveDateTime.to_iso8601(~N[2000-02-28 23:00:13.001], :basic)
|
||||
"20000228T230013.001"
|
||||
|
||||
This function can also be used to convert a DateTime to ISO 8601 without
|
||||
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.to_iso8601(dt)
|
||||
"2000-02-29T23:00:07"
|
||||
|
||||
"""
|
||||
@spec to_iso8601(Calendar.naive_datetime(), :basic | :extended) :: String.t()
|
||||
def to_iso8601(naive_datetime, format \\ :extended)
|
||||
|
||||
def to_iso8601(%{calendar: Calendar.ISO} = naive_datetime, format)
|
||||
when format in [:basic, :extended] do
|
||||
%{
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
} = naive_datetime
|
||||
|
||||
Calendar.ISO.naive_datetime_to_iso8601(
|
||||
year,
|
||||
month,
|
||||
day,
|
||||
hour,
|
||||
minute,
|
||||
second,
|
||||
microsecond,
|
||||
format
|
||||
)
|
||||
end
|
||||
|
||||
def to_iso8601(%{calendar: _} = naive_datetime, format) when format in [:basic, :extended] do
|
||||
naive_datetime
|
||||
|> convert!(Calendar.ISO)
|
||||
|> to_iso8601(format)
|
||||
end
|
||||
|
||||
def to_iso8601(_date, format) do
|
||||
raise ArgumentError,
|
||||
"NaiveDateTime.to_iso8601/2 expects format to be :extended or :basic, " <>
|
||||
"got: #{inspect(format)}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts a `NaiveDateTime` struct to an Erlang datetime tuple.
|
||||
|
||||
Only supports converting naive datetimes which are in the ISO calendar,
|
||||
attempting to convert naive datetimes from other calendars will raise.
|
||||
|
||||
WARNING: Loss of precision may occur, as Erlang time tuples only store
|
||||
hour/minute/second.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.to_erl(~N[2000-01-01 13:30:15])
|
||||
{{2000, 1, 1}, {13, 30, 15}}
|
||||
|
||||
This function can also be used to convert a DateTime to a erl format
|
||||
without 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.to_erl(dt)
|
||||
{{2000, 2, 29}, {23, 00, 07}}
|
||||
|
||||
"""
|
||||
@spec to_erl(Calendar.naive_datetime()) :: :calendar.datetime()
|
||||
def to_erl(%{calendar: _} = naive_datetime) do
|
||||
%{year: year, month: month, day: day, hour: hour, minute: minute, second: second} =
|
||||
convert!(naive_datetime, Calendar.ISO)
|
||||
|
||||
{{year, month, day}, {hour, minute, second}}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts an Erlang datetime tuple to a `NaiveDateTime` struct.
|
||||
|
||||
Attempting to convert an invalid ISO calendar date will produce an error tuple.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.from_erl({{2000, 1, 1}, {13, 30, 15}})
|
||||
{:ok, ~N[2000-01-01 13:30:15]}
|
||||
iex> NaiveDateTime.from_erl({{2000, 1, 1}, {13, 30, 15}}, {5000, 3})
|
||||
{:ok, ~N[2000-01-01 13:30:15.005]}
|
||||
iex> NaiveDateTime.from_erl({{2000, 13, 1}, {13, 30, 15}})
|
||||
{:error, :invalid_date}
|
||||
iex> NaiveDateTime.from_erl({{2000, 13, 1},{13, 30, 15}})
|
||||
{:error, :invalid_date}
|
||||
|
||||
"""
|
||||
@spec from_erl(:calendar.datetime(), Calendar.microsecond(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, atom}
|
||||
def from_erl(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_erl({{year, month, day}, {hour, minute, second}}, microsecond, calendar) do
|
||||
with {:ok, utc_date} <- new(year, month, day, hour, minute, second, microsecond),
|
||||
do: convert(utc_date, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts an Erlang datetime tuple to a `NaiveDateTime` struct.
|
||||
|
||||
Raises if the datetime is invalid.
|
||||
Attempting to convert an invalid ISO calendar date will produce an error tuple.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.from_erl!({{2000, 1, 1}, {13, 30, 15}})
|
||||
~N[2000-01-01 13:30:15]
|
||||
iex> NaiveDateTime.from_erl!({{2000, 1, 1}, {13, 30, 15}}, {5000, 3})
|
||||
~N[2000-01-01 13:30:15.005]
|
||||
iex> NaiveDateTime.from_erl!({{2000, 13, 1}, {13, 30, 15}})
|
||||
** (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 | no_return
|
||||
def from_erl!(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO) do
|
||||
case from_erl(tuple, microsecond, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(tuple)} to naive datetime, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares two `NaiveDateTime` structs.
|
||||
|
||||
Returns `:gt` if first is later than the second
|
||||
and `:lt` for vice versa. If the two NaiveDateTime
|
||||
are equal `:eq` is returned.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> NaiveDateTime.compare(~N[2016-04-16 13:30:15], ~N[2016-04-28 16:19:25])
|
||||
:lt
|
||||
iex> NaiveDateTime.compare(~N[2016-04-16 13:30:15.1], ~N[2016-04-16 13:30:15.01])
|
||||
:gt
|
||||
|
||||
This function can also be used to compare a DateTime without
|
||||
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.compare(dt, ~N[2000-02-29 23:00:07])
|
||||
:eq
|
||||
iex> NaiveDateTime.compare(dt, ~N[2000-01-29 23:00:07])
|
||||
:gt
|
||||
iex> NaiveDateTime.compare(dt, ~N[2000-03-29 23:00:07])
|
||||
:lt
|
||||
|
||||
"""
|
||||
@spec compare(Calendar.naive_datetime(), Calendar.naive_datetime()) :: :lt | :eq | :gt
|
||||
def compare(%{calendar: calendar1} = naive_datetime1, %{calendar: calendar2} = naive_datetime2) do
|
||||
if Calendar.compatible_calendars?(calendar1, calendar2) do
|
||||
case {to_iso_days(naive_datetime1), to_iso_days(naive_datetime2)} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
_ -> :eq
|
||||
end
|
||||
else
|
||||
raise ArgumentError, """
|
||||
cannot compare #{inspect(naive_datetime1)} with #{inspect(naive_datetime2)}.
|
||||
|
||||
This comparison would be ambiguous as their calendars have incompatible day rollover moments.
|
||||
Specify an exact time of day (using `DateTime`s) to resolve this ambiguity
|
||||
"""
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `naive_datetime` from one calendar to another.
|
||||
|
||||
If it is not possible to convert unambiguously between the calendars
|
||||
(see `Calendar.compatible_calendars?/2`), an `{:error, :incompatible_calendars}` tuple
|
||||
is returned.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> NaiveDateTime.convert(~N[2000-01-01 13:30:15], Calendar.Holocene)
|
||||
{:ok, %NaiveDateTime{calendar: Calendar.Holocene, year: 12000, month: 1, day: 1,
|
||||
hour: 13, minute: 30, second: 15, microsecond: {0, 0}}}
|
||||
|
||||
"""
|
||||
@spec convert(Calendar.naive_datetime(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, :incompatible_calendars}
|
||||
|
||||
# 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
|
||||
},
|
||||
calendar
|
||||
) do
|
||||
naive_datetime = %NaiveDateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}
|
||||
|
||||
{:ok, naive_datetime}
|
||||
end
|
||||
|
||||
def convert(%{calendar: ndt_calendar, microsecond: {_, precision}} = naive_datetime, calendar) do
|
||||
if Calendar.compatible_calendars?(ndt_calendar, calendar) do
|
||||
result_naive_datetime =
|
||||
naive_datetime
|
||||
|> to_iso_days
|
||||
|> from_iso_days(calendar, precision)
|
||||
|
||||
{:ok, result_naive_datetime}
|
||||
else
|
||||
{:error, :incompatible_calendars}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `naive_datetime` from one calendar to another.
|
||||
|
||||
If it is not possible to convert unambiguously between the calendars
|
||||
(see `Calendar.compatible_calendars?/2`), an ArgumentError is raised.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> NaiveDateTime.convert!(~N[2000-01-01 13:30:15], Calendar.Holocene)
|
||||
%NaiveDateTime{calendar: Calendar.Holocene, year: 12000, month: 1, day: 1,
|
||||
hour: 13, minute: 30, second: 15, microsecond: {0, 0}}
|
||||
|
||||
"""
|
||||
@spec convert!(Calendar.naive_datetime(), Calendar.calendar()) :: t
|
||||
def convert!(naive_datetime, calendar) do
|
||||
case convert(naive_datetime, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, :incompatible_calendars} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(naive_datetime)} to target calendar #{inspect(calendar)}, " <>
|
||||
"reason: #{inspect(naive_datetime.calendar)} and #{inspect(calendar)} " <>
|
||||
"have different day rollover moments, making this conversion ambiguous"
|
||||
end
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
# Keep it multiline for proper function clause errors.
|
||||
defp to_iso_days(%{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}) do
|
||||
calendar.naive_datetime_to_iso_days(year, month, day, hour, minute, second, microsecond)
|
||||
end
|
||||
|
||||
defp from_iso_days(iso_days, calendar, precision) do
|
||||
{year, month, day, hour, minute, second, {microsecond, _}} =
|
||||
calendar.naive_datetime_from_iso_days(iso_days)
|
||||
|
||||
%NaiveDateTime{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {microsecond, precision}
|
||||
}
|
||||
end
|
||||
|
||||
defimpl String.Chars do
|
||||
def to_string(naive_datetime) do
|
||||
%{
|
||||
calendar: calendar,
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
} = naive_datetime
|
||||
|
||||
calendar.naive_datetime_to_string(year, month, day, hour, minute, second, microsecond)
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(%{calendar: Calendar.ISO} = naive_datetime, _) do
|
||||
%{
|
||||
year: year,
|
||||
month: month,
|
||||
day: day,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
} = naive_datetime
|
||||
|
||||
formatted =
|
||||
Calendar.ISO.naive_datetime_to_string(year, month, day, hour, minute, second, microsecond)
|
||||
|
||||
"~N[" <> formatted <> "]"
|
||||
end
|
||||
|
||||
def inspect(naive, opts) do
|
||||
Inspect.Any.inspect(naive, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1,653 +0,0 @@
|
||||
defmodule Time do
|
||||
@moduledoc """
|
||||
A Time struct and functions.
|
||||
|
||||
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`
|
||||
sigil:
|
||||
|
||||
iex> ~T[23:00:07.001]
|
||||
~T[23:00:07.001]
|
||||
|
||||
Both `new/4` and sigil return a struct where the time fields can
|
||||
be accessed directly:
|
||||
|
||||
iex> time = ~T[23:00:07.001]
|
||||
iex> time.hour
|
||||
23
|
||||
iex> time.microsecond
|
||||
{1000, 3}
|
||||
|
||||
The functions on this module work with the `Time` struct as well
|
||||
as any struct that contains the same fields as the `Time` struct,
|
||||
such as `NaiveDateTime` and `DateTime`. Such functions expect
|
||||
`t:Calendar.time/0` in their typespecs (instead of `t:t/0`).
|
||||
|
||||
Developers should avoid creating the Time structs directly
|
||||
and instead rely on the functions provided by this module as well
|
||||
as the ones in 3rd party calendar libraries.
|
||||
|
||||
## Comparing times
|
||||
|
||||
Comparisons in Elixir using `==`, `>`, `<` and similar are structural
|
||||
and based on the `Time` struct fields. For proper comparison between
|
||||
times, use the `compare/2` function.
|
||||
"""
|
||||
|
||||
@enforce_keys [:hour, :minute, :second]
|
||||
defstruct [:hour, :minute, :second, microsecond: {0, 0}, calendar: Calendar.ISO]
|
||||
|
||||
@type t :: %Time{
|
||||
hour: Calendar.hour(),
|
||||
minute: Calendar.minute(),
|
||||
second: Calendar.second(),
|
||||
microsecond: Calendar.microsecond(),
|
||||
calendar: Calendar.calendar()
|
||||
}
|
||||
|
||||
@doc """
|
||||
Returns the current time in UTC.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> time = Time.utc_now()
|
||||
iex> time.hour >= 0
|
||||
true
|
||||
|
||||
"""
|
||||
@spec utc_now(Calendar.calendar()) :: t
|
||||
def utc_now(calendar \\ Calendar.ISO) do
|
||||
{:ok, _, time, microsecond} = Calendar.ISO.from_unix(:os.system_time(), :native)
|
||||
{hour, minute, second} = time
|
||||
|
||||
iso_time = %Time{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: Calendar.ISO
|
||||
}
|
||||
|
||||
convert!(iso_time, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a new time.
|
||||
|
||||
Expects all values to be integers. Returns `{:ok, time}` if each
|
||||
entry fits its appropriate range, returns `{:error, reason}` otherwise.
|
||||
|
||||
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
|
||||
|
||||
iex> Time.new(0, 0, 0, 0)
|
||||
{: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, 61, 999_999)
|
||||
{:error, :invalid_time}
|
||||
iex> Time.new(23, 59, 59, 1_000_000)
|
||||
{:error, :invalid_time}
|
||||
|
||||
# Invalid precision
|
||||
Time.new(23, 59, 59, {999_999, 10})
|
||||
{:error, :invalid_time}
|
||||
|
||||
"""
|
||||
@spec new(
|
||||
Calendar.hour(),
|
||||
Calendar.minute(),
|
||||
Calendar.second(),
|
||||
Calendar.microsecond() | integer,
|
||||
Calendar.calendar()
|
||||
) :: {:ok, t} | {:error, atom}
|
||||
def new(hour, minute, second, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
|
||||
def new(hour, minute, second, microsecond, calendar) when is_integer(microsecond) do
|
||||
new(hour, minute, second, {microsecond, 6}, calendar)
|
||||
end
|
||||
|
||||
def new(hour, minute, second, {microsecond, precision}, calendar)
|
||||
when is_integer(hour) and is_integer(minute) and is_integer(second) and
|
||||
is_integer(microsecond) and is_integer(precision) do
|
||||
case calendar.valid_time?(hour, minute, second, {microsecond, precision}) do
|
||||
true ->
|
||||
time = %Time{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {microsecond, precision},
|
||||
calendar: calendar
|
||||
}
|
||||
|
||||
{:ok, time}
|
||||
|
||||
false ->
|
||||
{:error, :invalid_time}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given `time` to a string.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> Time.to_string(~T[23:00:00])
|
||||
"23:00:00"
|
||||
iex> Time.to_string(~T[23:00:00.001])
|
||||
"23:00:00.001"
|
||||
iex> Time.to_string(~T[23:00:00.123456])
|
||||
"23:00:00.123456"
|
||||
|
||||
iex> Time.to_string(~N[2015-01-01 23:00:00.001])
|
||||
"23:00:00.001"
|
||||
iex> Time.to_string(~N[2015-01-01 23:00:00.123456])
|
||||
"23:00:00.123456"
|
||||
|
||||
"""
|
||||
@spec to_string(Calendar.time()) :: String.t()
|
||||
def to_string(time)
|
||||
|
||||
def to_string(%{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
}) do
|
||||
calendar.time_to_string(hour, minute, second, microsecond)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Local time" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Timezone offset may be included in the string but they will be
|
||||
simply discarded as such information is not included in times.
|
||||
|
||||
As specified in the standard, the separator "T" may be omitted if
|
||||
desired as there is no ambiguity within this function.
|
||||
|
||||
Time representations with reduced accuracy are not supported.
|
||||
|
||||
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.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.from_iso8601("23:50:07")
|
||||
{:ok, ~T[23:50:07]}
|
||||
iex> Time.from_iso8601("23:50:07Z")
|
||||
{:ok, ~T[23:50:07]}
|
||||
iex> Time.from_iso8601("T23:50:07Z")
|
||||
{:ok, ~T[23:50:07]}
|
||||
|
||||
iex> Time.from_iso8601("23:50:07,0123456")
|
||||
{:ok, ~T[23:50:07.012345]}
|
||||
iex> Time.from_iso8601("23:50:07.0123456")
|
||||
{:ok, ~T[23:50:07.012345]}
|
||||
iex> Time.from_iso8601("23:50:07.123Z")
|
||||
{:ok, ~T[23:50:07.123]}
|
||||
|
||||
iex> Time.from_iso8601("2015:01:23 23-50-07")
|
||||
{:error, :invalid_format}
|
||||
iex> Time.from_iso8601("23:50:07A")
|
||||
{:error, :invalid_format}
|
||||
iex> Time.from_iso8601("23:50:07.")
|
||||
{:error, :invalid_format}
|
||||
iex> Time.from_iso8601("23:50:61")
|
||||
{:error, :invalid_time}
|
||||
|
||||
"""
|
||||
@spec from_iso8601(String.t(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
def from_iso8601(string, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_iso8601(<<?T, h, rest::binary>>, calendar) when h in ?0..?9 do
|
||||
from_iso8601(<<h, rest::binary>>, calendar)
|
||||
end
|
||||
|
||||
def from_iso8601(<<hour::2-bytes, ?:, min::2-bytes, ?:, sec::2-bytes, rest::binary>>, calendar) do
|
||||
with {hour, ""} <- Integer.parse(hour),
|
||||
{min, ""} <- Integer.parse(min),
|
||||
{sec, ""} <- Integer.parse(sec),
|
||||
{microsec, rest} <- Calendar.ISO.parse_microsecond(rest),
|
||||
{_offset, ""} <- Calendar.ISO.parse_offset(rest) do
|
||||
with {:ok, utc_time} <- new(hour, min, sec, microsec, Calendar.ISO),
|
||||
do: convert(utc_time, calendar)
|
||||
else
|
||||
_ -> {:error, :invalid_format}
|
||||
end
|
||||
end
|
||||
|
||||
def from_iso8601(<<_::binary>>, _calendar) do
|
||||
{:error, :invalid_format}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Parses the extended "Local time" format described by
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
Raises if the format is invalid.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.from_iso8601!("23:50:07,123Z")
|
||||
~T[23:50:07.123]
|
||||
iex> Time.from_iso8601!("23:50:07.123Z")
|
||||
~T[23:50:07.123]
|
||||
iex> Time.from_iso8601!("2015:01:23 23-50-07")
|
||||
** (ArgumentError) cannot parse "2015:01:23 23-50-07" as time, reason: :invalid_format
|
||||
"""
|
||||
@spec from_iso8601!(String.t(), Calendar.calendar()) :: t
|
||||
def from_iso8601!(string, calendar \\ Calendar.ISO) do
|
||||
case from_iso8601(string, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError, "cannot parse #{inspect(string)} as time, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given time to
|
||||
[ISO 8601:2004](https://en.wikipedia.org/wiki/ISO_8601).
|
||||
|
||||
By default, `Time.to_iso8601/2` returns times formatted in the "extended"
|
||||
format, for human readability. It also supports the "basic" format through
|
||||
passing the `:basic` option.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> Time.to_iso8601(~T[23:00:13])
|
||||
"23:00:13"
|
||||
|
||||
iex> Time.to_iso8601(~T[23:00:13.001])
|
||||
"23:00:13.001"
|
||||
|
||||
iex> Time.to_iso8601(~T[23:00:13.001], :basic)
|
||||
"230013.001"
|
||||
|
||||
iex> Time.to_iso8601(~N[2010-04-17 23:00:13])
|
||||
"23:00:13"
|
||||
|
||||
"""
|
||||
@spec to_iso8601(Calendar.time(), :extended | :basic) :: String.t()
|
||||
def to_iso8601(time, format \\ :extended) when format in [:extended, :basic] do
|
||||
%{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
} = convert!(time, Calendar.ISO)
|
||||
|
||||
Calendar.ISO.time_to_iso8601(hour, minute, second, microsecond, format)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts given `time` to an Erlang time tuple.
|
||||
|
||||
WARNING: Loss of precision may occur, as Erlang time tuples
|
||||
only contain hours/minutes/seconds.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.to_erl(~T[23:30:15.999])
|
||||
{23, 30, 15}
|
||||
|
||||
iex> Time.to_erl(~N[2010-04-17 23:30:15.999])
|
||||
{23, 30, 15}
|
||||
|
||||
"""
|
||||
@spec to_erl(Calendar.time()) :: :calendar.time()
|
||||
def to_erl(time) do
|
||||
%{hour: hour, minute: minute, second: second} = convert!(time, Calendar.ISO)
|
||||
{hour, minute, second}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts an Erlang time tuple to a `Time` struct.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.from_erl({23, 30, 15}, {5000, 3})
|
||||
{:ok, ~T[23:30:15.005]}
|
||||
iex> Time.from_erl({24, 30, 15})
|
||||
{:error, :invalid_time}
|
||||
|
||||
"""
|
||||
@spec from_erl(:calendar.time(), Calendar.microsecond(), Calendar.calendar()) ::
|
||||
{:ok, t} | {:error, atom}
|
||||
def from_erl(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO)
|
||||
|
||||
def from_erl({hour, minute, second}, microsecond, calendar) do
|
||||
with {:ok, time} <- new(hour, minute, second, microsecond, Calendar.ISO),
|
||||
do: convert(time, calendar)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts an Erlang time tuple to a `Time` struct.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.from_erl!({23, 30, 15})
|
||||
~T[23:30:15]
|
||||
iex> Time.from_erl!({23, 30, 15}, {5000, 3})
|
||||
~T[23:30:15.005]
|
||||
iex> Time.from_erl!({24, 30, 15})
|
||||
** (ArgumentError) cannot convert {24, 30, 15} to time, reason: :invalid_time
|
||||
|
||||
"""
|
||||
@spec from_erl!(:calendar.time(), Calendar.microsecond(), Calendar.calendar()) :: t
|
||||
def from_erl!(tuple, microsecond \\ {0, 0}, calendar \\ Calendar.ISO) do
|
||||
case from_erl(tuple, microsecond, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(tuple)} to time, reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds the `number` of `unit`s to the given `time`.
|
||||
|
||||
This function accepts the `number` measured according to `Calendar.ISO`.
|
||||
The time is returned in the same calendar as it was given in.
|
||||
|
||||
Note the result value represents the time of day, meaning that it is cyclic,
|
||||
for instance, it will never go over 24 hours for the ISO calendar.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.add(~T[10:00:00], 27000)
|
||||
~T[17:30:00.000000]
|
||||
iex> Time.add(~T[11:00:00.005], 2400)
|
||||
~T[11:40:00.005000]
|
||||
iex> Time.add(~T[00:00:00], 86399999, :millisecond)
|
||||
~T[23:59:59.999000]
|
||||
iex> Time.add(~T[17:10:05], 86400)
|
||||
~T[17:10:05.000000]
|
||||
iex> Time.add(~T[23:00:00], -60)
|
||||
~T[22:59:00.000000]
|
||||
|
||||
"""
|
||||
@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)
|
||||
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,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compares two time structs.
|
||||
|
||||
Returns `:gt` if first time is later than the second
|
||||
and `:lt` for vice versa. If the two times are equal
|
||||
`:eq` is returned.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.compare(~T[16:04:16], ~T[16:04:28])
|
||||
:lt
|
||||
iex> Time.compare(~T[16:04:16], ~T[16:04:16])
|
||||
:eq
|
||||
iex> Time.compare(~T[16:04:16.01], ~T[16:04:16.001])
|
||||
:gt
|
||||
|
||||
This function can also be used to compare across more
|
||||
complex calendar types by considering only the time fields:
|
||||
|
||||
iex> Time.compare(~N[1900-01-01 16:04:16], ~N[2015-01-01 16:04:16])
|
||||
:eq
|
||||
iex> Time.compare(~N[2015-01-01 16:04:16], ~N[2015-01-01 16:04:28])
|
||||
:lt
|
||||
iex> Time.compare(~N[2015-01-01 16:04:16.01], ~N[2000-01-01 16:04:16.001])
|
||||
:gt
|
||||
|
||||
"""
|
||||
@spec compare(Calendar.time(), Calendar.time()) :: :lt | :eq | :gt
|
||||
def compare(%{calendar: calendar} = time1, %{calendar: calendar} = time2) do
|
||||
%{hour: hour1, minute: minute1, second: second1, microsecond: {microsecond1, _}} = time1
|
||||
%{hour: hour2, minute: minute2, second: second2, microsecond: {microsecond2, _}} = time2
|
||||
|
||||
case {{hour1, minute1, second1, microsecond1}, {hour2, minute2, second2, microsecond2}} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
_ -> :eq
|
||||
end
|
||||
end
|
||||
|
||||
def compare(time1, time2) do
|
||||
{parts1, ppd1} = to_day_fraction(time1)
|
||||
{parts2, ppd2} = to_day_fraction(time2)
|
||||
|
||||
case {parts1 * ppd2, parts2 * ppd1} do
|
||||
{first, second} when first > second -> :gt
|
||||
{first, second} when first < second -> :lt
|
||||
_ -> :eq
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts given `time` to a different calendar.
|
||||
|
||||
Returns `{:ok, time}` if the conversion was successful,
|
||||
or `{:error, reason}` if it was not, for some reason.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> Time.convert(~T[13:30:15], Calendar.Holocene)
|
||||
{:ok, %Time{calendar: Calendar.Holocene, hour: 13, minute: 30, second: 15, microsecond: {0, 0}}}
|
||||
|
||||
"""
|
||||
@spec convert(Calendar.time(), Calendar.calendar()) :: {:ok, t} | {:error, atom}
|
||||
|
||||
# Keep it multiline for proper function clause errors.
|
||||
def convert(
|
||||
%{
|
||||
calendar: calendar,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
},
|
||||
calendar
|
||||
) do
|
||||
time = %Time{
|
||||
calendar: calendar,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond
|
||||
}
|
||||
|
||||
{:ok, time}
|
||||
end
|
||||
|
||||
def convert(%{microsecond: {_, precision}} = time, calendar) do
|
||||
{hour, minute, second, {microsecond, _}} =
|
||||
time
|
||||
|> to_day_fraction()
|
||||
|> calendar.time_from_day_fraction()
|
||||
|
||||
time = %Time{
|
||||
calendar: calendar,
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {microsecond, precision}
|
||||
}
|
||||
|
||||
{:ok, time}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Similar to `Time.convert/2`, but raises an `ArgumentError`
|
||||
if the conversion between the two calendars is not possible.
|
||||
|
||||
## Examples
|
||||
|
||||
Imagine someone implements `Calendar.Holocene`, a calendar based on the
|
||||
Gregorian calendar that adds exactly 10,000 years to the current Gregorian
|
||||
year:
|
||||
|
||||
iex> Time.convert!(~T[13:30:15], Calendar.Holocene)
|
||||
%Time{calendar: Calendar.Holocene, hour: 13, minute: 30, second: 15, microsecond: {0, 0}}
|
||||
|
||||
"""
|
||||
@spec convert!(Calendar.time(), Calendar.calendar()) :: t
|
||||
def convert!(time, calendar) do
|
||||
case convert(time, calendar) do
|
||||
{:ok, value} ->
|
||||
value
|
||||
|
||||
{:error, reason} ->
|
||||
raise ArgumentError,
|
||||
"cannot convert #{inspect(time)} to target calendar #{inspect(calendar)}, " <>
|
||||
"reason: #{inspect(reason)}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the difference between two times, considering only the hour, minute
|
||||
second and microsecond.
|
||||
|
||||
As with the `compare/2` function both `Time` structs and other structures
|
||||
containing time can be used. If for instance a `NaiveDateTime` or `DateTime`
|
||||
is passed, only the hour, month, second, and microsecond is considered. Any
|
||||
additional information about a date or time zone is ignored when calculating
|
||||
the difference.
|
||||
|
||||
The answer can be returned in any `unit` available from
|
||||
`t:System.time_unit/0`. If the first unit is smaller than
|
||||
the second, a negative number is returned.
|
||||
|
||||
This function returns the difference in seconds where seconds
|
||||
are measured according to `Calendar.ISO`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.diff(~T[00:29:12], ~T[00:29:10])
|
||||
2
|
||||
|
||||
# When passing a `NaiveDateTime` the date part is ignored.
|
||||
iex> Time.diff(~N[2017-01-01 00:29:12], ~T[00:29:10])
|
||||
2
|
||||
|
||||
# Two `NaiveDateTime` structs could have big differences in the date
|
||||
# but only the time part is considered.
|
||||
iex> Time.diff(~N[2017-01-01 00:29:12], (~N[1900-02-03 00:29:10]))
|
||||
2
|
||||
|
||||
iex> Time.diff(~T[00:29:12], ~T[00:29:10], :microsecond)
|
||||
2_000_000
|
||||
iex> Time.diff(~T[00:29:10], ~T[00:29:12], :microsecond)
|
||||
-2_000_000
|
||||
|
||||
"""
|
||||
@spec diff(Calendar.time(), Calendar.time(), System.time_unit()) :: integer
|
||||
def diff(time1, time2, unit \\ :second) do
|
||||
fraction1 = to_day_fraction(time1)
|
||||
fraction2 = to_day_fraction(time2)
|
||||
|
||||
Calendar.ISO.iso_days_to_unit({0, fraction1}, unit) -
|
||||
Calendar.ISO.iso_days_to_unit({0, fraction2}, unit)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the given time with the microsecond field truncated to the given
|
||||
precision (`:microsecond`, `millisecond` or `:second`).
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Time.truncate(~T[01:01:01.123456], :microsecond)
|
||||
~T[01:01:01.123456]
|
||||
|
||||
iex> Time.truncate(~T[01:01:01.123456], :millisecond)
|
||||
~T[01:01:01.123]
|
||||
|
||||
iex> Time.truncate(~T[01:01:01.123456], :second)
|
||||
~T[01:01:01]
|
||||
|
||||
"""
|
||||
@spec truncate(t(), :microsecond | :millisecond | :second) :: t()
|
||||
def truncate(%Time{microsecond: microsecond} = time, precision) do
|
||||
%{time | microsecond: Calendar.truncate(microsecond, precision)}
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
defp to_day_fraction(%{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: {_, _} = microsecond,
|
||||
calendar: calendar
|
||||
}) do
|
||||
calendar.time_to_day_fraction(hour, minute, second, microsecond)
|
||||
end
|
||||
|
||||
defimpl String.Chars do
|
||||
def to_string(time) do
|
||||
%{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: calendar
|
||||
} = time
|
||||
|
||||
calendar.time_to_string(hour, minute, second, microsecond)
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
def inspect(%{calendar: Calendar.ISO} = time, _) do
|
||||
%{
|
||||
hour: hour,
|
||||
minute: minute,
|
||||
second: second,
|
||||
microsecond: microsecond,
|
||||
calendar: Calendar.ISO
|
||||
} = time
|
||||
|
||||
"~T[" <> Calendar.ISO.time_to_string(hour, minute, second, microsecond) <> "]"
|
||||
end
|
||||
|
||||
def inspect(time, opts) do
|
||||
Inspect.Any.inspect(time, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
+132
-474
@@ -1,6 +1,6 @@
|
||||
defmodule Code do
|
||||
@moduledoc """
|
||||
Utilities for managing code compilation, code evaluation, and code loading.
|
||||
Utilities for managing code compilation, code evaluation and code loading.
|
||||
|
||||
This module complements Erlang's [`:code` module](http://www.erlang.org/doc/man/code.html)
|
||||
to add behaviour which is specific to Elixir. Almost all of the functions in this module
|
||||
@@ -13,13 +13,11 @@ defmodule Code do
|
||||
## Examples
|
||||
|
||||
Code.require_file("../eex/test/eex_test.exs")
|
||||
List.first(Code.loaded_files()) =~ "eex_test.exs"
|
||||
#=> true
|
||||
List.first(Code.loaded_files) =~ "eex_test.exs" #=> true
|
||||
|
||||
"""
|
||||
@spec loaded_files() :: [binary]
|
||||
def loaded_files do
|
||||
:elixir_code_server.call(:loaded)
|
||||
:elixir_code_server.call :loaded
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -33,15 +31,12 @@ defmodule Code do
|
||||
|
||||
# Load EEx test code, unload file, check for functions still available
|
||||
Code.load_file("../eex/test/eex_test.exs")
|
||||
|
||||
Code.unload_files(Code.loaded_files())
|
||||
function_exported?(EExTest.Compiled, :before_compile, 0)
|
||||
#=> true
|
||||
Code.unload_files(Code.loaded_files)
|
||||
function_exported?(EExTest.Compiled, :before_compile, 0) #=> true
|
||||
|
||||
"""
|
||||
@spec unload_files([binary]) :: :ok
|
||||
def unload_files(files) do
|
||||
:elixir_code_server.cast({:unload_files, files})
|
||||
:elixir_code_server.cast {:unload_files, files}
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -55,16 +50,13 @@ defmodule Code do
|
||||
|
||||
## Examples
|
||||
|
||||
Code.append_path(".")
|
||||
#=> true
|
||||
Code.append_path(".") #=> true
|
||||
|
||||
Code.append_path("/does_not_exist")
|
||||
#=> {:error, :bad_directory}
|
||||
Code.append_path("/does_not_exist") #=> {:error, :bad_directory}
|
||||
|
||||
"""
|
||||
@spec append_path(Path.t()) :: true | {:error, :bad_directory}
|
||||
def append_path(path) do
|
||||
:code.add_pathz(to_charlist(Path.expand(path)))
|
||||
:code.add_pathz(to_charlist(Path.expand path))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -78,16 +70,13 @@ defmodule Code do
|
||||
|
||||
## Examples
|
||||
|
||||
Code.prepend_path(".")
|
||||
#=> true
|
||||
Code.prepend_path(".") #=> true
|
||||
|
||||
Code.prepend_path("/does_not_exist")
|
||||
#=> {:error, :bad_directory}
|
||||
Code.prepend_path("/does_not_exist") #=> {:error, :bad_directory}
|
||||
|
||||
"""
|
||||
@spec prepend_path(Path.t()) :: true | {:error, :bad_directory}
|
||||
def prepend_path(path) do
|
||||
:code.add_patha(to_charlist(Path.expand(path)))
|
||||
:code.add_patha(to_charlist(Path.expand path))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -95,21 +84,18 @@ defmodule Code do
|
||||
directories the Erlang VM uses for finding module code.
|
||||
|
||||
The path is expanded with `Path.expand/1` before being deleted. If the
|
||||
path does not exist, this function returns `false`.
|
||||
path does not exist it returns `false`.
|
||||
|
||||
## Examples
|
||||
|
||||
Code.prepend_path(".")
|
||||
Code.delete_path(".")
|
||||
#=> true
|
||||
Code.delete_path(".") #=> true
|
||||
|
||||
Code.delete_path("/does_not_exist")
|
||||
#=> false
|
||||
Code.delete_path("/does_not_exist") #=> false
|
||||
|
||||
"""
|
||||
@spec delete_path(Path.t()) :: boolean
|
||||
def delete_path(path) do
|
||||
:code.del_path(to_charlist(Path.expand(path)))
|
||||
:code.del_path(to_charlist(Path.expand path))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -118,18 +104,11 @@ defmodule Code do
|
||||
The `binding` argument is a keyword list of variable bindings.
|
||||
The `opts` argument is a keyword list of environment options.
|
||||
|
||||
**Warning**: `string` can be any Elixir code and will be executed with
|
||||
the same privileges as the Erlang VM: this means that such code could
|
||||
compromise the machine (for example by executing system commands).
|
||||
Don't use `eval_string/3` with untrusted input (such as strings coming
|
||||
from the network).
|
||||
|
||||
## Options
|
||||
|
||||
Options can be:
|
||||
|
||||
* `:file` - the file to be considered in the evaluation
|
||||
|
||||
* `:line` - the line on which the script starts
|
||||
|
||||
Additionally, the following scope values can be configured:
|
||||
@@ -147,10 +126,10 @@ defmodule Code do
|
||||
of function names and arity must be sorted
|
||||
|
||||
Notice that setting any of the values above overrides Elixir's default
|
||||
values. For example, setting `:requires` to `[]` will no longer
|
||||
automatically require the `Kernel` module. In the same way setting
|
||||
`:macros` will no longer auto-import `Kernel` macros like `Kernel.if/2`,
|
||||
`Kernel.SpecialForms.case/2`, and so on.
|
||||
values. For example, setting `:requires` to `[]`, will no longer
|
||||
automatically require the `Kernel` module; in the same way setting
|
||||
`:macros` will no longer auto-import `Kernel` macros like `if/2`, `case/2`,
|
||||
etc.
|
||||
|
||||
Returns a tuple of the form `{value, binding}`,
|
||||
where `value` is the value returned from evaluating `string`.
|
||||
@@ -179,283 +158,19 @@ defmodule Code do
|
||||
{3, [a: 1, b: 2]}
|
||||
|
||||
"""
|
||||
@spec eval_string(List.Chars.t(), list, Macro.Env.t() | keyword) :: {term, binding :: list}
|
||||
def eval_string(string, binding \\ [], opts \\ [])
|
||||
|
||||
def eval_string(string, binding, %Macro.Env{} = env) do
|
||||
{value, binding, _env, _scope} = :elixir.eval(to_charlist(string), binding, Map.to_list(env))
|
||||
{value, binding, _env, _scope} = :elixir.eval to_charlist(string), binding, Map.to_list(env)
|
||||
{value, binding}
|
||||
end
|
||||
|
||||
def eval_string(string, binding, opts) when is_list(opts) do
|
||||
validate_eval_opts(opts)
|
||||
{value, binding, _env, _scope} = :elixir.eval(to_charlist(string), binding, opts)
|
||||
{value, binding, _env, _scope} = :elixir.eval to_charlist(string), binding, opts
|
||||
{value, binding}
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
Formats the given code `string`.
|
||||
|
||||
The formatter receives a string representing Elixir code and
|
||||
returns iodata representing the formatted code according to
|
||||
pre-defined rules.
|
||||
|
||||
## Options
|
||||
|
||||
* `:file` - the file which contains the string, used for error
|
||||
reporting
|
||||
|
||||
* `:line` - the line the string starts, used for error reporting
|
||||
|
||||
* `:line_length` - the line length to aim for when formatting
|
||||
the document. Defaults to 98.
|
||||
|
||||
* `:locals_without_parens` - a keyword list of name and arity
|
||||
pairs that should be kept without parens whenever possible.
|
||||
The arity may be the atom `:*`, which implies all arities of
|
||||
that name. The formatter already includes a list of functions
|
||||
and this option augments this list.
|
||||
|
||||
* `:rename_deprecated_at` - rename all known deprecated functions
|
||||
at the given version to their non-deprecated equivalent. It
|
||||
expects a valid `Version` which is usually the minimum Elixir
|
||||
version supported by the project.
|
||||
|
||||
## Design principles
|
||||
|
||||
The formatter was designed under three principles.
|
||||
|
||||
First, the formatter never changes the semantics of the code by
|
||||
default. This means the input AST and the output AST are equivalent.
|
||||
Optional behaviour, such as `:rename_deprecated_at`, is allowed to
|
||||
break this guarantee.
|
||||
|
||||
The second principle is to provide as little configuration as possible.
|
||||
This eases the formatter adoption by removing contention points while
|
||||
making sure a single style is followed consistently by the community as
|
||||
a whole.
|
||||
|
||||
The formatter does not hard code names. The formatter will not behave
|
||||
specially because a function is named `defmodule`, `def`, etc. This
|
||||
principle mirrors Elixir's goal of being an extensible language where
|
||||
developers can extend the language with new constructs as if they were
|
||||
part of the language. When it is absolutely necessary to change behaviour
|
||||
based on the name, this behaviour should be configurable, such as the
|
||||
`:locals_without_parens` option.
|
||||
|
||||
## Keeping user's formatting
|
||||
|
||||
The formatter respects the input format in some cases. Those are
|
||||
listed below:
|
||||
|
||||
* Insignificant digits in numbers are kept as is. The formatter
|
||||
however always inserts underscores for decimal numbers with more
|
||||
than 5 digits and converts hexadecimal digits to uppercase
|
||||
|
||||
* Strings, charlists, atoms and sigils are kept as is. No character
|
||||
is automatically escaped or unescaped. The choice of delimiter is
|
||||
also respected from the input
|
||||
|
||||
* Newlines inside blocks are kept as in the input except for:
|
||||
1) expressions that take multiple lines will always have an empty
|
||||
line before and after and 2) empty lines are always squeezed
|
||||
together into a single empty line
|
||||
|
||||
* The choice between `:do` keyword and `do/end` blocks is left
|
||||
to the user
|
||||
|
||||
* Lists, tuples, bitstrings, maps, structs and function calls will be
|
||||
broken into multiple lines if they are followed by a newline in the
|
||||
opening bracket and preceded by a new line in the closing bracket
|
||||
|
||||
* Pipeline operators, like `|>` and others with the same precedence,
|
||||
will span multiple lines if they spanned multiple lines in the input
|
||||
|
||||
The behaviours above are not guaranteed. We may remove or add new
|
||||
rules in the future. The goal of documenting them is to provide better
|
||||
understanding on what to expect from the formatter.
|
||||
|
||||
## Adjusting formatted output
|
||||
|
||||
The formatter attempts to the fit the most it can on a single line.
|
||||
When the code does not fit a single line, the formatter introduces
|
||||
line breaks in the code.
|
||||
|
||||
In some rare situations, this may lead to undesired formatting.
|
||||
For example, the code below:
|
||||
|
||||
"this is a very long string ... #{inspect(some_value)}"
|
||||
|
||||
may be formatted as:
|
||||
|
||||
"this is a very long string ... #{
|
||||
inspect(some_value)
|
||||
}"
|
||||
|
||||
This happens because the only place the formatter can introduce a
|
||||
new line without changing the code semantics is in the interpolation.
|
||||
In those scenarios, we recommend developers to directly adjust the
|
||||
code. Here we can use the binary concatenation operator `<>`:
|
||||
|
||||
"this is a very long string " <>
|
||||
"... #{inspect(some_value)}"
|
||||
|
||||
The string concatenation makes the code fit on a single line and also
|
||||
gives more options to the formatter.
|
||||
|
||||
A similar example is when the formatter breaks a function definition
|
||||
over multiple clauses:
|
||||
|
||||
def my_function(
|
||||
%User{name: name, age: age, ...},
|
||||
arg1,
|
||||
arg2
|
||||
) do
|
||||
|
||||
While the code above is completely valid, you may prefer to match on
|
||||
the struct variables inside the function body in order to keep the
|
||||
definition on a single line:
|
||||
|
||||
def my_function(%User{} = user, arg1, arg2) do
|
||||
%{name: name, age: age, ...} = user
|
||||
|
||||
Since the formatter cannot change the semantics of your code,
|
||||
sometimes it is necessary to tweak the code to get optimal formatting.
|
||||
|
||||
### 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
|
||||
bracket and a new line before the closing bracket lines. For example:
|
||||
|
||||
[
|
||||
foo,
|
||||
bar
|
||||
]
|
||||
|
||||
If there are no newlines around the brackets, then the formatter will
|
||||
try to fit everything on a single line, such that the snippet below
|
||||
|
||||
[foo,
|
||||
bar]
|
||||
|
||||
will be formatted as
|
||||
|
||||
[foo, bar]
|
||||
|
||||
You can also force function calls and keywords to be rendered on multiple
|
||||
lines by having each entry on its own line:
|
||||
|
||||
defstruct name: nil,
|
||||
age: 0
|
||||
|
||||
The code above will be kept with one keyword entry per line by the
|
||||
formatter. To avoid that, just squash everything into a single line.
|
||||
|
||||
### Parens and no parens in function calls
|
||||
|
||||
Elixir has two syntaxes for function calls. With parens and no parens.
|
||||
By default, Elixir will add parens to all calls except for:
|
||||
|
||||
1. calls that have do/end blocks
|
||||
2. local calls without parens where the name and arity of the local
|
||||
call is also listed under `:locals_without_parens`
|
||||
|
||||
The choice of parens and no parens also affects indentation. When a
|
||||
function call with parens doesn't fit on the same line, the formatter
|
||||
introduces a newline around parens and indents the arguments with two
|
||||
spaces:
|
||||
|
||||
some_call(
|
||||
arg1,
|
||||
arg2,
|
||||
arg3
|
||||
)
|
||||
|
||||
On the other hand, function calls without parens are always indented
|
||||
by the function call length itself, like this:
|
||||
|
||||
some_call arg1,
|
||||
arg2,
|
||||
arg3
|
||||
|
||||
If the last argument is a data structure, such as maps and lists, and
|
||||
the beginning of the data structure fits on the same line as the function
|
||||
call, then no indentation happens, this allows code like this:
|
||||
|
||||
Enum.reduce(some_collection, initial_value, fn element, acc ->
|
||||
# code
|
||||
end)
|
||||
|
||||
some_funtion_without_parens %{
|
||||
foo: :bar,
|
||||
baz: :bat
|
||||
}
|
||||
|
||||
## Code comments
|
||||
|
||||
The formatter also handles code comments in a way to guarantee a space
|
||||
is always added between the beginning of the comment (#) and the next
|
||||
character.
|
||||
|
||||
The formatter also extracts all trailing comments to their previous line.
|
||||
For example, the code below
|
||||
|
||||
hello # world
|
||||
|
||||
will be rewritten to
|
||||
|
||||
# world
|
||||
hello
|
||||
|
||||
Because code comments are handled apart from the code representation (AST),
|
||||
there are some situations where code comments are seen as ambiguous by the
|
||||
code formatter. For example, the comment in the anonymous function below
|
||||
|
||||
fn
|
||||
arg1 ->
|
||||
body1
|
||||
# comment
|
||||
|
||||
arg2 ->
|
||||
body2
|
||||
end
|
||||
|
||||
and in this one
|
||||
|
||||
fn
|
||||
arg1 ->
|
||||
body1
|
||||
|
||||
# comment
|
||||
arg2 ->
|
||||
body2
|
||||
end
|
||||
|
||||
are considered equivalent (the nesting is discarded alongside most of
|
||||
user formatting). In such cases, the code formatter will always format to
|
||||
the latter.
|
||||
"""
|
||||
@spec format_string!(binary, keyword) :: iodata
|
||||
def format_string!(string, opts \\ []) when is_binary(string) and is_list(opts) do
|
||||
line_length = Keyword.get(opts, :line_length, 98)
|
||||
algebra = Code.Formatter.to_algebra!(string, opts)
|
||||
Inspect.Algebra.format(algebra, line_length)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Formats a file.
|
||||
|
||||
See `format_string!/2` for more information on code formatting and
|
||||
available options.
|
||||
"""
|
||||
@spec format_file!(binary, keyword) :: iodata
|
||||
def format_file!(file, opts \\ []) when is_binary(file) and is_list(opts) do
|
||||
string = File.read!(file)
|
||||
formatted = format_string!(string, [file: file, line: 1] ++ opts)
|
||||
[formatted, ?\n]
|
||||
end
|
||||
|
||||
@doc """
|
||||
Evaluates the quoted contents.
|
||||
|
||||
@@ -480,25 +195,24 @@ defmodule Code do
|
||||
{3, [a: 1, b: 2]}
|
||||
|
||||
"""
|
||||
@spec eval_quoted(Macro.t(), list, Macro.Env.t() | keyword) :: {term, binding :: list}
|
||||
def eval_quoted(quoted, binding \\ [], opts \\ [])
|
||||
|
||||
def eval_quoted(quoted, binding, %Macro.Env{} = env) do
|
||||
{value, binding, _env, _scope} = :elixir.eval_quoted(quoted, binding, Map.to_list(env))
|
||||
{value, binding, _env, _scope} = :elixir.eval_quoted quoted, binding, Map.to_list(env)
|
||||
{value, binding}
|
||||
end
|
||||
|
||||
def eval_quoted(quoted, binding, opts) when is_list(opts) do
|
||||
validate_eval_opts(opts)
|
||||
{value, binding, _env, _scope} = :elixir.eval_quoted(quoted, binding, opts)
|
||||
{value, binding, _env, _scope} = :elixir.eval_quoted quoted, binding, opts
|
||||
{value, binding}
|
||||
end
|
||||
|
||||
defp validate_eval_opts(opts) do
|
||||
if f = opts[:functions], do: validate_imports(:functions, f)
|
||||
if m = opts[:macros], do: validate_imports(:macros, m)
|
||||
if a = opts[:aliases], do: validate_aliases(:aliases, a)
|
||||
if r = opts[:requires], do: validate_requires(:requires, r)
|
||||
if m = opts[:macros], do: validate_imports(:macros, m)
|
||||
if a = opts[:aliases], do: validate_aliases(:aliases, a)
|
||||
if r = opts[:requires], do: validate_requires(:requires, r)
|
||||
end
|
||||
|
||||
defp validate_requires(kind, requires) do
|
||||
@@ -510,64 +224,53 @@ defmodule Code do
|
||||
end
|
||||
|
||||
defp validate_aliases(kind, aliases) do
|
||||
valid = is_list(aliases) and Enum.all?(aliases, fn {k, v} -> is_atom(k) and is_atom(v) end)
|
||||
valid = is_list(aliases) and Enum.all?(aliases, fn {k, v} ->
|
||||
is_atom(k) and is_atom(v)
|
||||
end)
|
||||
|
||||
unless valid do
|
||||
raise ArgumentError,
|
||||
"expected :#{kind} option given to eval in the format: [{module, module}]"
|
||||
raise ArgumentError, "expected :#{kind} option given to eval in the format: [{module, module}]"
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_imports(kind, imports) do
|
||||
valid =
|
||||
is_list(imports) and
|
||||
Enum.all?(imports, fn {k, v} ->
|
||||
is_atom(k) and is_list(v) and
|
||||
Enum.all?(v, fn {name, arity} -> is_atom(name) and is_integer(arity) end)
|
||||
end)
|
||||
valid = is_list(imports) and Enum.all?(imports, fn {k, v} ->
|
||||
is_atom(k) and is_list(v) and Enum.all?(v, fn {name, arity} ->
|
||||
is_atom(name) and is_integer(arity)
|
||||
end)
|
||||
end)
|
||||
|
||||
unless valid do
|
||||
raise ArgumentError,
|
||||
"expected :#{kind} option given to eval in the format: [{module, [{name, arity}]}]"
|
||||
raise ArgumentError, "expected :#{kind} option given to eval in the format: [{module, [{name, arity}]}]"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts the given string to its quoted form.
|
||||
|
||||
Returns `{:ok, quoted_form}` if it succeeds,
|
||||
`{:error, {line, error, token}}` otherwise.
|
||||
Returns `{:ok, quoted_form}`
|
||||
if it succeeds, `{:error, {line, error, token}}` otherwise.
|
||||
|
||||
## Options
|
||||
|
||||
* `:file` - the filename to be reported in case of parsing errors.
|
||||
Defaults to "nofile".
|
||||
* `:file` - the filename to be used in stacktraces
|
||||
and the file reported in the `__ENV__/0` macro
|
||||
|
||||
* `:line` - the starting line of the string being parsed.
|
||||
Defaults to 1.
|
||||
|
||||
* `:columns` - when `true`, attach a `:column` key to the quoted
|
||||
metadata. Defaults to `false`.
|
||||
* `:line` - the line reported in the `__ENV__/0` macro
|
||||
|
||||
* `:existing_atoms_only` - when `true`, raises an error
|
||||
when non-existing atoms are found by the tokenizer.
|
||||
Defaults to `false`.
|
||||
when non-existing atoms are found by the tokenizer
|
||||
|
||||
## `Macro.to_string/2`
|
||||
## Macro.to_string/2
|
||||
|
||||
The opposite of converting a string to its quoted form is
|
||||
`Macro.to_string/2`, which converts a quoted form to a string/binary
|
||||
representation.
|
||||
"""
|
||||
@spec string_to_quoted(List.Chars.t(), keyword) ::
|
||||
{:ok, Macro.t()} | {:error, {line :: pos_integer, term, term}}
|
||||
def string_to_quoted(string, opts \\ []) when is_list(opts) do
|
||||
file = Keyword.get(opts, :file, "nofile")
|
||||
line = Keyword.get(opts, :line, 1)
|
||||
|
||||
with {:ok, tokens} <- :elixir.string_to_tokens(to_charlist(string), line, file, opts) do
|
||||
:elixir.tokens_to_quoted(tokens, file, opts)
|
||||
end
|
||||
file = Keyword.get opts, :file, "nofile"
|
||||
line = Keyword.get opts, :line, 1
|
||||
:elixir.string_to_quoted(to_charlist(string), line, file, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -580,10 +283,9 @@ defmodule Code do
|
||||
|
||||
Check `string_to_quoted/2` for options information.
|
||||
"""
|
||||
@spec string_to_quoted!(List.Chars.t(), keyword) :: Macro.t()
|
||||
def string_to_quoted!(string, opts \\ []) when is_list(opts) do
|
||||
file = Keyword.get(opts, :file, "nofile")
|
||||
line = Keyword.get(opts, :line, 1)
|
||||
file = Keyword.get opts, :file, "nofile"
|
||||
line = Keyword.get opts, :line, 1
|
||||
:elixir.string_to_quoted!(to_charlist(string), line, file, opts)
|
||||
end
|
||||
|
||||
@@ -592,14 +294,13 @@ defmodule Code do
|
||||
|
||||
Accepts `relative_to` as an argument to tell where the file is located.
|
||||
|
||||
While `load_file/2` loads a file and returns the loaded modules and their
|
||||
byte code, `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`).
|
||||
While `load_file` loads a file and returns the loaded modules and their
|
||||
byte code, `eval_file` simply evaluates the file contents and returns the
|
||||
evaluation result and its bindings.
|
||||
"""
|
||||
@spec eval_file(binary, nil | binary) :: {term, binding :: list}
|
||||
def eval_file(file, relative_to \\ nil) when is_binary(file) do
|
||||
def eval_file(file, relative_to \\ nil) do
|
||||
file = find_file(file, relative_to)
|
||||
eval_string(File.read!(file), [], file: file, line: 1)
|
||||
eval_string File.read!(file), [], [file: file, line: 1]
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -608,26 +309,24 @@ defmodule Code do
|
||||
Accepts `relative_to` as an argument to tell where the file is located.
|
||||
If the file was already required/loaded, loads it again.
|
||||
|
||||
It returns a list of tuples `{ModuleName, bytecode}`, one tuple for
|
||||
It returns a list of tuples `{ModuleName, <<byte_code>>}`, one tuple for
|
||||
each module defined in the file.
|
||||
|
||||
Notice that if `load_file/2` is invoked by different processes concurrently,
|
||||
Notice that if `load_file` is invoked by different processes concurrently,
|
||||
the target file will be loaded concurrently many times. Check `require_file/2`
|
||||
if you don't want a file to be loaded concurrently.
|
||||
|
||||
## Examples
|
||||
|
||||
modules = Code.load_file("eex_test.exs", "../eex/test")
|
||||
List.first(modules)
|
||||
Code.load_file("eex_test.exs", "../eex/test") |> List.first
|
||||
#=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>}
|
||||
|
||||
"""
|
||||
@spec load_file(binary, nil | binary) :: [{module, binary}]
|
||||
def load_file(file, relative_to \\ nil) when is_binary(file) do
|
||||
file = find_file(file, relative_to)
|
||||
:elixir_code_server.call({:acquire, file})
|
||||
loaded = :elixir_compiler.file(file)
|
||||
:elixir_code_server.cast({:loaded, file})
|
||||
:elixir_code_server.call {:acquire, file}
|
||||
loaded = :elixir_compiler.file file
|
||||
:elixir_code_server.cast {:loaded, file}
|
||||
loaded
|
||||
end
|
||||
|
||||
@@ -636,46 +335,40 @@ defmodule Code do
|
||||
|
||||
Accepts `relative_to` as an argument to tell where the file is located.
|
||||
The return value is the same as that of `load_file/2`. If the file was already
|
||||
required or loaded, `require_file/2` doesn't do anything and returns `nil`.
|
||||
required/loaded, doesn't do anything and returns `nil`.
|
||||
|
||||
Notice that if `require_file/2` is invoked by different processes concurrently,
|
||||
the first process to invoke `require_file/2` acquires a lock and the remaining
|
||||
ones will block until the file is available. This means that if `require_file/2` is called
|
||||
more than one times with a given file, that file will be loaded only once. The first process to
|
||||
call `require_file/2` will get the list of loaded modules, others will get `nil`.
|
||||
Notice that if `require_file` is invoked by different processes concurrently,
|
||||
the first process to invoke `require_file` acquires a lock and the remaining
|
||||
ones will block until the file is available. I.e. if `require_file` is called
|
||||
N times with a given file, it will be loaded only once. The first process to
|
||||
call `require_file` will get the list of loaded modules, others will get `nil`.
|
||||
|
||||
Check `load_file/2` if you want to load a file multiple times. See also `unload_files/1`.
|
||||
Check `load_file/2` if you want a file to be loaded multiple times. See also
|
||||
`unload_files/1`
|
||||
|
||||
## Examples
|
||||
|
||||
If the code is already loaded, it returns `nil`:
|
||||
|
||||
Code.require_file("eex_test.exs", "../eex/test")
|
||||
#=> nil
|
||||
Code.require_file("eex_test.exs", "../eex/test") #=> nil
|
||||
|
||||
If the code is not loaded yet, it returns the same as `load_file/2`:
|
||||
|
||||
modules = Code.require_file("eex_test.exs", "../eex/test")
|
||||
List.first(modules)
|
||||
Code.require_file("eex_test.exs", "../eex/test") |> List.first
|
||||
#=> {EExTest.Compiled, <<70, 79, 82, 49, ...>>}
|
||||
|
||||
"""
|
||||
@spec require_file(binary, nil | binary) :: [{module, binary}] | nil
|
||||
def require_file(file, relative_to \\ nil) when is_binary(file) do
|
||||
file = find_file(file, relative_to)
|
||||
|
||||
case :elixir_code_server.call({:acquire, file}) do
|
||||
:loaded ->
|
||||
:loaded ->
|
||||
nil
|
||||
|
||||
{:queued, ref} ->
|
||||
receive do
|
||||
{:elixir_code_server, ^ref, :loaded} -> nil
|
||||
end
|
||||
|
||||
{:queued, ref} ->
|
||||
receive do {:elixir_code_server, ^ref, :loaded} -> nil end
|
||||
:proceed ->
|
||||
loaded = :elixir_compiler.file(file)
|
||||
:elixir_code_server.cast({:loaded, file})
|
||||
loaded = :elixir_compiler.file file
|
||||
:elixir_code_server.cast {:loaded, file}
|
||||
loaded
|
||||
end
|
||||
end
|
||||
@@ -687,20 +380,19 @@ defmodule Code do
|
||||
|
||||
## Examples
|
||||
|
||||
Code.compiler_options()
|
||||
Code.compiler_options
|
||||
#=> %{debug_info: true, docs: true,
|
||||
#=> warnings_as_errors: false, ignore_module_conflict: false}
|
||||
warnings_as_errors: false, ignore_module_conflict: false}
|
||||
|
||||
"""
|
||||
@spec compiler_options() :: %{optional(atom) => boolean}
|
||||
def compiler_options do
|
||||
:elixir_config.get(:compiler_options)
|
||||
:elixir_config.get :compiler_options
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a list with the available compiler options.
|
||||
|
||||
See `compiler_options/1` for more info.
|
||||
See `Code.compiler_options/1` for more info.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -708,7 +400,6 @@ defmodule Code do
|
||||
[:docs, :debug_info, :ignore_module_conflict, :relative_paths, :warnings_as_errors]
|
||||
|
||||
"""
|
||||
@spec available_compiler_options() :: [atom]
|
||||
def available_compiler_options do
|
||||
[:docs, :debug_info, :ignore_module_conflict, :relative_paths, :warnings_as_errors]
|
||||
end
|
||||
@@ -720,78 +411,69 @@ defmodule Code do
|
||||
|
||||
Available options are:
|
||||
|
||||
* `:docs` - when `true`, retain documentation in the compiled module.
|
||||
Defaults to `true`.
|
||||
* `:docs` - when `true`, retain documentation in the compiled module,
|
||||
`true` by default
|
||||
|
||||
* `:debug_info` - when `true`, retain debug information in the compiled
|
||||
module. This allows a developer to reconstruct the original source
|
||||
code. Defaults to `false`.
|
||||
module; this allows a developer to reconstruct the original source
|
||||
code, `false` by default
|
||||
|
||||
* `:ignore_module_conflict` - when `true`, override modules that were
|
||||
already defined without raising errors. Defaults to `false`.
|
||||
already defined without raising errors, `false` by default
|
||||
|
||||
* `:relative_paths` - when `true`, use relative paths in quoted nodes,
|
||||
warnings and errors generated by the compiler. Note disabling this option
|
||||
won't affect runtime warnings and errors. Defaults to `true`.
|
||||
warnings and errors generated by the compiler, `true` by default.
|
||||
Note disabling this option won't affect runtime warnings and errors.
|
||||
|
||||
* `:warnings_as_errors` - causes compilation to fail when warnings are
|
||||
generated. Defaults to `false`.
|
||||
generated
|
||||
|
||||
It returns the new map of compiler options.
|
||||
It returns the new list of compiler options.
|
||||
|
||||
## Examples
|
||||
|
||||
Code.compiler_options(debug_info: true)
|
||||
#=> %{debug_info: true, docs: true,
|
||||
#=> warnings_as_errors: false, ignore_module_conflict: false}
|
||||
warnings_as_errors: false, ignore_module_conflict: false}
|
||||
|
||||
"""
|
||||
@spec compiler_options(Enumerable.t()) :: %{optional(atom) => boolean}
|
||||
def compiler_options(opts) do
|
||||
available = available_compiler_options()
|
||||
|
||||
Enum.each(opts, fn {key, value} ->
|
||||
Enum.each(opts, fn({key, value}) ->
|
||||
cond do
|
||||
key not in available ->
|
||||
not key in available ->
|
||||
raise "unknown compiler option: #{inspect(key)}"
|
||||
|
||||
not is_boolean(value) ->
|
||||
raise "compiler option #{inspect(key)} should be a boolean, got: #{inspect(value)}"
|
||||
|
||||
true ->
|
||||
:ok
|
||||
end
|
||||
end)
|
||||
|
||||
:elixir_config.update(:compiler_options, &Enum.into(opts, &1))
|
||||
:elixir_config.update :compiler_options, &Enum.into(opts, &1)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compiles the given string.
|
||||
|
||||
Returns a list of tuples where the first element is the module name
|
||||
and the second one is its bytecode (as a binary). A `file` can be
|
||||
given as second argument which will be used for reporting warnings
|
||||
and errors.
|
||||
and the second one is its byte code (as a binary).
|
||||
|
||||
For compiling many files at once, check `Kernel.ParallelCompiler.compile/2`.
|
||||
For compiling many files at once, check `Kernel.ParallelCompiler.files/2`.
|
||||
"""
|
||||
@spec compile_string(List.Chars.t(), binary) :: [{module, binary}]
|
||||
def compile_string(string, file \\ "nofile") when is_binary(file) do
|
||||
:elixir_compiler.string(to_charlist(string), file)
|
||||
:elixir_compiler.string to_charlist(string), file
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compiles the quoted expression.
|
||||
|
||||
Returns a list of tuples where the first element is the module name and
|
||||
the second one is its bytecode (as a binary). A `file` can be
|
||||
given as second argument which will be used for reporting warnings
|
||||
and errors.
|
||||
the second one is its byte code (as a binary).
|
||||
"""
|
||||
@spec compile_quoted(Macro.t(), binary) :: [{module, binary}]
|
||||
def compile_quoted(quoted, file \\ "nofile") when is_binary(file) do
|
||||
:elixir_compiler.quoted(quoted, file)
|
||||
:elixir_compiler.quoted quoted, file
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -800,7 +482,7 @@ defmodule Code do
|
||||
If the module is already loaded, this works as no-op. If the module
|
||||
was not yet loaded, it tries to load it.
|
||||
|
||||
If it succeeds in loading the module, it returns `{:module, module}`.
|
||||
If it succeeds loading the module, it returns `{:module, module}`.
|
||||
If not, returns `{:error, reason}` with the error reason.
|
||||
|
||||
## Code loading on the Erlang VM
|
||||
@@ -816,7 +498,7 @@ defmodule Code do
|
||||
module uses this function to check if a specific parser exists for a given
|
||||
URI scheme.
|
||||
|
||||
## `ensure_compiled/1`
|
||||
## Code.ensure_compiled/1
|
||||
|
||||
Elixir also contains an `ensure_compiled/1` function that is a
|
||||
superset of `ensure_loaded/1`.
|
||||
@@ -825,13 +507,8 @@ defmodule Code do
|
||||
you may need to use a module that was not yet compiled, therefore
|
||||
it can't even be loaded.
|
||||
|
||||
When invoked, `ensure_compiled/1` halts the compilation of the caller
|
||||
until the module given to `ensure_compiled/1` becomes available or
|
||||
all files for the current project have been compiled. If compilation
|
||||
finishes and the module is not available, an error tuple is returned.
|
||||
|
||||
`ensure_compiled/1` does not apply to dependencies, as dependencies
|
||||
must be compiled upfront.
|
||||
`ensure_compiled/1` halts the current process until the
|
||||
module we are depending on is available.
|
||||
|
||||
In most cases, `ensure_loaded/1` is enough. `ensure_compiled/1`
|
||||
must be used in rare cases, usually involving macros that need to
|
||||
@@ -847,7 +524,7 @@ defmodule Code do
|
||||
|
||||
"""
|
||||
@spec ensure_loaded(module) ::
|
||||
{:module, module} | {:error, :embedded | :badfile | :nofile | :on_load_failure}
|
||||
{:module, module} | {:error, :embedded | :badfile | :nofile | :on_load_failure}
|
||||
def ensure_loaded(module) when is_atom(module) do
|
||||
:code.ensure_loaded(module)
|
||||
end
|
||||
@@ -865,7 +542,6 @@ defmodule Code do
|
||||
true
|
||||
|
||||
"""
|
||||
@spec ensure_loaded?(module) :: boolean
|
||||
def ensure_loaded?(module) when is_atom(module) do
|
||||
match?({:module, ^module}, ensure_loaded(module))
|
||||
end
|
||||
@@ -877,26 +553,24 @@ defmodule Code do
|
||||
not loaded yet, it checks if it needs to be compiled first and then
|
||||
tries to load it.
|
||||
|
||||
If it succeeds in loading the module, it returns `{:module, module}`.
|
||||
If it succeeds loading the module, it returns `{:module, module}`.
|
||||
If not, returns `{:error, reason}` with the error reason.
|
||||
|
||||
Check `ensure_loaded/1` for more information on module loading
|
||||
and when to use `ensure_loaded/1` or `ensure_compiled/1`.
|
||||
"""
|
||||
@spec ensure_compiled(module) ::
|
||||
{:module, module} | {:error, :embedded | :badfile | :nofile | :on_load_failure}
|
||||
{:module, module} | {:error, :embedded | :badfile | :nofile | :on_load_failure}
|
||||
def ensure_compiled(module) when is_atom(module) do
|
||||
case :code.ensure_loaded(module) do
|
||||
{:error, :nofile} = error ->
|
||||
if is_pid(:erlang.get(:elixir_compiler_pid)) and
|
||||
Kernel.ErrorHandler.ensure_compiled(module, :module) do
|
||||
Kernel.ErrorHandler.ensure_compiled(module, :module) do
|
||||
{:module, module}
|
||||
else
|
||||
error
|
||||
end
|
||||
|
||||
other ->
|
||||
other
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
|
||||
@@ -917,64 +591,48 @@ defmodule Code do
|
||||
|
||||
When given a module name, it finds its BEAM code and reads the docs from it.
|
||||
|
||||
When given a path to a `.beam` file, it will load the docs directly from that
|
||||
When given a path to a .beam file, it will load the docs directly from that
|
||||
file.
|
||||
|
||||
The return value depends on the `kind` value:
|
||||
|
||||
* `:moduledoc` - tuple `{line, doc}` where `line` is the line on
|
||||
which the module definition starts and `doc` is the string
|
||||
attached to the module using the `@moduledoc` attribute,
|
||||
`false` if `@moduledoc false` was used, or `nil` if no `@moduledoc`
|
||||
was used.
|
||||
|
||||
* `:docs` - list of all docstrings attached to functions and macros
|
||||
using the `@doc` attribute. Each tuple has the form
|
||||
`{{name, arity}, line, kind, arguments, doc}`. `doc` can be either a
|
||||
string, `false` if `@doc false` was used, or `nil` if no doc was used.
|
||||
using the `@doc` attribute
|
||||
|
||||
* `:moduledoc` - tuple `{<line>, <doc>}` where `line` is the line on
|
||||
which module definition starts and `doc` is the string
|
||||
attached to the module using the `@moduledoc` attribute
|
||||
|
||||
* `:callback_docs` - list of all docstrings attached to
|
||||
`@callbacks` using the `@doc` attribute. Each tuple has the form
|
||||
`{{name, arity}, line, kind, doc}`. `doc` can be either a string or
|
||||
`nil` if no `@doc` was set.
|
||||
`@callbacks` using the `@doc` attribute
|
||||
|
||||
* `:type_docs` - list of all docstrings attached to `@type` callbacks
|
||||
using the `@typedoc` attribute. Each tuple has the form
|
||||
`{{name, arity}, line, kind, doc}`. `doc` can be either a string or
|
||||
`nil` if no `@typedoc` was used.
|
||||
* `:type_docs` - list of all docstrings attached to
|
||||
`@type` callbacks using the `@typedoc` attribute
|
||||
|
||||
* `:all` - a keyword list with `:docs`, `:moduledoc`, `:callback_docs`,
|
||||
* `:all` - a keyword list with `:docs` and `:moduledoc`, `:callback_docs`,
|
||||
and `:type_docs`.
|
||||
|
||||
If the module cannot be found, it returns `nil`.
|
||||
|
||||
## Examples
|
||||
|
||||
# Module documentation of an existing module
|
||||
# Get the module documentation
|
||||
iex> {_line, text} = Code.get_docs(Atom, :moduledoc)
|
||||
iex> text |> String.split("\n") |> Enum.at(0)
|
||||
iex> String.split(text, "\n") |> Enum.at(0)
|
||||
"Convenience functions for working with atoms."
|
||||
|
||||
# A module that doesn't exist
|
||||
# Module doesn't exist
|
||||
iex> Code.get_docs(ModuleNotGood, :all)
|
||||
nil
|
||||
|
||||
"""
|
||||
@doc_kinds [:docs, :moduledoc, :callback_docs, :type_docs, :all]
|
||||
|
||||
@spec get_docs(module, :moduledoc) :: {line :: pos_integer, doc :: false | binary} | nil
|
||||
@spec get_docs(module, :docs) :: [{function, line, kind, list, doc}] | nil
|
||||
when function: {atom, arity}, line: pos_integer, kind: atom, doc: nil | false | binary
|
||||
@spec get_docs(module, :callback_docs) :: [{callback, line, kind, doc}] | nil
|
||||
when callback: {atom, arity}, line: pos_integer, kind: atom, doc: nil | false | binary
|
||||
@spec get_docs(module, :type_docs) :: [{type, line, kind, doc}] | nil
|
||||
when type: {atom, arity}, line: pos_integer, kind: atom, doc: nil | false | binary
|
||||
@spec get_docs(module, :all) :: keyword | nil
|
||||
def get_docs(module, kind)
|
||||
|
||||
def get_docs(module, kind) when is_atom(module) and kind in @doc_kinds do
|
||||
case :code.get_object_code(module) do
|
||||
{_module, bin, _beam_path} -> do_get_docs(bin, kind)
|
||||
{_module, bin, _beam_path} ->
|
||||
do_get_docs(bin, kind)
|
||||
|
||||
:error -> nil
|
||||
end
|
||||
end
|
||||
@@ -990,18 +648,19 @@ defmodule Code do
|
||||
{:ok, {_module, [{@docs_chunk, bin}]}} ->
|
||||
lookup_docs(:erlang.binary_to_term(bin), kind)
|
||||
|
||||
{:error, :beam_lib, {:missing_chunk, _, @docs_chunk}} ->
|
||||
nil
|
||||
{:error, :beam_lib, {:missing_chunk, _, @docs_chunk}} -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp lookup_docs({:elixir_docs_v1, docs}, kind), do: do_lookup_docs(docs, kind)
|
||||
defp lookup_docs({:elixir_docs_v1, docs}, kind),
|
||||
do: do_lookup_docs(docs, kind)
|
||||
|
||||
# unsupported chunk version
|
||||
defp lookup_docs(_, _), do: nil
|
||||
|
||||
defp do_lookup_docs(docs, :all), do: docs
|
||||
defp do_lookup_docs(docs, kind), do: Keyword.get(docs, kind)
|
||||
defp do_lookup_docs(docs, kind),
|
||||
do: Keyword.get(docs, kind)
|
||||
|
||||
## Helpers
|
||||
|
||||
@@ -1009,12 +668,11 @@ defmodule Code do
|
||||
#
|
||||
# If the file is found, returns its path in binary, fails otherwise.
|
||||
defp find_file(file, relative_to) do
|
||||
file =
|
||||
if relative_to do
|
||||
Path.expand(file, relative_to)
|
||||
else
|
||||
Path.expand(file)
|
||||
end
|
||||
file = if relative_to do
|
||||
Path.expand(file, relative_to)
|
||||
else
|
||||
Path.expand(file)
|
||||
end
|
||||
|
||||
if File.regular?(file) do
|
||||
file
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1,281 +0,0 @@
|
||||
defmodule Code.Identifier do
|
||||
@moduledoc false
|
||||
|
||||
@doc """
|
||||
Checks if the given identifier is an unary op.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Code.Identifier.unary_op(:+)
|
||||
{:non_associative, 300}
|
||||
|
||||
"""
|
||||
@spec unary_op(atom) :: {:non_associative, precedence :: pos_integer} | :error
|
||||
def unary_op(op) do
|
||||
cond do
|
||||
op in [:&] -> {:non_associative, 90}
|
||||
op in [:!, :^, :not, :+, :-, :~~~] -> {:non_associative, 300}
|
||||
op in [:@] -> {:non_associative, 320}
|
||||
true -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the given identifier is a binary op.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Code.Identifier.binary_op(:+)
|
||||
{:left, 210}
|
||||
|
||||
"""
|
||||
@spec binary_op(atom) :: {:left | :right, precedence :: pos_integer} | :error
|
||||
def binary_op(op) do
|
||||
cond do
|
||||
op in [:<-, :\\] -> {:left, 40}
|
||||
op in [:when] -> {:right, 50}
|
||||
op in [:::] -> {:right, 60}
|
||||
op in [:|] -> {:right, 70}
|
||||
op in [:=] -> {:right, 100}
|
||||
op in [:||, :|||, :or] -> {:left, 130}
|
||||
op in [:&&, :&&&, :and] -> {:left, 140}
|
||||
op in [:==, :!=, :=~, :===, :!==] -> {:left, 150}
|
||||
op in [:<, :<=, :>=, :>] -> {:left, 160}
|
||||
op in [:|>, :<<<, :>>>, :<~, :~>, :<<~, :~>>, :<~>, :<|>] -> {:left, 170}
|
||||
op in [:in] -> {:left, 180}
|
||||
op in [:^^^] -> {:left, 190}
|
||||
op in [:++, :--, :.., :<>] -> {:right, 200}
|
||||
op in [:+, :-] -> {:left, 210}
|
||||
op in [:*, :/] -> {:left, 220}
|
||||
op in [:.] -> {:left, 310}
|
||||
true -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Classifies the given atom into one of the following categories:
|
||||
|
||||
* :alias - a valid Elixir alias, like Foo, Foo.Bar and so on
|
||||
|
||||
* :callable_local - an atom that can be used as a local call;
|
||||
this category includes identifiers like :foo
|
||||
|
||||
* :callable_operators - all callable operators, such as `:<>`. Note
|
||||
operators such as `:..` are not callable because of ambiguity
|
||||
|
||||
* :not_callable - an atom that cannot be used as a function call after the
|
||||
. operator (for example, :<<>> is not callable because Foo.<<>> is a
|
||||
syntax error); this category includes atoms like :Foo, since they are
|
||||
valid identifiers but they need quotes to be used in function calls
|
||||
(Foo."Bar")
|
||||
|
||||
* :other - any other atom (these are usually escaped when inspected, like
|
||||
:"foo and bar")
|
||||
|
||||
"""
|
||||
def classify(atom) when is_atom(atom) do
|
||||
charlist = Atom.to_charlist(atom)
|
||||
|
||||
cond do
|
||||
atom in [:%, :%{}, :{}, :<<>>, :..., :.., :., :->] ->
|
||||
:not_callable
|
||||
|
||||
unary_op(atom) != :error or binary_op(atom) != :error ->
|
||||
:callable_operator
|
||||
|
||||
valid_alias?(charlist) ->
|
||||
:alias
|
||||
|
||||
true ->
|
||||
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
|
||||
else
|
||||
:not_callable
|
||||
end
|
||||
|
||||
_ ->
|
||||
:other
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp valid_alias?('Elixir' ++ rest), do: valid_alias_piece?(rest)
|
||||
defp valid_alias?(_other), do: false
|
||||
|
||||
defp valid_alias_piece?([?., char | rest]) when char >= ?A and char <= ?Z,
|
||||
do: valid_alias_piece?(trim_leading_while_valid_identifier(rest))
|
||||
|
||||
defp valid_alias_piece?([]), do: true
|
||||
defp valid_alias_piece?(_other), do: false
|
||||
|
||||
defp trim_leading_while_valid_identifier([char | rest])
|
||||
when char >= ?a and char <= ?z
|
||||
when char >= ?A and char <= ?Z
|
||||
when char >= ?0 and char <= ?9
|
||||
when char == ?_ do
|
||||
trim_leading_while_valid_identifier(rest)
|
||||
end
|
||||
|
||||
defp trim_leading_while_valid_identifier(other) do
|
||||
other
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inspects the identifier as an atom.
|
||||
"""
|
||||
def inspect_as_atom(atom) when is_nil(atom) or is_boolean(atom) do
|
||||
Atom.to_string(atom)
|
||||
end
|
||||
|
||||
def inspect_as_atom(atom) when is_atom(atom) do
|
||||
binary = Atom.to_string(atom)
|
||||
|
||||
case classify(atom) do
|
||||
:alias ->
|
||||
case binary do
|
||||
binary when binary in ["Elixir", "Elixir.Elixir"] -> binary
|
||||
"Elixir.Elixir." <> _rest -> binary
|
||||
"Elixir." <> rest -> rest
|
||||
end
|
||||
|
||||
type when type in [:callable_local, :callable_operator, :not_callable] ->
|
||||
":" <> binary
|
||||
|
||||
:other ->
|
||||
{escaped, _} = escape(binary, ?")
|
||||
IO.iodata_to_binary([?:, ?", escaped, ?"])
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inspects the given identifier as a key.
|
||||
"""
|
||||
def inspect_as_key(atom) when is_atom(atom) do
|
||||
binary = Atom.to_string(atom)
|
||||
|
||||
case classify(atom) do
|
||||
type when type in [:callable_local, :callable_operator, :not_callable] ->
|
||||
IO.iodata_to_binary([binary, ?:])
|
||||
|
||||
_ ->
|
||||
{escaped, _} = escape(binary, ?")
|
||||
IO.iodata_to_binary([?", escaped, ?", ?:])
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inspects the given identifier as a function name.
|
||||
"""
|
||||
def inspect_as_function(atom) when is_atom(atom) do
|
||||
binary = Atom.to_string(atom)
|
||||
|
||||
case classify(atom) do
|
||||
type when type in [:callable_local, :callable_operator] ->
|
||||
binary
|
||||
|
||||
type ->
|
||||
escaped =
|
||||
if type in [:not_callable, :alias] do
|
||||
binary
|
||||
else
|
||||
elem(escape(binary, ?"), 0)
|
||||
end
|
||||
|
||||
IO.iodata_to_binary([?", escaped, ?"])
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Extracts the name and arity of the parent from the anonymous function identifier.
|
||||
"""
|
||||
# Example of this format: -NAME/ARITY-fun-COUNT-
|
||||
def extract_anonymous_fun_parent(atom) when is_atom(atom) do
|
||||
with "-" <> rest <- Atom.to_string(atom),
|
||||
[trailing | reversed] = rest |> String.split("/") |> Enum.reverse(),
|
||||
[arity, _inner, _count, ""] <- String.split(trailing, "-") do
|
||||
{reversed |> Enum.reverse() |> Enum.join("/") |> String.to_atom(), arity}
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Escapes the given identifier.
|
||||
"""
|
||||
def escape(other, char, count \\ :infinity, fun \\ &escape_map/1) do
|
||||
escape(other, char, count, [], fun)
|
||||
end
|
||||
|
||||
defp escape(<<_, _::binary>> = binary, _char, 0, acc, _fun) do
|
||||
{acc, binary}
|
||||
end
|
||||
|
||||
defp escape(<<char, t::binary>>, char, count, acc, fun) do
|
||||
escape(t, char, decrement(count), [acc | [?\\, char]], fun)
|
||||
end
|
||||
|
||||
defp escape(<<?#, ?{, t::binary>>, char, count, acc, fun) do
|
||||
escape(t, char, decrement(count), [acc | '\\\#{'], fun)
|
||||
end
|
||||
|
||||
defp escape(<<h::utf8, t::binary>>, char, count, acc, fun) do
|
||||
escaped = if value = fun.(h), do: value, else: escape_char(h)
|
||||
escape(t, char, decrement(count), [acc | escaped], fun)
|
||||
end
|
||||
|
||||
defp escape(<<a::4, b::4, t::binary>>, char, count, acc, fun) do
|
||||
escape(t, char, decrement(count), [acc | ['\\x', to_hex(a), to_hex(b)]], fun)
|
||||
end
|
||||
|
||||
defp escape(<<>>, _char, _count, acc, _fun) do
|
||||
{acc, <<>>}
|
||||
end
|
||||
|
||||
defp escape_char(0), do: '\\0'
|
||||
|
||||
defp escape_char(65279), do: '\\uFEFF'
|
||||
|
||||
defp escape_char(char)
|
||||
when char in 0x20..0x7E
|
||||
when char in 0xA0..0xD7FF
|
||||
when char in 0xE000..0xFFFD
|
||||
when char in 0x10000..0x10FFFF do
|
||||
<<char::utf8>>
|
||||
end
|
||||
|
||||
defp escape_char(char) when char < 0x100 do
|
||||
<<a::4, b::4>> = <<char::8>>
|
||||
['\\x', to_hex(a), to_hex(b)]
|
||||
end
|
||||
|
||||
defp escape_char(char) when char < 0x10000 do
|
||||
<<a::4, b::4, c::4, d::4>> = <<char::16>>
|
||||
['\\x{', to_hex(a), to_hex(b), to_hex(c), to_hex(d), ?}]
|
||||
end
|
||||
|
||||
defp escape_char(char) when char < 0x1000000 do
|
||||
<<a::4, b::4, c::4, d::4, e::4, f::4>> = <<char::24>>
|
||||
['\\x{', to_hex(a), to_hex(b), to_hex(c), to_hex(d), to_hex(e), to_hex(f), ?}]
|
||||
end
|
||||
|
||||
defp escape_map(?\a), do: '\\a'
|
||||
defp escape_map(?\b), do: '\\b'
|
||||
defp escape_map(?\d), do: '\\d'
|
||||
defp escape_map(?\e), do: '\\e'
|
||||
defp escape_map(?\f), do: '\\f'
|
||||
defp escape_map(?\n), do: '\\n'
|
||||
defp escape_map(?\r), do: '\\r'
|
||||
defp escape_map(?\t), do: '\\t'
|
||||
defp escape_map(?\v), do: '\\v'
|
||||
defp escape_map(?\\), do: '\\\\'
|
||||
defp escape_map(_), do: false
|
||||
|
||||
@compile {:inline, to_hex: 1, decrement: 1}
|
||||
defp to_hex(c) when c in 0..9, do: ?0 + c
|
||||
defp to_hex(c) when c in 10..15, do: ?A + c - 10
|
||||
|
||||
defp decrement(:infinity), do: :infinity
|
||||
defp decrement(counter), do: counter - 1
|
||||
end
|
||||
@@ -24,54 +24,23 @@ defprotocol Collectable do
|
||||
`Enumerable` protocol. `into/1` can be seen as the opposite of
|
||||
`Enumerable.reduce/3`. If `Enumerable` is about taking values out,
|
||||
`Collectable.into/1` is about collecting those values into a structure.
|
||||
|
||||
## Examples
|
||||
|
||||
To show how to manually use the `Collectable` protocol, let's play with its
|
||||
implementation for `MapSet`.
|
||||
|
||||
iex> {initial_acc, collector_fun} = Collectable.into(MapSet.new())
|
||||
iex> updated_acc = Enum.reduce([1, 2, 3], initial_acc, fn elem, acc ->
|
||||
...> collector_fun.(acc, {:cont, elem})
|
||||
...> end)
|
||||
iex> collector_fun.(updated_acc, :done)
|
||||
#MapSet<[1, 2, 3]>
|
||||
|
||||
To show how the protocol can be implemented, we can take again a look at the
|
||||
implementation for `MapSet`. In this implementation "collecting" elements
|
||||
simply means inserting them in the set through `MapSet.put/2`.
|
||||
|
||||
defimpl Collectable do
|
||||
def into(original) do
|
||||
collector_fun = fn
|
||||
set, {:cont, elem} -> MapSet.put(set, elem)
|
||||
set, :done -> set
|
||||
_set, :halt -> :ok
|
||||
end
|
||||
|
||||
{original, collector_fun}
|
||||
end
|
||||
end
|
||||
|
||||
"""
|
||||
|
||||
@type command :: {:cont, term} | :done | :halt
|
||||
|
||||
@doc """
|
||||
Returns an initial accumulator and a "collector" function.
|
||||
Returns a function that collects values alongside
|
||||
the initial accumulation value.
|
||||
|
||||
The returned function receives a term and a command and injects the term into
|
||||
the collectable on every `{:cont, term}` command.
|
||||
The returned function receives a collectable and injects a given
|
||||
value into it for every `{:cont, term}` instruction.
|
||||
|
||||
`:done` is passed as a command when no further values will be injected. This
|
||||
is useful when there's a need to close resources or normalizing values. A
|
||||
collectable must be returned when the command is `:done`.
|
||||
`:done` is passed when no further values will be injected, useful
|
||||
for closing resources and normalizing values. A collectable must
|
||||
be returned on `:done`.
|
||||
|
||||
If injection is suddenly interrupted, `:halt` is passed and the function
|
||||
can return any value as it won't be used.
|
||||
|
||||
For examples on how to use the `Collectable` protocol and `into/1` see the
|
||||
module documentation.
|
||||
If injection is suddenly interrupted, `:halt` is passed and it can
|
||||
return any value, as it won't be used.
|
||||
"""
|
||||
@spec into(t) :: {term, (term, command -> t | term)}
|
||||
def into(collectable)
|
||||
@@ -79,65 +48,30 @@ end
|
||||
|
||||
defimpl Collectable, for: List do
|
||||
def into(original) do
|
||||
fun = fn
|
||||
{[], fn
|
||||
list, {:cont, x} -> [x | list]
|
||||
list, :done -> original ++ :lists.reverse(list)
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
{[], fun}
|
||||
end}
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Collectable, for: BitString do
|
||||
def into(original) when is_binary(original) do
|
||||
fun = fn
|
||||
acc, {:cont, x} when is_binary(x) and is_list(acc) ->
|
||||
[acc | x]
|
||||
|
||||
acc, {:cont, x} when is_bitstring(x) and is_bitstring(acc) ->
|
||||
<<acc::bitstring, x::bitstring>>
|
||||
|
||||
acc, {:cont, x} when is_bitstring(x) ->
|
||||
<<IO.iodata_to_binary(acc)::bitstring, x::bitstring>>
|
||||
|
||||
acc, :done when is_bitstring(acc) ->
|
||||
acc
|
||||
|
||||
acc, :done ->
|
||||
IO.iodata_to_binary(acc)
|
||||
|
||||
_, :halt ->
|
||||
:ok
|
||||
end
|
||||
|
||||
{[original], fun}
|
||||
end
|
||||
|
||||
def into(original) when is_bitstring(original) do
|
||||
fun = fn
|
||||
acc, {:cont, x} when is_bitstring(x) ->
|
||||
<<acc::bitstring, x::bitstring>>
|
||||
|
||||
acc, :done ->
|
||||
acc
|
||||
|
||||
_, :halt ->
|
||||
:ok
|
||||
end
|
||||
|
||||
{original, fun}
|
||||
def into(original) do
|
||||
{original, fn
|
||||
acc, {:cont, x} when is_bitstring(x) -> [acc | x]
|
||||
acc, :done -> IO.iodata_to_binary(acc)
|
||||
_, :halt -> :ok
|
||||
end}
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Collectable, for: Map do
|
||||
def into(original) do
|
||||
fun = fn
|
||||
{original, fn
|
||||
map, {:cont, {k, v}} -> :maps.put(k, v, map)
|
||||
map, :done -> map
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
{original, fun}
|
||||
end}
|
||||
end
|
||||
end
|
||||
|
||||
+43
-66
@@ -13,13 +13,14 @@ defmodule Dict do
|
||||
@type value :: any
|
||||
@type t :: list | map
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
|
||||
# TODO: Deprecate every function by 1.4
|
||||
defmacro __using__(_) do
|
||||
# Use this import to guarantee proper code expansion
|
||||
import Kernel, except: [size: 1]
|
||||
|
||||
%{file: file, line: line} = __CALLER__
|
||||
:elixir_errors.warn(line, file, "the Dict module is deprecated")
|
||||
|
||||
quote do
|
||||
def get(dict, key, default \\ nil) do
|
||||
case fetch(dict, key) do
|
||||
@@ -49,19 +50,19 @@ defmodule Dict do
|
||||
end
|
||||
|
||||
def has_key?(dict, key) do
|
||||
match?({:ok, _}, fetch(dict, key))
|
||||
match? {:ok, _}, fetch(dict, key)
|
||||
end
|
||||
|
||||
def put_new(dict, key, value) do
|
||||
case has_key?(dict, key) do
|
||||
true -> dict
|
||||
true -> dict
|
||||
false -> put(dict, key, value)
|
||||
end
|
||||
end
|
||||
|
||||
def put_new_lazy(dict, key, fun) when is_function(fun, 0) do
|
||||
case has_key?(dict, key) do
|
||||
true -> dict
|
||||
true -> dict
|
||||
false -> put(dict, key, fun.())
|
||||
end
|
||||
end
|
||||
@@ -80,21 +81,21 @@ defmodule Dict do
|
||||
end
|
||||
|
||||
def to_list(dict) do
|
||||
reduce(dict, {:cont, []}, fn kv, acc -> {:cont, [kv | acc]} end)
|
||||
|> elem(1)
|
||||
|> :lists.reverse()
|
||||
reduce(dict, {:cont, []}, fn
|
||||
kv, acc -> {:cont, [kv | acc]}
|
||||
end) |> elem(1) |> :lists.reverse
|
||||
end
|
||||
|
||||
def keys(dict) do
|
||||
reduce(dict, {:cont, []}, fn {k, _}, acc -> {:cont, [k | acc]} end)
|
||||
|> elem(1)
|
||||
|> :lists.reverse()
|
||||
reduce(dict, {:cont, []}, fn
|
||||
{k, _}, acc -> {:cont, [k | acc]}
|
||||
end) |> elem(1) |> :lists.reverse
|
||||
end
|
||||
|
||||
def values(dict) do
|
||||
reduce(dict, {:cont, []}, fn {_, v}, acc -> {:cont, [v | acc]} end)
|
||||
|> elem(1)
|
||||
|> :lists.reverse()
|
||||
reduce(dict, {:cont, []}, fn
|
||||
{_, v}, acc -> {:cont, [v | acc]}
|
||||
end) |> elem(1) |> :lists.reverse
|
||||
end
|
||||
|
||||
def equal?(dict1, dict2) do
|
||||
@@ -102,21 +103,18 @@ defmodule Dict do
|
||||
import Kernel, except: [size: 1]
|
||||
|
||||
case size(dict1) == size(dict2) do
|
||||
false ->
|
||||
false
|
||||
|
||||
true ->
|
||||
reduce(dict1, {:cont, true}, fn {k, v}, _acc ->
|
||||
false -> false
|
||||
true ->
|
||||
reduce(dict1, {:cont, true}, fn({k, v}, _acc) ->
|
||||
case fetch(dict2, k) do
|
||||
{:ok, ^v} -> {:cont, true}
|
||||
_ -> {:halt, false}
|
||||
end
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
end
|
||||
|
||||
def merge(dict1, dict2, fun \\ fn _k, _v1, v2 -> v2 end) do
|
||||
def merge(dict1, dict2, fun \\ fn(_k, _v1, v2) -> v2 end) do
|
||||
# Use this import to avoid conflicts in the user code
|
||||
import Kernel, except: [size: 1]
|
||||
|
||||
@@ -128,15 +126,13 @@ defmodule Dict do
|
||||
reduce(dict2, {:cont, dict1}, fn {k, v2}, acc ->
|
||||
{:cont, update(acc, k, v2, &fun.(k, &1, v2))}
|
||||
end)
|
||||
end
|
||||
|> elem(1)
|
||||
end |> elem(1)
|
||||
end
|
||||
|
||||
def update(dict, key, initial, fun) do
|
||||
case fetch(dict, key) do
|
||||
{:ok, value} ->
|
||||
put(dict, key, fun.(value))
|
||||
|
||||
:error ->
|
||||
put(dict, key, initial)
|
||||
end
|
||||
@@ -146,7 +142,6 @@ defmodule Dict do
|
||||
case fetch(dict, key) do
|
||||
{:ok, value} ->
|
||||
put(dict, key, fun.(value))
|
||||
|
||||
:error ->
|
||||
raise KeyError, key: key, term: dict
|
||||
end
|
||||
@@ -156,7 +151,6 @@ defmodule Dict do
|
||||
case fetch(dict, key) do
|
||||
{:ok, value} ->
|
||||
{value, delete(dict, key)}
|
||||
|
||||
:error ->
|
||||
{default, dict}
|
||||
end
|
||||
@@ -166,7 +160,6 @@ defmodule Dict do
|
||||
case fetch(dict, key) do
|
||||
{:ok, value} ->
|
||||
{value, delete(dict, key)}
|
||||
|
||||
:error ->
|
||||
{fun.(), dict}
|
||||
end
|
||||
@@ -177,45 +170,31 @@ defmodule Dict do
|
||||
case fetch(exc, key) do
|
||||
{:ok, value} ->
|
||||
{put(inc, key, value), delete(exc, key)}
|
||||
|
||||
:error ->
|
||||
acc
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defoverridable merge: 2,
|
||||
merge: 3,
|
||||
equal?: 2,
|
||||
to_list: 1,
|
||||
keys: 1,
|
||||
values: 1,
|
||||
take: 2,
|
||||
drop: 2,
|
||||
get: 2,
|
||||
get: 3,
|
||||
fetch!: 2,
|
||||
has_key?: 2,
|
||||
put_new: 3,
|
||||
pop: 2,
|
||||
pop: 3,
|
||||
split: 2,
|
||||
update: 4,
|
||||
update!: 3,
|
||||
get_and_update: 3,
|
||||
get_lazy: 3,
|
||||
pop_lazy: 3,
|
||||
put_new_lazy: 3
|
||||
defoverridable merge: 2, merge: 3, equal?: 2, to_list: 1, keys: 1,
|
||||
values: 1, take: 2, drop: 2, get: 2, get: 3, fetch!: 2,
|
||||
has_key?: 2, put_new: 3, pop: 2, pop: 3, split: 2,
|
||||
update: 4, update!: 3, get_and_update: 3, get_lazy: 3,
|
||||
pop_lazy: 3, put_new_lazy: 3
|
||||
end
|
||||
end
|
||||
|
||||
defmacrop target(dict) do
|
||||
quote do
|
||||
case unquote(dict) do
|
||||
%module{} -> module
|
||||
%{} -> Map
|
||||
dict when is_list(dict) -> Keyword
|
||||
dict -> unsupported_dict(dict)
|
||||
%{__struct__: x} when is_atom(x) ->
|
||||
x
|
||||
%{} ->
|
||||
Map
|
||||
x when is_list(x) ->
|
||||
Keyword
|
||||
x ->
|
||||
unsupported_dict(x)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -293,7 +272,7 @@ defmodule Dict do
|
||||
if target1 == target2 do
|
||||
target1.merge(dict1, dict2)
|
||||
else
|
||||
do_merge(target1, dict1, dict2, fn _k, _v1, v2 -> v2 end)
|
||||
do_merge(target1, dict1, dict2, fn(_k, _v1, v2) -> v2 end)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -310,10 +289,9 @@ defmodule Dict do
|
||||
end
|
||||
|
||||
defp do_merge(target1, dict1, dict2, fun) do
|
||||
Enumerable.reduce(dict2, {:cont, dict1}, fn {k, v}, acc ->
|
||||
{:cont, target1.update(acc, k, v, fn other -> fun.(k, other, v) end)}
|
||||
end)
|
||||
|> elem(1)
|
||||
Enumerable.reduce(dict2, {:cont, dict1}, fn({k, v}, acc) ->
|
||||
{:cont, target1.update(acc, k, v, fn(other) -> fun.(k, other, v) end)}
|
||||
end) |> elem(1)
|
||||
end
|
||||
|
||||
@spec pop(t, key, value) :: {value, t}
|
||||
@@ -366,13 +344,12 @@ defmodule Dict do
|
||||
target1.equal?(dict1, dict2)
|
||||
|
||||
target1.size(dict1) == target2.size(dict2) ->
|
||||
Enumerable.reduce(dict2, {:cont, true}, fn {k, v}, _acc ->
|
||||
Enumerable.reduce(dict2, {:cont, true}, fn({k, v}, _acc) ->
|
||||
case target1.fetch(dict1, k) do
|
||||
{:ok, ^v} -> {:cont, true}
|
||||
_ -> {:halt, false}
|
||||
_ -> {:halt, false}
|
||||
end
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
|
||||
true ->
|
||||
false
|
||||
@@ -386,6 +363,6 @@ defmodule Dict do
|
||||
|
||||
@spec unsupported_dict(t) :: no_return
|
||||
defp unsupported_dict(dict) do
|
||||
raise ArgumentError, "unsupported dict: #{inspect(dict)}"
|
||||
raise ArgumentError, "unsupported dict: #{inspect dict}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,993 +0,0 @@
|
||||
defmodule DynamicSupervisor do
|
||||
@moduledoc ~S"""
|
||||
A supervisor that starts children dynamically.
|
||||
|
||||
The `Supervisor` module was designed to handle mostly static children
|
||||
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 shutdown at the same time, with no guarantee
|
||||
of ordering.
|
||||
|
||||
## Examples
|
||||
|
||||
A dynamic supervisor is started with no children, often under a
|
||||
supervisor with the supervision strategy (the only strategy currently
|
||||
supported is `:one_for_one`) and a name:
|
||||
|
||||
children = [
|
||||
{DynamicSupervisor, strategy: :one_for_one, name: MyApp.DynamicSupervisor}
|
||||
]
|
||||
|
||||
Supervisor.start_link(strategy: :one_for_one)
|
||||
|
||||
The options given in the child specification are documented in `start_link/1`.
|
||||
|
||||
Once the dynamic supervisor is running, we can start children
|
||||
with `start_child/2`, which receives a child specification:
|
||||
|
||||
{:ok, agent1} = DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Agent, fn -> %{} end})
|
||||
Agent.update(agent1, &Map.put(&1, :key, "value"))
|
||||
Agent.get(agent1, & &1)
|
||||
#=> %{key: "value"}
|
||||
|
||||
{:ok, agent2} = DynamicSupervisor.start_child(MyApp.DynamicSupervisor, {Agent, fn -> %{} end})
|
||||
Agent.get(agent2, & &1)
|
||||
#=> %{}
|
||||
|
||||
DynamicSupervisor.count_children(sup)
|
||||
#=> %{active: 2, specs: 2, supervisors: 0, workers: 2}
|
||||
|
||||
## Module-based supervisors
|
||||
|
||||
Similar to `Supervisor`, dynamic supervisors also support module-based
|
||||
supervisors.
|
||||
|
||||
defmodule MyApp.DynamicSupervisor do
|
||||
# Automatically defines child_spec/1
|
||||
use DynamicSupervisor
|
||||
|
||||
def start_link(arg) do
|
||||
DynamicSupervisor.start_link(__MODULE__, arg, name: __MODULE__)
|
||||
end
|
||||
|
||||
@impl true
|
||||
def init(_arg) do
|
||||
DynamicSupervisor.init(strategy: :one_for_one)
|
||||
end
|
||||
end
|
||||
|
||||
See the `Supervisor` docs for a discussion of when you may want to use
|
||||
module-based supervisors.
|
||||
|
||||
## 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`.
|
||||
|
||||
## Migrating from Supervisor's :simple_one_for_one
|
||||
|
||||
In case you were using the deprecated `:simple_one_for_one` strategy from
|
||||
the `Supervisor` module, you can migrate to the `DynamicSupervisor` in
|
||||
few steps.
|
||||
|
||||
Imagine the given "old" code:
|
||||
|
||||
defmodule MySupervisor do
|
||||
use Supervisor
|
||||
|
||||
def start_link(arg) do
|
||||
Supervisor.start_link(__MODULE__, arg, name: __MODULE__)
|
||||
end
|
||||
|
||||
def start_child(foo, bar, baz) do
|
||||
# This will start child by calling MyWorker.start_link(initial_arg, foo, bar, baz)
|
||||
Supervisor.start_child(__MODULE__, [foo, bar, baz])
|
||||
end
|
||||
|
||||
@impl true
|
||||
def init(initial_arg) do
|
||||
children = [
|
||||
# Or the deprecated: worker(MyWorker, [initial_arg])
|
||||
%{id: MyWorker, start: {MyWorker, :start_link, [initial_arg]})
|
||||
]
|
||||
|
||||
Supervisor.init(children, strategy: :simple_one_for_one)
|
||||
end
|
||||
end
|
||||
|
||||
It can be upgraded to the DynamicSupervisor like this:
|
||||
|
||||
defmodule MySupervisor do
|
||||
use DynamicSupervisor
|
||||
|
||||
def start_link(arg) do
|
||||
DynamicSupervisor.start_link(__MODULE__, arg, name: __MODULE__)
|
||||
end
|
||||
|
||||
def start_child(foo, bar, baz) do
|
||||
# If MyWorker is not using the new child specs, we need to pass a map:
|
||||
# spec = %{id: MyWorker, start: {MyWorker, :start_link, [foo, bar, baz]}}
|
||||
spec = {MyWorker, foo: foo, bar: bar, baz: baz}
|
||||
DynamicSupervisor.start_child(__MODULE__, spec)
|
||||
end
|
||||
|
||||
@impl true
|
||||
def init(initial_arg) do
|
||||
DynamicSupervisor.init(
|
||||
strategy: :one_for_one,
|
||||
extra_arguments: [initial_arg]
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
The difference is that the `DynamicSupervisor` expects the child specification
|
||||
at the moment `start_child/2` is called, and no longer on the init callback.
|
||||
If there are any initial arguments given on initialization, such as `[initial_arg]`,
|
||||
it can be given in the `:extra_arguments` flag on `DynamicSupervisor.init/1`.
|
||||
"""
|
||||
|
||||
@behaviour GenServer
|
||||
|
||||
@doc """
|
||||
Callback invoked to start the supervisor and during hot code upgrades.
|
||||
|
||||
Developers typically invoke `DynamicSupervisor.init/1` at the end of
|
||||
their init callback to return the proper supervision flags.
|
||||
"""
|
||||
@callback init(args :: term) :: {:ok, sup_flags()} | :ignore
|
||||
|
||||
@typedoc "The supervisor flags returned on init"
|
||||
@type sup_flags() :: %{
|
||||
strategy: strategy(),
|
||||
intensity: non_neg_integer(),
|
||||
period: pos_integer(),
|
||||
max_children: non_neg_integer() | :infinity,
|
||||
extra_arguments: [term()]
|
||||
}
|
||||
|
||||
@typedoc "Option values used by the `start*` functions"
|
||||
@type option :: {:name, Supervisor.name()} | init_option()
|
||||
|
||||
@typedoc "Options used by the `start*` functions"
|
||||
@type options :: [option, ...]
|
||||
|
||||
@typedoc "Options given to `start_link/2` and `init/1`"
|
||||
@type init_option ::
|
||||
{:strategy, strategy()}
|
||||
| {:max_restarts, non_neg_integer()}
|
||||
| {:max_seconds, pos_integer()}
|
||||
| {:max_children, non_neg_integer() | :infinity}
|
||||
| {:extra_arguments, [term()]}
|
||||
|
||||
@typedoc "Supported strategies"
|
||||
@type strategy :: :one_for_one
|
||||
|
||||
@typedoc "Return values of `start_child` functions"
|
||||
@type on_start_child ::
|
||||
{:ok, pid}
|
||||
| {:ok, pid, info :: term}
|
||||
| :ignore
|
||||
| {:error, {:already_started, pid} | :max_children | term}
|
||||
|
||||
defstruct [
|
||||
:args,
|
||||
:extra_arguments,
|
||||
:mod,
|
||||
:name,
|
||||
:strategy,
|
||||
:max_children,
|
||||
:max_restarts,
|
||||
:max_seconds,
|
||||
children: %{},
|
||||
restarts: []
|
||||
]
|
||||
|
||||
@doc """
|
||||
Returns a specification to start a dynamic supervisor under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
@since "1.6.1"
|
||||
def child_spec(arg) do
|
||||
%{
|
||||
id: DynamicSupervisor,
|
||||
start: {DynamicSupervisor, :start_link, [arg]},
|
||||
type: :supervisor
|
||||
}
|
||||
end
|
||||
|
||||
@doc false
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
@behaviour DynamicSupervisor
|
||||
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
def child_spec(arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
start: {__MODULE__, :start_link, [arg]},
|
||||
type: :supervisor
|
||||
}
|
||||
|
||||
Supervisor.child_spec(default, unquote(Macro.escape(opts)))
|
||||
end
|
||||
|
||||
defoverridable child_spec: 1
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts a supervisor with the given options.
|
||||
|
||||
The `:strategy` is a required option and the currently supported
|
||||
value is `:one_for_one`. The remaining options can be found in the
|
||||
`init/1` docs.
|
||||
|
||||
The `:name` option can also be used to register a supervisor name.
|
||||
The supported values are described under the "Name registration"
|
||||
section in the `GenServer` module docs.
|
||||
|
||||
If the supervisor is successfully spawned, this function returns
|
||||
`{:ok, pid}`, where `pid` is the PID of the supervisor. If the supervisor
|
||||
is given a name and a process with the specified name already exists,
|
||||
the function returns `{:error, {:already_started, pid}}`, where `pid`
|
||||
is the PID of that process.
|
||||
|
||||
Note that a supervisor started with this function is linked to the parent
|
||||
process and exits not only on crashes but also if the parent process exits
|
||||
with `:normal` reason.
|
||||
"""
|
||||
@spec start_link(options) :: Supervisor.on_start()
|
||||
def start_link(options) when is_list(options) do
|
||||
keys = [:extra_arguments, :max_children, :max_seconds, :max_restarts, :strategy]
|
||||
{sup_opts, start_opts} = Keyword.split(options, keys)
|
||||
start_link(Supervisor.Default, init(sup_opts), start_opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
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 `arg` as its argument. The `c:init/1` callback must return a
|
||||
supervisor specification which can be created with the help of the `init/1`
|
||||
function.
|
||||
|
||||
If the `c:init/1` callback returns `:ignore`, this function returns
|
||||
`:ignore` as well and the supervisor terminates with reason `:normal`.
|
||||
If it fails or returns an incorrect value, this function returns
|
||||
`{:error, term}` where `term` is a term with information about the
|
||||
error, and the supervisor terminates with reason `term`.
|
||||
|
||||
The `:name` option can also be given in order to register a supervisor
|
||||
name, the supported values are described in the "Name registration"
|
||||
section in the `GenServer` module docs.
|
||||
"""
|
||||
@spec start_link(module, term, GenServer.options()) :: Supervisor.on_start()
|
||||
def start_link(mod, args, opts \\ []) do
|
||||
GenServer.start_link(__MODULE__, {mod, args, opts[:name]}, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Dynamically adds a child specification to `supervisor` and starts that child.
|
||||
|
||||
`child_spec` should be a valid child specification. The child process will
|
||||
be started as defined in the child specification.
|
||||
|
||||
If the child process start function returns `{:ok, child}` or `{:ok, child,
|
||||
info}`, then child specification and PID are added to the supervisor and
|
||||
this function returns the same value.
|
||||
|
||||
If the child process start function returns `:ignore`, then no child is added
|
||||
to the supervision tree and this function returns `:ignore` too.
|
||||
|
||||
If the child process start function returns an error tuple or an erroneous
|
||||
value, or if it fails, the child specification is discarded and this function
|
||||
returns `{:error, error}` where `error` is a term containing information about
|
||||
the error and child specification.
|
||||
|
||||
If the supervisor already has N children in a way that N exceeds the amount
|
||||
of `:max_children` set on the supervisor initialization (see `init/1`), then
|
||||
this function returns `{:error, :max_children}`.
|
||||
"""
|
||||
@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)
|
||||
end
|
||||
|
||||
def start_child(supervisor, child_spec) do
|
||||
validate_and_start_child(supervisor, Supervisor.child_spec(child_spec, []))
|
||||
end
|
||||
|
||||
defp validate_and_start_child(supervisor, child_spec) do
|
||||
case validate_child(child_spec) do
|
||||
{:ok, child} -> call(supervisor, {:start_child, child})
|
||||
error -> {:error, error}
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_child(%{id: _, start: {mod, _, _} = start} = child) do
|
||||
restart = Map.get(child, :restart, :permanent)
|
||||
type = Map.get(child, :type, :worker)
|
||||
modules = Map.get(child, :modules, [mod])
|
||||
|
||||
shutdown =
|
||||
case type do
|
||||
:worker -> Map.get(child, :shutdown, 5_000)
|
||||
:supervisor -> Map.get(child, :shutdown, :infinity)
|
||||
end
|
||||
|
||||
validate_child(start, restart, shutdown, type, modules)
|
||||
end
|
||||
|
||||
defp validate_child({_, start, restart, shutdown, type, modules}) do
|
||||
validate_child(start, restart, shutdown, type, modules)
|
||||
end
|
||||
|
||||
defp validate_child(other) do
|
||||
{:invalid_child_spec, other}
|
||||
end
|
||||
|
||||
defp validate_child(start, restart, shutdown, type, modules) do
|
||||
with :ok <- validate_start(start),
|
||||
:ok <- validate_restart(restart),
|
||||
:ok <- validate_shutdown(shutdown),
|
||||
:ok <- validate_type(type),
|
||||
:ok <- validate_modules(modules) do
|
||||
{:ok, {start, restart, shutdown, type, modules}}
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_start({m, f, args}) when is_atom(m) and is_atom(f) and is_list(args), do: :ok
|
||||
defp validate_start(mfa), do: {:invalid_mfa, mfa}
|
||||
|
||||
defp validate_type(type) when type in [:supervisor, :worker], do: :ok
|
||||
defp validate_type(type), do: {:invalid_child_type, type}
|
||||
|
||||
defp validate_restart(restart) when restart in [:permanent, :temporary, :transient], do: :ok
|
||||
defp validate_restart(restart), do: {:invalid_restart_type, restart}
|
||||
|
||||
defp validate_shutdown(shutdown) when is_integer(shutdown) and shutdown > 0, do: :ok
|
||||
defp validate_shutdown(shutdown) when shutdown in [:infinity, :brutal_kill], do: :ok
|
||||
defp validate_shutdown(shutdown), do: {:invalid_shutdown, shutdown}
|
||||
|
||||
defp validate_modules(:dynamic), do: :ok
|
||||
|
||||
defp validate_modules(mods) do
|
||||
if is_list(mods) and Enum.all?(mods, &is_atom/1) do
|
||||
:ok
|
||||
else
|
||||
{:invalid_modules, mods}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Terminates the given child identified by child id.
|
||||
|
||||
If successful, this function returns `:ok`. If there is no process with
|
||||
the given PID, this function returns `{:error, :not_found}`.
|
||||
"""
|
||||
@spec terminate_child(Supervisor.supervisor(), pid) :: :ok | {:error, :not_found}
|
||||
def terminate_child(supervisor, pid) when is_pid(pid) do
|
||||
call(supervisor, {:terminate_child, pid})
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a list with information about all children.
|
||||
|
||||
Note that calling this function when supervising a large number
|
||||
of children under low memory conditions can cause an out of memory
|
||||
exception.
|
||||
|
||||
This function returns a list of tuples containing:
|
||||
|
||||
* `id` - it is always `:undefined` for dynamic supervisors
|
||||
|
||||
* `child` - the pid of the corresponding child process or the
|
||||
atom `:restarting` if the process is about to be restarted
|
||||
|
||||
* `type` - `:worker` or `:supervisor` as defined in the child
|
||||
specification
|
||||
|
||||
* `modules` - as defined in the child specification
|
||||
|
||||
"""
|
||||
@spec which_children(Supervisor.supervisor()) :: [
|
||||
{:undefined, pid | :restarting, :worker | :supervisor, :supervisor.modules()}
|
||||
]
|
||||
def which_children(supervisor) do
|
||||
call(supervisor, :which_children)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a map containing count values for the supervisor.
|
||||
|
||||
The map contains the following keys:
|
||||
|
||||
* `:specs` - the number of children processes
|
||||
|
||||
* `:active` - the count of all actively running child processes managed by
|
||||
this supervisor
|
||||
|
||||
* `:supervisors` - the count of all supervisors whether or not the child
|
||||
process is still alive
|
||||
|
||||
* `:workers` - the count of all workers, whether or not the child process
|
||||
is still alive
|
||||
|
||||
"""
|
||||
@spec count_children(Supervisor.supervisor()) :: %{
|
||||
specs: non_neg_integer,
|
||||
active: non_neg_integer,
|
||||
supervisors: non_neg_integer,
|
||||
workers: non_neg_integer
|
||||
}
|
||||
def count_children(supervisor) do
|
||||
call(supervisor, :count_children) |> :maps.from_list()
|
||||
end
|
||||
|
||||
@doc """
|
||||
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 sections "Module-based supervisors"
|
||||
in the module documentation for more information.
|
||||
|
||||
The options received by this function are also supported by `start_link/2`.
|
||||
|
||||
This function returns a tuple containing the supervisor options.
|
||||
|
||||
## Examples
|
||||
|
||||
def init(_arg) do
|
||||
DynamicSupervisor.init(max_children: 1000, strategy: :one_for_one)
|
||||
end
|
||||
|
||||
## Options
|
||||
|
||||
* `:strategy` - the restart strategy option. The only supported
|
||||
value is `:one_for_one` which means that no other child is
|
||||
terminate if a child process terminates. You can learn more
|
||||
about strategies in the `Supervisor` module docs.
|
||||
|
||||
* `:max_restarts` - the maximum number of restarts allowed in
|
||||
a time frame. Defaults to `3`.
|
||||
|
||||
* `:max_seconds` - the time frame in which `:max_restarts` applies.
|
||||
Defaults to `5`.
|
||||
|
||||
* `:max_children` - the maximum amount of children to be running
|
||||
under this supervisor at the same time. When `:max_children` is
|
||||
exceeded, `start_child/2` returns `{:error, :dynamic}`. Defaults
|
||||
to `:infinity`.
|
||||
|
||||
* `:extra_arguments` - arguments that are prepended to the arguments
|
||||
specified in the child spec given to `start_child/2`. Defaults to
|
||||
an empty list.
|
||||
|
||||
"""
|
||||
@spec init([init_option]) :: {:ok, map()}
|
||||
def init(options) when is_list(options) do
|
||||
unless strategy = options[:strategy] do
|
||||
raise ArgumentError, "expected :strategy option to be given"
|
||||
end
|
||||
|
||||
intensity = Keyword.get(options, :max_restarts, 3)
|
||||
period = Keyword.get(options, :max_seconds, 5)
|
||||
max_children = Keyword.get(options, :max_children, :infinity)
|
||||
extra_arguments = Keyword.get(options, :extra_arguments, [])
|
||||
|
||||
flags = %{
|
||||
strategy: strategy,
|
||||
intensity: intensity,
|
||||
period: period,
|
||||
max_children: max_children,
|
||||
extra_arguments: extra_arguments
|
||||
}
|
||||
|
||||
{:ok, flags}
|
||||
end
|
||||
|
||||
## Callbacks
|
||||
|
||||
@impl true
|
||||
def init({mod, args, name}) do
|
||||
Process.put(:"$initial_call", {:supervisor, mod, 1})
|
||||
Process.flag(:trap_exit, true)
|
||||
|
||||
case mod.init(args) do
|
||||
{:ok, flags} when is_map(flags) ->
|
||||
name =
|
||||
cond do
|
||||
is_nil(name) -> {self(), mod}
|
||||
is_atom(name) -> {:local, name}
|
||||
is_tuple(name) -> name
|
||||
end
|
||||
|
||||
state = %DynamicSupervisor{mod: mod, args: args, name: name}
|
||||
|
||||
case init(state, flags) do
|
||||
{:ok, state} -> {:ok, state}
|
||||
{:error, reason} -> {:stop, {:supervisor_data, reason}}
|
||||
end
|
||||
|
||||
:ignore ->
|
||||
:ignore
|
||||
|
||||
other ->
|
||||
{:stop, {:bad_return, {mod, :init, other}}}
|
||||
end
|
||||
end
|
||||
|
||||
defp init(state, flags) do
|
||||
extra_arguments = Map.get(flags, :extra_arguments, [])
|
||||
max_children = Map.get(flags, :max_children, :infinity)
|
||||
max_restarts = Map.get(flags, :intensity, 1)
|
||||
max_seconds = Map.get(flags, :period, 5)
|
||||
strategy = Map.get(flags, :strategy, :one_for_one)
|
||||
|
||||
with :ok <- validate_strategy(strategy),
|
||||
:ok <- validate_restarts(max_restarts),
|
||||
:ok <- validate_seconds(max_seconds),
|
||||
:ok <- validate_dynamic(max_children),
|
||||
:ok <- validate_extra_arguments(extra_arguments) do
|
||||
{:ok,
|
||||
%{
|
||||
state
|
||||
| extra_arguments: extra_arguments,
|
||||
max_children: max_children,
|
||||
max_restarts: max_restarts,
|
||||
max_seconds: max_seconds,
|
||||
strategy: strategy
|
||||
}}
|
||||
end
|
||||
end
|
||||
|
||||
defp validate_strategy(strategy) when strategy in [:one_for_one], do: :ok
|
||||
defp validate_strategy(strategy), do: {:error, {:invalid_strategy, strategy}}
|
||||
|
||||
defp validate_restarts(restart) when is_integer(restart) and restart >= 0, do: :ok
|
||||
defp validate_restarts(restart), do: {:error, {:invalid_intensity, restart}}
|
||||
|
||||
defp validate_seconds(seconds) when is_integer(seconds) and seconds > 0, do: :ok
|
||||
defp validate_seconds(seconds), do: {:error, {:invalid_period, seconds}}
|
||||
|
||||
defp validate_dynamic(:infinity), do: :ok
|
||||
defp validate_dynamic(dynamic) when is_integer(dynamic) and dynamic >= 0, do: :ok
|
||||
defp validate_dynamic(dynamic), do: {:error, {:invalid_max_children, dynamic}}
|
||||
|
||||
defp validate_extra_arguments(list) when is_list(list), do: :ok
|
||||
defp validate_extra_arguments(extra), do: {:error, {:invalid_extra_arguments, extra}}
|
||||
|
||||
@impl true
|
||||
def handle_call(:which_children, _from, state) do
|
||||
%{children: children} = state
|
||||
|
||||
reply =
|
||||
for {pid, args} <- children do
|
||||
case args do
|
||||
{:restarting, {_, _, _, type, modules}} ->
|
||||
{:undefined, :restarting, type, modules}
|
||||
|
||||
{_, _, _, type, modules} ->
|
||||
{:undefined, pid, type, modules}
|
||||
end
|
||||
end
|
||||
|
||||
{:reply, reply, state}
|
||||
end
|
||||
|
||||
def handle_call(:count_children, _from, state) do
|
||||
%{children: children} = state
|
||||
specs = map_size(children)
|
||||
|
||||
{active, workers, supervisors} =
|
||||
Enum.reduce(children, {0, 0, 0}, fn
|
||||
{_pid, {:restarting, {_, _, _, :worker, _}}}, {active, worker, supervisor} ->
|
||||
{active, worker + 1, supervisor}
|
||||
|
||||
{_pid, {:restarting, {_, _, _, :supervisor, _}}}, {active, worker, supervisor} ->
|
||||
{active, worker, supervisor + 1}
|
||||
|
||||
{_pid, {_, _, _, :worker, _}}, {active, worker, supervisor} ->
|
||||
{active + 1, worker + 1, supervisor}
|
||||
|
||||
{_pid, {_, _, _, :supervisor, _}}, {active, worker, supervisor} ->
|
||||
{active + 1, worker, supervisor + 1}
|
||||
end)
|
||||
|
||||
reply = [specs: specs, active: active, supervisors: supervisors, workers: workers]
|
||||
{:reply, reply, state}
|
||||
end
|
||||
|
||||
def handle_call({:terminate_child, pid}, _from, %{children: children} = state) do
|
||||
case children do
|
||||
%{^pid => info} ->
|
||||
:ok = terminate_children(%{pid => info}, state)
|
||||
{:reply, :ok, delete_child(pid, state)}
|
||||
|
||||
%{} ->
|
||||
{:reply, {:error, :not_found}, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call({:start_task, args, restart, shutdown}, from, state) do
|
||||
{init_restart, init_shutdown} = Process.get(Task.Supervisor)
|
||||
restart = restart || init_restart
|
||||
shutdown = shutdown || init_shutdown
|
||||
child = {{Task.Supervised, :start_link, args}, restart, shutdown, :worker, [Task.Supervised]}
|
||||
handle_call({:start_child, child}, from, state)
|
||||
end
|
||||
|
||||
def handle_call({:start_child, child}, _from, state) do
|
||||
%{children: children, max_children: max_children} = state
|
||||
|
||||
if map_size(children) < max_children do
|
||||
handle_start_child(child, state)
|
||||
else
|
||||
{:reply, {:error, :max_children}, state}
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_start_child({{m, f, args} = mfa, restart, shutdown, type, modules}, state) do
|
||||
%{extra_arguments: extra} = state
|
||||
|
||||
case reply = start_child(m, f, extra ++ args) do
|
||||
{:ok, pid, _} ->
|
||||
{:reply, reply, save_child(pid, mfa, restart, shutdown, type, modules, state)}
|
||||
|
||||
{:ok, pid} ->
|
||||
{:reply, reply, save_child(pid, mfa, restart, shutdown, type, modules, state)}
|
||||
|
||||
_ ->
|
||||
{:reply, reply, state}
|
||||
end
|
||||
end
|
||||
|
||||
defp start_child(m, f, a) do
|
||||
try do
|
||||
apply(m, f, a)
|
||||
catch
|
||||
kind, reason ->
|
||||
{:error, exit_reason(kind, reason, System.stacktrace())}
|
||||
else
|
||||
{:ok, pid, extra} when is_pid(pid) -> {:ok, pid, extra}
|
||||
{:ok, pid} when is_pid(pid) -> {:ok, pid}
|
||||
:ignore -> :ignore
|
||||
{:error, _} = error -> error
|
||||
other -> {:error, other}
|
||||
end
|
||||
end
|
||||
|
||||
defp save_child(pid, mfa, restart, shutdown, type, modules, state) do
|
||||
mfa = mfa_for_restart(mfa, restart)
|
||||
put_in(state.children[pid], {mfa, restart, shutdown, type, modules})
|
||||
end
|
||||
|
||||
defp mfa_for_restart({m, f, _}, :temporary), do: {m, f, :undefined}
|
||||
defp mfa_for_restart(mfa, _), do: mfa
|
||||
|
||||
defp exit_reason(:exit, reason, _), do: reason
|
||||
defp exit_reason(:error, reason, stack), do: {reason, stack}
|
||||
defp exit_reason(:throw, value, stack), do: {{:nocatch, value}, stack}
|
||||
|
||||
@impl true
|
||||
def handle_cast(_msg, state) do
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_info({:EXIT, pid, reason}, state) do
|
||||
case maybe_restart_child(pid, reason, state) do
|
||||
{:ok, state} -> {:noreply, state}
|
||||
{:shutdown, state} -> {:stop, :shutdown, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_info({:"$gen_restart", pid}, state) do
|
||||
%{children: children} = state
|
||||
|
||||
case children do
|
||||
%{^pid => restarting_args} ->
|
||||
{:restarting, child} = restarting_args
|
||||
|
||||
case restart_child(pid, child, state) do
|
||||
{:ok, state} -> {:noreply, state}
|
||||
{:shutdown, state} -> {:stop, :shutdown, state}
|
||||
end
|
||||
|
||||
# We may hit clause if we send $gen_restart and then
|
||||
# someone calls terminate_child, removing the child.
|
||||
%{} ->
|
||||
{:noreply, state}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_info(msg, state) do
|
||||
:error_logger.error_msg('DynamicSupervisor received unexpected message: ~p~n', [msg])
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
@impl true
|
||||
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}
|
||||
{:error, reason} -> {:error, {:supervisor_data, reason}}
|
||||
end
|
||||
|
||||
:ignore ->
|
||||
{:ok, state}
|
||||
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
@impl true
|
||||
def terminate(_, %{children: children} = state) do
|
||||
:ok = terminate_children(children, state)
|
||||
end
|
||||
|
||||
defp terminate_children(children, state) do
|
||||
{pids, times, stacks} = monitor_children(children)
|
||||
size = map_size(pids)
|
||||
|
||||
timers =
|
||||
Enum.reduce(times, %{}, fn {time, pids}, acc ->
|
||||
Map.put(acc, :erlang.start_timer(time, self(), :kill), pids)
|
||||
end)
|
||||
|
||||
stacks = wait_children(pids, size, timers, stacks)
|
||||
|
||||
for {pid, {child, reason}} <- stacks do
|
||||
report_error(:shutdown_error, reason, pid, child, state)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp monitor_children(children) do
|
||||
Enum.reduce(children, {%{}, %{}, %{}}, fn
|
||||
{_, {:restarting, _}}, acc ->
|
||||
acc
|
||||
|
||||
{pid, {_, restart, _, _, _} = child}, {pids, times, stacks} ->
|
||||
case monitor_child(pid) do
|
||||
:ok ->
|
||||
times = exit_child(pid, child, times)
|
||||
{Map.put(pids, pid, child), times, stacks}
|
||||
|
||||
{:error, :normal} when restart != :permanent ->
|
||||
{pids, times, stacks}
|
||||
|
||||
{:error, reason} ->
|
||||
{pids, times, Map.put(stacks, pid, {child, reason})}
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
defp monitor_child(pid) do
|
||||
ref = Process.monitor(pid)
|
||||
Process.unlink(pid)
|
||||
|
||||
receive do
|
||||
{:EXIT, ^pid, reason} ->
|
||||
receive do
|
||||
{:DOWN, ^ref, :process, ^pid, _} -> {:error, reason}
|
||||
end
|
||||
after
|
||||
0 -> :ok
|
||||
end
|
||||
end
|
||||
|
||||
defp exit_child(pid, {_, _, shutdown, _, _}, times) do
|
||||
case shutdown do
|
||||
:brutal_kill ->
|
||||
Process.exit(pid, :kill)
|
||||
times
|
||||
|
||||
:infinity ->
|
||||
Process.exit(pid, :shutdown)
|
||||
times
|
||||
|
||||
time ->
|
||||
Process.exit(pid, :shutdown)
|
||||
Map.update(times, time, [pid], &[pid | &1])
|
||||
end
|
||||
end
|
||||
|
||||
defp wait_children(_pids, 0, timers, stacks) do
|
||||
for {timer, _} <- timers do
|
||||
_ = :erlang.cancel_timer(timer)
|
||||
|
||||
receive do
|
||||
{:timeout, ^timer, :kill} -> :ok
|
||||
after
|
||||
0 -> :ok
|
||||
end
|
||||
end
|
||||
|
||||
stacks
|
||||
end
|
||||
|
||||
defp wait_children(pids, size, timers, stacks) do
|
||||
receive do
|
||||
{:DOWN, _ref, :process, pid, reason} ->
|
||||
case pids do
|
||||
%{^pid => child} ->
|
||||
stacks = wait_child(pid, child, reason, stacks)
|
||||
wait_children(pids, size - 1, timers, stacks)
|
||||
|
||||
%{} ->
|
||||
wait_children(pids, size, timers, stacks)
|
||||
end
|
||||
|
||||
{:timeout, timer, :kill} ->
|
||||
for pid <- Map.fetch!(timers, timer), do: Process.exit(pid, :kill)
|
||||
wait_children(pids, size, Map.delete(timers, timer), stacks)
|
||||
end
|
||||
end
|
||||
|
||||
defp wait_child(pid, {_, _, :brutal_kill, _, _} = child, reason, stacks) do
|
||||
case reason do
|
||||
:killed -> stacks
|
||||
_ -> Map.put(stacks, pid, {child, reason})
|
||||
end
|
||||
end
|
||||
|
||||
defp wait_child(pid, {_, restart, _, _, _} = child, reason, stacks) do
|
||||
case reason do
|
||||
{:shutdown, _} -> stacks
|
||||
:shutdown -> stacks
|
||||
:normal when restart != :permanent -> stacks
|
||||
reason -> Map.put(stacks, pid, {child, reason})
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_restart_child(pid, reason, %{children: children} = state) do
|
||||
case children do
|
||||
%{^pid => {_, restart, _, _, _} = child} ->
|
||||
maybe_restart_child(restart, reason, pid, child, state)
|
||||
|
||||
%{} ->
|
||||
{:ok, state}
|
||||
end
|
||||
end
|
||||
|
||||
defp maybe_restart_child(:permanent, reason, pid, child, state) do
|
||||
report_error(:child_terminated, reason, pid, child, state)
|
||||
restart_child(pid, child, state)
|
||||
end
|
||||
|
||||
defp maybe_restart_child(_, :normal, pid, _child, state) do
|
||||
{:ok, delete_child(pid, state)}
|
||||
end
|
||||
|
||||
defp maybe_restart_child(_, :shutdown, pid, _child, state) do
|
||||
{:ok, delete_child(pid, state)}
|
||||
end
|
||||
|
||||
defp maybe_restart_child(_, {:shutdown, _}, pid, _child, state) do
|
||||
{:ok, delete_child(pid, state)}
|
||||
end
|
||||
|
||||
defp maybe_restart_child(:transient, reason, pid, child, state) do
|
||||
report_error(:child_terminated, reason, pid, child, state)
|
||||
restart_child(pid, child, state)
|
||||
end
|
||||
|
||||
defp maybe_restart_child(:temporary, reason, pid, child, state) do
|
||||
report_error(:child_terminated, reason, pid, child, state)
|
||||
{:ok, delete_child(pid, state)}
|
||||
end
|
||||
|
||||
defp delete_child(pid, %{children: children} = state) do
|
||||
%{state | children: Map.delete(children, pid)}
|
||||
end
|
||||
|
||||
defp restart_child(pid, child, state) do
|
||||
case add_restart(state) do
|
||||
{:ok, %{strategy: strategy} = state} ->
|
||||
case restart_child(strategy, pid, child, state) do
|
||||
{:ok, state} ->
|
||||
{:ok, state}
|
||||
|
||||
{:try_again, state} ->
|
||||
send(self(), {:"$gen_restart", pid})
|
||||
{:ok, state}
|
||||
end
|
||||
|
||||
{:shutdown, state} ->
|
||||
report_error(:shutdown, :reached_max_restart_intensity, pid, child, state)
|
||||
{:shutdown, delete_child(pid, state)}
|
||||
end
|
||||
end
|
||||
|
||||
defp add_restart(state) do
|
||||
%{max_seconds: max_seconds, max_restarts: max_restarts, restarts: restarts} = state
|
||||
|
||||
# The below is equivalent to 1 second. We avoid
|
||||
# :second because of incompatibilties with OTP < 20
|
||||
now = :erlang.monotonic_time(1)
|
||||
restarts = add_restart([now | restarts], now, max_seconds)
|
||||
state = %{state | restarts: restarts}
|
||||
|
||||
if length(restarts) <= max_restarts do
|
||||
{:ok, state}
|
||||
else
|
||||
{:shutdown, state}
|
||||
end
|
||||
end
|
||||
|
||||
defp add_restart(restarts, now, period) do
|
||||
for then <- restarts, now <= then + period, do: then
|
||||
end
|
||||
|
||||
defp restart_child(:one_for_one, current_pid, child, state) do
|
||||
{{m, f, args} = mfa, restart, shutdown, type, modules} = child
|
||||
%{extra_arguments: extra} = state
|
||||
|
||||
case start_child(m, f, extra ++ args) do
|
||||
{:ok, pid, _} ->
|
||||
state = delete_child(current_pid, state)
|
||||
{:ok, save_child(pid, mfa, restart, shutdown, type, modules, state)}
|
||||
|
||||
{:ok, pid} ->
|
||||
state = delete_child(current_pid, state)
|
||||
{:ok, save_child(pid, mfa, restart, shutdown, type, modules, state)}
|
||||
|
||||
:ignore ->
|
||||
{:ok, delete_child(current_pid, state)}
|
||||
|
||||
{:error, reason} ->
|
||||
report_error(:start_error, reason, {:restarting, current_pid}, child, state)
|
||||
state = put_in(state.children[current_pid], {:restarting, child})
|
||||
{:try_again, state}
|
||||
end
|
||||
end
|
||||
|
||||
defp report_error(error, reason, pid, child, %{name: name, extra_arguments: extra}) do
|
||||
:error_logger.error_report(
|
||||
:supervisor_report,
|
||||
supervisor: name,
|
||||
errorContext: error,
|
||||
reason: reason,
|
||||
offender: extract_child(pid, child, extra)
|
||||
)
|
||||
end
|
||||
|
||||
defp extract_child(pid, {{m, f, args}, restart, shutdown, type, _modules}, extra) do
|
||||
[
|
||||
pid: pid,
|
||||
id: :undefined,
|
||||
mfargs: {m, f, extra ++ args},
|
||||
restart_type: restart,
|
||||
shutdown: shutdown,
|
||||
child_type: type
|
||||
]
|
||||
end
|
||||
|
||||
@impl true
|
||||
def format_status(:terminate, [_pdict, state]) do
|
||||
state
|
||||
end
|
||||
|
||||
def format_status(_, [_pdict, %{mod: mod} = state]) do
|
||||
[data: [{~c"State", state}], supervisor: [{~c"Callback", mod}]]
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
@compile {:inline, call: 2}
|
||||
|
||||
defp call(supervisor, req) do
|
||||
GenServer.call(supervisor, req, :infinity)
|
||||
end
|
||||
end
|
||||
+795
-980
File diff suppressed because it is too large
Load Diff
+144
-473
@@ -16,61 +16,51 @@ defmodule Exception do
|
||||
|
||||
@typedoc "The exception type"
|
||||
@type t :: %{
|
||||
required(:__struct__) => module,
|
||||
required(:__exception__) => true,
|
||||
optional(atom) => any
|
||||
}
|
||||
required(:__struct__) => module,
|
||||
required(:__exception__) => true,
|
||||
atom => any
|
||||
}
|
||||
|
||||
@typedoc "The kind handled by formatting functions"
|
||||
@type kind :: :error | non_error_kind
|
||||
@typep non_error_kind :: :exit | :throw | {:EXIT, pid}
|
||||
@type kind :: :error | :exit | :throw | {:EXIT, pid}
|
||||
|
||||
@type stacktrace :: [stacktrace_entry]
|
||||
@type stacktrace_entry ::
|
||||
{module, atom, arity_or_args, location}
|
||||
| {(... -> any), arity_or_args, location}
|
||||
{module, atom, arity_or_args, location} |
|
||||
{(... -> any), arity_or_args, location}
|
||||
|
||||
@typep arity_or_args :: non_neg_integer | list
|
||||
@typep location :: keyword
|
||||
@typep location :: Keyword.t
|
||||
|
||||
@callback exception(term) :: t
|
||||
@callback message(t) :: String.t()
|
||||
|
||||
@doc """
|
||||
Called from `Exception.blame/3` to augment the exception struct.
|
||||
|
||||
Can be used to collect additional information about the exception
|
||||
or do some additional expensive computation.
|
||||
"""
|
||||
@callback blame(t, stacktrace) :: {t, stacktrace}
|
||||
@optional_callbacks [blame: 2]
|
||||
@callback message(t) :: String.t
|
||||
|
||||
@doc """
|
||||
Returns `true` if the given `term` is an exception.
|
||||
"""
|
||||
def exception?(term)
|
||||
def exception?(%_{__exception__: true}), do: true
|
||||
|
||||
def exception?(%{__struct__: struct, __exception__: true}) when is_atom(struct),
|
||||
do: true
|
||||
|
||||
def exception?(_), do: false
|
||||
|
||||
@doc """
|
||||
Gets the message for an `exception`.
|
||||
"""
|
||||
def message(%module{__exception__: true} = exception) do
|
||||
def message(%{__struct__: module, __exception__: true} = exception) when is_atom(module) do
|
||||
try do
|
||||
module.message(exception)
|
||||
rescue
|
||||
caught_exception ->
|
||||
"got #{inspect(caught_exception.__struct__)} with message " <>
|
||||
"#{inspect(message(caught_exception))} while retrieving Exception.message/1 " <>
|
||||
"for #{inspect(exception)}"
|
||||
e ->
|
||||
"got #{inspect e.__struct__} with message #{inspect message(e)} " <>
|
||||
"while retrieving Exception.message/1 for #{inspect(exception)}"
|
||||
else
|
||||
result when is_binary(result) ->
|
||||
result
|
||||
|
||||
result ->
|
||||
"got #{inspect(result)} " <>
|
||||
"while retrieving Exception.message/1 for #{inspect(exception)} " <>
|
||||
"(expected a string)"
|
||||
x when is_binary(x) -> x
|
||||
x ->
|
||||
"got #{inspect(x)} " <>
|
||||
"while retrieving Exception.message/1 for #{inspect(exception)} " <>
|
||||
"(expected a string)"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -90,7 +80,7 @@ defmodule Exception do
|
||||
an empty stacktrace, `[]`, must be used.
|
||||
"""
|
||||
@spec normalize(:error, any, stacktrace) :: t
|
||||
@spec normalize(non_error_kind, payload, stacktrace) :: payload when payload: var
|
||||
@spec normalize(kind, payload, stacktrace) :: payload when payload: var
|
||||
|
||||
# Generating a stacktrace is expensive, default to nil
|
||||
# to only fetch it when needed.
|
||||
@@ -121,7 +111,7 @@ defmodule Exception do
|
||||
not return the stacktrace corresponding to the exception
|
||||
an empty stacktrace, `[]`, must be used.
|
||||
"""
|
||||
@spec format_banner(kind, any, stacktrace | nil) :: String.t()
|
||||
@spec format_banner(kind, any, stacktrace | nil) :: String.t
|
||||
def format_banner(kind, exception, stacktrace \\ nil)
|
||||
|
||||
def format_banner(:error, exception, stacktrace) do
|
||||
@@ -130,7 +120,7 @@ defmodule Exception do
|
||||
end
|
||||
|
||||
def format_banner(:throw, reason, _stacktrace) do
|
||||
"** (throw) " <> inspect(reason)
|
||||
"** (throw) " <> inspect(reason)
|
||||
end
|
||||
|
||||
def format_banner(:exit, reason, _stacktrace) do
|
||||
@@ -138,7 +128,7 @@ defmodule Exception do
|
||||
end
|
||||
|
||||
def format_banner({:EXIT, pid}, reason, _stacktrace) do
|
||||
"** (EXIT from #{inspect(pid)}) " <> format_exit(reason, <<"\n ">>)
|
||||
"** (EXIT from #{inspect pid}) " <> format_exit(reason, <<"\n ">>)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -150,7 +140,9 @@ defmodule Exception do
|
||||
Note that `{:EXIT, pid}` do not generate a stacktrace though
|
||||
(as they are retrieved as messages without stacktraces).
|
||||
"""
|
||||
@spec format(kind, any, stacktrace | nil) :: String.t()
|
||||
|
||||
@spec format(kind, any, stacktrace | nil) :: String.t
|
||||
|
||||
def format(kind, payload, stacktrace \\ nil)
|
||||
|
||||
def format({:EXIT, _} = kind, any, _) do
|
||||
@@ -158,178 +150,14 @@ defmodule Exception do
|
||||
end
|
||||
|
||||
def format(kind, payload, stacktrace) do
|
||||
stacktrace = stacktrace || System.stacktrace()
|
||||
stacktrace = stacktrace || System.stacktrace
|
||||
message = format_banner(kind, payload, stacktrace)
|
||||
|
||||
case stacktrace do
|
||||
[] -> message
|
||||
_ -> message <> "\n" <> format_stacktrace(stacktrace)
|
||||
_ -> message <> "\n" <> format_stacktrace(stacktrace)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Attaches information to exceptions for extra debugging.
|
||||
|
||||
This operation is potentially expensive, as it reads data
|
||||
from the filesystem, parse beam files, evaluates code and
|
||||
so on.
|
||||
|
||||
If the exception module implements the optional `c:blame/2`
|
||||
callbak, it will be invoked to perform the computation.
|
||||
"""
|
||||
@spec blame(:error, any, stacktrace) :: {t, stacktrace}
|
||||
@spec blame(non_error_kind, payload, stacktrace) :: {payload, stacktrace} when payload: var
|
||||
def blame(kind, error, stacktrace)
|
||||
|
||||
def blame(:error, error, stacktrace) do
|
||||
%module{} = struct = normalize(:error, error, stacktrace)
|
||||
|
||||
if Code.ensure_loaded?(module) and function_exported?(module, :blame, 2) do
|
||||
module.blame(struct, stacktrace)
|
||||
else
|
||||
{struct, stacktrace}
|
||||
end
|
||||
end
|
||||
|
||||
def blame(_kind, reason, stacktrace) do
|
||||
{reason, stacktrace}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Blames the invocation of the given module, function and arguments.
|
||||
|
||||
This function will retrieve the available clauses from bytecode
|
||||
and evaluate them against the given arguments. The clauses are
|
||||
returned as a list of `{args, guards}` pairs where each argument
|
||||
and each top-level condition in a guard separated by `and`/`or`
|
||||
is wrapped in a tuple with blame metadata.
|
||||
|
||||
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.
|
||||
"""
|
||||
@spec blame_mfa(module, function, args :: [term]) ::
|
||||
{:ok, :def | :defp | :defmacro | :defmacrop, [{args :: [term], guards :: [term]}]}
|
||||
| :error
|
||||
def blame_mfa(module, function, args)
|
||||
when is_atom(module) and is_atom(function) and is_list(args) do
|
||||
try do
|
||||
blame_mfa(module, function, length(args), args)
|
||||
rescue
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp blame_mfa(module, function, arity, call_args) do
|
||||
with [_ | _] = path <- :code.which(module),
|
||||
{:ok, {_, [debug_info: debug_info]}} <- :beam_lib.chunks(path, [:debug_info]),
|
||||
{:debug_info_v1, backend, data} <- debug_info,
|
||||
{:ok, %{definitions: defs}} <- backend.debug_info(:elixir_v1, module, data, []),
|
||||
{_, kind, _, clauses} <- List.keyfind(defs, {function, arity}, 0) do
|
||||
clauses =
|
||||
for {meta, ex_args, guards, _block} <- clauses do
|
||||
scope = :elixir_erl.definition_scope(meta, "nofile")
|
||||
|
||||
{erl_args, scope} =
|
||||
:elixir_erl_clauses.match(&:elixir_erl_pass.translate_args/2, ex_args, scope)
|
||||
|
||||
{args, binding} =
|
||||
[call_args, ex_args, erl_args]
|
||||
|> Enum.zip()
|
||||
|> Enum.map_reduce([], &blame_arg/2)
|
||||
|
||||
guards = Enum.map(guards, &blame_guard(&1, scope, binding))
|
||||
{args, guards}
|
||||
end
|
||||
|
||||
{:ok, kind, clauses}
|
||||
else
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp blame_arg({call_arg, ex_arg, erl_arg}, binding) do
|
||||
{match?, binding} = blame_arg(erl_arg, call_arg, binding)
|
||||
{blame_wrap(match?, rewrite_arg(ex_arg)), binding}
|
||||
end
|
||||
|
||||
defp blame_arg(erl_arg, call_arg, binding) do
|
||||
binding = :orddict.store(:VAR, call_arg, binding)
|
||||
|
||||
try do
|
||||
{:value, _, binding} = :erl_eval.expr({:match, 0, erl_arg, {:var, 0, :VAR}}, binding, :none)
|
||||
{true, binding}
|
||||
rescue
|
||||
_ -> {false, binding}
|
||||
end
|
||||
end
|
||||
|
||||
defp rewrite_arg(arg) do
|
||||
Macro.prewalk(arg, fn
|
||||
{:%{}, meta, [__struct__: Range, first: first, last: last]} ->
|
||||
{:.., meta, [first, last]}
|
||||
|
||||
other ->
|
||||
other
|
||||
end)
|
||||
end
|
||||
|
||||
defp blame_guard({{:., _, [:erlang, op]}, meta, [left, right]}, scope, binding)
|
||||
when op == :andalso or op == :orelse do
|
||||
guards = [
|
||||
blame_guard(left, scope, binding),
|
||||
blame_guard(right, scope, binding)
|
||||
]
|
||||
|
||||
{rewrite_guard_call(op), meta, guards}
|
||||
end
|
||||
|
||||
defp blame_guard(ex_guard, scope, binding) do
|
||||
{erl_guard, _} = :elixir_erl_pass.translate(ex_guard, scope)
|
||||
|
||||
match? =
|
||||
try do
|
||||
{:value, true, _} = :erl_eval.expr(erl_guard, binding, :none)
|
||||
true
|
||||
rescue
|
||||
_ -> false
|
||||
end
|
||||
|
||||
blame_wrap(match?, rewrite_guard(ex_guard))
|
||||
end
|
||||
|
||||
defp rewrite_guard(guard) do
|
||||
Macro.prewalk(guard, fn
|
||||
{{:., _, [:erlang, :element]}, _, [{{:., _, [:erlang, :+]}, _, [int, 1]}, arg]} ->
|
||||
{:elem, [], [arg, int]}
|
||||
|
||||
{{:., _, [:erlang, :element]}, _, [int, arg]} when is_integer(int) ->
|
||||
{:elem, [], [arg, int - 1]}
|
||||
|
||||
{:., _, [:erlang, call]} ->
|
||||
rewrite_guard_call(call)
|
||||
|
||||
other ->
|
||||
other
|
||||
end)
|
||||
end
|
||||
|
||||
defp rewrite_guard_call(:orelse), do: :or
|
||||
defp rewrite_guard_call(:andalso), do: :and
|
||||
defp rewrite_guard_call(:"=<"), do: :<=
|
||||
defp rewrite_guard_call(:"/="), do: :!=
|
||||
defp rewrite_guard_call(:"=:="), do: :===
|
||||
defp rewrite_guard_call(:"=/="), do: :!==
|
||||
|
||||
defp rewrite_guard_call(op) when op in [:band, :bor, :bnot, :bsl, :bsr, :bxor],
|
||||
do: {:., [], [Bitwise, op]}
|
||||
|
||||
defp rewrite_guard_call(op) when op in [:xor, :element, :size], do: {:., [], [:erlang, op]}
|
||||
defp rewrite_guard_call(op), do: op
|
||||
|
||||
defp blame_wrap(match?, ast), do: %{match?: match?, node: ast}
|
||||
|
||||
@doc """
|
||||
Formats an exit. It returns a string.
|
||||
|
||||
@@ -338,60 +166,60 @@ defmodule Exception do
|
||||
formats exits in a way to nicely show the exit reason, caller
|
||||
and stacktrace.
|
||||
"""
|
||||
@spec format_exit(any) :: String.t()
|
||||
@spec format_exit(any) :: String.t
|
||||
def format_exit(reason) do
|
||||
format_exit(reason, <<"\n ">>)
|
||||
end
|
||||
|
||||
# 2-Tuple could be caused by an error if the second element is a stacktrace.
|
||||
defp format_exit({exception, maybe_stacktrace} = reason, joiner)
|
||||
when is_list(maybe_stacktrace) and maybe_stacktrace !== [] do
|
||||
when is_list(maybe_stacktrace) and maybe_stacktrace !== [] do
|
||||
try do
|
||||
Enum.map(maybe_stacktrace, &format_stacktrace_entry/1)
|
||||
catch
|
||||
:error, _ ->
|
||||
# Not a stacktrace, was an exit.
|
||||
format_exit_reason(reason)
|
||||
else
|
||||
formatted_stacktrace ->
|
||||
# Assume a non-empty list formattable as stacktrace is a
|
||||
# stacktrace, so exit was caused by an error.
|
||||
message =
|
||||
"an exception was raised:" <>
|
||||
joiner <> format_banner(:error, exception, maybe_stacktrace)
|
||||
|
||||
message = "an exception was raised:" <> joiner <>
|
||||
format_banner(:error, exception, maybe_stacktrace)
|
||||
Enum.join([message | formatted_stacktrace], joiner <> <<" ">>)
|
||||
catch
|
||||
:error, _ ->
|
||||
# Not a stacktrace, was an exit.
|
||||
format_exit_reason(reason)
|
||||
end
|
||||
end
|
||||
|
||||
# :supervisor.start_link returns this error reason when it fails to init
|
||||
# because a child's start_link raises.
|
||||
defp format_exit({:shutdown, {:failed_to_start_child, child, {:EXIT, reason}}}, joiner) do
|
||||
defp format_exit({:shutdown,
|
||||
{:failed_to_start_child, child, {:EXIT, reason}}}, joiner) do
|
||||
format_start_child(child, reason, joiner)
|
||||
end
|
||||
|
||||
# :supervisor.start_link returns this error reason when it fails to init
|
||||
# because a child's start_link returns {:error, reason}.
|
||||
defp format_exit({:shutdown, {:failed_to_start_child, child, reason}}, joiner) do
|
||||
defp format_exit({:shutdown, {:failed_to_start_child, child, reason}},
|
||||
joiner) do
|
||||
format_start_child(child, reason, joiner)
|
||||
end
|
||||
|
||||
# 2-Tuple could be an exit caused by mfa if second element is mfa, args
|
||||
# must be a list of arguments - max length 255 due to max arity.
|
||||
defp format_exit({reason2, {mod, fun, args}} = reason, joiner)
|
||||
when length(args) < 256 do
|
||||
when length(args) < 256 do
|
||||
try do
|
||||
format_mfa(mod, fun, args)
|
||||
catch
|
||||
:error, _ ->
|
||||
# Not an mfa, was an exit.
|
||||
format_exit_reason(reason)
|
||||
else
|
||||
mfa ->
|
||||
# Assume tuple formattable as an mfa is an mfa, so exit was caused by
|
||||
# failed mfa.
|
||||
"exited in: " <>
|
||||
mfa <> joiner <> "** (EXIT) " <> format_exit(reason2, joiner <> <<" ">>)
|
||||
"exited in: " <> mfa <> joiner <>
|
||||
"** (EXIT) " <> format_exit(reason2, joiner <> <<" ">>)
|
||||
catch
|
||||
:error, _ ->
|
||||
# Not an mfa, was an exit.
|
||||
format_exit_reason(reason)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -441,27 +269,27 @@ defmodule Exception do
|
||||
|
||||
# If value is a list will be formatted by mfa exit in format_exit/1
|
||||
defp format_exit_reason({:bad_return, {mod, :init, value}})
|
||||
when is_atom(mod) do
|
||||
when is_atom(mod) do
|
||||
format_mfa(mod, :init, 1) <> " returned a bad value: " <> inspect(value)
|
||||
end
|
||||
|
||||
defp format_exit_reason({:bad_start_spec, start_spec}) do
|
||||
"bad child specification, invalid children: " <> inspect(start_spec)
|
||||
"bad start spec: invalid children: " <> inspect(start_spec)
|
||||
end
|
||||
|
||||
defp format_exit_reason({:start_spec, start_spec}) do
|
||||
"bad child specification, " <> format_sup_spec(start_spec)
|
||||
"bad start spec: " <> format_sup_spec(start_spec)
|
||||
end
|
||||
|
||||
defp format_exit_reason({:supervisor_data, data}) do
|
||||
"bad supervisor configuration, " <> format_sup_data(data)
|
||||
"bad supervisor data: " <> format_sup_data(data)
|
||||
end
|
||||
|
||||
defp format_exit_reason(reason), do: inspect(reason)
|
||||
|
||||
defp format_start_child(child, reason, joiner) do
|
||||
"shutdown: failed to start child: " <>
|
||||
inspect(child) <> joiner <> "** (EXIT) " <> format_exit(reason, joiner <> <<" ">>)
|
||||
"shutdown: failed to start child: " <> inspect(child) <> joiner <>
|
||||
"** (EXIT) " <> format_exit(reason, joiner <> <<" ">>)
|
||||
end
|
||||
|
||||
defp format_sup_data({:invalid_type, type}) do
|
||||
@@ -473,70 +301,49 @@ defmodule Exception do
|
||||
end
|
||||
|
||||
defp format_sup_data({:invalid_intensity, intensity}) do
|
||||
"invalid max_restarts (intensity): " <> inspect(intensity)
|
||||
"invalid intensity: " <> inspect(intensity)
|
||||
end
|
||||
|
||||
defp format_sup_data({:invalid_period, period}) do
|
||||
"invalid max_seconds (period): " <> inspect(period)
|
||||
"invalid period: " <> inspect(period)
|
||||
end
|
||||
|
||||
defp format_sup_data({:invalid_max_children, max_children}) do
|
||||
"invalid max_children: " <> inspect(max_children)
|
||||
end
|
||||
|
||||
defp format_sup_data({:invalid_extra_arguments, extra}) do
|
||||
"invalid extra_arguments: " <> inspect(extra)
|
||||
end
|
||||
|
||||
defp format_sup_data(other), do: "got: #{inspect(other)}"
|
||||
|
||||
defp format_sup_spec({:duplicate_child_name, id}) do
|
||||
"""
|
||||
more than one child specification has the id: #{inspect(id)}.
|
||||
If using maps as child specifications, make sure the :id keys are unique.
|
||||
If using a module or {module, arg} as child, use Supervisor.child_spec/2 to change the :id, for example:
|
||||
|
||||
children = [
|
||||
Supervisor.child_spec({MyWorker, arg}, id: :my_worker_1),
|
||||
Supervisor.child_spec({MyWorker, arg}, id: :my_worker_2)
|
||||
]
|
||||
"""
|
||||
end
|
||||
defp format_sup_data(other), do: inspect(other)
|
||||
|
||||
defp format_sup_spec({:invalid_child_spec, child_spec}) do
|
||||
"invalid child specification: #{inspect(child_spec)}"
|
||||
"invalid child spec: " <> inspect(child_spec)
|
||||
end
|
||||
|
||||
defp format_sup_spec({:invalid_child_type, type}) do
|
||||
"invalid child type: #{inspect(type)}. Must be :worker or :supervisor."
|
||||
"invalid child type: " <> inspect(type)
|
||||
end
|
||||
|
||||
defp format_sup_spec({:invalid_mfa, mfa}) do
|
||||
"invalid mfa: #{inspect(mfa)}"
|
||||
"invalid mfa: " <> inspect(mfa)
|
||||
end
|
||||
|
||||
defp format_sup_spec({:invalid_restart_type, restart}) do
|
||||
"invalid restart type: #{inspect(restart)}. Must be :permanent, :transient or :temporary."
|
||||
"invalid restart type: " <> inspect(restart)
|
||||
end
|
||||
|
||||
defp format_sup_spec({:invalid_shutdown, shutdown}) do
|
||||
"invalid shutdown: #{inspect(shutdown)}. Must be an integer >= 0, :infinity or :brutal_kill."
|
||||
"invalid shutdown: " <> inspect(shutdown)
|
||||
end
|
||||
|
||||
defp format_sup_spec({:invalid_module, mod}) do
|
||||
"invalid module: #{inspect(mod)}. Must be an atom."
|
||||
"invalid module: " <> inspect(mod)
|
||||
end
|
||||
|
||||
defp format_sup_spec({:invalid_modules, modules}) do
|
||||
"invalid modules: #{inspect(modules)}. Must be a list of atoms or :dynamic."
|
||||
"invalid modules: " <> inspect(modules)
|
||||
end
|
||||
|
||||
defp format_sup_spec(other), do: "got: #{inspect(other)}"
|
||||
defp format_sup_spec(other), do: inspect(other)
|
||||
|
||||
@doc """
|
||||
Receives a stacktrace entry and formats it into a string.
|
||||
"""
|
||||
@spec format_stacktrace_entry(stacktrace_entry) :: String.t()
|
||||
@spec format_stacktrace_entry(stacktrace_entry) :: String.t
|
||||
def format_stacktrace_entry(entry)
|
||||
|
||||
# From Macro.Env.stacktrace
|
||||
@@ -577,14 +384,9 @@ defmodule Exception do
|
||||
is retrieved from `Process.info/2`.
|
||||
"""
|
||||
def format_stacktrace(trace \\ nil) do
|
||||
trace =
|
||||
if trace do
|
||||
trace
|
||||
else
|
||||
case Process.info(self(), :current_stacktrace) do
|
||||
{:current_stacktrace, t} -> Enum.drop(t, 3)
|
||||
end
|
||||
end
|
||||
trace = trace || case Process.info(self(), :current_stacktrace) do
|
||||
{:current_stacktrace, t} -> Enum.drop(t, 3)
|
||||
end
|
||||
|
||||
case trace do
|
||||
[] -> "\n"
|
||||
@@ -603,7 +405,7 @@ defmodule Exception do
|
||||
|
||||
"""
|
||||
def format_fa(fun, arity) when is_function(fun) do
|
||||
"#{inspect(fun)}#{format_arity(arity)}"
|
||||
"#{inspect fun}#{format_arity(arity)}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -627,15 +429,17 @@ defmodule Exception do
|
||||
"anonymous fn in func/arity"
|
||||
"""
|
||||
def format_mfa(module, fun, arity) when is_atom(module) and is_atom(fun) do
|
||||
case Code.Identifier.extract_anonymous_fun_parent(fun) do
|
||||
{outer_name, outer_arity} ->
|
||||
"anonymous fn#{format_arity(arity)} in " <>
|
||||
"#{Code.Identifier.inspect_as_atom(module)}." <>
|
||||
"#{Code.Identifier.inspect_as_function(outer_name)}/#{outer_arity}"
|
||||
fun =
|
||||
case inspect(fun) do
|
||||
":" <> fun -> fun
|
||||
fun -> fun
|
||||
end
|
||||
|
||||
:error ->
|
||||
"#{Code.Identifier.inspect_as_atom(module)}." <>
|
||||
"#{Code.Identifier.inspect_as_function(fun)}#{format_arity(arity)}"
|
||||
case match?("\"-" <> _, fun) and String.split(fun, "-") do
|
||||
[ "\"", outer_fun, "fun", _count, "\"" ] ->
|
||||
"anonymous fn#{format_arity(arity)} in #{inspect module}.#{outer_fun}"
|
||||
_ ->
|
||||
"#{inspect module}.#{fun}#{format_arity(arity)}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -677,7 +481,7 @@ defmodule Exception do
|
||||
end
|
||||
|
||||
defp format_location(opts) when is_list(opts) do
|
||||
format_file_line(Keyword.get(opts, :file), Keyword.get(opts, :line), " ")
|
||||
format_file_line Keyword.get(opts, :file), Keyword.get(opts, :line), " "
|
||||
end
|
||||
end
|
||||
|
||||
@@ -719,7 +523,8 @@ defmodule TokenMissingError do
|
||||
defexception [:file, :line, description: "expression is incomplete"]
|
||||
|
||||
def message(%{file: file, line: line, description: description}) do
|
||||
Exception.format_file_line(file && Path.relative_to_cwd(file), line) <> " " <> description
|
||||
Exception.format_file_line(file && Path.relative_to_cwd(file), line) <>
|
||||
" " <> description
|
||||
end
|
||||
end
|
||||
|
||||
@@ -727,7 +532,8 @@ defmodule CompileError do
|
||||
defexception [:file, :line, description: "compile error"]
|
||||
|
||||
def message(%{file: file, line: line, description: description}) do
|
||||
Exception.format_file_line(file && Path.relative_to_cwd(file), line) <> " " <> description
|
||||
Exception.format_file_line(file && Path.relative_to_cwd(file), line) <>
|
||||
" " <> description
|
||||
end
|
||||
end
|
||||
|
||||
@@ -807,7 +613,7 @@ defmodule BadArityError do
|
||||
defexception [:function, :args]
|
||||
|
||||
def message(exception) do
|
||||
fun = exception.function
|
||||
fun = exception.function
|
||||
args = exception.args
|
||||
insp = Enum.map_join(args, ", ", &inspect/1)
|
||||
{:arity, arity} = :erlang.fun_info(fun, :arity)
|
||||
@@ -815,8 +621,8 @@ defmodule BadArityError do
|
||||
end
|
||||
|
||||
defp count(0, _insp), do: "no arguments"
|
||||
defp count(1, insp), do: "1 argument (#{insp})"
|
||||
defp count(x, insp), do: "#{x} arguments (#{insp})"
|
||||
defp count(1, insp), do: "1 argument (#{insp})"
|
||||
defp count(x, insp), do: "#{x} arguments (#{insp})"
|
||||
end
|
||||
|
||||
defmodule UndefinedFunctionError do
|
||||
@@ -826,100 +632,73 @@ defmodule UndefinedFunctionError do
|
||||
cond do
|
||||
is_nil(function) or is_nil(arity) ->
|
||||
"undefined function"
|
||||
|
||||
not is_nil(module) and :code.is_loaded(module) == false ->
|
||||
not is_nil(module) and :code.is_loaded(module) === false ->
|
||||
message(%{e | reason: :"module could not be loaded"})
|
||||
|
||||
true ->
|
||||
message(%{e | reason: :"function not exported"})
|
||||
end
|
||||
end
|
||||
|
||||
def message(%{
|
||||
reason: :"module could not be loaded",
|
||||
module: module,
|
||||
function: function,
|
||||
arity: arity
|
||||
}) do
|
||||
formatted_fun = Exception.format_mfa(module, function, arity)
|
||||
"function #{formatted_fun} is undefined (module #{inspect(module)} is not available)"
|
||||
def message(%{reason: :"module could not be loaded", module: module, function: function, arity: arity}) do
|
||||
"function " <> Exception.format_mfa(module, function, arity) <>
|
||||
" is undefined (module #{inspect module} is not available)"
|
||||
end
|
||||
|
||||
def message(%{
|
||||
reason: :"function not exported",
|
||||
module: module,
|
||||
function: function,
|
||||
arity: arity
|
||||
}) do
|
||||
IO.iodata_to_binary(function_not_exported(module, function, arity, nil))
|
||||
end
|
||||
|
||||
def message(%{
|
||||
reason: :"function not available",
|
||||
module: module,
|
||||
function: function,
|
||||
arity: arity
|
||||
}) do
|
||||
"nil." <> fa = Exception.format_mfa(nil, function, arity)
|
||||
def message(%{reason: :"function not exported", module: module, function: function, arity: arity, exports: exports}) do
|
||||
suffix =
|
||||
if macro_exported?(module, function, arity) do
|
||||
". However there is a macro with the same name and arity." <>
|
||||
" Be sure to require #{inspect(module)} if you intend to invoke this macro"
|
||||
else
|
||||
did_you_mean(module, function, arity, exports)
|
||||
end
|
||||
|
||||
"function " <>
|
||||
Exception.format_mfa(module, function, arity) <>
|
||||
" is undefined (function #{fa} is not available)"
|
||||
end
|
||||
|
||||
def message(%{reason: reason, module: module, function: function, arity: arity}) do
|
||||
"function " <> Exception.format_mfa(module, function, arity) <> " is undefined (#{reason})"
|
||||
end
|
||||
|
||||
@doc false
|
||||
def function_not_exported(module, function, arity, exports) do
|
||||
suffix =
|
||||
if macro_exported?(module, function, arity) do
|
||||
". However there is a macro with the same name and arity. " <>
|
||||
"Be sure to require #{inspect(module)} if you intend to invoke this macro"
|
||||
else
|
||||
did_you_mean(module, function, exports)
|
||||
end
|
||||
|
||||
[
|
||||
"function ",
|
||||
Exception.format_mfa(module, function, arity),
|
||||
" is undefined or private",
|
||||
" is undefined or private" <>
|
||||
suffix
|
||||
]
|
||||
end
|
||||
|
||||
def message(%{reason: :"function not available", module: module, function: function, arity: arity}) do
|
||||
"nil." <> fa = Exception.format_mfa(nil, function, arity)
|
||||
"function " <> Exception.format_mfa(module, function, arity) <>
|
||||
" is undefined (function #{fa} is not available)"
|
||||
end
|
||||
|
||||
def message(%{reason: reason, module: module, function: function, arity: arity}) do
|
||||
"function " <> Exception.format_mfa(module, function, arity) <> " is undefined (#{reason})"
|
||||
end
|
||||
|
||||
@function_threshold 0.77
|
||||
@max_suggestions 5
|
||||
|
||||
defp did_you_mean(module, function, exports) do
|
||||
defp did_you_mean(module, function, _arity, exports) do
|
||||
exports = exports || exports_for(module)
|
||||
|
||||
result =
|
||||
case Keyword.take(exports, [function]) do
|
||||
[] ->
|
||||
base = Atom.to_string(function)
|
||||
|
||||
for {key, val} <- exports,
|
||||
dist = String.jaro_distance(base, Atom.to_string(key)),
|
||||
dist >= @function_threshold,
|
||||
do: {dist, key, val}
|
||||
|
||||
do: {dist, key, val}
|
||||
arities ->
|
||||
for {key, val} <- arities, do: {1.0, key, val}
|
||||
end
|
||||
|> Enum.sort(&(elem(&1, 0) >= elem(&2, 0)))
|
||||
|> Enum.sort(&elem(&1, 0) >= elem(&2, 0))
|
||||
|> Enum.take(@max_suggestions)
|
||||
|> Enum.sort(&(elem(&1, 1) <= elem(&2, 1)))
|
||||
|> Enum.sort(&elem(&1, 1) <= elem(&2, 1))
|
||||
|
||||
case result do
|
||||
[] -> []
|
||||
suggestions -> [". Did you mean one of:\n\n" | Enum.map(suggestions, &format_fa/1)]
|
||||
[] -> ""
|
||||
suggestions -> ". Did you mean one of:\n\n#{Enum.map(suggestions, &format_fa/1)}"
|
||||
end
|
||||
end
|
||||
|
||||
defp format_fa({_dist, fun, arity}) do
|
||||
[" * ", Code.Identifier.inspect_as_function(fun), ?/, Integer.to_string(arity), ?\n]
|
||||
fun = with ":" <> fun <- inspect(fun), do: fun
|
||||
" * " <> fun <> "/" <> Integer.to_string(arity) <> "\n"
|
||||
end
|
||||
|
||||
defp exports_for(module) do
|
||||
@@ -930,91 +709,21 @@ defmodule UndefinedFunctionError do
|
||||
end
|
||||
rescue
|
||||
# In case the module was removed while we are computing this
|
||||
UndefinedFunctionError ->
|
||||
[]
|
||||
UndefinedFunctionError -> []
|
||||
end
|
||||
end
|
||||
|
||||
defmodule FunctionClauseError do
|
||||
defexception [:module, :function, :arity, :kind, :args, :clauses]
|
||||
defexception [:module, :function, :arity]
|
||||
|
||||
def message(exception) do
|
||||
case exception do
|
||||
%{function: nil} ->
|
||||
"no function clause matches"
|
||||
|
||||
%{module: module, function: function, arity: arity} ->
|
||||
formatted = Exception.format_mfa(module, function, arity)
|
||||
blamed = blame(exception, &inspect/1, &blame_match/2)
|
||||
"no function clause matching in #{formatted}" <> blamed
|
||||
if exception.function do
|
||||
formatted = Exception.format_mfa exception.module, exception.function, exception.arity
|
||||
"no function clause matching in #{formatted}"
|
||||
else
|
||||
"no function clause matches"
|
||||
end
|
||||
end
|
||||
|
||||
def blame(%{module: module, function: function, arity: arity} = exception, stacktrace) do
|
||||
case stacktrace do
|
||||
[{^module, ^function, args, meta} | rest] when length(args) == arity ->
|
||||
exception =
|
||||
case Exception.blame_mfa(module, function, args) do
|
||||
{:ok, kind, clauses} -> %{exception | args: args, kind: kind, clauses: clauses}
|
||||
:error -> %{exception | args: args}
|
||||
end
|
||||
|
||||
{exception, [{module, function, arity, meta} | rest]}
|
||||
|
||||
stacktrace ->
|
||||
{exception, stacktrace}
|
||||
end
|
||||
end
|
||||
|
||||
defp blame_match(%{match?: true, node: node}, _), do: Macro.to_string(node)
|
||||
defp blame_match(%{match?: false, node: node}, _), do: "-" <> Macro.to_string(node) <> "-"
|
||||
defp blame_match(_, string), do: string
|
||||
|
||||
@doc false
|
||||
def blame(%{args: nil}, _, _) do
|
||||
""
|
||||
end
|
||||
|
||||
def blame(exception, inspect_fun, ast_fun) do
|
||||
%{module: module, function: function, arity: arity, kind: kind, args: args, clauses: clauses} =
|
||||
exception
|
||||
|
||||
mfa = Exception.format_mfa(module, function, arity)
|
||||
|
||||
formatted_args =
|
||||
args
|
||||
|> Enum.with_index(1)
|
||||
|> Enum.map(fn {arg, i} ->
|
||||
["\n # ", Integer.to_string(i), "\n ", pad(inspect_fun.(arg)), "\n"]
|
||||
end)
|
||||
|
||||
formatted_clauses =
|
||||
if clauses do
|
||||
format_clause_fun = fn {args, guards} ->
|
||||
code = Enum.reduce(guards, {function, [], args}, &{:when, [], [&2, &1]})
|
||||
" #{kind} " <> Macro.to_string(code, ast_fun) <> "\n"
|
||||
end
|
||||
|
||||
top_10 =
|
||||
clauses
|
||||
|> Enum.take(10)
|
||||
|> Enum.map(format_clause_fun)
|
||||
|
||||
[
|
||||
"\nAttempted function clauses (showing #{length(top_10)} out of #{length(clauses)}):",
|
||||
"\n\n",
|
||||
top_10
|
||||
]
|
||||
else
|
||||
""
|
||||
end
|
||||
|
||||
"\n\nThe following arguments were given to #{mfa}:\n#{formatted_args}#{formatted_clauses}"
|
||||
end
|
||||
|
||||
defp pad(string) do
|
||||
String.replace(string, "\n", "\n ")
|
||||
end
|
||||
end
|
||||
|
||||
defmodule Code.LoadError do
|
||||
@@ -1029,24 +738,11 @@ end
|
||||
defmodule Protocol.UndefinedError do
|
||||
defexception [:protocol, :value, description: ""]
|
||||
|
||||
def message(%{protocol: protocol, value: value, description: description}) do
|
||||
"protocol #{inspect(protocol)} not implemented for #{inspect(value)}" <>
|
||||
maybe_description(description) <> maybe_available(protocol)
|
||||
end
|
||||
|
||||
defp maybe_description(""), do: ""
|
||||
defp maybe_description(description), do: ", " <> description
|
||||
|
||||
defp maybe_available(protocol) do
|
||||
case protocol.__protocol__(:impls) do
|
||||
{:consolidated, []} ->
|
||||
". There are no implementations for this protocol."
|
||||
|
||||
{:consolidated, types} ->
|
||||
". This protocol is implemented for: #{Enum.map_join(types, ", ", &inspect/1)}"
|
||||
|
||||
:not_consolidated ->
|
||||
""
|
||||
def message(exception) do
|
||||
msg = "protocol #{inspect exception.protocol} not implemented for #{inspect exception.value}"
|
||||
case exception.description do
|
||||
"" -> msg
|
||||
descr -> msg <> ", " <> descr
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -1055,10 +751,9 @@ defmodule KeyError do
|
||||
defexception [:key, :term]
|
||||
|
||||
def message(exception) do
|
||||
msg = "key #{inspect(exception.key)} not found"
|
||||
|
||||
msg = "key #{inspect exception.key} not found"
|
||||
if exception.term != nil do
|
||||
msg <> " in: #{inspect(exception.term)}"
|
||||
msg <> " in: #{inspect exception.term}"
|
||||
else
|
||||
msg
|
||||
end
|
||||
@@ -1071,12 +766,12 @@ defmodule UnicodeConversionError do
|
||||
def exception(opts) do
|
||||
%UnicodeConversionError{
|
||||
encoded: Keyword.fetch!(opts, :encoded),
|
||||
message: "#{Keyword.fetch!(opts, :kind)} #{detail(Keyword.fetch!(opts, :rest))}"
|
||||
message: "#{Keyword.fetch!(opts, :kind)} #{detail Keyword.fetch!(opts, :rest)}"
|
||||
}
|
||||
end
|
||||
|
||||
defp detail(rest) when is_binary(rest) do
|
||||
"encoding starting at #{inspect(rest)}"
|
||||
"encoding starting at #{inspect rest}"
|
||||
end
|
||||
|
||||
defp detail([h | _]) when is_integer(h) do
|
||||
@@ -1104,7 +799,6 @@ defmodule File.Error do
|
||||
case {action, reason} do
|
||||
{"remove directory", :eexist} ->
|
||||
"directory is not empty"
|
||||
|
||||
_ ->
|
||||
IO.iodata_to_binary(:file.format_error(reason))
|
||||
end
|
||||
@@ -1117,10 +811,11 @@ defmodule File.CopyError do
|
||||
defexception [:reason, :source, :destination, on: "", action: ""]
|
||||
|
||||
def message(exception) do
|
||||
formatted = IO.iodata_to_binary(:file.format_error(exception.reason))
|
||||
formatted =
|
||||
IO.iodata_to_binary(:file.format_error(exception.reason))
|
||||
|
||||
location =
|
||||
case exception.on() do
|
||||
case exception.on do
|
||||
"" -> ""
|
||||
on -> ". #{on}"
|
||||
end
|
||||
@@ -1130,22 +825,11 @@ defmodule File.CopyError do
|
||||
end
|
||||
end
|
||||
|
||||
defmodule File.LinkError do
|
||||
defexception [:reason, :existing, :new, action: ""]
|
||||
|
||||
def message(exception) do
|
||||
formatted = IO.iodata_to_binary(:file.format_error(exception.reason))
|
||||
|
||||
"could not #{exception.action} from #{inspect(exception.existing)} to " <>
|
||||
"#{inspect(exception.new)}: #{formatted}"
|
||||
end
|
||||
end
|
||||
|
||||
defmodule ErlangError do
|
||||
defexception [:original]
|
||||
|
||||
def message(exception) do
|
||||
"Erlang error: #{inspect(exception.original)}"
|
||||
"erlang error: #{inspect(exception.original)}"
|
||||
end
|
||||
|
||||
@doc false
|
||||
@@ -1191,14 +875,13 @@ defmodule ErlangError do
|
||||
|
||||
def normalize({:badkey, key}, stacktrace) do
|
||||
term =
|
||||
case ensure_stacktrace(stacktrace) do
|
||||
case stacktrace || :erlang.get_stacktrace do
|
||||
[{Map, :get_and_update!, [map, _, _], _} | _] -> map
|
||||
[{Map, :update!, [map, _, _], _} | _] -> map
|
||||
[{:maps, :update, [_, _, map], _} | _] -> map
|
||||
[{:maps, :get, [_, map], _} | _] -> map
|
||||
_ -> nil
|
||||
end
|
||||
|
||||
%KeyError{key: key, term: term}
|
||||
end
|
||||
|
||||
@@ -1219,13 +902,13 @@ defmodule ErlangError do
|
||||
end
|
||||
|
||||
def normalize(:undef, stacktrace) do
|
||||
stacktrace = ensure_stacktrace(stacktrace)
|
||||
stacktrace = stacktrace || :erlang.get_stacktrace
|
||||
{mod, fun, arity} = from_stacktrace(stacktrace)
|
||||
%UndefinedFunctionError{module: mod, function: fun, arity: arity}
|
||||
end
|
||||
|
||||
def normalize(:function_clause, stacktrace) do
|
||||
{mod, fun, arity} = from_stacktrace(ensure_stacktrace(stacktrace))
|
||||
{mod, fun, arity} = from_stacktrace(stacktrace || :erlang.get_stacktrace)
|
||||
%FunctionClauseError{module: mod, function: fun, arity: arity}
|
||||
end
|
||||
|
||||
@@ -1237,18 +920,6 @@ defmodule ErlangError do
|
||||
%ErlangError{original: other}
|
||||
end
|
||||
|
||||
defp ensure_stacktrace(nil) do
|
||||
try do
|
||||
:erlang.get_stacktrace()
|
||||
rescue
|
||||
_ -> []
|
||||
end
|
||||
end
|
||||
|
||||
defp ensure_stacktrace(stacktrace) do
|
||||
stacktrace
|
||||
end
|
||||
|
||||
defp from_stacktrace([{module, function, args, _} | _]) when is_list(args) do
|
||||
{module, function, length(args)}
|
||||
end
|
||||
|
||||
+194
-492
File diff suppressed because it is too large
Load Diff
@@ -53,9 +53,9 @@ defmodule File.Stat do
|
||||
"""
|
||||
|
||||
record = Record.extract(:file_info, from_lib: "kernel/include/file.hrl")
|
||||
keys = :lists.map(&elem(&1, 0), record)
|
||||
vals = :lists.map(&{&1, [], nil}, keys)
|
||||
pairs = :lists.zip(keys, vals)
|
||||
keys = :lists.map(&elem(&1, 0), record)
|
||||
vals = :lists.map(&{&1, [], nil}, keys)
|
||||
pairs = :lists.zip(keys, vals)
|
||||
|
||||
defstruct keys
|
||||
@type t :: %__MODULE__{}
|
||||
@@ -71,7 +71,6 @@ defmodule File.Stat do
|
||||
Converts a `:file_info` record into a `File.Stat`.
|
||||
"""
|
||||
def from_record(file_info)
|
||||
|
||||
def from_record({:file_info, unquote_splicing(vals)}) do
|
||||
%File.Stat{unquote_splicing(pairs)}
|
||||
end
|
||||
|
||||
@@ -7,7 +7,7 @@ defmodule File.Stream do
|
||||
* `path` - the file path
|
||||
* `modes` - the file modes
|
||||
* `raw` - a boolean indicating if bin functions should be used
|
||||
* `line_or_bytes` - if reading should read lines or a given number of bytes
|
||||
* `line_or_bytes` - if reading should read lines or a given amount of bytes
|
||||
|
||||
"""
|
||||
|
||||
@@ -27,7 +27,6 @@ defmodule File.Stream do
|
||||
else
|
||||
[:raw, :read_ahead | modes]
|
||||
end
|
||||
|
||||
false ->
|
||||
modes
|
||||
end
|
||||
@@ -37,12 +36,11 @@ defmodule File.Stream do
|
||||
|
||||
defimpl Collectable do
|
||||
def into(%{path: path, modes: modes, raw: raw} = stream) do
|
||||
modes = for mode <- modes, mode not in [:read], do: mode
|
||||
modes = for mode <- modes, not mode in [:read], do: mode
|
||||
|
||||
case :file.open(path, [:write | modes]) do
|
||||
{:ok, device} ->
|
||||
{:ok, into(device, stream, raw)}
|
||||
|
||||
{:error, reason} ->
|
||||
raise File.Error, reason: reason, action: "stream", path: path
|
||||
end
|
||||
@@ -52,16 +50,14 @@ defmodule File.Stream do
|
||||
fn
|
||||
:ok, {:cont, x} ->
|
||||
case raw do
|
||||
true -> IO.binwrite(device, x)
|
||||
true -> IO.binwrite(device, x)
|
||||
false -> IO.write(device, x)
|
||||
end
|
||||
|
||||
:ok, :done ->
|
||||
# If delayed_write option is used and the last write failed will
|
||||
# MatchError here as {:error, _} is returned.
|
||||
:ok = :file.close(device)
|
||||
stream
|
||||
|
||||
:ok, :halt ->
|
||||
# If delayed_write option is used and the last write failed will
|
||||
# MatchError here as {:error, _} is returned.
|
||||
@@ -71,95 +67,33 @@ defmodule File.Stream do
|
||||
end
|
||||
|
||||
defimpl Enumerable do
|
||||
@read_ahead_size 64 * 1024
|
||||
|
||||
def reduce(%{path: path, modes: modes, line_or_bytes: line_or_bytes, raw: raw}, acc, fun) do
|
||||
start_fun = fn ->
|
||||
case :file.open(path, read_modes(modes)) do
|
||||
{:ok, device} ->
|
||||
if :trim_bom in modes, do: trim_bom(device), else: device
|
||||
modes = for mode <- modes, not mode in [:write, :append], do: mode
|
||||
|
||||
{:error, reason} ->
|
||||
raise File.Error, reason: reason, action: "stream", path: path
|
||||
start_fun =
|
||||
fn ->
|
||||
case :file.open(path, modes) do
|
||||
{:ok, device} -> device
|
||||
{:error, reason} ->
|
||||
raise File.Error, reason: reason, action: "stream", path: path
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
next_fun =
|
||||
case raw do
|
||||
true -> &IO.each_binstream(&1, line_or_bytes)
|
||||
true -> &IO.each_binstream(&1, line_or_bytes)
|
||||
false -> &IO.each_stream(&1, line_or_bytes)
|
||||
end
|
||||
|
||||
Stream.resource(start_fun, next_fun, &:file.close/1).(acc, fun)
|
||||
end
|
||||
|
||||
def count(%{path: path, modes: modes, line_or_bytes: :line} = stream) do
|
||||
pattern = :binary.compile_pattern("\n")
|
||||
counter = &count_lines(&1, path, pattern, read_function(stream), 0)
|
||||
|
||||
case File.open(path, read_modes(modes), counter) do
|
||||
{:ok, count} ->
|
||||
{:ok, count}
|
||||
|
||||
{:error, reason} ->
|
||||
raise File.Error, reason: reason, action: "stream", path: path
|
||||
end
|
||||
end
|
||||
|
||||
def count(%{path: path, line_or_bytes: bytes}) do
|
||||
case File.stat(path) do
|
||||
{:ok, %{size: 0}} ->
|
||||
{:error, __MODULE__}
|
||||
|
||||
{:ok, %{size: size}} ->
|
||||
{:ok, div(size, bytes) + if(rem(size, bytes) == 0, do: 0, else: 1)}
|
||||
|
||||
{:error, reason} ->
|
||||
raise File.Error, reason: reason, action: "stream", path: path
|
||||
end
|
||||
def count(_stream) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
|
||||
def member?(_stream, _term) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
|
||||
def slice(_stream) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
|
||||
defp trim_bom(device) do
|
||||
header = IO.binread(device, 4)
|
||||
{:ok, _new_pos} = :file.position(device, bom_length(header))
|
||||
device
|
||||
end
|
||||
|
||||
defp bom_length(<<239, 187, 191, _rest::binary>>), do: 3
|
||||
defp bom_length(<<254, 255, _rest::binary>>), do: 2
|
||||
defp bom_length(<<255, 254, _rest::binary>>), do: 2
|
||||
defp bom_length(<<0, 0, 254, 255, _rest::binary>>), do: 4
|
||||
defp bom_length(<<254, 255, 0, 0, _rest::binary>>), do: 4
|
||||
defp bom_length(_binary), do: 0
|
||||
|
||||
defp read_modes(modes) do
|
||||
for mode <- modes, mode not in [:write, :append, :trim_bom], do: mode
|
||||
end
|
||||
|
||||
defp count_lines(device, path, pattern, read, count) do
|
||||
case read.(device) do
|
||||
data when is_binary(data) ->
|
||||
count_lines(device, path, pattern, read, count + count_lines(data, pattern))
|
||||
|
||||
:eof ->
|
||||
count
|
||||
|
||||
{:error, reason} ->
|
||||
raise File.Error, reason: reason, action: "stream", path: path
|
||||
end
|
||||
end
|
||||
|
||||
defp count_lines(data, pattern), do: length(:binary.matches(data, pattern))
|
||||
|
||||
defp read_function(%{raw: true}), do: &IO.binread(&1, @read_ahead_size)
|
||||
defp read_function(%{raw: false}), do: &IO.read(&1, @read_ahead_size)
|
||||
end
|
||||
end
|
||||
|
||||
+47
-118
@@ -2,41 +2,12 @@ import Kernel, except: [round: 1]
|
||||
|
||||
defmodule Float do
|
||||
@moduledoc """
|
||||
Functions for working with floating-point numbers.
|
||||
|
||||
## Kernel functions
|
||||
|
||||
There are functions related to floating-point numbers on the `Kernel` module
|
||||
too. Here is a list of them:
|
||||
|
||||
* `Kernel.round/1`: rounds a number to the nearest integer.
|
||||
* `Kernel.trunc/1`: returns the integer part of a number.
|
||||
|
||||
## Known issues
|
||||
|
||||
There are some very well known problems with floating-point numbers
|
||||
and arithmetics due to the fact most decimal fractions cannot be
|
||||
represented by a floating-point binary.
|
||||
|
||||
For example, the numbers 0.1 and 0.01 are two of them, what means the result
|
||||
of squaring 0.1 does not give 0.01 neither the closest representable. Here is
|
||||
what happens in this case:
|
||||
|
||||
* The closest representable number to 0.1 is 0.1000000014
|
||||
* The closest representable number to 0.01 is 0.0099999997
|
||||
* Doing 0.1 * 0.1 should return 0.01, but because 0.1 is actually 0.1000000014,
|
||||
the result is 0.010000000000000002, and because this is not the closest
|
||||
representable number to 0.01, you'll get the wrong result for this operation
|
||||
|
||||
There are also other known problems like flooring or rounding numbers. See
|
||||
`round/2` and `floor/2` for more details about them.
|
||||
Functions for working with floating point numbers.
|
||||
"""
|
||||
|
||||
import Bitwise
|
||||
|
||||
@power_of_2_to_52 4_503_599_627_370_496
|
||||
@precision_range 0..15
|
||||
@type precision_range :: 0..15
|
||||
@power_of_2_to_52 4503599627370496
|
||||
|
||||
@doc """
|
||||
Parses a binary into a float.
|
||||
@@ -80,44 +51,38 @@ defmodule Float do
|
||||
parse_unsigned(binary)
|
||||
end
|
||||
|
||||
defp parse_unsigned(<<digit, rest::binary>>) when digit in ?0..?9,
|
||||
do: parse_unsigned(rest, false, false, <<digit>>)
|
||||
defp parse_unsigned(<<digit, rest::binary>>) when digit in ?0..?9, do:
|
||||
parse_unsigned(rest, false, false, <<digit>>)
|
||||
|
||||
defp parse_unsigned(binary) when is_binary(binary), do: :error
|
||||
defp parse_unsigned(binary) when is_binary(binary), do:
|
||||
:error
|
||||
|
||||
defp parse_unsigned(<<digit, rest::binary>>, dot?, e?, acc) when digit in ?0..?9,
|
||||
do: parse_unsigned(rest, dot?, e?, <<acc::binary, digit>>)
|
||||
defp parse_unsigned(<<digit, rest::binary>>, dot?, e?, acc) when digit in ?0..?9, do:
|
||||
parse_unsigned(rest, dot?, e?, <<acc::binary, digit>>)
|
||||
|
||||
defp parse_unsigned(<<?., digit, rest::binary>>, false, false, acc) when digit in ?0..?9,
|
||||
do: parse_unsigned(rest, true, false, <<acc::binary, ?., digit>>)
|
||||
defp parse_unsigned(<<?., digit, rest::binary>>, false, false, acc) when digit in ?0..?9, do:
|
||||
parse_unsigned(rest, true, false, <<acc::binary, ?., digit>>)
|
||||
|
||||
defp parse_unsigned(<<exp_marker, digit, rest::binary>>, dot?, false, acc)
|
||||
when exp_marker in 'eE' and digit in ?0..?9,
|
||||
do: parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, digit>>)
|
||||
defp parse_unsigned(<<exp_marker, digit, rest::binary>>, dot?, false, acc) when exp_marker in 'eE' and digit in ?0..?9, do:
|
||||
parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, digit>>)
|
||||
|
||||
defp parse_unsigned(<<exp_marker, sign, digit, rest::binary>>, dot?, false, acc)
|
||||
when exp_marker in 'eE' and sign in '-+' and digit in ?0..?9,
|
||||
do: parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, sign, digit>>)
|
||||
defp parse_unsigned(<<exp_marker, sign, digit, rest::binary>>, dot?, false, acc) when exp_marker in 'eE' and sign in '-+' and digit in ?0..?9, do:
|
||||
parse_unsigned(rest, true, true, <<add_dot(acc, dot?)::binary, ?e, sign, digit>>)
|
||||
|
||||
defp parse_unsigned(rest, dot?, _e?, acc),
|
||||
do: {:erlang.binary_to_float(add_dot(acc, dot?)), rest}
|
||||
defp parse_unsigned(rest, dot?, _e?, acc), do:
|
||||
{:erlang.binary_to_float(add_dot(acc, dot?)), rest}
|
||||
|
||||
defp add_dot(acc, true), do: acc
|
||||
defp add_dot(acc, true), do: acc
|
||||
defp add_dot(acc, false), do: acc <> ".0"
|
||||
|
||||
@doc """
|
||||
Rounds a float to the largest number less than or equal to `num`.
|
||||
Rounds a float to the largest integer less than or equal to `num`.
|
||||
|
||||
`floor/2` also accepts a precision to round a floating-point value down
|
||||
`floor/2` also accepts a precision to round a floating point value down
|
||||
to an arbitrary number of fractional digits (between 0 and 15).
|
||||
The operation is performed on the binary floating point, without a
|
||||
conversion to decimal.
|
||||
|
||||
This function always returns a float. `Kernel.trunc/1` may be used instead to
|
||||
truncate the result to an integer afterwards.
|
||||
|
||||
## Known issues
|
||||
|
||||
The behaviour of `floor/2` for floats can be surprising. For example:
|
||||
|
||||
iex> Float.floor(12.52, 2)
|
||||
@@ -128,6 +93,9 @@ defmodule Float do
|
||||
and therefore the number above is internally represented as 12.51999999,
|
||||
which explains the behaviour above.
|
||||
|
||||
This function always returns a float. `Kernel.trunc/1` may be used instead to
|
||||
truncate the result to an integer afterwards.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Float.floor(34.25)
|
||||
@@ -138,21 +106,15 @@ defmodule Float do
|
||||
34.25
|
||||
|
||||
"""
|
||||
@spec floor(float, precision_range) :: float
|
||||
def floor(number, precision \\ 0)
|
||||
|
||||
def floor(number, precision) when is_float(number) and precision in @precision_range do
|
||||
@spec floor(float, 0..15) :: float
|
||||
def floor(number, precision \\ 0) when is_float(number) and precision in 0..15 do
|
||||
round(number, precision, :floor)
|
||||
end
|
||||
|
||||
def floor(number, precision) when is_float(number) do
|
||||
raise ArgumentError, invalid_precision_message(precision)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Rounds a float to the smallest integer greater than or equal to `num`.
|
||||
|
||||
`ceil/2` also accepts a precision to round a floating-point value down
|
||||
`ceil/2` also accepts a precision to round a floating point value down
|
||||
to an arbitrary number of fractional digits (between 0 and 15).
|
||||
|
||||
The operation is performed on the binary floating point, without a
|
||||
@@ -181,19 +143,13 @@ defmodule Float do
|
||||
34.26
|
||||
|
||||
"""
|
||||
@spec ceil(float, precision_range) :: float
|
||||
def ceil(number, precision \\ 0)
|
||||
|
||||
def ceil(number, precision) when is_float(number) and precision in @precision_range do
|
||||
@spec ceil(float, 0..15) :: float
|
||||
def ceil(number, precision \\ 0) when is_float(number) and precision in 0..15 do
|
||||
round(number, precision, :ceil)
|
||||
end
|
||||
|
||||
def ceil(number, precision) when is_float(number) do
|
||||
raise ArgumentError, invalid_precision_message(precision)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Rounds a floating-point value to an arbitrary number of fractional
|
||||
Rounds a floating point value to an arbitrary number of fractional
|
||||
digits (between 0 and 15).
|
||||
|
||||
The rounding direction always ties to half up. The operation is
|
||||
@@ -203,8 +159,6 @@ defmodule Float do
|
||||
`Kernel.round/1` if you want a function that accepts both floats
|
||||
and integers and always returns an integer.
|
||||
|
||||
## Known issues
|
||||
|
||||
The behaviour of `round/2` for floats can be surprising. For example:
|
||||
|
||||
iex> Float.round(5.5675, 3)
|
||||
@@ -234,41 +188,33 @@ defmodule Float do
|
||||
12.341444444444441
|
||||
|
||||
"""
|
||||
@spec round(float, precision_range) :: float
|
||||
@spec round(float, 0..15) :: float
|
||||
|
||||
# This implementation is slow since it relies on big integers.
|
||||
# Faster implementations are available on more recent papers
|
||||
# and could be implemented in the future.
|
||||
def round(float, precision \\ 0)
|
||||
|
||||
def round(float, precision) when is_float(float) and precision in @precision_range do
|
||||
def round(float, precision \\ 0) when is_float(float) and precision in 0..15 do
|
||||
round(float, precision, :half_up)
|
||||
end
|
||||
|
||||
def round(number, precision) when is_float(number) do
|
||||
raise ArgumentError, invalid_precision_message(precision)
|
||||
end
|
||||
|
||||
defp round(float, precision, rounding) do
|
||||
<<sign::1, exp::11, significant::52-bitstring>> = <<float::float>>
|
||||
{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) ->
|
||||
count <= 0 or # There is no decimal precision
|
||||
(0 == exp and <<0::52>> == significant) -> #zero or minus zero
|
||||
float
|
||||
|
||||
# Precision beyond 15 digits
|
||||
count >= 104 ->
|
||||
count >= 104 -> # Precision beyond 15 digits
|
||||
case rounding do
|
||||
:ceil when sign === 0 -> 1 / power_of_10(precision)
|
||||
:floor when sign === 1 -> -1 / power_of_10(precision)
|
||||
_ -> 0.0
|
||||
end
|
||||
|
||||
# We are asking more precision than we have
|
||||
count <= precision ->
|
||||
count <= precision -> # We are asking more precision than we have
|
||||
float
|
||||
|
||||
true ->
|
||||
@@ -295,11 +241,9 @@ defmodule Float do
|
||||
cond do
|
||||
num == 0 ->
|
||||
0.0
|
||||
|
||||
num >= boundary ->
|
||||
{den, exp} = scale_down(num, boundary, 52)
|
||||
decimal_to_float(sign, num, den, exp)
|
||||
|
||||
true ->
|
||||
{num, exp} = scale_up(num, boundary, 52)
|
||||
decimal_to_float(sign, num, den, exp)
|
||||
@@ -312,7 +256,6 @@ defmodule Float do
|
||||
|
||||
defp scale_down(num, den, exp) do
|
||||
new_den = den <<< 1
|
||||
|
||||
if num < new_den do
|
||||
{den >>> 52, exp}
|
||||
else
|
||||
@@ -333,31 +276,29 @@ defmodule Float do
|
||||
end
|
||||
|
||||
tmp = tmp - @power_of_2_to_52
|
||||
<<tmp::float>> = <<sign::1, exp + 1023::11, tmp::52>>
|
||||
<<tmp::float>> = <<sign::1, (exp + 1023)::11, tmp::52>>
|
||||
tmp
|
||||
end
|
||||
|
||||
defp rounding(:floor, 1, _num, div), do: div + 1
|
||||
defp rounding(:ceil, 0, _num, div), do: div + 1
|
||||
|
||||
defp rounding(:half_up, _sign, num, div) do
|
||||
case rem(num, 10) do
|
||||
rem when rem < 5 -> div
|
||||
rem when rem >= 5 -> div + 1
|
||||
end
|
||||
end
|
||||
|
||||
defp rounding(_, _, _, div), do: div
|
||||
|
||||
Enum.reduce(0..104, 1, fn x, acc ->
|
||||
Enum.reduce 0..104, 1, fn x, acc ->
|
||||
defp power_of_10(unquote(x)), do: unquote(acc)
|
||||
acc * 10
|
||||
end)
|
||||
end
|
||||
|
||||
Enum.reduce(0..104, 1, fn x, acc ->
|
||||
Enum.reduce 0..104, 1, fn x, acc ->
|
||||
defp power_of_5(unquote(x)), do: unquote(acc)
|
||||
acc * 5
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a pair of integers whose ratio is exactly equal
|
||||
@@ -383,15 +324,12 @@ defmodule Float do
|
||||
<<sign::1, exp::11, significant::52-bitstring>> = <<float::float>>
|
||||
{num, _, den} = decompose(significant)
|
||||
num = sign(sign, num)
|
||||
|
||||
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)}
|
||||
|
||||
0 ->
|
||||
{num, den}
|
||||
end
|
||||
@@ -404,11 +342,9 @@ defmodule Float do
|
||||
defp decompose(<<1::1, bits::bitstring>>, count, last_count, power, _last_power, acc) do
|
||||
decompose(bits, count + 1, count, power <<< 1, power, shift_left(acc, count - last_count) + 1)
|
||||
end
|
||||
|
||||
defp decompose(<<0::1, bits::bitstring>>, count, last_count, power, last_power, acc) do
|
||||
decompose(bits, count + 1, last_count, power <<< 1, last_power, acc)
|
||||
end
|
||||
|
||||
defp decompose(<<>>, _count, last_count, _power, last_power, acc) do
|
||||
{acc, last_count, last_power}
|
||||
end
|
||||
@@ -458,36 +394,29 @@ defmodule Float do
|
||||
"7.0"
|
||||
|
||||
"""
|
||||
@spec to_string(float) :: String.t()
|
||||
@spec to_string(float) :: String.t
|
||||
def to_string(float) when is_float(float) do
|
||||
IO.iodata_to_binary(:io_lib_format.fwrite_g(float))
|
||||
end
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
# TODO: Deprecate by v1.5
|
||||
@doc false
|
||||
def to_char_list(float), do: Float.to_charlist(float)
|
||||
|
||||
@doc false
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
def to_char_list(float, options) do
|
||||
IO.warn "Float.to_char_list/2 is deprecated, use :erlang.float_to_list/2 instead"
|
||||
:erlang.float_to_list(float, expand_compact(options))
|
||||
end
|
||||
|
||||
@doc false
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
def to_string(float, options) do
|
||||
IO.warn "Float.to_string/2 is deprecated, use :erlang.float_to_binary/2 instead"
|
||||
:erlang.float_to_binary(float, expand_compact(options))
|
||||
end
|
||||
|
||||
defp invalid_precision_message(precision) do
|
||||
"precision #{precision} is out of valid range of #{inspect(@precision_range)}"
|
||||
end
|
||||
|
||||
defp expand_compact([{:compact, false} | t]), do: expand_compact(t)
|
||||
defp expand_compact([{:compact, true} | t]), do: [:compact | expand_compact(t)]
|
||||
defp expand_compact([h | t]), do: [h | expand_compact(t)]
|
||||
defp expand_compact([]), do: []
|
||||
defp expand_compact([{:compact, true} | t]), do: [:compact | expand_compact(t)]
|
||||
defp expand_compact([h | t]), do: [h | expand_compact(t)]
|
||||
defp expand_compact([]), do: []
|
||||
end
|
||||
|
||||
+513
-220
File diff suppressed because it is too large
Load Diff
@@ -2,7 +2,9 @@ defmodule GenEvent.Stream do
|
||||
@moduledoc false
|
||||
defstruct manager: nil, timeout: :infinity
|
||||
|
||||
@type t :: %__MODULE__{manager: GenEvent.manager(), timeout: timeout}
|
||||
@type t :: %__MODULE__{
|
||||
manager: GenEvent.manager,
|
||||
timeout: timeout}
|
||||
|
||||
@doc false
|
||||
def init({_pid, _ref} = state) do
|
||||
@@ -22,7 +24,6 @@ defmodule GenEvent.Stream do
|
||||
def handle_call(msg, _state) do
|
||||
# We do this to trick Dialyzer to not complain about non-local returns.
|
||||
reason = {:bad_call, msg}
|
||||
|
||||
case :erlang.phash2(1, 1) do
|
||||
0 -> exit(reason)
|
||||
1 -> {:remove_handler, reason}
|
||||
@@ -47,7 +48,7 @@ end
|
||||
|
||||
defimpl Enumerable, for: GenEvent.Stream do
|
||||
def reduce(stream, acc, fun) do
|
||||
start_fun = fn -> start(stream) end
|
||||
start_fun = fn() -> start(stream) end
|
||||
next_fun = &next(stream, &1)
|
||||
stop_fun = &stop(stream, &1)
|
||||
Stream.resource(start_fun, next_fun, stop_fun).(acc, wrap_reducer(fun))
|
||||
@@ -61,33 +62,26 @@ defimpl Enumerable, for: GenEvent.Stream do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
|
||||
def slice(_stream) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
|
||||
defp wrap_reducer(fun) do
|
||||
fn
|
||||
{:ack, manager, ref, event}, acc ->
|
||||
send(manager, {ref, :ok})
|
||||
send manager, {ref, :ok}
|
||||
fun.(event, acc)
|
||||
|
||||
{:async, _manager, _ref, event}, acc ->
|
||||
fun.(event, acc)
|
||||
|
||||
{:sync, manager, ref, event}, acc ->
|
||||
try do
|
||||
fun.(event, acc)
|
||||
after
|
||||
send(manager, {ref, :ok})
|
||||
send manager, {ref, :ok}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp start(%{manager: manager} = stream) do
|
||||
try do
|
||||
{:ok, {pid, ref}} =
|
||||
:gen.call(manager, self(), {:add_process_handler, self(), self()}, :infinity)
|
||||
|
||||
{:ok, {pid, ref}} = :gen.call(manager, self(),
|
||||
{:add_process_handler, self(), self()}, :infinity)
|
||||
mon_ref = Process.monitor(pid)
|
||||
{pid, ref, mon_ref}
|
||||
catch
|
||||
@@ -135,7 +129,6 @@ defimpl Enumerable, for: GenEvent.Stream do
|
||||
case wait_for_handler_removal(pid, ref, mon_ref) do
|
||||
:ok ->
|
||||
flush_events(ref)
|
||||
|
||||
{:error, reason} ->
|
||||
exit({reason, {__MODULE__, :stop, [stream, acc]}})
|
||||
end
|
||||
@@ -144,7 +137,7 @@ defimpl Enumerable, for: GenEvent.Stream do
|
||||
# If we reach this branch, the handler was not removed yet,
|
||||
# so we trigger a request for doing so.
|
||||
defp stop(stream, {pid, ref, _} = acc) do
|
||||
_ = :gen_event.delete_handler(pid, {pid, ref}, :shutdown)
|
||||
_ = GenEvent.remove_handler(pid, {pid, ref}, :shutdown)
|
||||
stop(stream, {:removed, acc})
|
||||
end
|
||||
|
||||
@@ -153,7 +146,6 @@ defimpl Enumerable, for: GenEvent.Stream do
|
||||
{:gen_event_EXIT, {^pid, ^ref}, _reason} ->
|
||||
Process.demonitor(mon_ref, [:flush])
|
||||
:ok
|
||||
|
||||
{:DOWN, ^mon_ref, _, _, reason} ->
|
||||
{:error, reason}
|
||||
end
|
||||
@@ -161,8 +153,7 @@ defimpl Enumerable, for: GenEvent.Stream do
|
||||
|
||||
defp flush_events(ref) do
|
||||
receive do
|
||||
{_from, {_pid, ^ref}, {notify, _event}}
|
||||
when notify in [:notify, :ack_notify, :sync_notify] ->
|
||||
{_from, {_pid, ^ref}, {notify, _event}} when notify in [:notify, :ack_notify, :sync_notify] ->
|
||||
flush_events(ref)
|
||||
after
|
||||
0 -> :ok
|
||||
|
||||
+101
-207
@@ -11,8 +11,8 @@ defmodule GenServer do
|
||||
## Example
|
||||
|
||||
The GenServer behaviour abstracts the common client-server interaction.
|
||||
Developers are only required to implement the callbacks and functionality
|
||||
they are interested in.
|
||||
Developers are only required to implement the callbacks and functionality they are
|
||||
interested in.
|
||||
|
||||
Let's start with a code example and then explore the available callbacks.
|
||||
Imagine we want a GenServer that works like a stack, allowing us to push
|
||||
@@ -23,17 +23,10 @@ defmodule GenServer do
|
||||
|
||||
# Callbacks
|
||||
|
||||
@impl true
|
||||
def init(stack) do
|
||||
{:ok, stack}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call(:pop, _from, [h | t]) do
|
||||
{:reply, h, t}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_cast({:push, item}, state) do
|
||||
{:noreply, [item | state]}
|
||||
end
|
||||
@@ -63,28 +56,13 @@ defmodule GenServer do
|
||||
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`.
|
||||
|
||||
## use GenServer and callbacks
|
||||
## Callbacks
|
||||
|
||||
There are 6 callbacks required to be implemented in a `GenServer`. By
|
||||
adding `use GenServer` to your module, Elixir will automatically define
|
||||
all 6 callbacks for you, leaving it up to you to implement the ones
|
||||
you want to customize.
|
||||
|
||||
`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 id, 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
|
||||
|
||||
For example:
|
||||
|
||||
use GenServer, restart: :transient, shutdown: 10_000
|
||||
|
||||
See the `Supervisor` docs for more information.
|
||||
|
||||
## Name Registration
|
||||
|
||||
Both `start_link/3` and `start/3` support the `GenServer` to register
|
||||
@@ -95,12 +73,12 @@ defmodule GenServer do
|
||||
using `Process.register/2`.
|
||||
|
||||
* `{:global, term}`- the GenServer is registered globally with the given
|
||||
term using the functions in the [`:global` module](http://www.erlang.org/doc/man/global.html).
|
||||
term using the functions in the `:global` module.
|
||||
|
||||
* `{:via, module, term}` - the GenServer is registered with the given
|
||||
mechanism and name. The `:via` option expects a module that exports
|
||||
`register_name/2`, `unregister_name/1`, `whereis_name/1` and `send/2`.
|
||||
One such example is the [`:global` module](http://www.erlang.org/doc/man/global.html) which uses these functions
|
||||
One such example is the `:global` module which uses these functions
|
||||
for keeping the list of names of processes and their associated PIDs
|
||||
that are available globally for a network of Elixir nodes. Elixir also
|
||||
ships with a local, decentralized and scalable registry called `Registry`
|
||||
@@ -158,15 +136,22 @@ defmodule GenServer do
|
||||
|
||||
# Server (callbacks)
|
||||
|
||||
@impl true
|
||||
def handle_call(:pop, _from, [h | t]) do
|
||||
{:reply, h, t}
|
||||
end
|
||||
|
||||
@impl true
|
||||
def handle_call(request, from, state) do
|
||||
# Call the default implementation from GenServer
|
||||
super(request, from, state)
|
||||
end
|
||||
|
||||
def handle_cast({:push, item}, state) do
|
||||
{:noreply, [item | state]}
|
||||
end
|
||||
|
||||
def handle_cast(request, state) do
|
||||
super(request, state)
|
||||
end
|
||||
end
|
||||
|
||||
In practice, it is common to have both server and client functions in
|
||||
@@ -196,13 +181,11 @@ defmodule GenServer do
|
||||
GenServer.start_link(__MODULE__, %{})
|
||||
end
|
||||
|
||||
@impl true
|
||||
def init(state) do
|
||||
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
|
||||
schedule_work() # Reschedule once more
|
||||
@@ -217,33 +200,33 @@ defmodule GenServer do
|
||||
## Debugging with the :sys module
|
||||
|
||||
GenServers, as [special processes](http://erlang.org/doc/design_principles/spec_proc.html),
|
||||
can be debugged using the [`:sys` module](http://www.erlang.org/doc/man/sys.html). Through various hooks, this module
|
||||
can be debugged using the `:sys` module. Through various hooks, this module
|
||||
allows developers to introspect the state of the process and trace
|
||||
system events that happen during its execution, such as received messages,
|
||||
sent replies and state changes.
|
||||
|
||||
Let's explore the basic functions from the
|
||||
[`:sys` module](http://www.erlang.org/doc/man/sys.html) used for debugging:
|
||||
Let's explore the basic functions from the `:sys` module used for debugging:
|
||||
|
||||
* `:sys.get_state/2` - allows retrieval of the state of the process.
|
||||
In the case of a GenServer process, it will be the callback module state,
|
||||
as passed into the callback functions as last argument.
|
||||
* `:sys.get_status/2` - allows retrieval of the status of the process.
|
||||
This status includes the process dictionary, if the process is running
|
||||
or is suspended, the parent PID, the debugger state, and the state of
|
||||
the behaviour module, which includes the callback module state
|
||||
(as returned by `:sys.get_state/2`). It's possible to change how this
|
||||
status is represented by defining the optional `c:GenServer.format_status/2`
|
||||
callback.
|
||||
* `:sys.trace/3` - prints all the system events to `:stdio`.
|
||||
* `:sys.statistics/3` - manages collection of process statistics.
|
||||
* `:sys.no_debug/2` - turns off all debug handlers for the given process.
|
||||
It is very important to switch off debugging once we're done. Excessive
|
||||
debug handlers or those that should be turned off, but weren't, can
|
||||
seriously damage the performance of the system.
|
||||
* `:sys.suspend/2` - allows to suspend a process so that it only
|
||||
replies to system messages but no other messages. A suspended process
|
||||
can be reactivated via `:sys.resume/2`.
|
||||
* [`:sys.get_state/2`](http://erlang.org/doc/man/sys.html#get_state-2) -
|
||||
allows retrieval of the state of the process. In the case of
|
||||
a GenServer process, it will be the callback module state, as
|
||||
passed into the callback functions as last argument.
|
||||
* [`:sys.get_status/2`](http://erlang.org/doc/man/sys.html#get_status-2) -
|
||||
allows retrieval of the status of the process. This status includes
|
||||
the process dictionary, if the process is running or is suspended,
|
||||
the parent PID, the debugger state, and the state of the behaviour module,
|
||||
which includes the callback module state (as returned by `:sys.get_state/2`).
|
||||
It's possible to change how this status is represented by defining
|
||||
the optional `c:GenServer.format_status/2` callback.
|
||||
* [`:sys.trace/3`](http://erlang.org/doc/man/sys.html#trace-3) -
|
||||
prints all the system events to `:stdio`.
|
||||
* [`:sys.statistics/3`](http://erlang.org/doc/man/sys.html#statistics-3) -
|
||||
manages collection of process statistics.
|
||||
* [`:sys.no_debug/2`](http://erlang.org/doc/man/sys.html#no_debug-2) -
|
||||
turns off all debug handlers for the given process. It is very important
|
||||
to switch off debugging once we're done. Excessive debug handlers or
|
||||
those that should be turned off, but weren't, can seriously damage
|
||||
the performance of the system.
|
||||
|
||||
Let's see how we could use those functions for debugging the stack server
|
||||
we defined earlier.
|
||||
@@ -327,11 +310,10 @@ defmodule GenServer do
|
||||
entering the loop or calling `c:terminate/2`.
|
||||
"""
|
||||
@callback init(args :: term) ::
|
||||
{:ok, state}
|
||||
| {:ok, state, timeout | :hibernate}
|
||||
| :ignore
|
||||
| {:stop, reason :: any}
|
||||
when state: any
|
||||
{:ok, state} |
|
||||
{:ok, state, timeout | :hibernate} |
|
||||
:ignore |
|
||||
{:stop, reason :: any} when state: any
|
||||
|
||||
@doc """
|
||||
Invoked to handle synchronous `call/3` messages. `call/3` will block until a
|
||||
@@ -388,17 +370,15 @@ defmodule GenServer do
|
||||
`{:stop, reason, reply, new_state}` except a reply is not sent.
|
||||
|
||||
If this callback is not implemented, the default implementation by
|
||||
`use GenServer` will fail with a `RuntimeError` exception with a message:
|
||||
attempted to call `GenServer` but no `handle_call/3` clause was provided.
|
||||
`use GenServer` will return `{:stop, {:bad_call, request}, state}`.
|
||||
"""
|
||||
@callback handle_call(request :: term, from, state :: term) ::
|
||||
{:reply, reply, new_state}
|
||||
| {:reply, reply, new_state, timeout | :hibernate}
|
||||
| {:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate}
|
||||
| {:stop, reason, reply, new_state}
|
||||
| {:stop, reason, new_state}
|
||||
when reply: term, new_state: term, reason: term
|
||||
{:reply, reply, new_state} |
|
||||
{:reply, reply, new_state, timeout | :hibernate} |
|
||||
{:noreply, new_state} |
|
||||
{:noreply, new_state, timeout | :hibernate} |
|
||||
{:stop, reason, reply, new_state} |
|
||||
{:stop, reason, new_state} when reply: term, new_state: term, reason: term
|
||||
|
||||
@doc """
|
||||
Invoked to handle asynchronous `cast/2` messages.
|
||||
@@ -421,14 +401,12 @@ defmodule GenServer do
|
||||
reason `reason`.
|
||||
|
||||
If this callback is not implemented, the default implementation by
|
||||
`use GenServer` will fail with a `RuntimeError` exception with a message:
|
||||
attempted to call `GenServer` but no `handle_cast/2` clause was provided.
|
||||
`use GenServer` will return `{:stop, {:bad_cast, request}, state}`.
|
||||
"""
|
||||
@callback handle_cast(request :: term, state :: term) ::
|
||||
{:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate}
|
||||
| {:stop, reason :: term, new_state}
|
||||
when new_state: term
|
||||
{:noreply, new_state} |
|
||||
{:noreply, new_state, timeout | :hibernate} |
|
||||
{:stop, reason :: term, new_state} when new_state: term
|
||||
|
||||
@doc """
|
||||
Invoked to handle all other messages.
|
||||
@@ -442,10 +420,9 @@ defmodule GenServer do
|
||||
`use GenServer` will return `{:noreply, state}`.
|
||||
"""
|
||||
@callback handle_info(msg :: :timeout | term, state :: term) ::
|
||||
{:noreply, new_state}
|
||||
| {:noreply, new_state, timeout | :hibernate}
|
||||
| {:stop, reason :: term, new_state}
|
||||
when new_state: term
|
||||
{:noreply, new_state} |
|
||||
{:noreply, new_state, timeout | :hibernate} |
|
||||
{:stop, reason :: term, new_state} when new_state: term
|
||||
|
||||
@doc """
|
||||
Invoked when the server is about to exit. It should do any cleanup required.
|
||||
@@ -453,17 +430,12 @@ defmodule GenServer do
|
||||
`reason` is exit reason and `state` is the current state of the `GenServer`.
|
||||
The return value is ignored.
|
||||
|
||||
`c:terminate/2` is called if a callback (except `c:init/1`) does one of the
|
||||
following:
|
||||
`c:terminate/2` is called if a callback (except `c:init/1`) returns a `:stop`
|
||||
tuple, raises, calls `Kernel.exit/1` or returns an invalid value. It may also
|
||||
be called if the `GenServer` traps exits using `Process.flag/2` *and* the
|
||||
parent process sends an exit signal.
|
||||
|
||||
* returns a `:stop` tuple
|
||||
* raises
|
||||
* calls `Kernel.exit/1`
|
||||
* returns an invalid value
|
||||
* the `GenServer` traps exits (using `Process.flag/2`) *and* the parent
|
||||
process sends an exit signal
|
||||
|
||||
If part of a supervision tree, a `GenServer`'s `Supervisor` will send an exit
|
||||
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
|
||||
@@ -484,11 +456,11 @@ defmodule GenServer do
|
||||
`:gen_tcp.socket`) or `t:File.io_device/0`, they will be closed on receiving a
|
||||
`GenServer`'s exit signal and do not need to be closed in `c:terminate/2`.
|
||||
|
||||
If `reason` is not `:normal`, `:shutdown`, nor `{:shutdown, term}` an error is
|
||||
If `reason` is not `:normal`, `:shutdown` nor `{:shutdown, term}` an error is
|
||||
logged.
|
||||
"""
|
||||
@callback terminate(reason, state :: term) :: term
|
||||
when reason: :normal | :shutdown | {:shutdown, term}
|
||||
@callback terminate(reason, state :: term) ::
|
||||
term when reason: :normal | :shutdown | {:shutdown, term} | term
|
||||
|
||||
@doc """
|
||||
Invoked to change the state of the `GenServer` when a different version of a
|
||||
@@ -510,10 +482,8 @@ defmodule GenServer do
|
||||
with its previous state. Therefore this callback does not usually contain side effects.
|
||||
"""
|
||||
@callback code_change(old_vsn, state :: term, extra :: term) ::
|
||||
{:ok, new_state :: term}
|
||||
| {:error, reason :: term}
|
||||
| {:down, term}
|
||||
when old_vsn: term
|
||||
{:ok, new_state :: term} |
|
||||
{:error, reason :: term} when old_vsn: term | {:down, term}
|
||||
|
||||
@doc """
|
||||
Invoked in some cases to retrieve a formatted version of the `GenServer` status.
|
||||
@@ -532,8 +502,8 @@ defmodule GenServer do
|
||||
list of `{key, value}` tuples representing the current process dictionary of
|
||||
the `GenServer` and `state` is the current state of the `GenServer`.
|
||||
"""
|
||||
@callback format_status(reason, pdict_and_state :: list) :: term
|
||||
when reason: :normal | :terminate
|
||||
@callback format_status(reason, pdict_and_state :: list) ::
|
||||
term when reason: :normal | :terminate
|
||||
|
||||
@optional_callbacks format_status: 2
|
||||
|
||||
@@ -547,14 +517,13 @@ defmodule GenServer do
|
||||
@type options :: [option]
|
||||
|
||||
@typedoc "Option values used by the `start*` functions"
|
||||
@type option ::
|
||||
{:debug, debug}
|
||||
| {:name, name}
|
||||
| {:timeout, timeout}
|
||||
| {:spawn_opt, Process.spawn_opt()}
|
||||
@type option :: {:debug, debug} |
|
||||
{:name, name} |
|
||||
{:timeout, timeout} |
|
||||
{:spawn_opt, Process.spawn_opt}
|
||||
|
||||
@typedoc "Debug options supported by the `start*` functions"
|
||||
@type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t()}]
|
||||
@type debug :: [:trace | :log | :statistics | {:log_to_file, Path.t}]
|
||||
|
||||
@typedoc "The server reference"
|
||||
@type server :: pid | name | {atom, node}
|
||||
@@ -568,44 +537,27 @@ defmodule GenServer do
|
||||
@type from :: {pid, tag :: term}
|
||||
|
||||
@doc false
|
||||
defmacro __using__(opts) do
|
||||
quote location: :keep, bind_quoted: [opts: opts] do
|
||||
defmacro __using__(_) do
|
||||
quote location: :keep do
|
||||
@behaviour GenServer
|
||||
|
||||
@doc """
|
||||
Returns a specification to start this module under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
def child_spec(arg) do
|
||||
default = %{
|
||||
id: __MODULE__,
|
||||
start: {__MODULE__, :start_link, [arg]}
|
||||
}
|
||||
|
||||
Supervisor.child_spec(default, unquote(Macro.escape(opts)))
|
||||
@doc false
|
||||
def init(args) do
|
||||
{:ok, args}
|
||||
end
|
||||
|
||||
defoverridable child_spec: 1
|
||||
|
||||
# TODO: Remove this on Elixir v2.0
|
||||
@before_compile GenServer
|
||||
|
||||
@doc false
|
||||
def handle_call(msg, _from, state) do
|
||||
proc =
|
||||
case Process.info(self(), :registered_name) do
|
||||
{_, []} -> self()
|
||||
{_, []} -> self()
|
||||
{_, name} -> name
|
||||
end
|
||||
|
||||
# We do this to trick Dialyzer to not complain about non-local returns.
|
||||
case :erlang.phash2(1, 1) do
|
||||
0 ->
|
||||
raise "attempted to call GenServer #{inspect(proc)} but no handle_call/3 clause was provided"
|
||||
|
||||
1 ->
|
||||
{:stop, {:bad_call, msg}, state}
|
||||
0 -> raise "attempted to call GenServer #{inspect proc} but no handle_call/3 clause was provided"
|
||||
1 -> {:stop, {:bad_call, msg}, state}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -613,12 +565,11 @@ defmodule GenServer do
|
||||
def handle_info(msg, state) do
|
||||
proc =
|
||||
case Process.info(self(), :registered_name) do
|
||||
{_, []} -> self()
|
||||
{_, []} -> self()
|
||||
{_, name} -> name
|
||||
end
|
||||
|
||||
pattern = '~p ~p received unexpected message in handle_info/2: ~p~n'
|
||||
:error_logger.error_msg(pattern, [__MODULE__, proc, msg])
|
||||
:error_logger.warning_msg('~p ~p received unexpected message in handle_info/2: ~p~n',
|
||||
[__MODULE__, proc, msg])
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
@@ -626,17 +577,14 @@ defmodule GenServer do
|
||||
def handle_cast(msg, state) do
|
||||
proc =
|
||||
case Process.info(self(), :registered_name) do
|
||||
{_, []} -> self()
|
||||
{_, []} -> self()
|
||||
{_, name} -> name
|
||||
end
|
||||
|
||||
# We do this to trick Dialyzer to not complain about non-local returns.
|
||||
case :erlang.phash2(1, 1) do
|
||||
0 ->
|
||||
raise "attempted to cast GenServer #{inspect(proc)} but no handle_cast/2 clause was provided"
|
||||
|
||||
1 ->
|
||||
{:stop, {:bad_cast, msg}, state}
|
||||
0 -> raise "attempted to cast GenServer #{inspect proc} but no handle_cast/2 clause was provided"
|
||||
1 -> {:stop, {:bad_cast, msg}, state}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -650,36 +598,8 @@ defmodule GenServer do
|
||||
{:ok, state}
|
||||
end
|
||||
|
||||
defoverridable GenServer
|
||||
end
|
||||
end
|
||||
|
||||
defmacro __before_compile__(env) do
|
||||
unless Module.defines?(env.module, {:init, 1}) do
|
||||
message = """
|
||||
function init/1 required by behaviour GenServer is not implemented \
|
||||
(in module #{inspect(env.module)}).
|
||||
|
||||
We will inject a default implementation for now:
|
||||
|
||||
def init(args) do
|
||||
{:ok, args}
|
||||
end
|
||||
|
||||
You can copy the implementation above or define your own that converts \
|
||||
the arguments given to GenServer.start_link/3 to the server state.
|
||||
"""
|
||||
|
||||
:elixir_errors.warn(env.line, env.file, message)
|
||||
|
||||
quote do
|
||||
@doc false
|
||||
def init(args) do
|
||||
{:ok, args}
|
||||
end
|
||||
|
||||
defoverridable init: 1
|
||||
end
|
||||
defoverridable [init: 1, handle_call: 3, handle_info: 2,
|
||||
handle_cast: 2, terminate: 2, code_change: 3]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -703,11 +623,12 @@ defmodule GenServer do
|
||||
* `:name` - used for name registration as described in the "Name
|
||||
registration" section of the module documentation
|
||||
|
||||
* `:timeout` - if present, the server is allowed to spend the given number of
|
||||
* `:timeout` - if present, the server is allowed to spend the given amount of
|
||||
milliseconds initializing or it will be terminated and the start function
|
||||
will return `{:error, :timeout}`
|
||||
|
||||
* `:debug` - if present, the corresponding function in the [`:sys` module](http://www.erlang.org/doc/man/sys.html) is invoked
|
||||
* `:debug` - if present, the corresponding function in the [`:sys`
|
||||
module](http://www.erlang.org/doc/man/sys.html) is invoked
|
||||
|
||||
* `:spawn_opt` - if present, its value is passed as options to the
|
||||
underlying process as in `Process.spawn/4`
|
||||
@@ -743,17 +664,13 @@ defmodule GenServer do
|
||||
case Keyword.pop(options, :name) do
|
||||
{nil, opts} ->
|
||||
:gen.start(:gen_server, link, module, args, opts)
|
||||
|
||||
{atom, opts} when is_atom(atom) ->
|
||||
:gen.start(:gen_server, link, {:local, atom}, module, args, opts)
|
||||
|
||||
{{:global, _term} = tuple, 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, args, opts)
|
||||
|
||||
{other, _} ->
|
||||
other ->
|
||||
raise ArgumentError, """
|
||||
expected :name option to be one of:
|
||||
|
||||
@@ -768,7 +685,7 @@ defmodule GenServer do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Synchronously stops the server with the given `reason`.
|
||||
Stops the server with the given `reason`.
|
||||
|
||||
The `c:terminate/2` callback of the given `server` will be invoked before
|
||||
exiting. This function returns `:ok` if the server terminates with the
|
||||
@@ -780,21 +697,7 @@ defmodule GenServer do
|
||||
"""
|
||||
@spec stop(server, reason :: term, timeout) :: :ok
|
||||
def stop(server, reason \\ :normal, timeout \\ :infinity) do
|
||||
case whereis(server) do
|
||||
nil ->
|
||||
exit({:noproc, {__MODULE__, :stop, [server, reason, timeout]}})
|
||||
|
||||
pid when pid == self() ->
|
||||
exit({:calling_self, {__MODULE__, :stop, [server, reason, timeout]}})
|
||||
|
||||
pid ->
|
||||
try do
|
||||
:proc_lib.stop(pid, reason, timeout)
|
||||
catch
|
||||
:exit, err ->
|
||||
exit({err, {__MODULE__, :stop, [server, reason, timeout]}})
|
||||
end
|
||||
end
|
||||
:gen.stop(server, reason, timeout)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -824,10 +727,8 @@ defmodule GenServer do
|
||||
case whereis(server) do
|
||||
nil ->
|
||||
exit({:noproc, {__MODULE__, :call, [server, request, timeout]}})
|
||||
|
||||
pid when pid == self() ->
|
||||
exit({:calling_self, {__MODULE__, :call, [server, request, timeout]}})
|
||||
|
||||
pid ->
|
||||
try do
|
||||
:gen.call(pid, :"$gen_call", request, timeout)
|
||||
@@ -880,7 +781,8 @@ defmodule GenServer do
|
||||
def cast({name, node}, request) when is_atom(name) and is_atom(node),
|
||||
do: do_send({name, node}, cast_msg(request))
|
||||
|
||||
def cast(dest, request) when is_atom(dest) or is_pid(dest), do: do_send(dest, cast_msg(request))
|
||||
def cast(dest, request) when is_atom(dest) or is_pid(dest),
|
||||
do: do_send(dest, cast_msg(request))
|
||||
|
||||
@doc """
|
||||
Casts all servers locally registered as `name` at the specified nodes.
|
||||
@@ -891,10 +793,9 @@ defmodule GenServer do
|
||||
See `multi_call/4` for more information.
|
||||
"""
|
||||
@spec abcast([node], name :: atom, term) :: :abcast
|
||||
def abcast(nodes \\ [node() | Node.list()], name, request)
|
||||
when is_list(nodes) and is_atom(name) do
|
||||
def abcast(nodes \\ [node() | Node.list()], name, request) when is_list(nodes) and is_atom(name) do
|
||||
msg = cast_msg(request)
|
||||
_ = for node <- nodes, do: do_send({name, node}, msg)
|
||||
_ = for node <- nodes, do: do_send({name, node}, msg)
|
||||
:abcast
|
||||
end
|
||||
|
||||
@@ -941,7 +842,7 @@ defmodule GenServer do
|
||||
|
||||
"""
|
||||
@spec multi_call([node], name :: atom, term, timeout) ::
|
||||
{replies :: [{node, term}], bad_nodes :: [node]}
|
||||
{replies :: [{node, term}], bad_nodes :: [node]}
|
||||
def multi_call(nodes \\ [node() | Node.list()], name, request, timeout \\ :infinity) do
|
||||
:gen_server.multi_call(nodes, name, request, timeout)
|
||||
end
|
||||
@@ -990,7 +891,7 @@ defmodule GenServer do
|
||||
|
||||
@doc """
|
||||
Returns the `pid` or `{name, node}` of a GenServer process, or `nil` if
|
||||
no process is associated with the given `server`.
|
||||
no process is associated with the given name.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -1002,32 +903,25 @@ defmodule GenServer do
|
||||
|
||||
"""
|
||||
@spec whereis(server) :: pid | {atom, node} | nil
|
||||
def whereis(server)
|
||||
|
||||
def whereis(pid) when is_pid(pid), do: pid
|
||||
|
||||
def whereis(name) when is_atom(name) do
|
||||
Process.whereis(name)
|
||||
end
|
||||
|
||||
def whereis({:global, name}) do
|
||||
case :global.whereis_name(name) do
|
||||
pid when is_pid(pid) -> pid
|
||||
:undefined -> nil
|
||||
:undefined -> nil
|
||||
end
|
||||
end
|
||||
|
||||
def whereis({:via, mod, name}) do
|
||||
case apply(mod, :whereis_name, [name]) do
|
||||
pid when is_pid(pid) -> pid
|
||||
:undefined -> nil
|
||||
:undefined -> nil
|
||||
end
|
||||
end
|
||||
|
||||
def whereis({name, local}) when is_atom(name) and local == node() do
|
||||
Process.whereis(name)
|
||||
end
|
||||
|
||||
def whereis({name, node} = server) when is_atom(name) and is_atom(node) do
|
||||
server
|
||||
end
|
||||
|
||||
+23
-77
@@ -5,8 +5,7 @@ defmodule HashDict do
|
||||
Use the `Map` module instead.
|
||||
"""
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
# TODO: Deprecate every function by 1.4
|
||||
|
||||
use Dict
|
||||
|
||||
@@ -26,7 +25,7 @@ defmodule HashDict do
|
||||
@doc """
|
||||
Creates a new empty dict.
|
||||
"""
|
||||
@spec new :: Dict.t()
|
||||
@spec new :: Dict.t
|
||||
def new do
|
||||
%HashDict{}
|
||||
end
|
||||
@@ -37,9 +36,8 @@ defmodule HashDict do
|
||||
end
|
||||
|
||||
def update!(%HashDict{root: root, size: size} = dict, key, fun) when is_function(fun, 1) do
|
||||
{root, counter} =
|
||||
do_update(root, key, fn -> raise KeyError, key: key, term: dict end, fun, key_hash(key))
|
||||
|
||||
{root, counter} = do_update(root, key, fn -> raise KeyError, key: key, term: dict end,
|
||||
fun, key_hash(key))
|
||||
%HashDict{root: root, size: size + counter}
|
||||
end
|
||||
|
||||
@@ -55,14 +53,14 @@ defmodule HashDict do
|
||||
def delete(dict, key) do
|
||||
case dict_delete(dict, key) do
|
||||
{dict, _value} -> dict
|
||||
:error -> dict
|
||||
:error -> dict
|
||||
end
|
||||
end
|
||||
|
||||
def pop(dict, key, default \\ nil) do
|
||||
case dict_delete(dict, key) do
|
||||
{dict, value} -> {value, dict}
|
||||
:error -> {default, dict}
|
||||
:error -> {default, dict}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -74,8 +72,8 @@ defmodule HashDict do
|
||||
def reduce(%HashDict{root: root}, acc, fun) do
|
||||
do_reduce(root, acc, fun, @node_size, fn
|
||||
{:suspend, acc} -> {:suspended, acc, &{:done, elem(&1, 1)}}
|
||||
{:halt, acc} -> {:halted, acc}
|
||||
{:cont, acc} -> {:done, acc}
|
||||
{:halt, acc} -> {:halted, acc}
|
||||
{:cont, acc} -> {:done, acc}
|
||||
end)
|
||||
end
|
||||
|
||||
@@ -85,7 +83,7 @@ defmodule HashDict do
|
||||
def dict_delete(%HashDict{root: root, size: size}, key) do
|
||||
case do_delete(root, key, key_hash(key)) do
|
||||
{root, value} -> {%HashDict{root: root, size: size - 1}, value}
|
||||
:error -> :error
|
||||
:error -> :error
|
||||
end
|
||||
end
|
||||
|
||||
@@ -93,32 +91,26 @@ defmodule HashDict do
|
||||
|
||||
defp do_fetch(node, key, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[^key | v] -> {:ok, v}
|
||||
[^key | v] -> {:ok, v}
|
||||
{^key, v, _} -> {:ok, v}
|
||||
{_, _, n} -> do_fetch(n, key, key_shift(hash))
|
||||
_ -> :error
|
||||
{_, _, n} -> do_fetch(n, key, key_shift(hash))
|
||||
_ -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp do_put(node, key, value, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[] ->
|
||||
{put_elem(node, index, [key | value]), 1}
|
||||
|
||||
[^key | _] ->
|
||||
{put_elem(node, index, [key | value]), 0}
|
||||
|
||||
[k | v] ->
|
||||
n = put_elem(@node_template, key_mask(key_shift(hash)), [key | value])
|
||||
{put_elem(node, index, {k, v, n}), 1}
|
||||
|
||||
{^key, _, n} ->
|
||||
{put_elem(node, index, {key, value, n}), 0}
|
||||
|
||||
{k, v, n} ->
|
||||
{n, counter} = do_put(n, key, value, key_shift(hash))
|
||||
{put_elem(node, index, {k, v, n}), counter}
|
||||
@@ -127,21 +119,16 @@ defmodule HashDict do
|
||||
|
||||
defp do_update(node, key, initial, fun, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[] ->
|
||||
{put_elem(node, index, [key | initial.()]), 1}
|
||||
|
||||
[^key | value] ->
|
||||
{put_elem(node, index, [key | fun.(value)]), 0}
|
||||
|
||||
[k | v] ->
|
||||
n = put_elem(@node_template, key_mask(key_shift(hash)), [key | initial.()])
|
||||
{put_elem(node, index, {k, v, n}), 1}
|
||||
|
||||
{^key, value, n} ->
|
||||
{put_elem(node, index, {key, fun.(value), n}), 0}
|
||||
|
||||
{k, v, n} ->
|
||||
{n, counter} = do_update(n, key, initial, fun, key_shift(hash))
|
||||
{put_elem(node, index, {k, v, n}), counter}
|
||||
@@ -150,35 +137,28 @@ defmodule HashDict do
|
||||
|
||||
defp do_delete(node, key, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[] ->
|
||||
:error
|
||||
|
||||
[^key | value] ->
|
||||
{put_elem(node, index, []), value}
|
||||
|
||||
[_ | _] ->
|
||||
:error
|
||||
|
||||
{^key, value, n} ->
|
||||
{put_elem(node, index, do_compact_node(n)), value}
|
||||
|
||||
{k, v, n} ->
|
||||
case do_delete(n, key, key_shift(hash)) do
|
||||
{@node_template, value} ->
|
||||
{put_elem(node, index, [k | v]), value}
|
||||
|
||||
{n, value} ->
|
||||
{put_elem(node, index, {k, v, n}), value}
|
||||
|
||||
:error ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Enum.each(0..(@node_size - 1), fn index ->
|
||||
Enum.each 0..(@node_size - 1), fn index ->
|
||||
defp do_compact_node(node) when elem(node, unquote(index)) != [] do
|
||||
case elem(node, unquote(index)) do
|
||||
[k | v] ->
|
||||
@@ -186,12 +166,11 @@ defmodule HashDict do
|
||||
@node_template -> [k | v]
|
||||
n -> {k, v, n}
|
||||
end
|
||||
|
||||
{k, v, n} ->
|
||||
{k, v, put_elem(node, unquote(index), do_compact_node(n))}
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
## Dict reduce
|
||||
|
||||
@@ -216,12 +195,7 @@ defmodule HashDict do
|
||||
end
|
||||
|
||||
defp do_reduce(node, acc, fun, count, next) when count > 0 do
|
||||
do_reduce_each(
|
||||
:erlang.element(count, node),
|
||||
acc,
|
||||
fun,
|
||||
&do_reduce(node, &1, fun, count - 1, next)
|
||||
)
|
||||
do_reduce_each(:erlang.element(count, node), acc, fun, &do_reduce(node, &1, fun, count - 1, next))
|
||||
end
|
||||
|
||||
defp do_reduce(_node, acc, _fun, 0, next) do
|
||||
@@ -246,45 +220,19 @@ defmodule HashDict do
|
||||
end
|
||||
|
||||
defimpl Enumerable, for: HashDict do
|
||||
def reduce(dict, acc, fun) do
|
||||
# Avoid warnings about HashDict being deprecated.
|
||||
module = HashDict
|
||||
module.reduce(dict, acc, fun)
|
||||
end
|
||||
|
||||
def member?(dict, {key, value}) do
|
||||
# Avoid warnings about HashDict being deprecated.
|
||||
module = HashDict
|
||||
{:ok, match?({:ok, ^value}, module.fetch(dict, key))}
|
||||
end
|
||||
|
||||
def member?(_dict, _) do
|
||||
{:ok, false}
|
||||
end
|
||||
|
||||
def count(dict) do
|
||||
# Avoid warnings about HashDict being deprecated.
|
||||
module = HashDict
|
||||
{:ok, module.size(dict)}
|
||||
end
|
||||
|
||||
def slice(_dict) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
def reduce(dict, acc, fun), do: HashDict.reduce(dict, acc, fun)
|
||||
def member?(dict, {k, v}), do: {:ok, match?({:ok, ^v}, HashDict.fetch(dict, k))}
|
||||
def member?(_dict, _), do: {:ok, false}
|
||||
def count(dict), do: {:ok, HashDict.size(dict)}
|
||||
end
|
||||
|
||||
defimpl Collectable, for: HashDict do
|
||||
def into(original) do
|
||||
# Avoid warnings about HashDict being deprecated.
|
||||
module = HashDict
|
||||
|
||||
collector_fun = fn
|
||||
dict, {:cont, {key, value}} -> module.put(dict, key, value)
|
||||
{original, fn
|
||||
dict, {:cont, {k, v}} -> HashDict.put(dict, k, v)
|
||||
dict, :done -> dict
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
{original, collector_fun}
|
||||
end}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -292,8 +240,6 @@ defimpl Inspect, for: HashDict do
|
||||
import Inspect.Algebra
|
||||
|
||||
def inspect(dict, opts) do
|
||||
# Avoid warnings about HashDict being deprecated.
|
||||
module = HashDict
|
||||
concat(["#HashDict<", Inspect.List.inspect(module.to_list(dict), opts), ">"])
|
||||
concat ["#HashDict<", Inspect.List.inspect(HashDict.to_list(dict), opts), ">"]
|
||||
end
|
||||
end
|
||||
|
||||
+31
-77
@@ -5,8 +5,7 @@ defmodule HashSet do
|
||||
Use the `MapSet` module instead.
|
||||
"""
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
# TODO: Deprecate every function by 1.4
|
||||
|
||||
@node_bitmap 0b111
|
||||
@node_shift 3
|
||||
@@ -21,37 +20,37 @@ defmodule HashSet do
|
||||
@compile :inline_list_funcs
|
||||
@compile {:inline, key_hash: 1, key_mask: 1, key_shift: 1}
|
||||
|
||||
@spec new :: Set.t()
|
||||
@spec new :: Set.t
|
||||
def new do
|
||||
%HashSet{}
|
||||
end
|
||||
|
||||
def union(%HashSet{size: size1} = set1, %HashSet{size: size2} = set2) when size1 <= size2 do
|
||||
set_fold(set1, set2, fn v, acc -> put(acc, v) end)
|
||||
set_fold set1, set2, fn v, acc -> put(acc, v) end
|
||||
end
|
||||
|
||||
def union(%HashSet{} = set1, %HashSet{} = set2) do
|
||||
set_fold(set2, set1, fn v, acc -> put(acc, v) end)
|
||||
set_fold set2, set1, fn v, acc -> put(acc, v) end
|
||||
end
|
||||
|
||||
def intersection(%HashSet{} = set1, %HashSet{} = set2) do
|
||||
set_fold(set1, %HashSet{}, fn v, acc ->
|
||||
set_fold set1, %HashSet{}, fn v, acc ->
|
||||
if member?(set2, v), do: put(acc, v), else: acc
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
def difference(%HashSet{} = set1, %HashSet{} = set2) do
|
||||
set_fold(set2, set1, fn v, acc -> delete(acc, v) end)
|
||||
set_fold set2, set1, fn v, acc -> delete(acc, v) end
|
||||
end
|
||||
|
||||
def to_list(set) do
|
||||
set_fold(set, [], &[&1 | &2]) |> :lists.reverse()
|
||||
set_fold(set, [], &[&1 | &2]) |> :lists.reverse
|
||||
end
|
||||
|
||||
def equal?(%HashSet{size: size1} = set1, %HashSet{size: size2} = set2) do
|
||||
case size1 do
|
||||
^size2 -> subset?(set1, set2)
|
||||
_ -> false
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
@@ -59,20 +58,18 @@ defmodule HashSet do
|
||||
reduce(set1, {:cont, true}, fn member, acc ->
|
||||
case member?(set2, member) do
|
||||
true -> {:cont, acc}
|
||||
_ -> {:halt, false}
|
||||
_ -> {:halt, false}
|
||||
end
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
|
||||
def disjoint?(%HashSet{} = set1, %HashSet{} = set2) do
|
||||
reduce(set2, {:cont, true}, fn member, acc ->
|
||||
case member?(set1, member) do
|
||||
false -> {:cont, acc}
|
||||
_ -> {:halt, false}
|
||||
_ -> {:halt, false}
|
||||
end
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
|
||||
def member?(%HashSet{root: root}, term) do
|
||||
@@ -87,7 +84,7 @@ defmodule HashSet do
|
||||
def delete(%HashSet{root: root, size: size} = set, term) do
|
||||
case do_delete(root, term, key_hash(term)) do
|
||||
{:ok, root} -> %HashSet{root: root, size: size - 1}
|
||||
:error -> set
|
||||
:error -> set
|
||||
end
|
||||
end
|
||||
|
||||
@@ -95,8 +92,8 @@ defmodule HashSet do
|
||||
def reduce(%HashSet{root: root}, acc, fun) do
|
||||
do_reduce(root, acc, fun, @node_size, fn
|
||||
{:suspend, acc} -> {:suspended, acc, &{:done, elem(&1, 1)}}
|
||||
{:halt, acc} -> {:halted, acc}
|
||||
{:cont, acc} -> {:done, acc}
|
||||
{:halt, acc} -> {:halted, acc}
|
||||
{:cont, acc} -> {:done, acc}
|
||||
end)
|
||||
end
|
||||
|
||||
@@ -114,29 +111,24 @@ defmodule HashSet do
|
||||
|
||||
defp do_member?(node, term, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[] -> false
|
||||
[] -> false
|
||||
[^term | _] -> true
|
||||
[_] -> false
|
||||
[_ | n] -> do_member?(n, term, key_shift(hash))
|
||||
[_] -> false
|
||||
[_ | n] -> do_member?(n, term, key_shift(hash))
|
||||
end
|
||||
end
|
||||
|
||||
defp do_put(node, term, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[] ->
|
||||
{put_elem(node, index, [term]), 1}
|
||||
|
||||
[^term | _] ->
|
||||
{node, 0}
|
||||
|
||||
[t] ->
|
||||
n = put_elem(@node_template, key_mask(key_shift(hash)), [term])
|
||||
{put_elem(node, index, [t | n]), 1}
|
||||
|
||||
[t | n] ->
|
||||
{n, counter} = do_put(n, term, key_shift(hash))
|
||||
{put_elem(node, index, [t | n]), counter}
|
||||
@@ -145,35 +137,28 @@ defmodule HashSet do
|
||||
|
||||
defp do_delete(node, term, hash) do
|
||||
index = key_mask(hash)
|
||||
|
||||
case elem(node, index) do
|
||||
[] ->
|
||||
:error
|
||||
|
||||
[^term] ->
|
||||
{:ok, put_elem(node, index, [])}
|
||||
|
||||
[_] ->
|
||||
:error
|
||||
|
||||
[^term | n] ->
|
||||
{:ok, put_elem(node, index, do_compact_node(n))}
|
||||
|
||||
[t | n] ->
|
||||
case do_delete(n, term, key_shift(hash)) do
|
||||
{:ok, @node_template} ->
|
||||
{:ok, put_elem(node, index, [t])}
|
||||
|
||||
{:ok, n} ->
|
||||
{:ok, put_elem(node, index, [t | n])}
|
||||
|
||||
:error ->
|
||||
:error
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Enum.each(0..(@node_size - 1), fn index ->
|
||||
Enum.each 0..(@node_size - 1), fn index ->
|
||||
defp do_compact_node(node) when elem(node, unquote(index)) != [] do
|
||||
case elem(node, unquote(index)) do
|
||||
[t] ->
|
||||
@@ -181,17 +166,16 @@ defmodule HashSet do
|
||||
@node_template -> [t]
|
||||
n -> [t | n]
|
||||
end
|
||||
|
||||
[t | n] ->
|
||||
[t | put_elem(node, unquote(index), do_compact_node(n))]
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
## Set fold
|
||||
|
||||
defp do_fold_each([], acc, _fun), do: acc
|
||||
defp do_fold_each([t], acc, fun), do: fun.(t, acc)
|
||||
defp do_fold_each([], acc, _fun), do: acc
|
||||
defp do_fold_each([t], acc, fun), do: fun.(t, acc)
|
||||
defp do_fold_each([t | n], acc, fun), do: do_fold(n, fun.(t, acc), fun, @node_size)
|
||||
|
||||
defp do_fold(node, acc, fun, count) when count > 0 do
|
||||
@@ -226,12 +210,7 @@ defmodule HashSet do
|
||||
end
|
||||
|
||||
defp do_reduce(node, acc, fun, count, next) when count > 0 do
|
||||
do_reduce_each(
|
||||
:erlang.element(count, node),
|
||||
acc,
|
||||
fun,
|
||||
&do_reduce(node, &1, fun, count - 1, next)
|
||||
)
|
||||
do_reduce_each(:erlang.element(count, node), acc, fun, &do_reduce(node, &1, fun, count - 1, next))
|
||||
end
|
||||
|
||||
defp do_reduce(_node, acc, _fun, 0, next) do
|
||||
@@ -256,41 +235,18 @@ defmodule HashSet do
|
||||
end
|
||||
|
||||
defimpl Enumerable, for: HashSet do
|
||||
def reduce(set, acc, fun) do
|
||||
# Avoid warnings about HashSet being deprecated.
|
||||
module = HashSet
|
||||
module.reduce(set, acc, fun)
|
||||
end
|
||||
|
||||
def member?(set, term) do
|
||||
# Avoid warnings about HashSet being deprecated.
|
||||
module = HashSet
|
||||
{:ok, module.member?(set, term)}
|
||||
end
|
||||
|
||||
def count(set) do
|
||||
# Avoid warnings about HashSet being deprecated.
|
||||
module = HashSet
|
||||
{:ok, module.size(set)}
|
||||
end
|
||||
|
||||
def slice(_set) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
def reduce(set, acc, fun), do: HashSet.reduce(set, acc, fun)
|
||||
def member?(set, v), do: {:ok, HashSet.member?(set, v)}
|
||||
def count(set), do: {:ok, HashSet.size(set)}
|
||||
end
|
||||
|
||||
defimpl Collectable, for: HashSet do
|
||||
def into(original) do
|
||||
# Avoid warnings about HashSet being deprecated.
|
||||
module = HashSet
|
||||
|
||||
collector_fun = fn
|
||||
set, {:cont, term} -> module.put(set, term)
|
||||
{original, fn
|
||||
set, {:cont, x} -> HashSet.put(set, x)
|
||||
set, :done -> set
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
{original, collector_fun}
|
||||
end}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -298,8 +254,6 @@ defimpl Inspect, for: HashSet do
|
||||
import Inspect.Algebra
|
||||
|
||||
def inspect(set, opts) do
|
||||
# Avoid warnings about HashSet being deprecated.
|
||||
module = HashSet
|
||||
concat(["#HashSet<", Inspect.List.inspect(module.to_list(set), opts), ">"])
|
||||
concat ["#HashSet<", Inspect.List.inspect(HashSet.to_list(set), opts), ">"]
|
||||
end
|
||||
end
|
||||
|
||||
+275
-112
@@ -1,8 +1,6 @@
|
||||
import Kernel, except: [inspect: 1]
|
||||
import Inspect.Algebra
|
||||
|
||||
alias Code.Identifier
|
||||
|
||||
defprotocol Inspect do
|
||||
@moduledoc """
|
||||
The `Inspect` protocol is responsible for converting any Elixir
|
||||
@@ -25,7 +23,7 @@ defprotocol Inspect do
|
||||
import Inspect.Algebra
|
||||
|
||||
def inspect(dict, opts) do
|
||||
concat(["#MapSet<", to_doc(MapSet.to_list(dict), opts), ">"])
|
||||
concat ["#MapSet<", to_doc(MapSet.to_list(dict), opts), ">"]
|
||||
end
|
||||
end
|
||||
|
||||
@@ -50,7 +48,7 @@ defprotocol Inspect do
|
||||
implementation directly. For example, to test Inspect.MapSet above,
|
||||
you can invoke it as:
|
||||
|
||||
Inspect.MapSet.inspect(MapSet.new(), %Inspect.Opts{})
|
||||
Inspect.MapSet.inspect(MapSet.new, %Inspect.Opts{})
|
||||
|
||||
"""
|
||||
|
||||
@@ -64,27 +62,93 @@ defimpl Inspect, for: Atom do
|
||||
require Macro
|
||||
|
||||
def inspect(atom, opts) do
|
||||
color(Identifier.inspect_as_atom(atom), color_key(atom), opts)
|
||||
color(inspect(atom), color_key(atom), opts)
|
||||
end
|
||||
|
||||
defp color_key(atom) when is_boolean(atom), do: :boolean
|
||||
defp color_key(nil), do: nil
|
||||
defp color_key(nil), do: :nil
|
||||
defp color_key(_), do: :atom
|
||||
|
||||
def inspect(false), do: "false"
|
||||
def inspect(true), do: "true"
|
||||
def inspect(nil), do: "nil"
|
||||
def inspect(:""), do: ":\"\""
|
||||
|
||||
def inspect(atom) do
|
||||
binary = Atom.to_string(atom)
|
||||
|
||||
cond do
|
||||
valid_ref_identifier?(binary) ->
|
||||
if only_elixir?(binary) do
|
||||
binary
|
||||
else
|
||||
"Elixir." <> rest = binary
|
||||
rest
|
||||
end
|
||||
valid_atom_identifier?(binary) ->
|
||||
":" <> binary
|
||||
atom in [:%{}, :{}, :<<>>, :..., :%] ->
|
||||
":" <> binary
|
||||
atom in Macro.binary_ops or atom in Macro.unary_ops ->
|
||||
":" <> binary
|
||||
true ->
|
||||
IO.iodata_to_binary [?:, ?", Inspect.BitString.escape(binary, ?"), ?"]
|
||||
end
|
||||
end
|
||||
|
||||
defp only_elixir?("Elixir." <> rest), do: only_elixir?(rest)
|
||||
defp only_elixir?("Elixir"), do: true
|
||||
defp only_elixir?(_), do: false
|
||||
|
||||
# Detect if atom is an atom alias (Elixir.Foo.Bar.Baz)
|
||||
|
||||
defp valid_ref_identifier?("Elixir" <> rest) do
|
||||
valid_ref_piece?(rest)
|
||||
end
|
||||
|
||||
defp valid_ref_identifier?(_), do: false
|
||||
|
||||
defp valid_ref_piece?(<<?., h, t::binary>>) when h in ?A..?Z do
|
||||
valid_ref_piece? valid_identifier?(t)
|
||||
end
|
||||
|
||||
defp valid_ref_piece?(<<>>), do: true
|
||||
defp valid_ref_piece?(_), do: false
|
||||
|
||||
# Detect if atom
|
||||
|
||||
defp valid_atom_identifier?(<<h, t::binary>>) when h in ?a..?z or h in ?A..?Z or h == ?_ do
|
||||
valid_atom_piece?(t)
|
||||
end
|
||||
|
||||
defp valid_atom_identifier?(_), do: false
|
||||
|
||||
defp valid_atom_piece?(t) do
|
||||
case valid_identifier?(t) do
|
||||
<<>> -> true
|
||||
<<??>> -> true
|
||||
<<?!>> -> true
|
||||
<<?@, t::binary>> -> valid_atom_piece?(t)
|
||||
_ -> false
|
||||
end
|
||||
end
|
||||
|
||||
defp valid_identifier?(<<h, t::binary>>)
|
||||
when h in ?a..?z
|
||||
when h in ?A..?Z
|
||||
when h in ?0..?9
|
||||
when h == ?_ do
|
||||
valid_identifier? t
|
||||
end
|
||||
|
||||
defp valid_identifier?(other), do: other
|
||||
end
|
||||
|
||||
defimpl Inspect, for: BitString do
|
||||
def inspect(term, opts) when is_binary(term) do
|
||||
%Inspect.Opts{binaries: bins, base: base, printable_limit: printable_limit} = opts
|
||||
|
||||
if base == :decimal and
|
||||
(bins == :as_strings or (bins == :infer and String.printable?(term, printable_limit))) do
|
||||
inspected =
|
||||
case Identifier.escape(term, ?", printable_limit) do
|
||||
{escaped, ""} -> [?", escaped, ?"]
|
||||
{escaped, _} -> [?", escaped, ?", " <> ..."]
|
||||
end
|
||||
|
||||
color(IO.iodata_to_binary(inspected), :string, opts)
|
||||
def inspect(term, %Inspect.Opts{binaries: bins, base: base} = opts) when is_binary(term) do
|
||||
if base == :decimal and (bins == :as_strings or (bins == :infer and String.printable?(term))) do
|
||||
inspected = IO.iodata_to_binary([?", escape(term, ?"), ?"])
|
||||
color(inspected, :string, opts)
|
||||
else
|
||||
inspect_bitstring(term, opts)
|
||||
end
|
||||
@@ -94,6 +158,88 @@ defimpl Inspect, for: BitString do
|
||||
inspect_bitstring(term, opts)
|
||||
end
|
||||
|
||||
## Escaping
|
||||
|
||||
@doc false
|
||||
def escape(other, char) do
|
||||
escape(other, char, [])
|
||||
end
|
||||
|
||||
defp escape(<<char, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | [?\\, char]])
|
||||
end
|
||||
defp escape(<<?#, ?{, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\\#{'])
|
||||
end
|
||||
defp escape(<<?\a, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\a'])
|
||||
end
|
||||
defp escape(<<?\b, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\b'])
|
||||
end
|
||||
defp escape(<<?\d, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\d'])
|
||||
end
|
||||
defp escape(<<?\e, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\e'])
|
||||
end
|
||||
defp escape(<<?\f, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\f'])
|
||||
end
|
||||
defp escape(<<?\n, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\n'])
|
||||
end
|
||||
defp escape(<<?\r, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\r'])
|
||||
end
|
||||
defp escape(<<?\\, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\\\'])
|
||||
end
|
||||
defp escape(<<?\t, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\t'])
|
||||
end
|
||||
defp escape(<<?\v, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | '\\v'])
|
||||
end
|
||||
defp escape(<<h::utf8, t::binary>>, char, acc)
|
||||
when h in 0x20..0x7E
|
||||
when h in 0xA0..0xD7FF
|
||||
when h in 0xE000..0xFFFD
|
||||
when h in 0x10000..0x10FFFF do
|
||||
escape(t, char, [acc | <<h::utf8>>])
|
||||
end
|
||||
defp escape(<<h, t::binary>>, char, acc) do
|
||||
escape(t, char, [acc | escape_char(h)])
|
||||
end
|
||||
defp escape(<<>>, _char, acc), do: acc
|
||||
|
||||
@doc false
|
||||
# Also used by Regex
|
||||
def escape_char(0) do
|
||||
'\\0'
|
||||
end
|
||||
|
||||
def escape_char(char) when char < 0x100 do
|
||||
<<a::4, b::4>> = <<char::8>>
|
||||
['\\x', to_hex(a), to_hex(b)]
|
||||
end
|
||||
|
||||
def escape_char(char) when char < 0x10000 do
|
||||
<<a::4, b::4, c::4, d::4>> = <<char::16>>
|
||||
['\\x{', to_hex(a), to_hex(b), to_hex(c), to_hex(d), ?}]
|
||||
end
|
||||
|
||||
def escape_char(char) when char < 0x1000000 do
|
||||
<<a::4, b::4, c::4, d::4, e::4, f::4>> = <<char::24>>
|
||||
['\\x{', to_hex(a), to_hex(b), to_hex(c),
|
||||
to_hex(d), to_hex(e), to_hex(f), ?}]
|
||||
end
|
||||
|
||||
defp to_hex(c) when c in 0..9, do: ?0+c
|
||||
defp to_hex(c) when c in 10..15, do: ?A+c-10
|
||||
|
||||
## Bitstrings
|
||||
|
||||
defp inspect_bitstring("", opts) do
|
||||
color("<<>>", :binary, opts)
|
||||
end
|
||||
@@ -101,8 +247,7 @@ defimpl Inspect, for: BitString do
|
||||
defp inspect_bitstring(bitstring, opts) do
|
||||
left = color("<<", :binary, opts)
|
||||
right = color(">>", :binary, opts)
|
||||
inner = each_bit(bitstring, opts.limit, opts)
|
||||
group(concat(concat(left, nest(inner, 2)), right))
|
||||
nest surround(left, each_bit(bitstring, opts.limit, opts), right), 1
|
||||
end
|
||||
|
||||
defp each_bit(_, 0, _) do
|
||||
@@ -118,10 +263,8 @@ defimpl Inspect, for: BitString do
|
||||
end
|
||||
|
||||
defp each_bit(<<h, t::bitstring>>, counter, opts) do
|
||||
flex_glue(
|
||||
concat(Inspect.Integer.inspect(h, opts), ","),
|
||||
each_bit(t, decrement(counter), opts)
|
||||
)
|
||||
glue(concat(Inspect.Integer.inspect(h, opts), ","),
|
||||
each_bit(t, decrement(counter), opts))
|
||||
end
|
||||
|
||||
defp each_bit(bitstring, _counter, opts) do
|
||||
@@ -130,9 +273,8 @@ defimpl Inspect, for: BitString do
|
||||
Inspect.Integer.inspect(h, opts) <> "::size(" <> Integer.to_string(size) <> ")"
|
||||
end
|
||||
|
||||
@compile {:inline, decrement: 1}
|
||||
defp decrement(:infinity), do: :infinity
|
||||
defp decrement(counter), do: counter - 1
|
||||
defp decrement(counter), do: counter - 1
|
||||
end
|
||||
|
||||
defimpl Inspect, for: List do
|
||||
@@ -140,28 +282,14 @@ defimpl Inspect, for: List do
|
||||
color("[]", :list, opts)
|
||||
end
|
||||
|
||||
# TODO: Remove :char_list and :as_char_lists handling in 2.0
|
||||
def inspect(term, opts) do
|
||||
%Inspect.Opts{
|
||||
charlists: lists,
|
||||
char_lists: lists_deprecated,
|
||||
printable_limit: printable_limit
|
||||
} = opts
|
||||
|
||||
# TODO: Deprecate :char_lists and :as_char_lists keys in v1.5
|
||||
def inspect(term, %Inspect.Opts{charlists: lists, char_lists: lists_deprecated} = opts) do
|
||||
lists =
|
||||
if lists == :infer and lists_deprecated != :infer do
|
||||
case lists_deprecated do
|
||||
:as_char_lists ->
|
||||
IO.warn(
|
||||
"the :char_lists inspect option and its :as_char_lists " <>
|
||||
"value are deprecated, use the :charlists option and its " <>
|
||||
":as_charlists value instead"
|
||||
)
|
||||
|
||||
:as_charlists
|
||||
|
||||
_ ->
|
||||
IO.warn("the :char_lists inspect option is deprecated, use :charlists instead")
|
||||
lists_deprecated
|
||||
end
|
||||
else
|
||||
@@ -173,27 +301,19 @@ defimpl Inspect, for: List do
|
||||
close = color("]", :list, opts)
|
||||
|
||||
cond do
|
||||
lists == :as_charlists or (lists == :infer and List.ascii_printable?(term, printable_limit)) ->
|
||||
inspected =
|
||||
case Identifier.escape(IO.chardata_to_string(term), ?', printable_limit) do
|
||||
{escaped, ""} -> [?', escaped, ?']
|
||||
{escaped, _} -> [?', escaped, ?', " ++ ..."]
|
||||
end
|
||||
|
||||
IO.iodata_to_binary(inspected)
|
||||
|
||||
lists == :as_charlists or (lists == :infer and printable?(term)) ->
|
||||
IO.iodata_to_binary [?', Inspect.BitString.escape(IO.chardata_to_string(term), ?'), ?']
|
||||
keyword?(term) ->
|
||||
container_doc(open, term, close, opts, &keyword/2, separator: sep, break: :strict)
|
||||
|
||||
surround_many(open, term, close, opts, &keyword/2, sep)
|
||||
true ->
|
||||
container_doc(open, term, close, opts, &to_doc/2, separator: sep)
|
||||
surround_many(open, term, close, opts, &to_doc/2, sep)
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def keyword({key, value}, opts) do
|
||||
key = color(Identifier.inspect_as_key(key), :atom, opts)
|
||||
concat(key, concat(" ", to_doc(value, opts)))
|
||||
key = color(key_to_binary(key) <> ": ", :atom, opts)
|
||||
concat(key, to_doc(value, opts))
|
||||
end
|
||||
|
||||
@doc false
|
||||
@@ -204,8 +324,30 @@ defimpl Inspect, for: List do
|
||||
end
|
||||
end
|
||||
|
||||
def keyword?([]), do: true
|
||||
def keyword?([]), do: true
|
||||
def keyword?(_other), do: false
|
||||
|
||||
@doc false
|
||||
def printable?([char | rest]) when char in 32..126, do: printable?(rest)
|
||||
def printable?([?\n | rest]), do: printable?(rest)
|
||||
def printable?([?\r | rest]), do: printable?(rest)
|
||||
def printable?([?\t | rest]), do: printable?(rest)
|
||||
def printable?([?\v | rest]), do: printable?(rest)
|
||||
def printable?([?\b | rest]), do: printable?(rest)
|
||||
def printable?([?\f | rest]), do: printable?(rest)
|
||||
def printable?([?\e | rest]), do: printable?(rest)
|
||||
def printable?([?\a | rest]), do: printable?(rest)
|
||||
def printable?([]), do: true
|
||||
def printable?(_), do: false
|
||||
|
||||
## Private
|
||||
|
||||
defp key_to_binary(key) do
|
||||
case Inspect.Atom.inspect(key) do
|
||||
":" <> right -> right
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Tuple do
|
||||
@@ -213,14 +355,13 @@ defimpl Inspect, for: Tuple do
|
||||
open = color("{", :tuple, opts)
|
||||
sep = color(",", :tuple, opts)
|
||||
close = color("}", :tuple, opts)
|
||||
container_opts = [separator: sep, break: :flex]
|
||||
container_doc(open, Tuple.to_list(tuple), close, opts, &to_doc/2, container_opts)
|
||||
surround_many(open, Tuple.to_list(tuple), close, opts, &to_doc/2, sep)
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Map do
|
||||
def inspect(map, opts) do
|
||||
inspect(map, "", opts)
|
||||
nest inspect(map, "", opts), 1
|
||||
end
|
||||
|
||||
def inspect(map, name, opts) do
|
||||
@@ -228,20 +369,22 @@ defimpl Inspect, for: Map do
|
||||
open = color("%" <> name <> "{", :map, opts)
|
||||
sep = color(",", :map, opts)
|
||||
close = color("}", :map, opts)
|
||||
container_doc(open, map, close, opts, traverse_fun(map, opts), separator: sep, break: :strict)
|
||||
surround_many(open, map, close, opts, traverse_fun(map), sep)
|
||||
end
|
||||
|
||||
defp traverse_fun(list, opts) do
|
||||
defp traverse_fun(list) do
|
||||
if Inspect.List.keyword?(list) do
|
||||
&Inspect.List.keyword/2
|
||||
else
|
||||
sep = color(" => ", :map, opts)
|
||||
&to_map(&1, &2, sep)
|
||||
&to_map/2
|
||||
end
|
||||
end
|
||||
|
||||
defp to_map({key, value}, opts, sep) do
|
||||
concat(concat(to_doc(key, opts), sep), to_doc(value, opts))
|
||||
defp to_map({key, value}, opts) do
|
||||
concat(
|
||||
concat(to_doc(key, opts), " => "),
|
||||
to_doc(value, opts)
|
||||
)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -253,27 +396,20 @@ defimpl Inspect, for: Integer do
|
||||
|
||||
defp base_to_value(base) do
|
||||
case base do
|
||||
:binary -> 2
|
||||
:binary -> 2
|
||||
:decimal -> 10
|
||||
:octal -> 8
|
||||
:hex -> 16
|
||||
:octal -> 8
|
||||
:hex -> 16
|
||||
end
|
||||
end
|
||||
|
||||
defp prepend_prefix(value, :decimal), do: value
|
||||
|
||||
defp prepend_prefix(<<?-, value::binary>>, base) do
|
||||
"-" <> prepend_prefix(value, base)
|
||||
end
|
||||
|
||||
defp prepend_prefix(value, base) do
|
||||
prefix =
|
||||
case base do
|
||||
:binary -> "0b"
|
||||
:octal -> "0o"
|
||||
:hex -> "0x"
|
||||
end
|
||||
|
||||
prefix = case base do
|
||||
:binary -> "0b"
|
||||
:octal -> "0o"
|
||||
:hex -> "0x"
|
||||
end
|
||||
prefix <> value
|
||||
end
|
||||
end
|
||||
@@ -287,30 +423,60 @@ end
|
||||
|
||||
defimpl Inspect, for: Regex do
|
||||
def inspect(regex, opts) do
|
||||
{escaped, _} = Identifier.escape(regex.source, ?/, :infinity, &escape_map/1)
|
||||
source = IO.iodata_to_binary(['~r/', escaped, ?/, regex.opts])
|
||||
source = IO.iodata_to_binary(['~r/', escape(regex.source, ?/), ?/, regex.opts])
|
||||
color(source, :regex, opts)
|
||||
end
|
||||
|
||||
defp escape_map(?\a), do: '\\a'
|
||||
defp escape_map(?\f), do: '\\f'
|
||||
defp escape_map(?\n), do: '\\n'
|
||||
defp escape_map(?\r), do: '\\r'
|
||||
defp escape_map(?\t), do: '\\t'
|
||||
defp escape_map(?\v), do: '\\v'
|
||||
defp escape_map(_), do: false
|
||||
defp escape(bin, term),
|
||||
do: escape(bin, [], term)
|
||||
|
||||
defp escape(<<?\\, term>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | [?\\, term]], term)
|
||||
|
||||
defp escape(<<term>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | [?\\, term]], term)
|
||||
|
||||
# The list of characters is from 'String.printable?' implementation
|
||||
# minus characters treated specially by regex: \s, \d, \b, \e
|
||||
|
||||
defp escape(<<?\n>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | '\\n'], term)
|
||||
|
||||
defp escape(<<?\r>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | '\\r'], term)
|
||||
|
||||
defp escape(<<?\t>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | '\\t'], term)
|
||||
|
||||
defp escape(<<?\v>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | '\\v'], term)
|
||||
|
||||
defp escape(<<?\f>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | '\\f'], term)
|
||||
|
||||
defp escape(<<?\a>> <> rest, buf, term),
|
||||
do: escape(rest, [buf | '\\a'], term)
|
||||
|
||||
defp escape(<<char::utf8, rest::binary>>, buf, term)
|
||||
when char in 0x20..0x7E
|
||||
when char in 0xA0..0xD7FF
|
||||
when char in 0xE000..0xFFFD
|
||||
when char in 0x10000..0x10FFFF,
|
||||
do: escape(rest, [buf | <<char::utf8>>], term)
|
||||
|
||||
defp escape(<<char, rest::binary>>, buf, term),
|
||||
do: escape(rest, [buf | Inspect.BitString.escape_char(char)], term)
|
||||
|
||||
defp escape(<<>>, buf, _), do: buf
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Function do
|
||||
def inspect(function, _opts) do
|
||||
fun_info = :erlang.fun_info(function)
|
||||
mod = fun_info[:module]
|
||||
name = fun_info[:name]
|
||||
|
||||
if fun_info[:type] == :external and fun_info[:env] == [] do
|
||||
inspected_as_atom = Identifier.inspect_as_atom(mod)
|
||||
inspected_as_function = Identifier.inspect_as_function(name)
|
||||
"&#{inspected_as_atom}.#{inspected_as_function}/#{fun_info[:arity]}"
|
||||
"&#{Inspect.Atom.inspect(mod)}.#{fun_info[:name]}/#{fun_info[:arity]}"
|
||||
else
|
||||
case Atom.to_charlist(mod) do
|
||||
'elixir_compiler_' ++ _ ->
|
||||
@@ -319,7 +485,6 @@ defimpl Inspect, for: Function do
|
||||
else
|
||||
default_inspect(mod, fun_info)
|
||||
end
|
||||
|
||||
_ ->
|
||||
default_inspect(mod, fun_info)
|
||||
end
|
||||
@@ -327,9 +492,8 @@ defimpl Inspect, for: Function do
|
||||
end
|
||||
|
||||
defp default_inspect(mod, fun_info) do
|
||||
inspected_as_atom = Identifier.inspect_as_atom(mod)
|
||||
extracted_name = extract_name(fun_info[:name])
|
||||
"#Function<#{uniq(fun_info)}/#{fun_info[:arity]} in #{inspected_as_atom}#{extracted_name}>"
|
||||
"#Function<#{uniq(fun_info)}/#{fun_info[:arity]} in " <>
|
||||
"#{Inspect.Atom.inspect(mod)}#{extract_name(fun_info[:name])}>"
|
||||
end
|
||||
|
||||
defp extract_name([]) do
|
||||
@@ -337,17 +501,16 @@ defimpl Inspect, for: Function do
|
||||
end
|
||||
|
||||
defp extract_name(name) do
|
||||
case Identifier.extract_anonymous_fun_parent(name) do
|
||||
{name, arity} ->
|
||||
"." <> Identifier.inspect_as_function(name) <> "/" <> arity
|
||||
|
||||
:error ->
|
||||
"." <> Identifier.inspect_as_function(name)
|
||||
name = Atom.to_string(name)
|
||||
case :binary.split(name, "-", [:global]) do
|
||||
["", name | _] -> "." <> name
|
||||
_ -> "." <> name
|
||||
end
|
||||
end
|
||||
|
||||
defp uniq(fun_info) do
|
||||
Integer.to_string(fun_info[:new_index]) <> "." <> Integer.to_string(fun_info[:uniq])
|
||||
Integer.to_string(fun_info[:new_index]) <> "." <>
|
||||
Integer.to_string(fun_info[:uniq])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -371,19 +534,19 @@ defimpl Inspect, for: Reference do
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Any do
|
||||
def inspect(%module{} = struct, opts) do
|
||||
def inspect(%{__struct__: struct} = map, opts) do
|
||||
try do
|
||||
module.__struct__
|
||||
struct.__struct__
|
||||
rescue
|
||||
_ -> Inspect.Map.inspect(struct, opts)
|
||||
_ -> Inspect.Map.inspect(map, opts)
|
||||
else
|
||||
dunder ->
|
||||
if :maps.keys(dunder) == :maps.keys(struct) do
|
||||
pruned = :maps.remove(:__exception__, :maps.remove(:__struct__, struct))
|
||||
if :maps.keys(dunder) == :maps.keys(map) do
|
||||
pruned = :maps.remove(:__exception__, :maps.remove(:__struct__, map))
|
||||
colorless_opts = %{opts | syntax_colors: []}
|
||||
Inspect.Map.inspect(pruned, Inspect.Atom.inspect(module, colorless_opts), opts)
|
||||
Inspect.Map.inspect(pruned, Inspect.Atom.inspect(struct, colorless_opts), opts)
|
||||
else
|
||||
Inspect.Map.inspect(struct, opts)
|
||||
Inspect.Map.inspect(map, opts)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+246
-602
File diff suppressed because it is too large
Load Diff
+83
-93
@@ -28,7 +28,9 @@ defmodule Integer do
|
||||
false
|
||||
|
||||
"""
|
||||
defguard is_odd(integer) when is_integer(integer) and (integer &&& 1) == 1
|
||||
defmacro is_odd(integer) do
|
||||
quote do: (unquote(integer) &&& 1) == 1
|
||||
end
|
||||
|
||||
@doc """
|
||||
Determines if an `integer` is even.
|
||||
@@ -53,7 +55,9 @@ defmodule Integer do
|
||||
true
|
||||
|
||||
"""
|
||||
defguard is_even(integer) when is_integer(integer) and (integer &&& 1) == 0
|
||||
defmacro is_even(integer) do
|
||||
quote do: (unquote(integer) &&& 1) == 0
|
||||
end
|
||||
|
||||
@doc """
|
||||
Computes the modulo remainder of an integer division.
|
||||
@@ -75,7 +79,6 @@ defmodule Integer do
|
||||
@spec mod(integer, neg_integer | pos_integer) :: integer
|
||||
def mod(dividend, divisor) do
|
||||
remainder = rem(dividend, divisor)
|
||||
|
||||
if remainder * divisor < 0 do
|
||||
remainder + divisor
|
||||
else
|
||||
@@ -107,7 +110,7 @@ defmodule Integer do
|
||||
"""
|
||||
@spec floor_div(integer, neg_integer | pos_integer) :: integer
|
||||
def floor_div(dividend, divisor) do
|
||||
if dividend * divisor < 0 and rem(dividend, divisor) != 0 do
|
||||
if (dividend * divisor < 0) and rem(dividend, divisor) != 0 do
|
||||
div(dividend, divisor) - 1
|
||||
else
|
||||
div(dividend, divisor)
|
||||
@@ -138,11 +141,14 @@ defmodule Integer do
|
||||
do_digits(integer, base, [])
|
||||
end
|
||||
|
||||
defp do_digits(digit, base, []) when abs(digit) < base, do: [digit]
|
||||
defp do_digits(digit, base, []) when digit == -base, do: [-1, 0]
|
||||
defp do_digits(base, base, []), do: [1, 0]
|
||||
defp do_digits(0, _base, acc), do: acc
|
||||
|
||||
defp do_digits(digit, base, []) when abs(digit) < base,
|
||||
do: [digit]
|
||||
defp do_digits(digit, base, []) when digit == -base,
|
||||
do: [-1, 0]
|
||||
defp do_digits(base, base, []),
|
||||
do: [1, 0]
|
||||
defp do_digits(0, _base, acc),
|
||||
do: acc
|
||||
defp do_digits(integer, base, acc),
|
||||
do: do_digits(div(integer, base), base, [rem(integer, base) | acc])
|
||||
|
||||
@@ -150,7 +156,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 or equal than `2`.
|
||||
This one can be an integer >= 2.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -164,20 +170,24 @@ defmodule Integer do
|
||||
0
|
||||
|
||||
"""
|
||||
@spec undigits([integer], pos_integer) :: integer
|
||||
@spec undigits([integer], integer) :: integer
|
||||
def undigits(digits, base \\ 10) when is_list(digits) and is_integer(base) and base >= 2 do
|
||||
do_undigits(digits, base, 0)
|
||||
end
|
||||
|
||||
defp do_undigits([], _base, 0), do: 0
|
||||
defp do_undigits([digit], base, 0) when is_integer(digit) and digit < base, do: digit
|
||||
defp do_undigits([1, 0], base, 0), do: base
|
||||
defp do_undigits([0 | tail], base, 0), do: do_undigits(tail, base, 0)
|
||||
defp do_undigits([], _base, acc), do: acc
|
||||
defp do_undigits([], _base, 0),
|
||||
do: 0
|
||||
defp do_undigits([digit], base, 0) when is_integer(digit) and digit < base,
|
||||
do: digit
|
||||
defp do_undigits([1, 0], base, 0),
|
||||
do: base
|
||||
defp do_undigits([0 | tail], base, 0),
|
||||
do: do_undigits(tail, base, 0)
|
||||
|
||||
defp do_undigits([], _base, acc),
|
||||
do: acc
|
||||
defp do_undigits([digit | _], base, _) when is_integer(digit) and digit >= base,
|
||||
do: raise(ArgumentError, "invalid digit #{digit} in base #{base}")
|
||||
|
||||
do: raise ArgumentError, "invalid digit #{digit} in base #{base}"
|
||||
defp do_undigits([digit | tail], base, acc) when is_integer(digit),
|
||||
do: do_undigits(tail, base, acc * base + digit)
|
||||
|
||||
@@ -222,48 +232,74 @@ defmodule Integer do
|
||||
** (ArgumentError) invalid base 38
|
||||
|
||||
"""
|
||||
@spec parse(binary, 2..36) :: {integer, binary} | :error
|
||||
@spec parse(binary, 2..36) :: {integer, binary} | :error | no_return
|
||||
def parse(binary, base \\ 10)
|
||||
|
||||
def parse(_binary, base) when base not in 2..36 do
|
||||
raise ArgumentError, "invalid base #{inspect(base)}"
|
||||
def parse("", base) when base in 2..36,
|
||||
do: :error
|
||||
|
||||
def parse(binary, base) when is_binary(binary) and base in 2..36 do
|
||||
parse_in_base(binary, base)
|
||||
end
|
||||
|
||||
def parse(binary, base) do
|
||||
case count_digits(binary, base) do
|
||||
0 ->
|
||||
:error
|
||||
def parse(binary, base) when is_binary(binary) do
|
||||
raise ArgumentError, "invalid base #{base}"
|
||||
end
|
||||
|
||||
count ->
|
||||
{digits, rem} = :erlang.split_binary(binary, count)
|
||||
{:erlang.binary_to_integer(digits, base), rem}
|
||||
defp parse_in_base("-" <> bin, base) do
|
||||
case do_parse(bin, base) do
|
||||
{number, remainder} -> {-number, remainder}
|
||||
:error -> :error
|
||||
end
|
||||
end
|
||||
|
||||
defp count_digits(<<sign, rest::binary>>, base) when sign in '+-' do
|
||||
case count_digits_nosign(rest, base, 1) do
|
||||
1 -> 0
|
||||
count -> count
|
||||
defp parse_in_base("+" <> bin, base) do
|
||||
do_parse(bin, base)
|
||||
end
|
||||
|
||||
defp parse_in_base(binary, base) when is_binary(binary) do
|
||||
do_parse(binary, base)
|
||||
end
|
||||
|
||||
defp do_parse(<<char, rest::binary>>, base) do
|
||||
if valid_digit_in_base?(char, base) do
|
||||
do_parse(rest, base, parse_digit(char))
|
||||
else
|
||||
:error
|
||||
end
|
||||
end
|
||||
|
||||
defp count_digits(<<rest::binary>>, base) do
|
||||
count_digits_nosign(rest, base, 0)
|
||||
defp do_parse(_, _) do
|
||||
:error
|
||||
end
|
||||
|
||||
digits = [{?0..?9, -?0}, {?A..?Z, 10 - ?A}, {?a..?z, 10 - ?a}]
|
||||
|
||||
for {chars, diff} <- digits,
|
||||
char <- chars do
|
||||
digit = char + diff
|
||||
|
||||
defp count_digits_nosign(<<unquote(char), rest::binary>>, base, count)
|
||||
when base > unquote(digit) do
|
||||
count_digits_nosign(rest, base, count + 1)
|
||||
defp do_parse(<<char, rest::binary>> = bin, base, acc) do
|
||||
if valid_digit_in_base?(char, base) do
|
||||
do_parse(rest, base, base * acc + parse_digit(char))
|
||||
else
|
||||
{acc, bin}
|
||||
end
|
||||
end
|
||||
|
||||
defp count_digits_nosign(<<_::binary>>, _, count), do: count
|
||||
defp do_parse(bitstring, _, acc) do
|
||||
{acc, bitstring}
|
||||
end
|
||||
|
||||
defp parse_digit(char) do
|
||||
cond do
|
||||
char in ?0..?9 -> char - ?0
|
||||
char in ?A..?Z -> char - ?A + 10
|
||||
true -> char - ?a + 10
|
||||
end
|
||||
end
|
||||
|
||||
defp valid_digit_in_base?(char, base) do
|
||||
if base <= 10 do
|
||||
char in ?0..(?0 + base - 1)
|
||||
else
|
||||
char in ?0..?9 or char in ?A..(?A + base - 11) or char in ?a..(?a + base - 11)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a binary which corresponds to the text representation
|
||||
@@ -286,7 +322,7 @@ defmodule Integer do
|
||||
"123"
|
||||
|
||||
"""
|
||||
@spec to_string(integer) :: String.t()
|
||||
@spec to_string(integer) :: String.t
|
||||
def to_string(integer) do
|
||||
:erlang.integer_to_binary(integer)
|
||||
end
|
||||
@@ -311,7 +347,7 @@ defmodule Integer do
|
||||
"ELIXIR"
|
||||
|
||||
"""
|
||||
@spec to_string(integer, 2..36) :: String.t()
|
||||
@spec to_string(integer, 2..36) :: String.t
|
||||
def to_string(integer, base) do
|
||||
:erlang.integer_to_binary(integer, base)
|
||||
end
|
||||
@@ -365,54 +401,8 @@ defmodule Integer do
|
||||
:erlang.integer_to_list(integer, base)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the greatest common divisor of the two given integers.
|
||||
|
||||
The greatest common divisor (GCD) of `integer1` and `integer2` is the largest positive
|
||||
integer that divides both `integer1` and `integer2` without leaving a remainder.
|
||||
|
||||
By convention, `gcd(0, 0)` returns `0`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Integer.gcd(2, 3)
|
||||
1
|
||||
|
||||
iex> Integer.gcd(8, 12)
|
||||
4
|
||||
|
||||
iex> Integer.gcd(8, -12)
|
||||
4
|
||||
|
||||
iex> Integer.gcd(10, 0)
|
||||
10
|
||||
|
||||
iex> Integer.gcd(7, 7)
|
||||
7
|
||||
|
||||
iex> Integer.gcd(0, 0)
|
||||
0
|
||||
|
||||
"""
|
||||
@spec gcd(0, 0) :: 0
|
||||
@spec gcd(integer, integer) :: pos_integer
|
||||
def gcd(integer1, integer2) when is_integer(integer1) and is_integer(integer2) do
|
||||
gcd_positive(abs(integer1), abs(integer2))
|
||||
end
|
||||
|
||||
defp gcd_positive(0, integer2), do: integer2
|
||||
defp gcd_positive(integer1, 0), do: integer1
|
||||
defp gcd_positive(integer1, integer2), do: gcd_positive(integer2, rem(integer1, integer2))
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
# TODO: Deprecate by v1.5
|
||||
@doc false
|
||||
@spec to_char_list(integer) :: charlist
|
||||
def to_char_list(integer), do: Integer.to_charlist(integer)
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
@doc false
|
||||
@spec to_char_list(integer, 2..36) :: charlist
|
||||
def to_char_list(integer, base), do: Integer.to_charlist(integer, base)
|
||||
end
|
||||
|
||||
+31
-51
@@ -27,9 +27,9 @@ defmodule IO do
|
||||
* `:stderr` - a shortcut for the named process `:standard_error`
|
||||
provided in Erlang
|
||||
|
||||
IO devices maintain their position, which means subsequent calls to any
|
||||
reading or writing functions will start from the place where the device
|
||||
was last accessed. The position of files can be changed using the
|
||||
IO devices maintain their position, that means subsequent calls to any
|
||||
reading or writing functions will start from the place when the device
|
||||
was last accessed. Position of files can be changed using the
|
||||
`:file.position/2` function.
|
||||
|
||||
"""
|
||||
@@ -143,7 +143,8 @@ defmodule IO do
|
||||
@doc """
|
||||
Writes `item` to the given `device`.
|
||||
|
||||
By default, the `device` is the standard output.
|
||||
By default the `device` is the standard output.
|
||||
It returns `:ok` if it succeeds.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -154,9 +155,9 @@ defmodule IO do
|
||||
#=> error
|
||||
|
||||
"""
|
||||
@spec write(device, chardata | String.Chars.t()) :: :ok
|
||||
@spec write(device, chardata | String.Chars.t) :: :ok
|
||||
def write(device \\ :stdio, item) do
|
||||
:io.put_chars(map_dev(device), to_chardata(item))
|
||||
:io.put_chars map_dev(device), to_chardata(item)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -171,28 +172,16 @@ defmodule IO do
|
||||
"""
|
||||
@spec binwrite(device, iodata) :: :ok | {:error, term}
|
||||
def binwrite(device \\ :stdio, item) when is_iodata(item) do
|
||||
:file.write(map_dev(device), item)
|
||||
:file.write map_dev(device), item
|
||||
end
|
||||
|
||||
@doc """
|
||||
Writes `item` to the given `device`, similar to `write/2`,
|
||||
but adds a newline at the end.
|
||||
|
||||
By default, the `device` is the standard output. It returns `:ok`
|
||||
if it succeeds.
|
||||
|
||||
## Examples
|
||||
|
||||
IO.puts "Hello World!"
|
||||
#=> Hello World!
|
||||
|
||||
IO.puts :stderr, "error"
|
||||
#=> error
|
||||
|
||||
"""
|
||||
@spec puts(device, chardata | String.Chars.t()) :: :ok
|
||||
@spec puts(device, chardata | String.Chars.t) :: :ok
|
||||
def puts(device \\ :stdio, item) do
|
||||
:io.put_chars(map_dev(device), [to_chardata(item), ?\n])
|
||||
:io.put_chars map_dev(device), [to_chardata(item), ?\n]
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -212,17 +201,13 @@ defmodule IO do
|
||||
#=> my_app.ex:4: MyApp.main/1
|
||||
|
||||
"""
|
||||
@spec warn(chardata | String.Chars.t(), Exception.stacktrace()) :: :ok
|
||||
@spec warn(chardata | String.Chars.t, Exception.stacktrace) :: :ok
|
||||
def warn(message, []) do
|
||||
:elixir_errors.bare_warn(nil, nil, [to_chardata(message), ?\n])
|
||||
:elixir_errors.warn([to_chardata(message), ?\n])
|
||||
end
|
||||
|
||||
def warn(message, [{_, _, _, opts} | _] = stacktrace) do
|
||||
formatted_trace = Enum.map_join(stacktrace, "\n ", &Exception.format_stacktrace_entry(&1))
|
||||
message = [to_chardata(message), ?\n, " ", formatted_trace, ?\n]
|
||||
line = opts[:line]
|
||||
file = opts[:file]
|
||||
:elixir_errors.bare_warn(line, file && List.to_string(file), message)
|
||||
def warn(message, stacktrace) when is_list(stacktrace) do
|
||||
formatted = Enum.map_join(stacktrace, "\n ", &Exception.format_stacktrace_entry(&1))
|
||||
:elixir_errors.warn([to_chardata(message), ?\n, " ", formatted, ?\n])
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -237,7 +222,7 @@ defmodule IO do
|
||||
#=> (iex) evaluator.ex:108: IEx.Evaluator.eval/4
|
||||
|
||||
"""
|
||||
@spec warn(chardata | String.Chars.t()) :: :ok
|
||||
@spec warn(chardata | String.Chars.t) :: :ok
|
||||
def warn(message) do
|
||||
{:current_stacktrace, stacktrace} = Process.info(self(), :current_stacktrace)
|
||||
warn(message, Enum.drop(stacktrace, 2))
|
||||
@@ -291,9 +276,9 @@ defmodule IO do
|
||||
after: [2, 4, 6]
|
||||
|
||||
"""
|
||||
@spec inspect(item, keyword) :: item when item: var
|
||||
@spec inspect(item, Keyword.t) :: item when item: var
|
||||
def inspect(item, opts \\ []) do
|
||||
inspect(:stdio, item, opts)
|
||||
inspect :stdio, item, opts
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -301,13 +286,12 @@ defmodule IO do
|
||||
|
||||
See `inspect/2` for a full list of options.
|
||||
"""
|
||||
@spec inspect(device, item, keyword) :: item when item: var
|
||||
@spec inspect(device, item, Keyword.t) :: item when item: var
|
||||
def inspect(device, item, opts) when is_list(opts) do
|
||||
label = if label = opts[:label], do: [to_chardata(label), ": "], else: []
|
||||
opts = struct(Inspect.Opts, opts)
|
||||
doc = Inspect.Algebra.group(Inspect.Algebra.to_doc(item, opts))
|
||||
chardata = Inspect.Algebra.format(doc, opts.width)
|
||||
puts(device, [label, chardata])
|
||||
label = if (label = opts[:label]), do: [to_chardata(label), ": "], else: []
|
||||
opts = struct(Inspect.Opts, opts)
|
||||
chardata = Inspect.Algebra.format(Inspect.Algebra.to_doc(item, opts), opts.width)
|
||||
puts device, [label, chardata]
|
||||
item
|
||||
end
|
||||
|
||||
@@ -321,8 +305,8 @@ defmodule IO do
|
||||
See `IO.getn/3` for a description of return values.
|
||||
|
||||
"""
|
||||
@spec getn(chardata | String.Chars.t(), pos_integer) :: chardata | nodata
|
||||
@spec getn(device, chardata | String.Chars.t()) :: chardata | nodata
|
||||
@spec getn(chardata | String.Chars.t, pos_integer) :: chardata | nodata
|
||||
@spec getn(device, chardata | String.Chars.t) :: chardata | nodata
|
||||
def getn(prompt, count \\ 1)
|
||||
|
||||
def getn(prompt, count) when is_integer(count) and count > 0 do
|
||||
@@ -351,7 +335,7 @@ defmodule IO do
|
||||
NFS volume
|
||||
|
||||
"""
|
||||
@spec getn(device, chardata | String.Chars.t(), pos_integer) :: chardata | nodata
|
||||
@spec getn(device, chardata | String.Chars.t, pos_integer) :: chardata | nodata
|
||||
def getn(device, prompt, count) when is_integer(count) and count > 0 do
|
||||
:io.get_chars(map_dev(device), to_chardata(prompt), count)
|
||||
end
|
||||
@@ -377,7 +361,7 @@ defmodule IO do
|
||||
IO.gets "What is your name?\n"
|
||||
|
||||
"""
|
||||
@spec gets(device, chardata | String.Chars.t()) :: chardata | nodata
|
||||
@spec gets(device, chardata | String.Chars.t) :: chardata | nodata
|
||||
def gets(device \\ :stdio, prompt) do
|
||||
:io.get_line(map_dev(device), to_chardata(prompt))
|
||||
end
|
||||
@@ -406,7 +390,7 @@ defmodule IO do
|
||||
Enum.each IO.stream(:stdio, :line), &IO.write(&1)
|
||||
|
||||
"""
|
||||
@spec stream(device, :line | pos_integer) :: Enumerable.t()
|
||||
@spec stream(device, :line | pos_integer) :: Enumerable.t
|
||||
def stream(device, line_or_codepoints)
|
||||
when line_or_codepoints == :line
|
||||
when is_integer(line_or_codepoints) and line_or_codepoints > 0 do
|
||||
@@ -431,7 +415,7 @@ defmodule IO do
|
||||
mode as it will return the wrong result.
|
||||
|
||||
"""
|
||||
@spec binstream(device, :line | pos_integer) :: Enumerable.t()
|
||||
@spec binstream(device, :line | pos_integer) :: Enumerable.t
|
||||
def binstream(device, line_or_bytes)
|
||||
when line_or_bytes == :line
|
||||
when is_integer(line_or_bytes) and line_or_bytes > 0 do
|
||||
@@ -457,7 +441,7 @@ defmodule IO do
|
||||
"string"
|
||||
|
||||
"""
|
||||
@spec chardata_to_string(chardata) :: String.t() | no_return
|
||||
@spec chardata_to_string(chardata) :: String.t | no_return
|
||||
def chardata_to_string(string) when is_binary(string) do
|
||||
string
|
||||
end
|
||||
@@ -519,10 +503,8 @@ defmodule IO do
|
||||
case read(device, line_or_codepoints) do
|
||||
:eof ->
|
||||
{:halt, device}
|
||||
|
||||
{:error, reason} ->
|
||||
raise IO.StreamError, reason: reason
|
||||
|
||||
data ->
|
||||
{[data], device}
|
||||
end
|
||||
@@ -533,10 +515,8 @@ defmodule IO do
|
||||
case binread(device, line_or_chars) do
|
||||
:eof ->
|
||||
{:halt, device}
|
||||
|
||||
{:error, reason} ->
|
||||
raise IO.StreamError, reason: reason
|
||||
|
||||
data ->
|
||||
{[data], device}
|
||||
end
|
||||
@@ -545,7 +525,7 @@ defmodule IO do
|
||||
@compile {:inline, map_dev: 1, to_chardata: 1}
|
||||
|
||||
# Map the Elixir names for standard IO and error to Erlang names
|
||||
defp map_dev(:stdio), do: :standard_io
|
||||
defp map_dev(:stdio), do: :standard_io
|
||||
defp map_dev(:stderr), do: :standard_error
|
||||
defp map_dev(other) when is_atom(other) or is_pid(other) or is_tuple(other), do: other
|
||||
|
||||
|
||||
+44
-45
@@ -25,10 +25,9 @@ defmodule IO.ANSI do
|
||||
|
||||
import IO.ANSI.Sequence
|
||||
|
||||
@type ansicode :: atom
|
||||
@type ansilist ::
|
||||
maybe_improper_list(char | ansicode | binary | ansilist, binary | ansicode | [])
|
||||
@type ansidata :: ansilist | ansicode | binary
|
||||
@typep ansicode :: atom
|
||||
@typep ansilist :: maybe_improper_list(char | ansicode | binary | ansilist, binary | ansicode | [])
|
||||
@type ansidata :: ansilist | ansicode | binary
|
||||
|
||||
@doc """
|
||||
Checks if ANSI coloring is supported and enabled on this machine.
|
||||
@@ -44,7 +43,7 @@ defmodule IO.ANSI do
|
||||
end
|
||||
|
||||
@doc "Sets foreground color."
|
||||
@spec color(0..255) :: String.t()
|
||||
@spec color(0..255) :: String.t
|
||||
def color(code) when code in 0..255, do: "\e[38;5;#{code}m"
|
||||
|
||||
@doc ~S"""
|
||||
@@ -52,13 +51,13 @@ defmodule IO.ANSI do
|
||||
|
||||
Valid values for each color are in the range 0 to 5.
|
||||
"""
|
||||
@spec color(0..5, 0..5, 0..5) :: String.t()
|
||||
@spec color(0..5, 0..5, 0..5) :: String.t
|
||||
def color(r, g, b) when r in 0..5 and g in 0..5 and b in 0..5 do
|
||||
color(16 + 36 * r + 6 * g + b)
|
||||
color(16 + (36 * r) + (6 * g) + b)
|
||||
end
|
||||
|
||||
@doc "Sets background color."
|
||||
@spec color_background(0..255) :: String.t()
|
||||
@spec color_background(0..255) :: String.t
|
||||
def color_background(code) when code in 0..255, do: "\e[48;5;#{code}m"
|
||||
|
||||
@doc ~S"""
|
||||
@@ -66,118 +65,118 @@ defmodule IO.ANSI do
|
||||
|
||||
Valid values for each color are in the range 0 to 5.
|
||||
"""
|
||||
@spec color_background(0..5, 0..5, 0..5) :: String.t()
|
||||
@spec color_background(0..5, 0..5, 0..5) :: String.t
|
||||
def color_background(r, g, b) when r in 0..5 and g in 0..5 and b in 0..5 do
|
||||
color_background(16 + 36 * r + 6 * g + b)
|
||||
color_background(16 + (36 * r) + (6 * g) + b)
|
||||
end
|
||||
|
||||
@doc "Resets all attributes."
|
||||
defsequence(:reset, 0)
|
||||
defsequence :reset, 0
|
||||
|
||||
@doc "Bright (increased intensity) or bold."
|
||||
defsequence(:bright, 1)
|
||||
defsequence :bright, 1
|
||||
|
||||
@doc "Faint (decreased intensity). Not widely supported."
|
||||
defsequence(:faint, 2)
|
||||
defsequence :faint, 2
|
||||
|
||||
@doc "Italic: on. Not widely supported. Sometimes treated as inverse."
|
||||
defsequence(:italic, 3)
|
||||
defsequence :italic, 3
|
||||
|
||||
@doc "Underline: single."
|
||||
defsequence(:underline, 4)
|
||||
defsequence :underline, 4
|
||||
|
||||
@doc "Blink: slow. Less than 150 per minute."
|
||||
defsequence(:blink_slow, 5)
|
||||
defsequence :blink_slow, 5
|
||||
|
||||
@doc "Blink: rapid. MS-DOS ANSI.SYS; 150 per minute or more; not widely supported."
|
||||
defsequence(:blink_rapid, 6)
|
||||
defsequence :blink_rapid, 6
|
||||
|
||||
@doc "Image: negative. Swap foreground and background."
|
||||
defsequence(:inverse, 7)
|
||||
defsequence :inverse, 7
|
||||
|
||||
@doc "Image: negative. Swap foreground and background."
|
||||
defsequence(:reverse, 7)
|
||||
defsequence :reverse, 7
|
||||
|
||||
@doc "Conceal. Not widely supported."
|
||||
defsequence(:conceal, 8)
|
||||
defsequence :conceal, 8
|
||||
|
||||
@doc "Crossed-out. Characters legible, but marked for deletion. Not widely supported."
|
||||
defsequence(:crossed_out, 9)
|
||||
defsequence :crossed_out, 9
|
||||
|
||||
@doc "Sets primary (default) font."
|
||||
defsequence(:primary_font, 10)
|
||||
defsequence :primary_font, 10
|
||||
|
||||
for font_n <- [1, 2, 3, 4, 5, 6, 7, 8, 9] do
|
||||
@doc "Sets alternative font #{font_n}."
|
||||
defsequence(:"font_#{font_n}", font_n + 10)
|
||||
defsequence :"font_#{font_n}", font_n + 10
|
||||
end
|
||||
|
||||
@doc "Normal color or intensity."
|
||||
defsequence(:normal, 22)
|
||||
defsequence :normal, 22
|
||||
|
||||
@doc "Not italic."
|
||||
defsequence(:not_italic, 23)
|
||||
defsequence :not_italic, 23
|
||||
|
||||
@doc "Underline: none."
|
||||
defsequence(:no_underline, 24)
|
||||
defsequence :no_underline, 24
|
||||
|
||||
@doc "Blink: off."
|
||||
defsequence(:blink_off, 25)
|
||||
defsequence :blink_off, 25
|
||||
|
||||
@doc "Image: positive. Normal foreground and background."
|
||||
defsequence(:inverse_off, 27)
|
||||
defsequence :inverse_off, 27
|
||||
|
||||
@doc "Image: positive. Normal foreground and background."
|
||||
defsequence(:reverse_off, 27)
|
||||
defsequence :reverse_off, 27
|
||||
|
||||
colors = [:black, :red, :green, :yellow, :blue, :magenta, :cyan, :white]
|
||||
|
||||
for {color, code} <- Enum.with_index(colors) do
|
||||
@doc "Sets foreground color to #{color}."
|
||||
defsequence(color, code + 30)
|
||||
defsequence color, code + 30
|
||||
|
||||
@doc "Sets foreground color to light #{color}."
|
||||
defsequence(:"light_#{color}", code + 90)
|
||||
defsequence :"light_#{color}", code + 90
|
||||
|
||||
@doc "Sets background color to #{color}."
|
||||
defsequence(:"#{color}_background", code + 40)
|
||||
defsequence :"#{color}_background", code + 40
|
||||
|
||||
@doc "Sets background color to light #{color}."
|
||||
defsequence(:"light_#{color}_background", code + 100)
|
||||
defsequence :"light_#{color}_background", code + 100
|
||||
end
|
||||
|
||||
@doc "Default text color."
|
||||
defsequence(:default_color, 39)
|
||||
defsequence :default_color, 39
|
||||
|
||||
@doc "Default background color."
|
||||
defsequence(:default_background, 49)
|
||||
defsequence :default_background, 49
|
||||
|
||||
@doc "Framed."
|
||||
defsequence(:framed, 51)
|
||||
defsequence :framed, 51
|
||||
|
||||
@doc "Encircled."
|
||||
defsequence(:encircled, 52)
|
||||
defsequence :encircled, 52
|
||||
|
||||
@doc "Overlined."
|
||||
defsequence(:overlined, 53)
|
||||
defsequence :overlined, 53
|
||||
|
||||
@doc "Not framed or encircled."
|
||||
defsequence(:not_framed_encircled, 54)
|
||||
defsequence :not_framed_encircled, 54
|
||||
|
||||
@doc "Not overlined."
|
||||
defsequence(:not_overlined, 55)
|
||||
defsequence :not_overlined, 55
|
||||
|
||||
@doc "Sends cursor home."
|
||||
defsequence(:home, "", "H")
|
||||
defsequence :home, "", "H"
|
||||
|
||||
@doc "Clears screen."
|
||||
defsequence(:clear, "2", "J")
|
||||
defsequence :clear, "2", "J"
|
||||
|
||||
@doc "Clears line."
|
||||
defsequence(:clear_line, "2", "K")
|
||||
defsequence :clear_line, "2", "K"
|
||||
|
||||
defp format_sequence(other) do
|
||||
raise ArgumentError, "invalid ANSI sequence specification: #{inspect(other)}"
|
||||
raise ArgumentError, "invalid ANSI sequence specification: #{inspect other}"
|
||||
end
|
||||
|
||||
@doc ~S"""
|
||||
@@ -244,7 +243,7 @@ defmodule IO.ANSI do
|
||||
end
|
||||
|
||||
defp do_format([], [], acc, true, true) do
|
||||
[acc | IO.ANSI.reset()]
|
||||
[acc | IO.ANSI.reset]
|
||||
end
|
||||
|
||||
defp do_format([], [], acc, _emit?, _append_reset) do
|
||||
|
||||
+67
-131
@@ -2,7 +2,6 @@ defmodule IO.ANSI.Docs do
|
||||
@moduledoc false
|
||||
|
||||
@bullets [?*, ?-, ?+]
|
||||
@spaces [" ", "\n", "\t"]
|
||||
|
||||
@doc """
|
||||
The default options used by this module.
|
||||
@@ -23,17 +22,15 @@ defmodule IO.ANSI.Docs do
|
||||
comma-separated ANSI values.
|
||||
"""
|
||||
def default_options do
|
||||
[
|
||||
enabled: true,
|
||||
doc_bold: [:bright],
|
||||
doc_code: [:cyan],
|
||||
doc_headings: [:yellow],
|
||||
doc_inline_code: [:cyan],
|
||||
doc_table_heading: [:reverse],
|
||||
doc_title: [:reverse, :yellow],
|
||||
doc_underline: [:underline],
|
||||
width: 80
|
||||
]
|
||||
[enabled: true,
|
||||
doc_bold: [:bright],
|
||||
doc_code: [:cyan],
|
||||
doc_headings: [:yellow],
|
||||
doc_inline_code: [:cyan],
|
||||
doc_table_heading: [:reverse],
|
||||
doc_title: [:reverse, :yellow],
|
||||
doc_underline: [:underline],
|
||||
width: 80]
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -42,9 +39,9 @@ defmodule IO.ANSI.Docs do
|
||||
See `default_options/0` for docs on the supported options.
|
||||
"""
|
||||
def print_heading(heading, options \\ []) do
|
||||
IO.puts(IO.ANSI.reset())
|
||||
IO.puts IO.ANSI.reset
|
||||
options = Keyword.merge(default_options(), options)
|
||||
width = options[:width]
|
||||
width = options[:width]
|
||||
padding = div(width + String.length(heading), 2)
|
||||
heading = heading |> String.pad_leading(padding) |> String.pad_trailing(width)
|
||||
write(:doc_title, heading, options)
|
||||
@@ -59,7 +56,6 @@ defmodule IO.ANSI.Docs do
|
||||
"""
|
||||
def print(doc, options \\ []) do
|
||||
options = Keyword.merge(default_options(), options)
|
||||
|
||||
doc
|
||||
|> String.split(["\r\n", "\n"], trim: false)
|
||||
|> Enum.map(&String.trim_trailing/1)
|
||||
@@ -73,23 +69,18 @@ defmodule IO.ANSI.Docs do
|
||||
defp process(["# " <> _ = heading | rest], text, indent, options) do
|
||||
write_heading(heading, rest, text, indent, options)
|
||||
end
|
||||
|
||||
defp process(["## " <> _ = heading | rest], text, indent, options) do
|
||||
write_heading(heading, rest, text, indent, options)
|
||||
end
|
||||
|
||||
defp process(["### " <> _ = heading | rest], text, indent, options) do
|
||||
write_heading(heading, rest, text, indent, options)
|
||||
end
|
||||
|
||||
defp process(["#### " <> _ = heading | rest], text, indent, options) do
|
||||
write_heading(heading, rest, text, indent, options)
|
||||
end
|
||||
|
||||
defp process(["##### " <> _ = heading | rest], text, indent, options) do
|
||||
write_heading(heading, rest, text, indent, options)
|
||||
end
|
||||
|
||||
defp process(["###### " <> _ = heading | rest], text, indent, options) do
|
||||
write_heading(heading, rest, text, indent, options)
|
||||
end
|
||||
@@ -112,18 +103,15 @@ defmodule IO.ANSI.Docs do
|
||||
process_fenced_code_block(rest, text, indent, options, _delimiter = "~~~")
|
||||
end
|
||||
|
||||
defp process(all = [line | rest], text, indent, options) do
|
||||
defp process(all=[line | rest], text, indent, options) do
|
||||
{stripped, count} = strip_spaces(line, 0, :infinity)
|
||||
|
||||
cond do
|
||||
link_label?(stripped, count) ->
|
||||
write_text([line], indent, options, true)
|
||||
process(rest, text, indent, options)
|
||||
|
||||
table_line?(stripped) and rest != [] and table_line?(hd(rest)) ->
|
||||
write_text(text, indent, options)
|
||||
process_table(all, indent, options)
|
||||
|
||||
true ->
|
||||
process_rest(stripped, rest, count, text, indent, options)
|
||||
end
|
||||
@@ -145,15 +133,12 @@ defmodule IO.ANSI.Docs do
|
||||
<<bullet, ?\s, item::binary>> when bullet in @bullets ->
|
||||
write_text(text, indent, options)
|
||||
process_list("• ", item, rest, count, indent, options)
|
||||
|
||||
<<d1, ?., ?\s, item::binary>> when d1 in ?0..?9 ->
|
||||
write_text(text, indent, options)
|
||||
process_list(<<d1, ?., ?\s>>, item, rest, count, indent, options)
|
||||
|
||||
<<d1, d2, ?., ?\s, item::binary>> when d1 in ?0..?9 and d2 in ?0..?9 ->
|
||||
write_text(text, indent, options)
|
||||
process_list(<<d1, d2, ?., ?\s>>, item, rest, count, indent, options)
|
||||
|
||||
_ ->
|
||||
process(rest, [stripped | text], indent, options)
|
||||
end
|
||||
@@ -173,7 +158,6 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
defp process_list_next([line | rest], count, max, acc) do
|
||||
{stripped, next_count} = strip_spaces(line, 0, max)
|
||||
|
||||
case process_list_next_kind(stripped, rest, count, next_count) do
|
||||
:next -> process_list_next(rest, count, max, [stripped | acc])
|
||||
:done -> {Enum.reverse(acc), [line | rest], true}
|
||||
@@ -189,20 +173,14 @@ defmodule IO.ANSI.Docs do
|
||||
case {stripped, rest} do
|
||||
{<<bullet, ?\s, _::binary>>, _} when bullet in @bullets and next_count <= count ->
|
||||
:list
|
||||
|
||||
{<<d1, ?., ?\s, _::binary>>, _} when d1 in ?0..?9 and next_count <= count ->
|
||||
:list
|
||||
|
||||
{<<d1, d2, ?., ?\s, _::binary>>, _}
|
||||
when d1 in ?0..?9 and d2 in ?0..?9 and next_count <= count ->
|
||||
{<<d1, d2, ?., ?\s, _::binary>>, _} when d1 in ?0..?9 and d2 in ?0..?9 and next_count <= count ->
|
||||
:list
|
||||
|
||||
{"", [" " <> _ | _]} ->
|
||||
:next
|
||||
|
||||
{"", _} ->
|
||||
:done
|
||||
|
||||
_ ->
|
||||
:next
|
||||
end
|
||||
@@ -226,7 +204,7 @@ defmodule IO.ANSI.Docs do
|
||||
|> Enum.join(" ")
|
||||
|> handle_links
|
||||
|> handle_inline(options)
|
||||
|> String.split(@spaces)
|
||||
|> String.split(~r{\s})
|
||||
|> write_with_wrap(options[:width] - byte_size(indent), indent, no_wrap)
|
||||
|
||||
unless no_wrap, do: newline_after_block()
|
||||
@@ -285,19 +263,16 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
defp table_lines(lines, options) do
|
||||
lines = Enum.map(lines, &split_into_columns(&1, options))
|
||||
count = Enum.map(lines, &length/1) |> Enum.max()
|
||||
count = Enum.map(lines, &length/1) |> Enum.max
|
||||
lines = Enum.map(lines, &pad_to_number_of_columns(&1, count))
|
||||
|
||||
widths =
|
||||
for line <- lines do
|
||||
if table_header?(line) do
|
||||
for _ <- line, do: 0
|
||||
else
|
||||
for {_col, length} <- line, do: length
|
||||
end
|
||||
end
|
||||
widths = for line <- lines, do:
|
||||
(for {_col, length} <- line, do: length)
|
||||
|
||||
col_widths = Enum.reduce(widths,
|
||||
List.duplicate(0, count),
|
||||
&max_column_widths/2)
|
||||
|
||||
col_widths = Enum.reduce(widths, List.duplicate(0, count), &max_column_widths/2)
|
||||
render_table(lines, col_widths, options)
|
||||
end
|
||||
|
||||
@@ -305,18 +280,15 @@ defmodule IO.ANSI.Docs do
|
||||
line
|
||||
|> String.trim("|")
|
||||
|> String.trim()
|
||||
|> String.split(" | ")
|
||||
|> String.split(~r/\s\|\s/)
|
||||
|> Enum.map(&render_column(&1, options))
|
||||
end
|
||||
|
||||
defp render_column(col, options) do
|
||||
col =
|
||||
col
|
||||
|> String.replace("\\\|", "|")
|
||||
|> String.trim()
|
||||
|> handle_links
|
||||
|> handle_inline(options)
|
||||
|
||||
col = col
|
||||
|> String.replace(~r/\\ \|/x, "|")
|
||||
|> handle_links
|
||||
|> handle_inline(options)
|
||||
{col, length_without_escape(col, 0)}
|
||||
end
|
||||
|
||||
@@ -329,10 +301,7 @@ defmodule IO.ANSI.Docs do
|
||||
# If second line is heading separator, use the heading style on the first
|
||||
defp render_table([first, second | rest], widths, options) do
|
||||
combined = Enum.zip(first, widths)
|
||||
|
||||
if table_header?(second) do
|
||||
alignments = Enum.map(second, &column_alignment/1)
|
||||
options = Keyword.put_new(options, :alignments, alignments)
|
||||
draw_table_row(combined, options, :heading)
|
||||
render_table(rest, widths, options)
|
||||
else
|
||||
@@ -347,60 +316,31 @@ defmodule IO.ANSI.Docs do
|
||||
render_table(rest, widths, options)
|
||||
end
|
||||
|
||||
defp render_table([], _, _), do: nil
|
||||
defp render_table([], _, _),
|
||||
do: nil
|
||||
|
||||
defp column_alignment({line, _}) do
|
||||
cond do
|
||||
String.starts_with?(line, ":") and String.ends_with?(line, ":") -> :center
|
||||
String.ends_with?(line, ":") -> :right
|
||||
true -> :left
|
||||
end
|
||||
end
|
||||
|
||||
defp table_header?(line) do
|
||||
Enum.all?(line, fn {col, _} -> table_header_column?(col) end)
|
||||
end
|
||||
|
||||
defp table_header_column?(":" <> rest), do: table_header_contents?(rest)
|
||||
defp table_header_column?(col), do: table_header_contents?(col)
|
||||
|
||||
defp table_header_contents?("-" <> rest), do: table_header_contents?(rest)
|
||||
defp table_header_contents?(":"), do: true
|
||||
defp table_header_contents?(""), do: true
|
||||
defp table_header_contents?(_), do: false
|
||||
defp table_header?(row), do:
|
||||
Enum.all?(row, fn {col, _} -> col =~ ~r/^:?-+:?$/ end)
|
||||
|
||||
defp draw_table_row(cols_and_widths, options, heading \\ false) do
|
||||
default_alignments = List.duplicate(:left, length(cols_and_widths))
|
||||
alignments = Keyword.get(options, :alignments, default_alignments)
|
||||
|
||||
columns =
|
||||
cols_and_widths
|
||||
|> Enum.zip(alignments)
|
||||
|> Enum.map_join(" | ", &generate_table_cell/1)
|
||||
Enum.map_join(cols_and_widths, " | ", fn {{col, length}, width} ->
|
||||
col <> String.duplicate(" ", width - length)
|
||||
end)
|
||||
|
||||
if heading do
|
||||
write(:doc_table_heading, columns, options)
|
||||
else
|
||||
IO.puts(columns)
|
||||
IO.puts columns
|
||||
end
|
||||
end
|
||||
|
||||
defp generate_table_cell({{{col, length}, width}, :center}) do
|
||||
col
|
||||
|> String.pad_leading(div(width, 2) - div(length, 2) + length)
|
||||
|> String.pad_trailing(width + 1 - rem(width, 2))
|
||||
end
|
||||
|
||||
defp generate_table_cell({{{col, _length}, width}, :right}) do
|
||||
String.pad_leading(col, width)
|
||||
end
|
||||
|
||||
defp generate_table_cell({{{col, _length}, width}, :left}) do
|
||||
String.pad_trailing(col, width)
|
||||
end
|
||||
|
||||
defp table_line?(line) do
|
||||
line =~ " | "
|
||||
Regex.match?(~r'''
|
||||
( ^ \s{0,3} \| (?: [^|]+ \|)+ \s* $ )
|
||||
|
|
||||
(\s \| \s)
|
||||
'''x, line)
|
||||
end
|
||||
|
||||
## Helpers
|
||||
@@ -413,11 +353,13 @@ defmodule IO.ANSI.Docs do
|
||||
defp link_label?(""), do: false
|
||||
defp link_label?(<<_>> <> rest), do: link_label?(rest)
|
||||
|
||||
defp strip_spaces(" " <> line, acc, max) when acc < max, do: strip_spaces(line, acc + 1, max)
|
||||
defp strip_spaces(rest, acc, _max), do: {rest, acc}
|
||||
defp strip_spaces(" " <> line, acc, max) when acc < max,
|
||||
do: strip_spaces(line, acc + 1, max)
|
||||
defp strip_spaces(rest, acc, _max),
|
||||
do: {rest, acc}
|
||||
|
||||
defp write(style, string, options) do
|
||||
IO.puts([color(style, options), string, IO.ANSI.reset()])
|
||||
IO.puts [color(style, options), string, IO.ANSI.reset]
|
||||
end
|
||||
|
||||
defp write_with_wrap([], _available, _indent, _first) do
|
||||
@@ -426,7 +368,7 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
defp write_with_wrap(words, available, indent, first) do
|
||||
{words, rest} = take_words(words, available, [])
|
||||
IO.puts(if(first, do: "", else: indent) <> Enum.join(words, " "))
|
||||
IO.puts (if first, do: "", else: indent) <> Enum.join(words, " ")
|
||||
write_with_wrap(rest, available, indent, false)
|
||||
end
|
||||
|
||||
@@ -474,17 +416,14 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp escape_underlines_in_link(text) do
|
||||
~r{https?\S*}
|
||||
|> Regex.recompile!()
|
||||
|> Regex.replace(text, &String.replace(&1, "_", "\\_"))
|
||||
Regex.replace(~r{https?\S*}, text, &String.replace(&1, "_", "\\_"))
|
||||
end
|
||||
|
||||
defp remove_square_brackets_in_link(text) do
|
||||
~r{\[(.*?)\]\((.*?)\)}
|
||||
|> Regex.recompile!()
|
||||
|> Regex.replace(text, "\\1 (\\2)")
|
||||
Regex.replace(~r{\[(.*?)\]\((.*?)\)}, text, "\\1 (\\2)")
|
||||
end
|
||||
|
||||
|
||||
# We have four entries: **, *, _ and `.
|
||||
#
|
||||
# The first three behave the same while the last one is simpler
|
||||
@@ -500,8 +439,7 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
# Characters that can mark the beginning or the end of a word.
|
||||
# Only support the most common ones at this moment.
|
||||
@delimiters [?\s, ?', ?", ?!, ?@, ?#, ?$, ?%, ?^, ?&] ++
|
||||
[?-, ?+, ?(, ?), ?[, ?], ?{, ?}, ?<, ?>, ?.]
|
||||
@delimiters [?\s, ?', ?", ?!, ?@, ?#, ?$, ?%, ?^, ?&, ?-, ?+, ?(, ?), ?[, ?], ?{, ?}, ?<, ?>, ?.]
|
||||
|
||||
# Inline start
|
||||
|
||||
@@ -520,29 +458,29 @@ defmodule IO.ANSI.Docs do
|
||||
# Inline delimiters
|
||||
|
||||
defp handle_inline(<<delimiter, ?*, ?*, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" and delimiter in @delimiters do
|
||||
when rest != "" and delimiter in @delimiters do
|
||||
handle_inline(rest, ?d, ["**"], [delimiter, Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<delimiter, mark, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" and delimiter in @delimiters and mark in @single do
|
||||
when rest != "" and delimiter in @delimiters and mark in @single do
|
||||
handle_inline(rest, mark, [<<mark>>], [delimiter, Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<?`, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" do
|
||||
when rest != "" do
|
||||
handle_inline(rest, ?`, ["`"], [Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
# Clauses for handling escape
|
||||
|
||||
defp handle_inline(<<?\\, ?\\, ?*, ?*, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" do
|
||||
when rest != "" do
|
||||
handle_inline(rest, ?d, ["**"], [?\\, Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<?\\, ?\\, mark, rest::binary>>, nil, buffer, acc, options)
|
||||
when rest != "" and mark in @single do
|
||||
when rest != "" and mark in @single do
|
||||
handle_inline(rest, mark, [<<mark>>], [?\\, Enum.reverse(buffer) | acc], options)
|
||||
end
|
||||
|
||||
@@ -552,31 +490,29 @@ defmodule IO.ANSI.Docs do
|
||||
|
||||
# An escape is not valid inside `
|
||||
defp handle_inline(<<?\\, mark, rest::binary>>, limit, buffer, acc, options)
|
||||
when not (mark == limit and mark == ?`) do
|
||||
when not(mark == limit and mark == ?`) do
|
||||
handle_inline(rest, limit, [mark | buffer], acc, options)
|
||||
end
|
||||
|
||||
# Inline end
|
||||
|
||||
defp handle_inline(<<?*, ?*, delimiter, rest::binary>>, ?d, buffer, acc, options)
|
||||
when delimiter in @delimiters do
|
||||
inline_buffer = inline_buffer(buffer, options)
|
||||
handle_inline(<<delimiter, rest::binary>>, nil, [], [inline_buffer | acc], options)
|
||||
when delimiter in @delimiters do
|
||||
handle_inline(<<delimiter, rest::binary>>, nil, [], [inline_buffer(buffer, options) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<mark, delimiter, rest::binary>>, mark, buffer, acc, options)
|
||||
when delimiter in @delimiters and mark in @single do
|
||||
inline_buffer = inline_buffer(buffer, options)
|
||||
handle_inline(<<delimiter, rest::binary>>, nil, [], [inline_buffer | acc], options)
|
||||
when delimiter in @delimiters and mark in @single do
|
||||
handle_inline(<<delimiter, rest::binary>>, nil, [], [inline_buffer(buffer, options) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<?*, ?*, rest::binary>>, ?d, buffer, acc, options)
|
||||
when rest == "" do
|
||||
when rest == "" do
|
||||
handle_inline(<<>>, nil, [], [inline_buffer(buffer, options) | acc], options)
|
||||
end
|
||||
|
||||
defp handle_inline(<<mark, rest::binary>>, mark, buffer, acc, options)
|
||||
when rest == "" and mark in @single do
|
||||
when rest == "" and mark in @single do
|
||||
handle_inline(<<>>, nil, [], [inline_buffer(buffer, options) | acc], options)
|
||||
end
|
||||
|
||||
@@ -591,19 +527,19 @@ defmodule IO.ANSI.Docs do
|
||||
end
|
||||
|
||||
defp handle_inline(<<>>, _mark, buffer, acc, _options) do
|
||||
IO.iodata_to_binary(Enum.reverse([Enum.reverse(buffer) | acc]))
|
||||
IO.iodata_to_binary Enum.reverse([Enum.reverse(buffer) | acc])
|
||||
end
|
||||
|
||||
defp inline_buffer(buffer, options) do
|
||||
[h | t] = Enum.reverse([IO.ANSI.reset() | buffer])
|
||||
[h | t] = Enum.reverse([IO.ANSI.reset | buffer])
|
||||
[color_for(h, options) | t]
|
||||
end
|
||||
|
||||
defp color_for(mark, colors) do
|
||||
case mark do
|
||||
"`" -> color(:doc_inline_code, colors)
|
||||
"_" -> color(:doc_underline, colors)
|
||||
"*" -> color(:doc_bold, colors)
|
||||
"`" -> color(:doc_inline_code, colors)
|
||||
"_" -> color(:doc_underline, colors)
|
||||
"*" -> color(:doc_bold, colors)
|
||||
"**" -> color(:doc_bold, colors)
|
||||
end
|
||||
end
|
||||
@@ -613,5 +549,5 @@ defmodule IO.ANSI.Docs do
|
||||
IO.ANSI.format_fragment(color, colors[:enabled])
|
||||
end
|
||||
|
||||
defp newline_after_block, do: IO.puts(IO.ANSI.reset())
|
||||
defp newline_after_block, do: IO.puts(IO.ANSI.reset)
|
||||
end
|
||||
|
||||
@@ -2,7 +2,7 @@ defmodule IO.StreamError do
|
||||
defexception [:reason, :message]
|
||||
|
||||
def exception(opts) do
|
||||
reason = opts[:reason]
|
||||
reason = opts[:reason]
|
||||
formatted = IO.iodata_to_binary(:file.format_error(reason))
|
||||
%IO.StreamError{message: "error during streaming: #{formatted}", reason: reason}
|
||||
end
|
||||
@@ -16,7 +16,7 @@ defmodule IO.Stream do
|
||||
|
||||
* `device` - the IO device
|
||||
* `raw` - a boolean indicating if bin functions should be used
|
||||
* `line_or_bytes` - if reading should read lines or a given number of bytes
|
||||
* `line_or_bytes` - if reading should read lines or a given amount of bytes
|
||||
|
||||
It is worth noting that an IO stream has side effects and every time you go
|
||||
over the stream you may get different results.
|
||||
@@ -41,12 +41,10 @@ defmodule IO.Stream do
|
||||
fn
|
||||
:ok, {:cont, x} ->
|
||||
case raw do
|
||||
true -> IO.binwrite(device, x)
|
||||
true -> IO.binwrite(device, x)
|
||||
false -> IO.write(device, x)
|
||||
end
|
||||
|
||||
:ok, _ ->
|
||||
stream
|
||||
:ok, _ -> stream
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -55,11 +53,10 @@ defmodule IO.Stream do
|
||||
def reduce(%{device: device, raw: raw, line_or_bytes: line_or_bytes}, acc, fun) do
|
||||
next_fun =
|
||||
case raw do
|
||||
true -> &IO.each_binstream(&1, line_or_bytes)
|
||||
true -> &IO.each_binstream(&1, line_or_bytes)
|
||||
false -> &IO.each_stream(&1, line_or_bytes)
|
||||
end
|
||||
|
||||
Stream.resource(fn -> device end, next_fun, & &1).(acc, fun)
|
||||
Stream.resource(fn -> device end, next_fun, &(&1)).(acc, fun)
|
||||
end
|
||||
|
||||
def count(_stream) do
|
||||
@@ -69,9 +66,5 @@ defmodule IO.Stream do
|
||||
def member?(_stream, _term) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
|
||||
def slice(_stream) do
|
||||
{:error, __MODULE__}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+466
-1173
File diff suppressed because it is too large
Load Diff
+86
-154
@@ -1,17 +1,9 @@
|
||||
defmodule Kernel.CLI do
|
||||
@moduledoc false
|
||||
|
||||
@blank_config %{
|
||||
commands: [],
|
||||
output: ".",
|
||||
compile: [],
|
||||
halt: true,
|
||||
compiler_options: [],
|
||||
errors: [],
|
||||
pa: [],
|
||||
pz: [],
|
||||
verbose_compile: false
|
||||
}
|
||||
@blank_config %{commands: [], output: ".", compile: [],
|
||||
halt: true, compiler_options: [], errors: [],
|
||||
pa: [], pz: [], verbose_compile: false}
|
||||
|
||||
@doc """
|
||||
This is the API invoked by Elixir boot process.
|
||||
@@ -22,16 +14,14 @@ defmodule Kernel.CLI do
|
||||
{config, argv} = parse_argv(argv)
|
||||
System.argv(argv)
|
||||
|
||||
fun = fn _ ->
|
||||
run fn _ ->
|
||||
errors = process_commands(config)
|
||||
|
||||
if errors != [] do
|
||||
Enum.each(errors, &IO.puts(:stderr, &1))
|
||||
System.halt(1)
|
||||
end
|
||||
end
|
||||
|
||||
run(fun, config.halt)
|
||||
end, config.halt
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -44,7 +34,6 @@ defmodule Kernel.CLI do
|
||||
"""
|
||||
def run(fun, halt \\ true) do
|
||||
{ok_or_shutdown, status} = exec_fun(fun, {:ok, 0})
|
||||
|
||||
if ok_or_shutdown == :shutdown or halt do
|
||||
{_, status} = at_exit({ok_or_shutdown, status})
|
||||
|
||||
@@ -66,28 +55,10 @@ defmodule Kernel.CLI do
|
||||
@doc false
|
||||
def process_commands(config) do
|
||||
results = Enum.map(Enum.reverse(config.commands), &process_command(&1, config))
|
||||
errors = for {:error, msg} <- results, do: msg
|
||||
errors = for {:error, msg} <- results, do: msg
|
||||
Enum.reverse(config.errors, errors)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def format_error(kind, reason, stacktrace) do
|
||||
{blamed, stacktrace} = Exception.blame(kind, reason, stacktrace)
|
||||
|
||||
iodata =
|
||||
case blamed do
|
||||
%FunctionClauseError{} ->
|
||||
formatted = Exception.format_banner(kind, reason, stacktrace)
|
||||
padded_blame = pad(FunctionClauseError.blame(blamed, &inspect/1, &blame_match/2))
|
||||
[formatted, padded_blame]
|
||||
|
||||
_ ->
|
||||
Exception.format_banner(kind, blamed, stacktrace)
|
||||
end
|
||||
|
||||
[iodata, ?\n, Exception.format_stacktrace(prune_stacktrace(stacktrace))]
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
defp at_exit(res) do
|
||||
@@ -105,24 +76,22 @@ defmodule Kernel.CLI do
|
||||
fun.(elem(res, 1))
|
||||
catch
|
||||
:exit, {:shutdown, int} when is_integer(int) ->
|
||||
send(parent, {self(), {:shutdown, int}})
|
||||
send parent, {self(), {:shutdown, int}}
|
||||
exit({:shutdown, int})
|
||||
|
||||
:exit, reason
|
||||
when reason == :normal
|
||||
when reason == :shutdown
|
||||
when tuple_size(reason) == 2 and elem(reason, 0) == :shutdown ->
|
||||
send(parent, {self(), {:shutdown, 0}})
|
||||
when reason == :normal
|
||||
when reason == :shutdown
|
||||
when tuple_size(reason) == 2 and elem(reason, 0) == :shutdown ->
|
||||
send parent, {self(), {:shutdown, 0}}
|
||||
exit(reason)
|
||||
|
||||
kind, reason ->
|
||||
stack = System.stacktrace()
|
||||
stack = System.stacktrace
|
||||
print_error(kind, reason, stack)
|
||||
send(parent, {self(), {:shutdown, 1}})
|
||||
send parent, {self(), {:shutdown, 1}}
|
||||
exit(to_exit(kind, reason, stack))
|
||||
else
|
||||
_ ->
|
||||
send(parent, {self(), res})
|
||||
send parent, {self(), res}
|
||||
end
|
||||
end)
|
||||
|
||||
@@ -130,7 +99,6 @@ defmodule Kernel.CLI do
|
||||
{^pid, res} ->
|
||||
:erlang.demonitor(ref, [:flush])
|
||||
res
|
||||
|
||||
{:DOWN, ^ref, _, _, other} ->
|
||||
print_error({:EXIT, pid}, other, [])
|
||||
{:shutdown, 1}
|
||||
@@ -146,39 +114,18 @@ defmodule Kernel.CLI do
|
||||
{[h | hs], _} when h == hd(list) ->
|
||||
new_config = %{config | errors: ["#{h} : Unknown option" | config.errors]}
|
||||
callback.(hs, new_config)
|
||||
|
||||
{new_list, new_config} ->
|
||||
callback.(new_list, new_config)
|
||||
end
|
||||
end
|
||||
|
||||
## Error handling
|
||||
|
||||
defp print_error(kind, reason, stacktrace) do
|
||||
IO.write(:stderr, format_error(kind, reason, stacktrace))
|
||||
defp print_error(kind, reason, trace) do
|
||||
IO.puts :stderr, Exception.format(kind, reason, prune_stacktrace(trace))
|
||||
end
|
||||
|
||||
defp blame_match(%{match?: true, node: node}, _), do: blame_ansi(:normal, "+", node)
|
||||
defp blame_match(%{match?: false, node: node}, _), do: blame_ansi(:red, "-", node)
|
||||
defp blame_match(_, string), do: string
|
||||
|
||||
defp blame_ansi(color, no_ansi, node) do
|
||||
if IO.ANSI.enabled?() do
|
||||
[color | Macro.to_string(node)]
|
||||
|> IO.ANSI.format(true)
|
||||
|> IO.iodata_to_binary()
|
||||
else
|
||||
no_ansi <> Macro.to_string(node) <> no_ansi
|
||||
end
|
||||
end
|
||||
|
||||
defp pad(string) do
|
||||
" " <> String.replace(string, "\n", "\n ")
|
||||
end
|
||||
|
||||
@elixir_internals [:elixir, :elixir_expand, :elixir_compiler, :elixir_module] ++
|
||||
[:elixir_clauses, :elixir_lexical, :elixir_def, :elixir_map] ++
|
||||
[:elixir_erl, :elixir_erl_clauses, :elixir_erl_pass, Kernel.ErrorHandler]
|
||||
@elixir_internals [:elixir, :elixir_exp, :elixir_compiler, :elixir_module, :elixir_clauses,
|
||||
:elixir_translator, :elixir_expand, :elixir_lexical, :elixir_exp_clauses,
|
||||
:elixir_def, :elixir_map]
|
||||
|
||||
defp prune_stacktrace([{mod, _, _, _} | t]) when mod in @elixir_internals do
|
||||
prune_stacktrace(t)
|
||||
@@ -199,59 +146,54 @@ defmodule Kernel.CLI do
|
||||
# Parse shared options
|
||||
|
||||
defp parse_shared([opt | _t], _config) when opt in ["-v", "--version"] do
|
||||
if function_exported?(IEx, :started?, 0) and IEx.started?() do
|
||||
IO.puts("IEx " <> System.build_info()[:build])
|
||||
if function_exported?(IEx, :started?, 0) and IEx.started? do
|
||||
IO.puts "IEx " <> System.build_info[:build]
|
||||
else
|
||||
IO.puts(:erlang.system_info(:system_version))
|
||||
IO.puts("Elixir " <> System.build_info()[:build])
|
||||
IO.puts :erlang.system_info(:system_version)
|
||||
IO.puts "Elixir " <> System.build_info[:build]
|
||||
end
|
||||
|
||||
System.halt(0)
|
||||
System.halt 0
|
||||
end
|
||||
|
||||
defp parse_shared(["-pa", h | t], config) do
|
||||
paths = expand_code_path(h)
|
||||
Enum.each(paths, &:code.add_patha/1)
|
||||
parse_shared(t, %{config | pa: config.pa ++ paths})
|
||||
parse_shared t, %{config | pa: config.pa ++ paths}
|
||||
end
|
||||
|
||||
defp parse_shared(["-pz", h | t], config) do
|
||||
paths = expand_code_path(h)
|
||||
Enum.each(paths, &:code.add_pathz/1)
|
||||
parse_shared(t, %{config | pz: config.pz ++ paths})
|
||||
parse_shared t, %{config | pz: config.pz ++ paths}
|
||||
end
|
||||
|
||||
defp parse_shared(["--app", h | t], config) do
|
||||
parse_shared(t, %{config | commands: [{:app, h} | config.commands]})
|
||||
parse_shared t, %{config | commands: [{:app, h} | config.commands]}
|
||||
end
|
||||
|
||||
defp parse_shared(["--no-halt" | t], config) do
|
||||
parse_shared(t, %{config | halt: false})
|
||||
parse_shared t, %{config | halt: false}
|
||||
end
|
||||
|
||||
defp parse_shared(["-e", h | t], config) do
|
||||
parse_shared(t, %{config | commands: [{:eval, h} | config.commands]})
|
||||
parse_shared t, %{config | commands: [{:eval, h} | config.commands]}
|
||||
end
|
||||
|
||||
defp parse_shared(["-r", h | t], config) do
|
||||
parse_shared(t, %{config | commands: [{:require, h} | config.commands]})
|
||||
parse_shared t, %{config | commands: [{:require, h} | config.commands]}
|
||||
end
|
||||
|
||||
defp parse_shared(["-pr", h | t], config) do
|
||||
parse_shared(t, %{config | commands: [{:parallel_require, h} | config.commands]})
|
||||
parse_shared t, %{config | commands: [{:parallel_require, h} | config.commands]}
|
||||
end
|
||||
|
||||
@erl_arg_options ["--erl", "--sname", "--name", "--cookie"] ++
|
||||
["--logger-otp-reports", "--logger-sasl-reports"]
|
||||
|
||||
@erl_boolean_options ["--detached", "--hidden", "--werl"]
|
||||
|
||||
defp parse_shared([erl, _ | t], config) when erl in @erl_arg_options do
|
||||
parse_shared(t, config)
|
||||
defp parse_shared([erl, _ | t], config) when erl in ["--erl", "--sname", "--name", "--cookie", "--logger-otp-reports", "--logger-sasl-reports"] do
|
||||
parse_shared t, config
|
||||
end
|
||||
|
||||
defp parse_shared([erl | t], config) when erl in @erl_boolean_options do
|
||||
parse_shared(t, config)
|
||||
defp parse_shared([erl | t], config) when erl in ["--detached", "--hidden", "--werl"] do
|
||||
parse_shared t, config
|
||||
end
|
||||
|
||||
defp parse_shared(list, config) do
|
||||
@@ -260,9 +202,8 @@ defmodule Kernel.CLI do
|
||||
|
||||
defp expand_code_path(path) do
|
||||
path = Path.expand(path)
|
||||
|
||||
case Path.wildcard(path) do
|
||||
[] -> [to_charlist(path)]
|
||||
[] -> [to_charlist(path)]
|
||||
list -> Enum.map(list, &to_charlist/1)
|
||||
end
|
||||
end
|
||||
@@ -274,11 +215,11 @@ defmodule Kernel.CLI do
|
||||
end
|
||||
|
||||
defp parse_argv(["+elixirc" | t], config) do
|
||||
parse_compiler(t, config)
|
||||
parse_compiler t, config
|
||||
end
|
||||
|
||||
defp parse_argv(["+iex" | t], config) do
|
||||
parse_iex(t, config)
|
||||
parse_iex t, config
|
||||
end
|
||||
|
||||
defp parse_argv(["-S", h | t], config) do
|
||||
@@ -288,8 +229,7 @@ defmodule Kernel.CLI do
|
||||
defp parse_argv([h | t] = list, config) do
|
||||
case h do
|
||||
"-" <> _ ->
|
||||
shared_option?(list, config, &parse_argv(&1, &2))
|
||||
|
||||
shared_option? list, config, &parse_argv(&1, &2)
|
||||
_ ->
|
||||
if Keyword.has_key?(config.commands, :eval) do
|
||||
{config, list}
|
||||
@@ -310,40 +250,36 @@ defmodule Kernel.CLI do
|
||||
end
|
||||
|
||||
defp parse_compiler(["-o", h | t], config) do
|
||||
parse_compiler(t, %{config | output: h})
|
||||
parse_compiler t, %{config | output: h}
|
||||
end
|
||||
|
||||
defp parse_compiler(["--no-docs" | t], config) do
|
||||
parse_compiler(t, %{config | compiler_options: [{:docs, false} | config.compiler_options]})
|
||||
parse_compiler t, %{config | compiler_options: [{:docs, false} | config.compiler_options]}
|
||||
end
|
||||
|
||||
defp parse_compiler(["--no-debug-info" | t], config) do
|
||||
compiler_options = [{:debug_info, false} | config.compiler_options]
|
||||
parse_compiler(t, %{config | compiler_options: compiler_options})
|
||||
parse_compiler t, %{config | compiler_options: [{:debug_info, false} | config.compiler_options]}
|
||||
end
|
||||
|
||||
defp parse_compiler(["--ignore-module-conflict" | t], config) do
|
||||
compiler_options = [{:ignore_module_conflict, true} | config.compiler_options]
|
||||
parse_compiler(t, %{config | compiler_options: compiler_options})
|
||||
parse_compiler t, %{config | compiler_options: [{:ignore_module_conflict, true} | config.compiler_options]}
|
||||
end
|
||||
|
||||
defp parse_compiler(["--warnings-as-errors" | t], config) do
|
||||
compiler_options = [{:warnings_as_errors, true} | config.compiler_options]
|
||||
parse_compiler(t, %{config | compiler_options: compiler_options})
|
||||
parse_compiler t, %{config | compiler_options: [{:warnings_as_errors, true} | config.compiler_options]}
|
||||
end
|
||||
|
||||
defp parse_compiler(["--verbose" | t], config) do
|
||||
parse_compiler(t, %{config | verbose_compile: true})
|
||||
parse_compiler t, %{config | verbose_compile: true}
|
||||
end
|
||||
|
||||
defp parse_compiler([h | t] = list, config) do
|
||||
case h do
|
||||
"-" <> _ ->
|
||||
shared_option?(list, config, &parse_compiler(&1, &2))
|
||||
|
||||
shared_option? list, config, &parse_compiler(&1, &2)
|
||||
_ ->
|
||||
pattern = if File.dir?(h), do: "#{h}/**/*.ex", else: h
|
||||
parse_compiler(t, %{config | compile: [pattern | config.compile]})
|
||||
parse_compiler t, %{config | compile: [pattern | config.compile]}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -360,11 +296,11 @@ defmodule Kernel.CLI do
|
||||
# This clause is here so that Kernel.CLI does not
|
||||
# error out with "unknown option"
|
||||
defp parse_iex(["--dot-iex", _ | t], config) do
|
||||
parse_iex(t, config)
|
||||
parse_iex t, config
|
||||
end
|
||||
|
||||
defp parse_iex([opt, _ | t], config) when opt in ["--remsh"] do
|
||||
parse_iex(t, config)
|
||||
parse_iex t, config
|
||||
end
|
||||
|
||||
defp parse_iex(["-S", h | t], config) do
|
||||
@@ -373,8 +309,10 @@ defmodule Kernel.CLI do
|
||||
|
||||
defp parse_iex([h | t] = list, config) do
|
||||
case h do
|
||||
"-" <> _ -> shared_option?(list, config, &parse_iex(&1, &2))
|
||||
_ -> {%{config | commands: [{:file, h} | config.commands]}, t}
|
||||
"-" <> _ ->
|
||||
shared_option? list, config, &parse_iex(&1, &2)
|
||||
_ ->
|
||||
{%{config | commands: [{:file, h} | config.commands]}, t}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -385,23 +323,22 @@ defmodule Kernel.CLI do
|
||||
# Process commands
|
||||
|
||||
defp process_command({:cookie, h}, _config) do
|
||||
if Node.alive?() do
|
||||
wrapper(fn -> Node.set_cookie(String.to_atom(h)) end)
|
||||
if Node.alive? do
|
||||
wrapper fn -> Node.set_cookie(String.to_atom(h)) end
|
||||
else
|
||||
{:error, "--cookie : Cannot set cookie if the node is not alive (set --name or --sname)"}
|
||||
end
|
||||
end
|
||||
|
||||
defp process_command({:eval, expr}, _config) when is_binary(expr) do
|
||||
wrapper(fn -> Code.eval_string(expr, []) end)
|
||||
wrapper fn -> Code.eval_string(expr, []) end
|
||||
end
|
||||
|
||||
defp process_command({:app, app}, _config) when is_binary(app) do
|
||||
case Application.ensure_all_started(String.to_atom(app)) do
|
||||
{:error, {app, reason}} ->
|
||||
msg = "--app : Could not start application #{app}: " <> Application.format_error(reason)
|
||||
{:error, msg}
|
||||
|
||||
{:error, "--app : Could not start application #{app}: " <>
|
||||
Application.format_error(reason)}
|
||||
{:ok, _} ->
|
||||
:ok
|
||||
end
|
||||
@@ -409,7 +346,7 @@ defmodule Kernel.CLI do
|
||||
|
||||
defp process_command({:script, file}, _config) when is_binary(file) do
|
||||
if exec = find_elixir_executable(file) do
|
||||
wrapper(fn -> Code.require_file(exec) end)
|
||||
wrapper fn -> Code.require_file(exec) end
|
||||
else
|
||||
{:error, "-S : Could not find executable #{file}"}
|
||||
end
|
||||
@@ -417,7 +354,7 @@ defmodule Kernel.CLI do
|
||||
|
||||
defp process_command({:file, file}, _config) when is_binary(file) do
|
||||
if File.regular?(file) do
|
||||
wrapper(fn -> Code.require_file(file) end)
|
||||
wrapper fn -> Code.require_file(file) end
|
||||
else
|
||||
{:error, "No file named #{file}"}
|
||||
end
|
||||
@@ -427,7 +364,7 @@ defmodule Kernel.CLI do
|
||||
files = filter_patterns(pattern)
|
||||
|
||||
if files != [] do
|
||||
wrapper(fn -> Enum.map(files, &Code.require_file(&1)) end)
|
||||
wrapper fn -> Enum.map files, &Code.require_file(&1) end
|
||||
else
|
||||
{:error, "-r : No files matched pattern #{pattern}"}
|
||||
end
|
||||
@@ -437,12 +374,7 @@ defmodule Kernel.CLI do
|
||||
files = filter_patterns(pattern)
|
||||
|
||||
if files != [] do
|
||||
wrapper(fn ->
|
||||
case Kernel.ParallelCompiler.require(files) do
|
||||
{:ok, _, _} -> :ok
|
||||
{:error, _, _} -> exit({:shutdown, 1})
|
||||
end
|
||||
end)
|
||||
wrapper fn -> Kernel.ParallelRequire.files(files) end
|
||||
else
|
||||
{:error, "-pr : No files matched pattern #{pattern}"}
|
||||
end
|
||||
@@ -455,24 +387,17 @@ defmodule Kernel.CLI do
|
||||
case filter_multiple_patterns(patterns) do
|
||||
{:ok, []} ->
|
||||
{:error, "No files matched provided patterns"}
|
||||
|
||||
{:ok, files} ->
|
||||
wrapper(fn ->
|
||||
wrapper fn ->
|
||||
Code.compiler_options(config.compiler_options)
|
||||
|
||||
opts =
|
||||
if config.verbose_compile do
|
||||
[each_long_compilation: &IO.puts("Compiling #{&1} (it's taking more than 15s)")]
|
||||
[each_long_compilation: &IO.puts("Compiling #{&1} (it's taking more than 5s)")]
|
||||
else
|
||||
[]
|
||||
end
|
||||
|
||||
case Kernel.ParallelCompiler.compile_to_path(files, config.output, opts) do
|
||||
{:ok, _, _} -> :ok
|
||||
{:error, _, _} -> exit({:shutdown, 1})
|
||||
end
|
||||
end)
|
||||
|
||||
Kernel.ParallelCompiler.files_to_path(files, config.output, opts)
|
||||
end
|
||||
{:missing, missing} ->
|
||||
{:error, "No files matched pattern(s) #{Enum.join(missing, ",")}"}
|
||||
end
|
||||
@@ -480,23 +405,31 @@ defmodule Kernel.CLI do
|
||||
|
||||
defp filter_patterns(pattern) do
|
||||
pattern
|
||||
|> Path.wildcard()
|
||||
|> :lists.usort()
|
||||
|> Path.wildcard
|
||||
|> :lists.usort
|
||||
|> Enum.filter(&File.regular?/1)
|
||||
end
|
||||
|
||||
defp filter_multiple_patterns(patterns) do
|
||||
{files, missing} =
|
||||
Enum.reduce(patterns, {[], []}, fn pattern, {files, missing} ->
|
||||
case filter_patterns(pattern) do
|
||||
[] -> {files, [pattern | missing]}
|
||||
match -> {match ++ files, missing}
|
||||
end
|
||||
end)
|
||||
matched_files = Enum.map patterns, fn(pattern) ->
|
||||
case filter_patterns(pattern) do
|
||||
[] -> {:missing, pattern}
|
||||
files -> {:ok, files}
|
||||
end
|
||||
end
|
||||
|
||||
case missing do
|
||||
[] -> {:ok, :lists.usort(files)}
|
||||
_ -> {:missing, :lists.usort(missing)}
|
||||
files = Enum.filter_map matched_files,
|
||||
fn(match) -> elem(match, 0) == :ok end,
|
||||
&elem(&1, 1)
|
||||
|
||||
missing_patterns = Enum.filter_map matched_files,
|
||||
fn(match) -> elem(match, 0) == :missing end,
|
||||
&elem(&1, 1)
|
||||
|
||||
if missing_patterns == [] do
|
||||
{:ok, :lists.usort(Enum.concat(files))}
|
||||
else
|
||||
{:missing, :lists.usort(missing_patterns)}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -514,7 +447,6 @@ defmodule Kernel.CLI do
|
||||
{:win32, _} ->
|
||||
base = Path.rootname(exec)
|
||||
if File.regular?(base), do: base, else: exec
|
||||
|
||||
_ ->
|
||||
exec
|
||||
end
|
||||
|
||||
@@ -31,12 +31,11 @@ defmodule Kernel.ErrorHandler do
|
||||
|
||||
def ensure_compiled(module, kind) do
|
||||
parent = :erlang.get(:elixir_compiler_pid)
|
||||
ref = :erlang.make_ref()
|
||||
send(parent, {:waiting, kind, self(), ref, module, :elixir_module.compiler_modules()})
|
||||
ref = :erlang.make_ref
|
||||
send parent, {:waiting, kind, self(), ref, module, :elixir_module.compiler_modules()}
|
||||
:erlang.garbage_collect(self())
|
||||
|
||||
receive do
|
||||
{^ref, :found} -> true
|
||||
{^ref, :found} -> true
|
||||
{^ref, :not_found} -> false
|
||||
end
|
||||
end
|
||||
|
||||
@@ -6,7 +6,7 @@
|
||||
# any of the `GenServer.Behaviour` conveniences.
|
||||
defmodule Kernel.LexicalTracker do
|
||||
@moduledoc false
|
||||
@timeout 30000
|
||||
@timeout 30_000
|
||||
@behaviour :gen_server
|
||||
|
||||
@doc """
|
||||
@@ -31,8 +31,7 @@ defmodule Kernel.LexicalTracker do
|
||||
:gen_server.call(to_pid(arg), :dest, @timeout)
|
||||
end
|
||||
|
||||
defp to_pid(pid) when is_pid(pid), do: pid
|
||||
|
||||
defp to_pid(pid) when is_pid(pid), do: pid
|
||||
defp to_pid(mod) when is_atom(mod) do
|
||||
table = :elixir_module.data_table(mod)
|
||||
[{_, val}] = :ets.lookup(table, {:elixir, :lexical_tracker})
|
||||
@@ -72,11 +71,6 @@ defmodule Kernel.LexicalTracker do
|
||||
:gen_server.cast(pid, {:remote_dispatch, module, fa, line, mode})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def remote_struct(pid, module, line) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:remote_struct, module, line})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def import_dispatch(pid, module, fa, line, mode) when is_atom(module) do
|
||||
:gen_server.cast(pid, {:import_dispatch, module, fa, line, mode})
|
||||
@@ -87,28 +81,6 @@ defmodule Kernel.LexicalTracker do
|
||||
:gen_server.cast(pid, {:alias_dispatch, module})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def set_file(pid, file) do
|
||||
:gen_server.cast(pid, {:set_file, file})
|
||||
end
|
||||
|
||||
@doc false
|
||||
def reset_file(pid) do
|
||||
:gen_server.cast(pid, :reset_file)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def write_cache(pid, value) do
|
||||
key = :erlang.unique_integer()
|
||||
:gen_server.cast(pid, {:write_cache, key, value})
|
||||
key
|
||||
end
|
||||
|
||||
@doc false
|
||||
def read_cache(pid, key) do
|
||||
:gen_server.call(pid, {:read_cache, key}, @timeout)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def collect_unused_imports(pid) do
|
||||
unused(pid, :import)
|
||||
@@ -126,33 +98,22 @@ defmodule Kernel.LexicalTracker do
|
||||
# Callbacks
|
||||
|
||||
def init(dest) do
|
||||
state = %{
|
||||
directives: %{},
|
||||
references: %{},
|
||||
compile: %{},
|
||||
runtime: %{},
|
||||
structs: %{},
|
||||
dest: dest,
|
||||
cache: %{},
|
||||
file: nil
|
||||
}
|
||||
|
||||
{:ok, state}
|
||||
{:ok, %{directives: %{}, references: %{}, compile: %{},
|
||||
runtime: %{}, dest: dest}}
|
||||
end
|
||||
|
||||
@doc false
|
||||
def handle_call({:unused, tag}, _from, state) do
|
||||
directives =
|
||||
for {{^tag, module_or_mfa}, marker} <- state.directives, is_integer(marker) do
|
||||
{module_or_mfa, marker}
|
||||
end
|
||||
for {{^tag, module_or_mfa}, marker} <- state.directives,
|
||||
is_integer(marker),
|
||||
do: {module_or_mfa, marker}
|
||||
|
||||
{:reply, Enum.sort(directives), state}
|
||||
end
|
||||
|
||||
def handle_call(:remote_references, _from, state) do
|
||||
{compile, runtime} = partition(:maps.to_list(state.references), [], [])
|
||||
{:reply, {compile, :maps.keys(state.structs), runtime}, state}
|
||||
{:reply, partition(Enum.to_list(state.references), [], []), state}
|
||||
end
|
||||
|
||||
def handle_call(:remote_dispatches, _from, state) do
|
||||
@@ -163,24 +124,10 @@ defmodule Kernel.LexicalTracker do
|
||||
{:reply, state.dest, state}
|
||||
end
|
||||
|
||||
def handle_call({:read_cache, key}, _from, %{cache: cache} = state) do
|
||||
{:reply, :maps.get(key, cache), state}
|
||||
end
|
||||
|
||||
def handle_cast({:write_cache, key, value}, %{cache: cache} = state) do
|
||||
{:noreply, %{state | cache: :maps.put(key, value, cache)}}
|
||||
end
|
||||
|
||||
def handle_cast({:remote_reference, module, mode}, state) do
|
||||
{:noreply, %{state | references: add_reference(state.references, module, mode)}}
|
||||
end
|
||||
|
||||
def handle_cast({:remote_struct, module, line}, state) do
|
||||
state = add_remote_dispatch(state, module, {:__struct__, 1}, line, :compile)
|
||||
structs = :maps.put(module, true, state.structs)
|
||||
{:noreply, %{state | structs: structs}}
|
||||
end
|
||||
|
||||
def handle_cast({:remote_dispatch, module, fa, line, mode}, state) do
|
||||
references = add_reference(state.references, module, mode)
|
||||
state = add_remote_dispatch(state, module, fa, line, mode)
|
||||
@@ -200,19 +147,11 @@ defmodule Kernel.LexicalTracker do
|
||||
{:noreply, %{state | directives: add_dispatch(state.directives, module, :alias)}}
|
||||
end
|
||||
|
||||
def handle_cast({:set_file, file}, state) do
|
||||
{:noreply, %{state | file: file}}
|
||||
end
|
||||
|
||||
def handle_cast(:reset_file, state) do
|
||||
{:noreply, %{state | file: nil}}
|
||||
end
|
||||
|
||||
def handle_cast({:add_import, module, fas, line, warn}, state) do
|
||||
directives =
|
||||
state.directives
|
||||
|> Enum.reject(&match?({{:import, {^module, _, _}}, _}, &1))
|
||||
|> :maps.from_list()
|
||||
|> :maps.from_list
|
||||
|> add_directive(module, line, warn, :import)
|
||||
|
||||
directives =
|
||||
@@ -248,42 +187,30 @@ defmodule Kernel.LexicalTracker do
|
||||
|
||||
defp partition([{remote, :compile} | t], compile, runtime),
|
||||
do: partition(t, [remote | compile], runtime)
|
||||
|
||||
defp partition([{remote, :runtime} | t], compile, runtime),
|
||||
do: partition(t, compile, [remote | runtime])
|
||||
|
||||
defp partition([], compile, runtime), do: {compile, runtime}
|
||||
defp partition([], compile, runtime),
|
||||
do: {compile, runtime}
|
||||
|
||||
# Callbacks helpers
|
||||
|
||||
defp add_reference(references, module, :runtime) when is_atom(module),
|
||||
do: map_put_new(module, :runtime, references)
|
||||
defp add_reference(references, module, :compile) when is_atom(module),
|
||||
do: :maps.put(module, :compile, references)
|
||||
|
||||
defp add_reference(references, module, :runtime) when is_atom(module) do
|
||||
case :maps.find(module, references) do
|
||||
{:ok, _} -> references
|
||||
:error -> :maps.put(module, :runtime, references)
|
||||
defp add_remote_dispatch(state, module, fa, line, mode) when is_atom(module) do
|
||||
map_update mode, %{module => %{fa => [line]}}, state, fn mode_dispatches ->
|
||||
map_update module, %{fa => [line]}, mode_dispatches, fn module_dispatches ->
|
||||
map_update fa, [line], module_dispatches, &[line | List.delete(&1, line)]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp add_remote_dispatch(state, module, fa, line, mode) when is_atom(module) do
|
||||
location = location(state.file, line)
|
||||
|
||||
map_update(mode, %{module => %{fa => [location]}}, state, fn mode_dispatches ->
|
||||
map_update(module, %{fa => [location]}, mode_dispatches, fn module_dispatches ->
|
||||
map_update(fa, [location], module_dispatches, &[location | List.delete(&1, location)])
|
||||
end)
|
||||
end)
|
||||
end
|
||||
|
||||
defp location(nil, line), do: line
|
||||
defp location(file, line), do: {file, line}
|
||||
|
||||
defp add_import_dispatch(state, module, function, arity) do
|
||||
directives =
|
||||
add_dispatch(state.directives, module, :import)
|
||||
|> add_dispatch({module, function, arity}, :import)
|
||||
|
||||
# Always compile time because we depend
|
||||
# on the module at compile time
|
||||
references = add_reference(state.references, module, :compile)
|
||||
@@ -309,4 +236,11 @@ defmodule Kernel.LexicalTracker do
|
||||
:error -> :maps.put(key, initial, map)
|
||||
end
|
||||
end
|
||||
|
||||
defp map_put_new(key, value, map) do
|
||||
case :maps.find(key, map) do
|
||||
{:ok, _} -> map
|
||||
:error -> :maps.put(key, value, map)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,37 +1,8 @@
|
||||
defmodule Kernel.ParallelCompiler do
|
||||
@moduledoc """
|
||||
A module responsible for compiling and requiring files in parallel.
|
||||
A module responsible for compiling files in parallel.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Starts a task for parallel compilation.
|
||||
|
||||
If you have a file that needs to compile other modules in parallel,
|
||||
the spawned processes need to be aware of the compiler environment.
|
||||
This function allows a developer to create a task that is aware of
|
||||
those environments.
|
||||
|
||||
See `Task.async/1` for more information. The task spawned must be
|
||||
always awaited on by calling `Task.await/1`
|
||||
"""
|
||||
def async(fun) when is_function(fun) do
|
||||
if parent = :erlang.get(:elixir_compiler_pid) do
|
||||
file = :erlang.get(:elixir_compiler_file)
|
||||
{:error_handler, error_handler} = :erlang.process_info(self(), :error_handler)
|
||||
|
||||
Task.async(fn ->
|
||||
:erlang.put(:elixir_compiler_pid, parent)
|
||||
:erlang.put(:elixir_compiler_file, file)
|
||||
:erlang.process_flag(:error_handler, error_handler)
|
||||
fun.()
|
||||
end)
|
||||
else
|
||||
raise ArgumentError,
|
||||
"cannot spawn parallel compiler task because " <>
|
||||
"the current file is not being compiled/required"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compiles the given files.
|
||||
|
||||
@@ -40,12 +11,11 @@ defmodule Kernel.ParallelCompiler do
|
||||
the current file stops being compiled until the dependency is
|
||||
resolved.
|
||||
|
||||
It returns `{:ok, modules, warnings}` or `{:error, errors, warnings}`.
|
||||
If there is an error during compilation or if `warnings_as_errors`
|
||||
is set to `true` and there is a warning, this function will fail
|
||||
with an exception.
|
||||
|
||||
Both errors and warnings are a list of three element tuples containing
|
||||
the file, line and the formatted error/warning.
|
||||
|
||||
## Options
|
||||
This function accepts the following options:
|
||||
|
||||
* `:each_file` - for each file compiled, invokes the callback passing the
|
||||
file
|
||||
@@ -54,189 +24,123 @@ defmodule Kernel.ParallelCompiler do
|
||||
timeout (see the `:long_compilation_threshold` option) to compile, invoke
|
||||
this callback passing the file as its argument
|
||||
|
||||
* `:long_compilation_threshold` - the timeout (in seconds) after the
|
||||
`:each_long_compilation` callback is invoked; defaults to `10`
|
||||
|
||||
* `:each_module` - for each module compiled, invokes the callback passing
|
||||
the file, module and the module bytecode
|
||||
|
||||
* `:each_cycle` - after the given files are compiled, invokes this function
|
||||
that return a list with potentially more files to compile
|
||||
|
||||
* `:long_compilation_threshold` - the timeout (in seconds) after the
|
||||
`:each_long_compilation` callback is invoked; defaults to `15`
|
||||
|
||||
* `:dest` - the destination directory for the BEAM files. When using `files/2`,
|
||||
this information is only used to properly annotate the BEAM files before
|
||||
they are loaded into memory. If you want a file to actually be written to
|
||||
`dest`, use `compile_to_path/3` instead.
|
||||
`dest`, use `files_to_path/3` instead.
|
||||
|
||||
Returns the modules generated by each compiled file.
|
||||
"""
|
||||
def compile(files, options \\ []) when is_list(options) do
|
||||
spawn_workers(files, :compile, options)
|
||||
end
|
||||
def files(files, options \\ [])
|
||||
|
||||
def compile_to_path(files, path, options \\ []) when is_binary(path) and is_list(options) do
|
||||
spawn_workers(files, {:compile, path}, options)
|
||||
def files(files, options) when is_list(options) do
|
||||
spawn_compilers(files, nil, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Requires the given files in parallel.
|
||||
|
||||
Opposite to compile, dependencies are not attempted to be
|
||||
automatically solved between files.
|
||||
|
||||
It returns `{:ok, modules, warnings}` or `{:error, errors, warnings}`.
|
||||
|
||||
Both errors and warnings are a list of three element tuples containing
|
||||
the file, line and the formatted error/warning.
|
||||
|
||||
## Options
|
||||
|
||||
* `:each_file` - for each file compiled, invokes the callback passing the
|
||||
file
|
||||
|
||||
* `:each_module` - for each module compiled, invokes the callback passing
|
||||
the file, module and the module bytecode
|
||||
|
||||
Compiles the given files to the given path.
|
||||
Read `files/2` for more information.
|
||||
"""
|
||||
def require(files, options \\ []) when is_list(options) do
|
||||
spawn_workers(files, :require, options)
|
||||
def files_to_path(files, path, options \\ [])
|
||||
|
||||
def files_to_path(files, path, options) when is_binary(path) and is_list(options) do
|
||||
spawn_compilers(files, path, options)
|
||||
end
|
||||
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
@doc false
|
||||
def files(files, options \\ []) when is_list(options) do
|
||||
case spawn_workers(files, :compile, options) do
|
||||
{:ok, modules, _} -> modules
|
||||
{:error, _, _} -> exit({:shutdown, 1})
|
||||
end
|
||||
end
|
||||
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
@doc false
|
||||
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
|
||||
{:error, _, _} -> exit({:shutdown, 1})
|
||||
end
|
||||
end
|
||||
|
||||
defp spawn_workers(files, output, options) do
|
||||
defp spawn_compilers(files, path, options) do
|
||||
true = Code.ensure_loaded?(Kernel.ErrorHandler)
|
||||
compiler_pid = self()
|
||||
:elixir_code_server.cast({:reset_warnings, compiler_pid})
|
||||
schedulers = max(:erlang.system_info(:schedulers_online), 2)
|
||||
|
||||
result =
|
||||
spawn_workers(files, [], [], [], [], %{
|
||||
dest: Keyword.get(options, :dest),
|
||||
each_cycle: Keyword.get(options, :each_cycle, fn -> [] end),
|
||||
each_file: Keyword.get(options, :each_file, fn _file -> :ok end),
|
||||
each_long_compilation: Keyword.get(options, :each_long_compilation, fn _file -> :ok end),
|
||||
each_module: Keyword.get(options, :each_module, fn _file, _module, _binary -> :ok end),
|
||||
output: output,
|
||||
long_compilation_threshold: Keyword.get(options, :long_compilation_threshold, 15),
|
||||
schedulers: schedulers
|
||||
})
|
||||
result = spawn_compilers(%{
|
||||
entries: files,
|
||||
original: files,
|
||||
output: path,
|
||||
options: options,
|
||||
waiting: [],
|
||||
queued: [],
|
||||
schedulers: schedulers,
|
||||
result: [],
|
||||
})
|
||||
|
||||
# In case --warning-as-errors is enabled and there was a warning,
|
||||
# compilation status will be set to error.
|
||||
compilation_status = :elixir_code_server.call({:compilation_status, compiler_pid})
|
||||
|
||||
case {result, compilation_status} do
|
||||
{{:ok, _, warnings}, :error} ->
|
||||
message = "Compilation failed due to warnings while using the --warnings-as-errors option"
|
||||
IO.puts(:stderr, message)
|
||||
{:error, warnings, []}
|
||||
|
||||
{{:error, errors, warnings}, :error} ->
|
||||
{:error, errors ++ warnings, []}
|
||||
|
||||
_ ->
|
||||
case :elixir_code_server.call({:compilation_status, compiler_pid}) do
|
||||
:ok ->
|
||||
result
|
||||
:error ->
|
||||
IO.puts :stderr, "Compilation failed due to warnings while using the --warnings-as-errors option"
|
||||
exit({:shutdown, 1})
|
||||
end
|
||||
end
|
||||
|
||||
# We already have n=schedulers currently running, don't spawn new ones
|
||||
defp spawn_workers(files, waiting, queued, result, warnings, %{schedulers: schedulers} = state)
|
||||
when length(queued) - length(waiting) >= schedulers do
|
||||
wait_for_messages(files, waiting, queued, result, warnings, state)
|
||||
defp spawn_compilers(%{queued: queued, waiting: waiting, schedulers: schedulers} = state)
|
||||
when length(queued) - length(waiting) >= schedulers do
|
||||
wait_for_messages(state)
|
||||
end
|
||||
|
||||
# Release waiting processes
|
||||
defp spawn_workers([{ref, found} | t], waiting, queued, result, warnings, state) do
|
||||
defp spawn_compilers(%{entries: [{ref, found} | t], waiting: waiting} = state) do
|
||||
waiting =
|
||||
case List.keytake(waiting, ref, 2) do
|
||||
{{_kind, pid, ^ref, _on, _defining}, waiting} ->
|
||||
send(pid, {ref, found})
|
||||
send pid, {ref, found}
|
||||
waiting
|
||||
|
||||
nil ->
|
||||
waiting
|
||||
end
|
||||
|
||||
spawn_workers(t, waiting, queued, result, warnings, state)
|
||||
spawn_compilers(%{state | entries: t, waiting: waiting})
|
||||
end
|
||||
|
||||
defp spawn_workers([file | files], waiting, queued, result, warnings, state) do
|
||||
%{output: output, long_compilation_threshold: threshold, dest: dest} = state
|
||||
defp spawn_compilers(%{entries: [file | files], queued: queued, output: output, options: options} = state) do
|
||||
parent = self()
|
||||
|
||||
{pid, ref} =
|
||||
:erlang.spawn_monitor(fn ->
|
||||
:erlang.spawn_monitor fn ->
|
||||
# Set the elixir_compiler_pid used by our custom Kernel.ErrorHandler.
|
||||
:erlang.put(:elixir_compiler_pid, parent)
|
||||
:erlang.put(:elixir_compiler_file, file)
|
||||
:erlang.process_flag(:error_handler, Kernel.ErrorHandler)
|
||||
|
||||
result =
|
||||
try do
|
||||
_ =
|
||||
case output do
|
||||
{:compile, path} ->
|
||||
:erlang.process_flag(:error_handler, Kernel.ErrorHandler)
|
||||
:elixir_compiler.file_to_path(file, path)
|
||||
|
||||
:compile ->
|
||||
:erlang.process_flag(:error_handler, Kernel.ErrorHandler)
|
||||
:elixir_compiler.file(file, dest)
|
||||
|
||||
:require ->
|
||||
Code.require_file(file)
|
||||
end
|
||||
|
||||
:ok
|
||||
catch
|
||||
kind, reason ->
|
||||
{kind, reason, System.stacktrace()}
|
||||
exit(try do
|
||||
_ = if output do
|
||||
:elixir_compiler.file_to_path(file, output)
|
||||
else
|
||||
:elixir_compiler.file(file, Keyword.get(options, :dest))
|
||||
end
|
||||
{:shutdown, file}
|
||||
catch
|
||||
kind, reason ->
|
||||
{:failure, kind, reason, System.stacktrace}
|
||||
end)
|
||||
end
|
||||
|
||||
send(parent, {:file_done, self(), file, result})
|
||||
exit(:shutdown)
|
||||
end)
|
||||
timeout = Keyword.get(options, :long_compilation_threshold, 10) * 1_000
|
||||
timer_ref = Process.send_after(self(), {:timed_out, pid}, timeout)
|
||||
|
||||
timer_ref = Process.send_after(self(), {:timed_out, pid}, threshold * 1000)
|
||||
queued = [{pid, ref, file, timer_ref} | queued]
|
||||
spawn_workers(files, waiting, queued, result, warnings, state)
|
||||
new_queued = [{pid, ref, file, timer_ref} | queued]
|
||||
spawn_compilers(%{state | entries: files, queued: new_queued})
|
||||
end
|
||||
|
||||
# No more files, nothing waiting, queue is empty, this cycle is done
|
||||
defp spawn_workers([], [], [], result, warnings, state) do
|
||||
case state.each_cycle.() do
|
||||
[] ->
|
||||
modules = for {:module, mod} <- result, do: mod
|
||||
warnings = Enum.reverse(warnings)
|
||||
{:ok, modules, warnings}
|
||||
|
||||
more ->
|
||||
spawn_workers(more, [], [], result, warnings, state)
|
||||
end
|
||||
# No more files, nothing waiting, queue is empty, we are done
|
||||
defp spawn_compilers(%{entries: [], waiting: [], queued: [], result: result}) do
|
||||
for {:module, mod} <- result, do: mod
|
||||
end
|
||||
|
||||
# Queued x, waiting for x: POSSIBLE ERROR! Release processes so we get the failures
|
||||
defp spawn_workers([], waiting, queued, result, warnings, state)
|
||||
when length(waiting) == length(queued) do
|
||||
pending =
|
||||
for {pid, _, _, _} <- queued,
|
||||
entry = waiting_on_without_definition(waiting, pid),
|
||||
{_, _, ref, on, _} = entry,
|
||||
do: {on, {ref, :not_found}}
|
||||
defp spawn_compilers(%{entries: [], waiting: waiting, queued: queued} = state) when length(waiting) == length(queued) do
|
||||
entries = for {pid, _, _, _} <- queued,
|
||||
entry = waiting_on_without_definition(waiting, pid),
|
||||
{_, _, ref, on, _} = entry,
|
||||
do: {on, {ref, :not_found}}
|
||||
|
||||
# Instead of releasing all files at once, we release them in groups
|
||||
# based on the module they are waiting on. We pick the module being
|
||||
@@ -247,27 +151,25 @@ defmodule Kernel.ParallelCompiler do
|
||||
# are waiting on the same module required by the faulty code. However,
|
||||
# since we need to pick something to be first, the one with fewer edges
|
||||
# sounds like a sane choice.
|
||||
pending
|
||||
|> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
|
||||
|> Enum.sort_by(&length(elem(&1, 1)))
|
||||
|> case do
|
||||
[{_on, refs} | _] ->
|
||||
spawn_workers(refs, waiting, queued, result, warnings, state)
|
||||
entries =
|
||||
entries
|
||||
|> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
|
||||
|> Enum.sort_by(&length(elem(&1, 1)))
|
||||
|> Enum.find_value([], &elem(&1, 1))
|
||||
|
||||
[] ->
|
||||
errors = handle_deadlock(waiting, queued)
|
||||
{:error, errors, warnings}
|
||||
case entries do
|
||||
[] -> handle_deadlock(waiting, queued)
|
||||
_ -> spawn_compilers(%{state | entries: entries})
|
||||
end
|
||||
end
|
||||
|
||||
# No more files, but queue and waiting are not full or do not match
|
||||
defp spawn_workers([], waiting, queued, result, warnings, state) do
|
||||
wait_for_messages([], waiting, queued, result, warnings, state)
|
||||
defp spawn_compilers(%{entries: []} = state) do
|
||||
wait_for_messages(state)
|
||||
end
|
||||
|
||||
defp waiting_on_without_definition(waiting, pid) do
|
||||
{_, ^pid, _, on, _} = entry = List.keyfind(waiting, pid, 1)
|
||||
|
||||
if Enum.any?(waiting, fn {_, _, _, _, defining} -> on in defining end) do
|
||||
nil
|
||||
else
|
||||
@@ -276,39 +178,32 @@ defmodule Kernel.ParallelCompiler do
|
||||
end
|
||||
|
||||
# Wait for messages from child processes
|
||||
defp wait_for_messages(files, waiting, queued, result, warnings, state) do
|
||||
%{output: output} = state
|
||||
defp wait_for_messages(state) do
|
||||
%{entries: entries, options: options, waiting: waiting, queued: queued, result: result} = state
|
||||
|
||||
receive do
|
||||
{:struct_available, module} ->
|
||||
available =
|
||||
for {:struct, _, ref, waiting_module, _defining} <- waiting,
|
||||
module == waiting_module,
|
||||
do: {ref, :found}
|
||||
available = for {:struct, _, ref, waiting_module, _defining} <- waiting,
|
||||
module == waiting_module,
|
||||
do: {ref, :found}
|
||||
|
||||
result = [{:struct, module} | result]
|
||||
spawn_workers(available ++ files, waiting, queued, result, warnings, state)
|
||||
spawn_compilers(%{state | entries: available ++ entries, result: [{:struct, module} | result]})
|
||||
|
||||
{:module_available, child, ref, file, module, binary} ->
|
||||
state.each_module.(file, module, binary)
|
||||
if callback = Keyword.get(options, :each_module) do
|
||||
callback.(file, module, binary)
|
||||
end
|
||||
|
||||
# Release the module loader which is waiting for an ack
|
||||
send(child, {ref, :ack})
|
||||
send child, {ref, :ack}
|
||||
|
||||
available =
|
||||
for {:module, _, ref, waiting_module, _defining} <- waiting,
|
||||
module == waiting_module,
|
||||
do: {ref, :found}
|
||||
available = for {:module, _, ref, waiting_module, _defining} <- waiting,
|
||||
module == waiting_module,
|
||||
do: {ref, :found}
|
||||
|
||||
cancel_waiting_timer(queued, child)
|
||||
|
||||
result = [{:module, module} | result]
|
||||
spawn_workers(available ++ files, waiting, queued, result, warnings, state)
|
||||
|
||||
# If we are simply requiring files, we do not add to waiting.
|
||||
{:waiting, _kind, child, ref, _on, _defining} when output == :require ->
|
||||
send(child, {ref, :not_found})
|
||||
spawn_workers(files, waiting, queued, result, warnings, state)
|
||||
spawn_compilers(%{state | entries: available ++ entries, result: [{:module, module} | result]})
|
||||
|
||||
{:waiting, kind, child, ref, on, defining} ->
|
||||
# Oops, we already got it, do not put it on waiting.
|
||||
@@ -316,77 +211,41 @@ defmodule Kernel.ParallelCompiler do
|
||||
# send :found so that we can crash with a better error.
|
||||
waiting =
|
||||
if :lists.any(&match?({^kind, ^on}, &1), result) or on in defining do
|
||||
send(child, {ref, :found})
|
||||
send child, {ref, :found}
|
||||
waiting
|
||||
else
|
||||
[{kind, child, ref, on, defining} | waiting]
|
||||
end
|
||||
|
||||
spawn_workers(files, waiting, queued, result, warnings, state)
|
||||
spawn_compilers(%{state | waiting: waiting})
|
||||
|
||||
{:timed_out, child} ->
|
||||
callback = Keyword.get(options, :each_long_compilation)
|
||||
case List.keyfind(queued, child, 0) do
|
||||
{^child, _, file, _} ->
|
||||
state.each_long_compilation.(file)
|
||||
|
||||
{^child, _, file, _} when not is_nil(callback) ->
|
||||
callback.(file)
|
||||
_ ->
|
||||
:ok
|
||||
end
|
||||
spawn_compilers(state)
|
||||
|
||||
spawn_workers(files, waiting, queued, result, warnings, state)
|
||||
{:DOWN, _down_ref, :process, down_pid, {:shutdown, file}} ->
|
||||
if callback = Keyword.get(options, :each_file) do
|
||||
callback.(file)
|
||||
end
|
||||
|
||||
{:warning, file, line, message} ->
|
||||
file = file && Path.absname(file)
|
||||
message = :unicode.characters_to_binary(message)
|
||||
warning = {file, line, message}
|
||||
wait_for_messages(files, waiting, queued, result, [warning | warnings], state)
|
||||
|
||||
{:file_done, child_pid, file, :ok} ->
|
||||
discard_down(child_pid)
|
||||
state.each_file.(file)
|
||||
cancel_waiting_timer(queued, child_pid)
|
||||
cancel_waiting_timer(queued, down_pid)
|
||||
|
||||
# Sometimes we may have spurious entries in the waiting
|
||||
# list because someone invoked try/rescue UndefinedFunctionError
|
||||
new_files = List.delete(files, child_pid)
|
||||
new_queued = List.keydelete(queued, child_pid, 0)
|
||||
new_waiting = List.keydelete(waiting, child_pid, 1)
|
||||
spawn_workers(new_files, new_waiting, new_queued, result, warnings, state)
|
||||
new_entries = List.delete(entries, down_pid)
|
||||
new_queued = List.keydelete(queued, down_pid, 0)
|
||||
new_waiting = List.keydelete(waiting, down_pid, 1)
|
||||
spawn_compilers(%{state | entries: new_entries, waiting: new_waiting, queued: new_queued})
|
||||
|
||||
{:file_done, child_pid, file, {kind, reason, stack}} ->
|
||||
discard_down(child_pid)
|
||||
print_error(file, kind, reason, stack)
|
||||
cancel_waiting_timer(queued, child_pid)
|
||||
terminate(queued)
|
||||
{:error, [to_error(file, kind, reason, stack)], warnings}
|
||||
|
||||
{:DOWN, ref, :process, _pid, reason} ->
|
||||
case handle_down(queued, ref, reason) do
|
||||
:ok -> wait_for_messages(files, waiting, queued, result, warnings, state)
|
||||
{:error, errors} -> {:error, errors, warnings}
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp discard_down(pid) do
|
||||
receive do
|
||||
{:DOWN, _, :process, ^pid, _} -> :ok
|
||||
end
|
||||
end
|
||||
|
||||
defp handle_down(_queued, _ref, :normal) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp handle_down(queued, ref, reason) do
|
||||
case List.keyfind(queued, ref, 1) do
|
||||
{_child, ^ref, file, _timer_ref} ->
|
||||
print_error(file, :exit, reason, [])
|
||||
terminate(queued)
|
||||
{:error, [to_error(file, :exit, reason, [])]}
|
||||
|
||||
_ ->
|
||||
:ok
|
||||
{:DOWN, down_ref, :process, _down_pid, reason} ->
|
||||
handle_failure(down_ref, reason, queued)
|
||||
wait_for_messages(state)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -397,44 +256,77 @@ defmodule Kernel.ParallelCompiler do
|
||||
Process.exit(pid, :kill)
|
||||
|
||||
{_kind, ^pid, _, on, _} = List.keyfind(waiting, pid, 1)
|
||||
description = "deadlocked waiting on module #{inspect(on)}"
|
||||
error = CompileError.exception(description: description, file: nil, line: nil)
|
||||
print_error(file, :error, error, stacktrace)
|
||||
error = CompileError.exception(description: "deadlocked waiting on module #{inspect on}",
|
||||
file: nil, line: nil)
|
||||
print_failure(file, {:failure, :error, error, stacktrace})
|
||||
|
||||
{file, on, description}
|
||||
{file, on}
|
||||
end
|
||||
|
||||
IO.puts("""
|
||||
IO.puts """
|
||||
|
||||
Compilation failed because of a deadlock between files.
|
||||
The following files depended on the following modules:
|
||||
""")
|
||||
"""
|
||||
|
||||
max =
|
||||
deadlock
|
||||
|> Enum.map(&(&1 |> elem(0) |> String.length()))
|
||||
|> Enum.max()
|
||||
|> Enum.map(& &1 |> elem(0) |> String.length)
|
||||
|> Enum.max
|
||||
|
||||
for {file, mod, _} <- deadlock do
|
||||
IO.puts([" ", String.pad_leading(file, max), " => " | inspect(mod)])
|
||||
for {file, mod} <- deadlock do
|
||||
IO.puts [" ", String.pad_leading(file, max), " => " | inspect(mod)]
|
||||
end
|
||||
|
||||
IO.puts("")
|
||||
|
||||
for {file, _, description} <- deadlock, do: {Path.absname(file), nil, description}
|
||||
IO.puts ""
|
||||
exit({:shutdown, 1})
|
||||
end
|
||||
|
||||
defp terminate(queued) do
|
||||
for {pid, _, _, _} <- queued do
|
||||
Process.exit(pid, :kill)
|
||||
defp handle_failure(ref, reason, queued) do
|
||||
if file = find_failure(ref, queued) do
|
||||
print_failure(file, reason)
|
||||
for {pid, _, _, _} <- queued do
|
||||
Process.exit(pid, :kill)
|
||||
end
|
||||
exit({:shutdown, 1})
|
||||
end
|
||||
end
|
||||
|
||||
defp print_error(file, kind, reason, stack) do
|
||||
IO.write([
|
||||
"\n== Compilation error in file #{Path.relative_to_cwd(file)} ==\n",
|
||||
Kernel.CLI.format_error(kind, reason, stack)
|
||||
])
|
||||
defp find_failure(ref, queued) do
|
||||
case List.keyfind(queued, ref, 1) do
|
||||
{_child, ^ref, file, _timer_ref} -> file
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
|
||||
defp print_failure(_file, {:shutdown, _}) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp print_failure(file, {:failure, kind, reason, stacktrace}) do
|
||||
IO.puts "\n== Compilation error on file #{Path.relative_to_cwd(file)} =="
|
||||
IO.puts Exception.format(kind, reason, prune_stacktrace(stacktrace))
|
||||
end
|
||||
|
||||
defp print_failure(file, reason) do
|
||||
IO.puts "\n== Compilation error on file #{Path.relative_to_cwd(file)} =="
|
||||
IO.puts Exception.format(:exit, reason, [])
|
||||
end
|
||||
|
||||
@elixir_internals [:elixir, :elixir_exp, :elixir_compiler, :elixir_module, :elixir_clauses,
|
||||
:elixir_translator, :elixir_expand, :elixir_lexical, :elixir_exp_clauses,
|
||||
:elixir_def, :elixir_map, Kernel.ErrorHandler]
|
||||
|
||||
defp prune_stacktrace([{mod, _, _, _} | t]) when mod in @elixir_internals do
|
||||
prune_stacktrace(t)
|
||||
end
|
||||
|
||||
defp prune_stacktrace([h | t]) do
|
||||
[h | prune_stacktrace(t)]
|
||||
end
|
||||
|
||||
defp prune_stacktrace([]) do
|
||||
[]
|
||||
end
|
||||
|
||||
defp cancel_waiting_timer(queued, child_pid) do
|
||||
@@ -448,36 +340,8 @@ defmodule Kernel.ParallelCompiler do
|
||||
after
|
||||
0 -> :ok
|
||||
end
|
||||
|
||||
nil ->
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
defp to_error(file, kind, reason, stack) do
|
||||
line = get_line(file, reason, stack)
|
||||
file = Path.absname(file)
|
||||
message = :unicode.characters_to_binary(Kernel.CLI.format_error(kind, reason, stack))
|
||||
{file, line, message}
|
||||
end
|
||||
|
||||
defp get_line(_file, %{line: line}, _stack) when is_integer(line) and line > 0 do
|
||||
line
|
||||
end
|
||||
|
||||
defp get_line(file, :undef, [{_, _, _, []}, {_, _, _, info} | _]) do
|
||||
if Keyword.get(info, :file) == to_charlist(Path.relative_to_cwd(file)) do
|
||||
Keyword.get(info, :line)
|
||||
end
|
||||
end
|
||||
|
||||
defp get_line(file, _reason, [{_, _, _, info} | _]) do
|
||||
if Keyword.get(info, :file) == to_charlist(Path.relative_to_cwd(file)) do
|
||||
Keyword.get(info, :line)
|
||||
end
|
||||
end
|
||||
|
||||
defp get_line(_, _, _) do
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1,17 +1,109 @@
|
||||
defmodule Kernel.ParallelRequire do
|
||||
# TODO: Deprecate on Elixir v1.8
|
||||
@moduledoc false
|
||||
@moduledoc """
|
||||
A module responsible for requiring files in parallel.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Requires the given files.
|
||||
|
||||
A callback that will be invoked with each file, or a keyword list of `callbacks` can be provided:
|
||||
|
||||
* `:each_file` - invoked with each file
|
||||
|
||||
* `:each_module` - invoked with file, module name, and binary code
|
||||
|
||||
Returns the modules generated by each required file.
|
||||
"""
|
||||
def files(files, callbacks \\ [])
|
||||
|
||||
def files(files, callback) when is_function(callback, 1) do
|
||||
files(files, each_file: callback)
|
||||
files(files, [each_file: callback])
|
||||
end
|
||||
|
||||
def files(files, options) when is_list(options) do
|
||||
case Kernel.ParallelCompiler.require(files, options) do
|
||||
{:ok, modules, _} -> modules
|
||||
{:error, _, _} -> exit({:shutdown, 1})
|
||||
def files(files, callbacks) when is_list(callbacks) do
|
||||
compiler_pid = self()
|
||||
:elixir_code_server.cast({:reset_warnings, compiler_pid})
|
||||
schedulers = max(:erlang.system_info(:schedulers_online), 2)
|
||||
result = spawn_requires(files, [], callbacks, schedulers, [])
|
||||
|
||||
# In case --warning-as-errors is enabled and there was a warning,
|
||||
# compilation status will be set to error.
|
||||
case :elixir_code_server.call({:compilation_status, compiler_pid}) do
|
||||
:ok ->
|
||||
result
|
||||
:error ->
|
||||
IO.puts :stderr, "\nExecution failed due to warnings while using the --warnings-as-errors option"
|
||||
exit({:shutdown, 1})
|
||||
end
|
||||
end
|
||||
|
||||
defp spawn_requires([], [], _callbacks, _schedulers, result), do: result
|
||||
|
||||
defp spawn_requires([], waiting, callbacks, schedulers, result) do
|
||||
wait_for_messages([], waiting, callbacks, schedulers, result)
|
||||
end
|
||||
|
||||
defp spawn_requires(files, waiting, callbacks, schedulers, result) when length(waiting) >= schedulers do
|
||||
wait_for_messages(files, waiting, callbacks, schedulers, result)
|
||||
end
|
||||
|
||||
defp spawn_requires([file | files], waiting, callbacks, schedulers, result) do
|
||||
parent = self()
|
||||
{pid, ref} = :erlang.spawn_monitor fn ->
|
||||
:erlang.put(:elixir_compiler_pid, parent)
|
||||
:erlang.put(:elixir_compiler_file, file)
|
||||
|
||||
exit(try do
|
||||
new = Code.require_file(file) || []
|
||||
{:required, Enum.map(new, &elem(&1, 0)), file}
|
||||
catch
|
||||
kind, reason ->
|
||||
{:failure, kind, reason, System.stacktrace}
|
||||
end)
|
||||
end
|
||||
|
||||
spawn_requires(files, [{pid, ref} | waiting], callbacks, schedulers, result)
|
||||
end
|
||||
|
||||
defp wait_for_messages(files, waiting, callbacks, schedulers, result) do
|
||||
receive do
|
||||
{:DOWN, ref, :process, pid, status} ->
|
||||
tuple = {pid, ref}
|
||||
if tuple in waiting do
|
||||
waiting = List.delete(waiting, tuple)
|
||||
|
||||
case status do
|
||||
{:required, mods, file} ->
|
||||
if each_file_callback = callbacks[:each_file] do
|
||||
each_file_callback.(file)
|
||||
end
|
||||
|
||||
spawn_requires(files, waiting, callbacks, schedulers, mods ++ result)
|
||||
|
||||
{:failure, kind, reason, stacktrace} ->
|
||||
:erlang.raise(kind, reason, stacktrace)
|
||||
|
||||
other ->
|
||||
:erlang.raise(:exit, other, [])
|
||||
end
|
||||
else
|
||||
spawn_requires(files, waiting, callbacks, schedulers, result)
|
||||
end
|
||||
|
||||
{:module_available, child, ref, file, module, binary} ->
|
||||
if each_module_callback = callbacks[:each_module] do
|
||||
each_module_callback.(file, module, binary)
|
||||
end
|
||||
|
||||
send(child, {ref, :ack})
|
||||
spawn_requires(files, waiting, callbacks, schedulers, result)
|
||||
|
||||
{:struct_available, _} ->
|
||||
spawn_requires(files, waiting, callbacks, schedulers, result)
|
||||
|
||||
{:waiting, _, child, ref, _, _} ->
|
||||
send(child, {ref, :not_found})
|
||||
spawn_requires(files, waiting, callbacks, schedulers, result)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -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 `{}` and `<<>>` are also special
|
||||
forms used to define tuple and binary data structures respectively.
|
||||
|
||||
This module also documents macros that return information about Elixir's
|
||||
@@ -19,10 +19,7 @@ defmodule Kernel.SpecialForms do
|
||||
defmacrop error!(args) do
|
||||
quote do
|
||||
_ = unquote(args)
|
||||
|
||||
message =
|
||||
"Elixir's special forms are expanded by the compiler and must not be invoked directly"
|
||||
|
||||
message = "Elixir's special forms are expanded by the compiler and must not be invoked directly"
|
||||
:erlang.error(RuntimeError.exception(message))
|
||||
end
|
||||
end
|
||||
@@ -319,7 +316,7 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro unquote(:<<>>)(args), do: error!([args])
|
||||
|
||||
@doc """
|
||||
Defines a remote call, a call to an anonymous function, or an alias.
|
||||
Defines a remote call or an alias.
|
||||
|
||||
The dot (`.`) in Elixir can be used for remote calls:
|
||||
|
||||
@@ -327,16 +324,8 @@ defmodule Kernel.SpecialForms do
|
||||
"foo"
|
||||
|
||||
In this example above, we have used `.` to invoke `downcase` in the
|
||||
`String` module, passing `"FOO"` as argument.
|
||||
|
||||
The dot may be used to invoke anonymous functions too:
|
||||
|
||||
iex> (fn(n) -> n end).(7)
|
||||
7
|
||||
|
||||
in which case there is a function on the left hand side.
|
||||
|
||||
We can also use the dot for creating aliases:
|
||||
`String` alias, passing "FOO" as argument. We can also use the dot
|
||||
for creating aliases:
|
||||
|
||||
iex> Hello.World
|
||||
Hello.World
|
||||
@@ -371,13 +360,6 @@ defmodule Kernel.SpecialForms do
|
||||
a remote call regardless of the quote contents. This decision is also reflected
|
||||
in the quoted expressions discussed below.
|
||||
|
||||
When the dot is used to invoke an anonymous function there is only one
|
||||
operand, but it is still written using a postfix notation:
|
||||
|
||||
iex> negate = fn(n) -> -n end
|
||||
iex> negate.(7)
|
||||
-7
|
||||
|
||||
## Quoted expression
|
||||
|
||||
When `.` is used, the quoted expression may take two distinct
|
||||
@@ -396,9 +378,9 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
This tuple follows the general quoted expression structure in Elixir,
|
||||
with the name as first argument, some keyword list as metadata as second,
|
||||
and the list of arguments as third. In this case, the arguments are the
|
||||
alias `String` and the atom `:downcase`. The second argument in a remote call
|
||||
is **always** an atom regardless of the literal used in the call:
|
||||
and the number of arguments as third. In this case, the arguments is the
|
||||
alias `String` and the atom `:downcase`. The second argument is **always**
|
||||
an atom:
|
||||
|
||||
iex> quote do
|
||||
...> String."downcase"("FOO")
|
||||
@@ -408,15 +390,6 @@ defmodule Kernel.SpecialForms do
|
||||
The tuple containing `:.` is wrapped in another tuple, which actually
|
||||
represents the function call, and has `"FOO"` as argument.
|
||||
|
||||
In the case of calls to anonymous functions, the inner tuple with the dot
|
||||
special form has only one argument, reflecting the fact that the operator is
|
||||
unary:
|
||||
|
||||
iex> quote do
|
||||
...> negate.(0)
|
||||
...> end
|
||||
{{:., [], [{:negate, [], __MODULE__}]}, [], [0]}
|
||||
|
||||
When the right side is an alias (i.e. starts with uppercase), we get instead:
|
||||
|
||||
iex> quote do
|
||||
@@ -512,12 +485,13 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro alias(module, opts), do: error!([module, opts])
|
||||
|
||||
@doc """
|
||||
Requires a module in order to use its macros.
|
||||
Requires a given module to be compiled and loaded.
|
||||
|
||||
## Examples
|
||||
|
||||
Public functions in modules are globally available, but in order to use
|
||||
macros, you need to opt-in by requiring the module they are defined in.
|
||||
Notice that usually modules should not be required before usage,
|
||||
the only exception is if you want to use the macros from a module.
|
||||
In such cases, you need to explicitly require them.
|
||||
|
||||
Let's suppose you created your own `if/2` implementation in the module
|
||||
`MyMacros`. If you want to invoke it, you need to first explicitly
|
||||
@@ -575,9 +549,8 @@ defmodule Kernel.SpecialForms do
|
||||
import List, only: [flatten: 1]
|
||||
import String, except: [split: 2]
|
||||
|
||||
Notice that calling `except` is always exclusive on a previously
|
||||
declared `import/2`. If there is no previous import, then it applies
|
||||
to all functions and macros in the module. For example:
|
||||
Notice that calling `except` for a previously declared `import/2`
|
||||
simply filters the previously imported elements. For example:
|
||||
|
||||
import List, only: [flatten: 1, keyfind: 4]
|
||||
import List, except: [flatten: 1]
|
||||
@@ -700,7 +673,7 @@ defmodule Kernel.SpecialForms do
|
||||
1
|
||||
|
||||
"""
|
||||
defmacro ^var, do: error!([var])
|
||||
defmacro ^(var), do: error!([var])
|
||||
|
||||
@doc """
|
||||
Matches the value on the right against the pattern on the left.
|
||||
@@ -767,8 +740,6 @@ defmodule Kernel.SpecialForms do
|
||||
quote. Read the Stacktrace information section below for more
|
||||
information.
|
||||
|
||||
* `:line` - sets the quoted expressions to have the given line.
|
||||
|
||||
* `:generated` - marks the given chunk as generated so it does not emit warnings.
|
||||
Currently it only works on special forms (for example, you can annotate a `case`
|
||||
but not an `if`).
|
||||
@@ -872,7 +843,7 @@ defmodule Kernel.SpecialForms do
|
||||
|
||||
`:bind_quoted` will translate to the same code as the example above.
|
||||
`:bind_quoted` can be used in many cases and is seen as good practice,
|
||||
not only because it helps prevent us from running into common mistakes, but also
|
||||
not only because it helps us from running into common mistakes but also
|
||||
because it allows us to leverage other tools exposed by macros, such as
|
||||
unquote fragments discussed in some sections below.
|
||||
|
||||
@@ -1319,18 +1290,6 @@ defmodule Kernel.SpecialForms do
|
||||
String.upcase(line)
|
||||
end
|
||||
|
||||
## 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)
|
||||
[2, 4, 6]
|
||||
|
||||
iex> for(<<x <- "abcabc">>, uniq: true, into: "", do: <<x-32>>)
|
||||
"ABC"
|
||||
|
||||
"""
|
||||
defmacro for(args), do: error!([args])
|
||||
|
||||
@@ -1374,12 +1333,6 @@ defmodule Kernel.SpecialForms do
|
||||
iex> width
|
||||
nil
|
||||
|
||||
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
|
||||
|
||||
An `else` option can be given to modify what is being returned from
|
||||
`with` in the case of a failed match:
|
||||
|
||||
@@ -1394,6 +1347,7 @@ defmodule Kernel.SpecialForms do
|
||||
{:error, :wrong_data}
|
||||
|
||||
If there is no matching `else` condition, then a `WithClauseError` exception is raised.
|
||||
|
||||
"""
|
||||
defmacro with(args), do: error!([args])
|
||||
|
||||
@@ -1406,16 +1360,6 @@ defmodule Kernel.SpecialForms do
|
||||
iex> add.(1, 2)
|
||||
3
|
||||
|
||||
Anonymous functions can also have multiple clauses. All clauses
|
||||
should expect the same number of arguments:
|
||||
|
||||
iex> negate = fn
|
||||
...> true -> false
|
||||
...> false -> true
|
||||
...> end
|
||||
iex> negate.(false)
|
||||
true
|
||||
|
||||
"""
|
||||
defmacro unquote(:fn)(clauses), do: error!([clauses])
|
||||
|
||||
@@ -1434,7 +1378,7 @@ defmodule Kernel.SpecialForms do
|
||||
{:__block__, [], [1, 2, 3]}
|
||||
|
||||
"""
|
||||
defmacro unquote(:__block__)(args), do: error!([args])
|
||||
defmacro __block__(args), do: error!([args])
|
||||
|
||||
@doc """
|
||||
Captures or creates an anonymous function.
|
||||
@@ -1470,18 +1414,11 @@ defmodule Kernel.SpecialForms do
|
||||
4
|
||||
|
||||
In other words, `&(&1 * 2)` is equivalent to `fn x -> x * 2 end`.
|
||||
Another example using a local function:
|
||||
|
||||
We can partially apply a remote function with placeholder:
|
||||
|
||||
iex> take_five = &Enum.take(&1, 5)
|
||||
iex> take_five.(1..10)
|
||||
[1, 2, 3, 4, 5]
|
||||
|
||||
Another example while using an imported or local function:
|
||||
|
||||
iex> first_elem = &elem(&1, 0)
|
||||
iex> first_elem.({0, 1})
|
||||
0
|
||||
iex> fun = &is_atom(&1)
|
||||
iex> fun.(:atom)
|
||||
true
|
||||
|
||||
The `&` operator can be used with more complex expressions:
|
||||
|
||||
@@ -1496,8 +1433,8 @@ defmodule Kernel.SpecialForms do
|
||||
{1, 2}
|
||||
|
||||
iex> fun = &[&1 | &2]
|
||||
iex> fun.(1, [2, 3])
|
||||
[1, 2, 3]
|
||||
iex> fun.(1, 2)
|
||||
[1 | 2]
|
||||
|
||||
The only restrictions when creating anonymous functions is that at
|
||||
least one placeholder must be present, i.e. it must contain at least
|
||||
@@ -1544,7 +1481,7 @@ defmodule Kernel.SpecialForms do
|
||||
3. When the head element of aliases is the atom `:Elixir`, no expansion happens.
|
||||
|
||||
"""
|
||||
defmacro unquote(:__aliases__)(args), do: error!([args])
|
||||
defmacro __aliases__(args), do: error!([args])
|
||||
|
||||
@doc """
|
||||
Calls the overridden function when overriding it with `Kernel.defoverridable/1`.
|
||||
@@ -1656,7 +1593,7 @@ defmodule Kernel.SpecialForms do
|
||||
defmacro cond(clauses), do: error!([clauses])
|
||||
|
||||
@doc ~S"""
|
||||
Evaluates the given expressions and handles any error, exit,
|
||||
Evaluates the given expressions and handles any error, exit
|
||||
or throw that may have happened.
|
||||
|
||||
## Examples
|
||||
@@ -1668,84 +1605,77 @@ defmodule Kernel.SpecialForms do
|
||||
IO.puts "Invalid argument given"
|
||||
catch
|
||||
value ->
|
||||
IO.puts "Caught #{inspect(value)}"
|
||||
IO.puts "caught #{value}"
|
||||
else
|
||||
value ->
|
||||
IO.puts "Success! The result was #{inspect(value)}"
|
||||
IO.puts "Success! The result was #{value}"
|
||||
after
|
||||
IO.puts "This is printed regardless if it failed or succeed"
|
||||
end
|
||||
|
||||
The `rescue` clause is used to handle exceptions while the `catch`
|
||||
clause can be used to catch thrown values and exits.
|
||||
The `else` clause can be used to control flow based on the result of
|
||||
the expression. `catch`, `rescue`, and `else` clauses work based on
|
||||
pattern matching (similar to the `case` special form).
|
||||
The rescue clause is used to handle exceptions, while the catch
|
||||
clause can be used to catch thrown values. The else clause can
|
||||
be used to control flow based on the result of the expression.
|
||||
Catch, rescue and else clauses work based on pattern matching.
|
||||
|
||||
Note that calls inside `try/1` are not tail recursive since the VM
|
||||
needs to keep the stacktrace in case an exception happens.
|
||||
|
||||
## `rescue` clauses
|
||||
## Rescue clauses
|
||||
|
||||
Besides relying on pattern matching, `rescue` clauses provide some
|
||||
conveniences around exceptions that allow one to rescue an
|
||||
exception by its name. All the following formats are valid patterns
|
||||
in `rescue` clauses:
|
||||
Besides relying on pattern matching, rescue clauses provides some
|
||||
conveniences around exceptions that allows one to rescue an
|
||||
exception by its name. All the following formats are valid rescue
|
||||
expressions:
|
||||
|
||||
# Rescue a single exception without binding the exception
|
||||
# to a variable
|
||||
try do
|
||||
UndefinedModule.undefined_function
|
||||
rescue
|
||||
UndefinedFunctionError -> nil
|
||||
end
|
||||
|
||||
# Rescue any of the given exception without binding
|
||||
try do
|
||||
UndefinedModule.undefined_function
|
||||
rescue
|
||||
[UndefinedFunctionError, ArgumentError] -> nil
|
||||
[UndefinedFunctionError] -> nil
|
||||
end
|
||||
|
||||
# Rescue and bind the exception to the variable "x"
|
||||
# rescue and bind to x
|
||||
try do
|
||||
UndefinedModule.undefined_function
|
||||
rescue
|
||||
x in [UndefinedFunctionError] -> nil
|
||||
end
|
||||
|
||||
# Rescue all kinds of exceptions and bind the rescued exception
|
||||
# to the variable "x"
|
||||
# rescue all and bind to x
|
||||
try do
|
||||
UndefinedModule.undefined_function
|
||||
rescue
|
||||
x -> nil
|
||||
end
|
||||
|
||||
### Erlang errors
|
||||
## Erlang errors
|
||||
|
||||
Erlang errors are transformed into Elixir ones when rescuing:
|
||||
Erlang errors are transformed into Elixir ones during rescue:
|
||||
|
||||
try do
|
||||
:erlang.error(:badarg)
|
||||
rescue
|
||||
ArgumentError -> :ok
|
||||
end
|
||||
#=> :ok
|
||||
|
||||
The most common Erlang errors will be transformed into their
|
||||
Elixir counterpart. Those which are not will be transformed
|
||||
into the more generic `ErlangError`:
|
||||
Elixir counter-part. Those which are not will be transformed
|
||||
into `ErlangError`:
|
||||
|
||||
try do
|
||||
:erlang.error(:unknown)
|
||||
rescue
|
||||
ErlangError -> :ok
|
||||
end
|
||||
#=> :ok
|
||||
|
||||
In fact, `ErlangError` can be used to rescue any error that is
|
||||
not a proper Elixir error. For example, it can be used to rescue
|
||||
not an Elixir error proper. For example, it can be used to rescue
|
||||
the earlier `:badarg` error too, prior to transformation:
|
||||
|
||||
try do
|
||||
@@ -1753,63 +1683,35 @@ defmodule Kernel.SpecialForms do
|
||||
rescue
|
||||
ErlangError -> :ok
|
||||
end
|
||||
#=> :ok
|
||||
|
||||
## `catch` clauses
|
||||
## Catching throws and exits
|
||||
|
||||
The `catch` clause can be used to catch thrown values, exits, and errors.
|
||||
|
||||
### Catching thrown values
|
||||
|
||||
`catch` can be used to catch values thrown by `Kernel.throw/1`:
|
||||
|
||||
try do
|
||||
throw(:some_value)
|
||||
catch
|
||||
thrown_value ->
|
||||
IO.puts "A value was thrown: #{inspect(thrown_value)}"
|
||||
end
|
||||
|
||||
### Catching values of any kind
|
||||
|
||||
The `catch` clause also supports catching exits and errors. To do that, it
|
||||
allows matching on both the *kind* of the caught value as well as the value
|
||||
itself:
|
||||
The catch clause can be used to catch throws values and exits.
|
||||
|
||||
try do
|
||||
exit(:shutdown)
|
||||
catch
|
||||
:exit, value
|
||||
IO.puts "Exited with value #{inspect(value)}"
|
||||
:exit, :shutdown -> IO.puts "Exited with shutdown reason"
|
||||
end
|
||||
|
||||
try do
|
||||
exit(:shutdown)
|
||||
throw(:sample)
|
||||
catch
|
||||
kind, value when kind in [:exit, :throw] ->
|
||||
IO.puts "Caught exit or throw with value #{inspect(value)}"
|
||||
:throw, :sample ->
|
||||
IO.puts "sample thrown"
|
||||
end
|
||||
|
||||
The `catch` clause also supports `:error` alongside `:exit` and `:throw` as
|
||||
in Erlang, although this is commonly avoided in favor of `raise`/`rescue` control
|
||||
mechanisms. One reason for this is that when catching `:error`, the error is
|
||||
not automatically transformed into an Elixir error:
|
||||
catch values also support `:error`, as in Erlang, although it is
|
||||
commonly avoided in favor of raise/rescue control mechanisms.
|
||||
|
||||
try do
|
||||
:erlang.error(:badarg)
|
||||
catch
|
||||
:error, :badarg -> :ok
|
||||
end
|
||||
#=> :ok
|
||||
|
||||
## `after` clauses
|
||||
## After clauses
|
||||
|
||||
An `after` clause allows you to define cleanup logic that will be invoked both
|
||||
when the block of code passed to `try/1` succeeds and also when an error is raised. Note
|
||||
that the process will exit as usual when receiving an exit signal that causes
|
||||
when the tried block of code succeeds and also when an error is raised. Note
|
||||
that the process will exit as usually when receiving an exit signal that causes
|
||||
it to exit abruptly and so the `after` clause is not guaranteed to be executed.
|
||||
Luckily, most resources in Elixir (such as open files, ETS tables, ports, sockets,
|
||||
and so on) are linked to or monitor the owning process and will automatically clean
|
||||
etc.) are linked to or monitor the owning process and will automatically clean
|
||||
themselves up if that process exits.
|
||||
|
||||
File.write!("tmp/story.txt", "Hello, World")
|
||||
@@ -1819,9 +1721,9 @@ defmodule Kernel.SpecialForms do
|
||||
File.rm("tmp/story.txt")
|
||||
end
|
||||
|
||||
## `else` clauses
|
||||
## Else clauses
|
||||
|
||||
`else` clauses allow the result of the body passed to `try/1` to be pattern
|
||||
Else clauses allow the result of the expression to be pattern
|
||||
matched on:
|
||||
|
||||
x = 2
|
||||
@@ -1837,7 +1739,7 @@ defmodule Kernel.SpecialForms do
|
||||
:large
|
||||
end
|
||||
|
||||
If an `else` clause is not present and no exceptions are raised,
|
||||
If an else clause is not present and no exceptions are raised,
|
||||
the result of the expression will be returned:
|
||||
|
||||
x = 1
|
||||
@@ -1849,16 +1751,16 @@ defmodule Kernel.SpecialForms do
|
||||
:infinity
|
||||
end
|
||||
|
||||
However, when an `else` clause is present but the result of the expression
|
||||
does not match any of the patterns then an exception will be raised. This
|
||||
exception will not be caught by a `catch` or `rescue` in the same `try`:
|
||||
However, when an else clause is present but the result of the expression
|
||||
does not match any of the patterns an exception will be raised. This
|
||||
exception will not be caught by a catch or rescue in the same try:
|
||||
|
||||
x = 1
|
||||
try do
|
||||
try do
|
||||
1 / x
|
||||
rescue
|
||||
# The TryClauseError cannot be rescued here:
|
||||
# The TryClauseError can not be rescued here:
|
||||
TryClauseError ->
|
||||
:error_a
|
||||
else
|
||||
@@ -1871,8 +1773,8 @@ defmodule Kernel.SpecialForms do
|
||||
:error_b
|
||||
end
|
||||
|
||||
Similarly, an exception inside an `else` clause is not caught or rescued
|
||||
inside the same `try`:
|
||||
Similarly, an exception inside an else clause is not caught or rescued
|
||||
inside the same try:
|
||||
|
||||
try do
|
||||
try do
|
||||
@@ -1892,25 +1794,10 @@ defmodule Kernel.SpecialForms do
|
||||
end
|
||||
|
||||
This means the VM no longer needs to keep the stacktrace once inside
|
||||
an `else` clause and so tail recursion is possible when using a `try`
|
||||
with a tail call as the final call inside an `else` clause. The same
|
||||
an else clause and so tail recursion is possible when using a `try`
|
||||
with a tail call as the final call inside an else clause. The same
|
||||
is true for `rescue` and `catch` clauses.
|
||||
|
||||
Only the result of the tried expression falls down to the `else` clause.
|
||||
If the `try` ends up in the `rescue` or `catch` clauses, their result
|
||||
will not fall down to `else`:
|
||||
|
||||
try do
|
||||
throw(:catch_this)
|
||||
catch
|
||||
:throw, :catch_this ->
|
||||
:it_was_caught
|
||||
else
|
||||
# :it_was_caught will not fall down to this "else" clause.
|
||||
other ->
|
||||
{:else, other}
|
||||
end
|
||||
|
||||
## Variable handling
|
||||
|
||||
Since an expression inside `try` may not have been evaluated
|
||||
@@ -1977,8 +1864,8 @@ defmodule Kernel.SpecialForms do
|
||||
end
|
||||
|
||||
The `after` clause can be specified even if there are no match clauses.
|
||||
The timeout value given to `after` can be any expression evaluating to
|
||||
one of the allowed values:
|
||||
The timeout value given to `after` can be a variable; two special
|
||||
values are allowed:
|
||||
|
||||
* `:infinity` - the process should wait indefinitely for a matching
|
||||
message, this is the same as not using a timeout
|
||||
@@ -1986,10 +1873,6 @@ defmodule Kernel.SpecialForms do
|
||||
* `0` - if there is no matching message in the mailbox, the timeout
|
||||
will occur immediately
|
||||
|
||||
* positive integer smaller than `4_294_967_295` (`0xFFFFFFFF`
|
||||
in hex notation) - it should be possible to represent the timeout
|
||||
value as an unsigned 32-bit integer.
|
||||
|
||||
## Variables handling
|
||||
|
||||
The `receive/1` special form handles variables exactly as the `case/2`
|
||||
|
||||
+201
-361
File diff suppressed because it is too large
Load Diff
+39
-180
@@ -6,13 +6,10 @@ defmodule Kernel.Utils do
|
||||
@doc """
|
||||
Callback for destructure.
|
||||
"""
|
||||
def destructure(list, count)
|
||||
when is_list(list) and is_integer(count) and count >= 0,
|
||||
do: destructure_list(list, count)
|
||||
|
||||
def destructure(nil, count)
|
||||
when is_integer(count) and count >= 0,
|
||||
do: destructure_nil(count)
|
||||
def destructure(list, count) when is_list(list) and is_integer(count) and count >= 0,
|
||||
do: destructure_list(list, count)
|
||||
def destructure(nil, count) when is_integer(count) and count >= 0,
|
||||
do: destructure_nil(count)
|
||||
|
||||
defp destructure_list(_, 0), do: []
|
||||
defp destructure_list([], count), do: destructure_nil(count)
|
||||
@@ -26,7 +23,7 @@ defmodule Kernel.Utils do
|
||||
"""
|
||||
def defdelegate(fun, opts) when is_list(opts) do
|
||||
# TODO: Remove by 2.0
|
||||
append_first? = Keyword.get(opts, :append_first, false)
|
||||
append_first = Keyword.get(opts, :append_first, false)
|
||||
|
||||
{name, args} =
|
||||
case Macro.decompose_call(fun) do
|
||||
@@ -34,31 +31,38 @@ defmodule Kernel.Utils do
|
||||
_ -> raise ArgumentError, "invalid syntax in defdelegate #{Macro.to_string(fun)}"
|
||||
end
|
||||
|
||||
as_args_list = normalize_args(args)
|
||||
as = Keyword.get(opts, :as, name)
|
||||
as_args = build_as_args(args, append_first?)
|
||||
|
||||
{name, args, as, as_args}
|
||||
:lists.map(fn as_args ->
|
||||
formal_args = make_formal_args(as_args)
|
||||
as_args = case append_first do
|
||||
true -> tl(as_args) ++ [hd(as_args)]
|
||||
false -> as_args
|
||||
end
|
||||
{name, formal_args, as, as_args}
|
||||
end, as_args_list)
|
||||
end
|
||||
|
||||
defp build_as_args(args, append_first?) do
|
||||
as_args = :lists.map(&build_as_arg/1, args)
|
||||
|
||||
case append_first? do
|
||||
true -> tl(as_args) ++ [hd(as_args)]
|
||||
false -> as_args
|
||||
end
|
||||
defp make_formal_args(args) do
|
||||
fun = &match?({name, _, mod} when is_atom(name) and is_atom(mod), &1)
|
||||
:lists.filter(fun, args)
|
||||
end
|
||||
|
||||
defp build_as_arg({:\\, _, [arg, _default_arg]}), do: validate_arg(arg)
|
||||
defp build_as_arg(arg), do: validate_arg(arg)
|
||||
|
||||
defp validate_arg({name, _, mod} = arg) when is_atom(name) and is_atom(mod) do
|
||||
arg
|
||||
defp normalize_args(raw_args) do
|
||||
:lists.foldr(fn
|
||||
({:\\, _, [arg, default_arg]}, [as_args | _] = as_args_list) ->
|
||||
new_as_args = [default_arg | as_args]
|
||||
[new_as_args | add_arg(as_args_list, arg)]
|
||||
(arg, as_args_list) ->
|
||||
add_arg(as_args_list, arg)
|
||||
end, [[]], raw_args)
|
||||
end
|
||||
|
||||
defp validate_arg(ast) do
|
||||
defp add_arg(as_args_list, {name, _, mod} = arg) when is_atom(name) and is_atom(mod),
|
||||
do: :lists.map(&([arg | &1]), as_args_list)
|
||||
defp add_arg(_, code) do
|
||||
raise ArgumentError,
|
||||
"defdelegate/2 only accepts function parameters, got: #{Macro.to_string(ast)}"
|
||||
"defdelegate/2 only accepts function parameters, got: #{Macro.to_string(code)}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -68,12 +72,11 @@ defmodule Kernel.Utils do
|
||||
case fields do
|
||||
fs when is_list(fs) ->
|
||||
:ok
|
||||
|
||||
other ->
|
||||
raise ArgumentError, "struct fields definition must be list, got: #{inspect(other)}"
|
||||
raise ArgumentError, "struct fields definition must be list, got: #{inspect other}"
|
||||
end
|
||||
|
||||
mapper = fn
|
||||
fields = :lists.map(fn
|
||||
{key, val} when is_atom(key) ->
|
||||
try do
|
||||
Macro.escape(val)
|
||||
@@ -83,29 +86,15 @@ defmodule Kernel.Utils do
|
||||
else
|
||||
_ -> {key, val}
|
||||
end
|
||||
|
||||
key when is_atom(key) ->
|
||||
{key, nil}
|
||||
|
||||
other ->
|
||||
raise ArgumentError, "struct field names must be atoms, got: #{inspect(other)}"
|
||||
end
|
||||
raise ArgumentError, "struct field names must be atoms, got: #{inspect other}"
|
||||
end, fields)
|
||||
|
||||
fields = :lists.map(mapper, fields)
|
||||
enforce_keys = List.wrap(Module.get_attribute(module, :enforce_keys))
|
||||
|
||||
foreach = fn
|
||||
key when is_atom(key) ->
|
||||
:ok
|
||||
|
||||
key ->
|
||||
raise ArgumentError, "keys given to @enforce_keys must be atoms, got: #{inspect(key)}"
|
||||
end
|
||||
|
||||
:lists.foreach(foreach, enforce_keys)
|
||||
|
||||
struct = :maps.put(:__struct__, module, :maps.from_list(fields))
|
||||
{struct, enforce_keys, Module.get_attribute(module, :derive)}
|
||||
{:maps.put(:__struct__, module, :maps.from_list(fields)),
|
||||
List.wrap(Module.get_attribute(module, :enforce_keys)),
|
||||
Module.get_attribute(module, :derive)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -124,144 +113,14 @@ defmodule Kernel.Utils do
|
||||
def raise(msg) when is_binary(msg) do
|
||||
RuntimeError.exception(msg)
|
||||
end
|
||||
|
||||
def raise(atom) when is_atom(atom) do
|
||||
atom.exception([])
|
||||
end
|
||||
|
||||
def raise(%_{__exception__: true} = exception) do
|
||||
def raise(%{__struct__: struct, __exception__: true} = exception) when is_atom(struct) do
|
||||
exception
|
||||
end
|
||||
|
||||
def raise(other) do
|
||||
ArgumentError.exception(
|
||||
"raise/1 and reraise/2 expect a module name, string or exception " <>
|
||||
"as the first argument, got: #{inspect(other)}"
|
||||
)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Callback for defguard.
|
||||
|
||||
Rewrites an expression so it can be used both inside and outside a guard.
|
||||
|
||||
Take, for example, the expression:
|
||||
|
||||
is_integer(value) and rem(value, 2) == 0
|
||||
|
||||
If we wanted to create a macro, `is_even`, from this expression, that could be
|
||||
used in guards, we'd have to take several things into account.
|
||||
|
||||
First, if this expression is being used inside a guard, `value` needs to be
|
||||
unquoted each place it occurs, since it has not yet been at that point in our
|
||||
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.
|
||||
|
||||
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
|
||||
that checks for its presence in a guard, then unquotes the variable references as
|
||||
appropriate.
|
||||
|
||||
The resulting transformation looks something like this:
|
||||
|
||||
> expression = quote do: is_integer(value) and rem(value, 2) == 0
|
||||
> 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
|
||||
end
|
||||
|
||||
"""
|
||||
defmacro defguard(args, expr) do
|
||||
defguard(args, expr, __CALLER__)
|
||||
end
|
||||
|
||||
@spec defguard([Macro.t()], Macro.t(), Macro.Env.t()) :: Macro.t()
|
||||
def defguard(args, expr, env) do
|
||||
{^args, vars} = extract_refs_from_args(args)
|
||||
{expr, _scope} = :elixir_expand.expand(expr, %{env | context: :guard, vars: vars})
|
||||
|
||||
quote do
|
||||
case Macro.Env.in_guard?(__CALLER__) do
|
||||
true -> unquote(literal_quote(unquote_every_ref(expr, vars)))
|
||||
false -> unquote(literal_quote(unquote_refs_once(expr, vars)))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp extract_refs_from_args(args) do
|
||||
Macro.postwalk(args, [], fn
|
||||
{ref, meta, context} = var, acc when is_atom(ref) and is_atom(context) ->
|
||||
{var, [{ref, var_context(meta, context)} | acc]}
|
||||
|
||||
node, acc ->
|
||||
{node, acc}
|
||||
end)
|
||||
end
|
||||
|
||||
# Finds every reference to `refs` in `guard` and wraps them in an unquote.
|
||||
defp unquote_every_ref(guard, refs) do
|
||||
Macro.postwalk(guard, fn
|
||||
{ref, meta, context} = var when is_atom(ref) and is_atom(context) ->
|
||||
case {ref, var_context(meta, context)} in refs do
|
||||
true -> literal_unquote(var)
|
||||
false -> var
|
||||
end
|
||||
|
||||
node ->
|
||||
node
|
||||
end)
|
||||
end
|
||||
|
||||
# Prefaces `guard` with unquoted versions of `refs`.
|
||||
defp unquote_refs_once(guard, refs) do
|
||||
{_, 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 and pair not in acc do
|
||||
true -> {var, [pair | acc]}
|
||||
false -> {var, acc}
|
||||
end
|
||||
|
||||
node, acc ->
|
||||
{node, acc}
|
||||
end)
|
||||
|
||||
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(exprs)}
|
||||
unquote(guard)
|
||||
end
|
||||
end
|
||||
|
||||
defp literal_quote(ast) do
|
||||
{:quote, [], [[do: ast]]}
|
||||
end
|
||||
|
||||
defp literal_unquote(ast) 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
|
||||
false -> kind
|
||||
end
|
||||
ArgumentError.exception("raise/1 expects an alias, string or exception as " <>
|
||||
"the first argument, got: #{inspect other}")
|
||||
end
|
||||
end
|
||||
|
||||
+22
-126
@@ -6,31 +6,6 @@ defmodule Keyword do
|
||||
element of the tuple is an atom and the second element
|
||||
can be any value.
|
||||
|
||||
For example, the following is a keyword list:
|
||||
|
||||
[{:exit_on_close, true}, {:active, :once}, {:packet_size, 1024}]
|
||||
|
||||
Elixir provides a special and more concise syntax for keyword lists
|
||||
that looks like this:
|
||||
|
||||
[exit_on_close: true, active: :once, packet_size: 1024]
|
||||
|
||||
This is also the syntax that Elixir uses to inspect keyword lists:
|
||||
|
||||
iex> [{:active, :once}]
|
||||
[active: :once]
|
||||
|
||||
The two syntaxes are completely equivalent. 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 can
|
||||
be omitted as well. For example, the following:
|
||||
|
||||
String.split("1-0", "-", trim: true, parts: 2)
|
||||
|
||||
is equivalent to:
|
||||
|
||||
String.split("1-0", "-", [trim: true, parts: 2])
|
||||
|
||||
A keyword may have duplicated keys so it is not strictly
|
||||
a key-value store. However most of the functions in this module
|
||||
behave exactly as a dictionary so they work similarly to
|
||||
@@ -40,10 +15,6 @@ defmodule Keyword do
|
||||
the given key, regardless if duplicated entries exist.
|
||||
Similarly, `Keyword.put/3` and `Keyword.delete/3` ensure all
|
||||
duplicated entries for a given key are removed when invoked.
|
||||
Note that operations that require keys to be found in the keyword
|
||||
list (like `Keyword.get/3`) need to traverse the list in order
|
||||
to find keys, so these operations may be slower than their map
|
||||
counterparts.
|
||||
|
||||
A handful of functions exist to handle duplicated keys, in
|
||||
particular, `Enum.into/2` allows creating new keywords without
|
||||
@@ -51,7 +22,7 @@ defmodule Keyword do
|
||||
a given key and `delete_first/2` deletes just one of the existing
|
||||
entries.
|
||||
|
||||
The functions in `Keyword` do not guarantee any property when
|
||||
The functions in Keyword do not guarantee any property when
|
||||
it comes to ordering. However, since a keyword list is simply a
|
||||
list, all the operations defined in `Enum` and `List` can be
|
||||
applied too, especially when ordering is required.
|
||||
@@ -88,7 +59,7 @@ defmodule Keyword do
|
||||
def keyword?(term)
|
||||
|
||||
def keyword?([{key, _value} | rest]) when is_atom(key), do: keyword?(rest)
|
||||
def keyword?([]), do: true
|
||||
def keyword?([]), do: true
|
||||
def keyword?(_other), do: false
|
||||
|
||||
@doc """
|
||||
@@ -119,7 +90,7 @@ defmodule Keyword do
|
||||
[a: 3]
|
||||
|
||||
"""
|
||||
@spec new(Enum.t()) :: t
|
||||
@spec new(Enum.t) :: t
|
||||
def new(pairs) do
|
||||
new(pairs, fn pair -> pair end)
|
||||
end
|
||||
@@ -137,13 +108,12 @@ defmodule Keyword do
|
||||
[a: :a, b: :b]
|
||||
|
||||
"""
|
||||
@spec new(Enum.t(), (term -> {key, value})) :: t
|
||||
@spec new(Enum.t, (term -> {key, value})) :: t
|
||||
def new(pairs, transform) do
|
||||
fun = fn el, acc ->
|
||||
{k, v} = transform.(el)
|
||||
put_new(acc, k, v)
|
||||
end
|
||||
|
||||
:lists.foldl(fun, [], Enum.reverse(pairs))
|
||||
end
|
||||
|
||||
@@ -175,6 +145,7 @@ defmodule Keyword do
|
||||
3
|
||||
|
||||
"""
|
||||
@spec get(t, key) :: value
|
||||
@spec get(t, key, value) :: value
|
||||
def get(keywords, key, default \\ nil) when is_list(keywords) and is_atom(key) do
|
||||
case :lists.keyfind(key, 1, keywords) do
|
||||
@@ -250,32 +221,29 @@ defmodule Keyword do
|
||||
"""
|
||||
@spec get_and_update(t, key, (value -> {get, value} | :pop)) :: {get, t} when get: term
|
||||
def get_and_update(keywords, key, fun)
|
||||
when is_list(keywords) and is_atom(key),
|
||||
do: get_and_update(keywords, [], key, fun)
|
||||
when is_list(keywords) and is_atom(key),
|
||||
do: get_and_update(keywords, [], key, fun)
|
||||
|
||||
defp get_and_update([{key, current} | t], acc, key, fun) do
|
||||
case fun.(current) do
|
||||
{get, value} ->
|
||||
{get, :lists.reverse(acc, [{key, value} | t])}
|
||||
|
||||
:pop ->
|
||||
{current, :lists.reverse(acc, t)}
|
||||
|
||||
other ->
|
||||
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
|
||||
end
|
||||
end
|
||||
|
||||
defp get_and_update([{_, _} = h | t], acc, key, fun), do: get_and_update(t, [h | acc], key, fun)
|
||||
defp get_and_update([{_, _} = h | t], acc, key, fun),
|
||||
do: get_and_update(t, [h | acc], key, fun)
|
||||
|
||||
defp get_and_update([], acc, key, fun) do
|
||||
case fun.(nil) do
|
||||
{get, update} ->
|
||||
{get, [{key, update} | :lists.reverse(acc)]}
|
||||
|
||||
:pop ->
|
||||
{nil, :lists.reverse(acc)}
|
||||
|
||||
other ->
|
||||
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
|
||||
end
|
||||
@@ -319,10 +287,8 @@ defmodule Keyword do
|
||||
case fun.(value) do
|
||||
{get, value} ->
|
||||
{get, :lists.reverse(acc, [{key, value} | delete(keywords, key)])}
|
||||
|
||||
:pop ->
|
||||
{value, :lists.reverse(acc, keywords)}
|
||||
|
||||
other ->
|
||||
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
|
||||
end
|
||||
@@ -397,7 +363,6 @@ defmodule Keyword do
|
||||
{^key, val} -> {true, val}
|
||||
{_, _} -> false
|
||||
end
|
||||
|
||||
:lists.filtermap(fun, keywords)
|
||||
end
|
||||
|
||||
@@ -456,20 +421,9 @@ defmodule Keyword do
|
||||
"""
|
||||
@spec delete(t, key, value) :: t
|
||||
def delete(keywords, key, value) when is_list(keywords) and is_atom(key) do
|
||||
delete_key_value(keywords, key, value, _deleted? = false)
|
||||
catch
|
||||
:not_deleted -> keywords
|
||||
:lists.filter(fn {k, v} -> k != key or v != value end, keywords)
|
||||
end
|
||||
|
||||
defp delete_key_value([{key, value} | rest], key, value, _deleted?),
|
||||
do: delete_key_value(rest, key, value, true)
|
||||
|
||||
defp delete_key_value([{_, _} = pair | rest], key, value, deleted?),
|
||||
do: [pair | delete_key_value(rest, key, value, deleted?)]
|
||||
|
||||
defp delete_key_value([], _key, _value, _deleted? = true), do: []
|
||||
defp delete_key_value([], _key, _value, _deleted? = false), do: throw(:not_deleted)
|
||||
|
||||
@doc """
|
||||
Deletes the entries in the keyword list for a specific `key`.
|
||||
|
||||
@@ -488,21 +442,10 @@ defmodule Keyword do
|
||||
|
||||
"""
|
||||
@spec delete(t, key) :: t
|
||||
@compile {:inline, delete: 2}
|
||||
def delete(keywords, key) when is_list(keywords) and is_atom(key) do
|
||||
delete_key(keywords, key, _deleted? = false)
|
||||
catch
|
||||
:not_deleted -> keywords
|
||||
:lists.filter(fn {k, _} -> k != key end, keywords)
|
||||
end
|
||||
|
||||
defp delete_key([{key, _} | rest], key, _deleted?), do: delete_key(rest, key, true)
|
||||
|
||||
defp delete_key([{_, _} = pair | rest], key, deleted?),
|
||||
do: [pair | delete_key(rest, key, deleted?)]
|
||||
|
||||
defp delete_key([], _key, _deleted? = true), do: []
|
||||
defp delete_key([], _key, _deleted? = false), do: throw(:not_deleted)
|
||||
|
||||
@doc """
|
||||
Deletes the first entry in the keyword list for a specific `key`.
|
||||
|
||||
@@ -518,15 +461,9 @@ defmodule Keyword do
|
||||
"""
|
||||
@spec delete_first(t, key) :: t
|
||||
def delete_first(keywords, key) when is_list(keywords) and is_atom(key) do
|
||||
delete_first_key(keywords, key)
|
||||
catch
|
||||
:not_deleted -> keywords
|
||||
:lists.keydelete(key, 1, keywords)
|
||||
end
|
||||
|
||||
defp delete_first_key([{key, _} | rest], key), do: rest
|
||||
defp delete_first_key([{_, _} = pair | rest], key), do: [pair | delete_first_key(rest, key)]
|
||||
defp delete_first_key([], _key), do: throw(:not_deleted)
|
||||
|
||||
@doc """
|
||||
Puts the given `value` under `key`.
|
||||
|
||||
@@ -597,37 +534,6 @@ defmodule Keyword do
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def replace(keywords, key, value) when is_list(keywords) and is_atom(key) do
|
||||
case :lists.keyfind(key, 1, keywords) do
|
||||
{^key, _} -> [{key, value} | delete(keywords, key)]
|
||||
false -> keywords
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Alters the value stored under `key` to `value`, but only
|
||||
if the entry `key` already exists in `keywords`.
|
||||
|
||||
If `key` is not present in `keywords`, a `KeyError` exception is raised.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Keyword.replace!([a: 1, b: 2, a: 4], :a, 3)
|
||||
[a: 3, b: 2]
|
||||
|
||||
iex> Keyword.replace!([a: 1], :b, 2)
|
||||
** (KeyError) key :b not found in: [a: 1]
|
||||
|
||||
"""
|
||||
@spec replace!(t, key, value) :: t
|
||||
def replace!(keywords, key, value) when is_list(keywords) and is_atom(key) do
|
||||
case :lists.keyfind(key, 1, keywords) do
|
||||
{^key, _} -> [{key, value} | delete(keywords, key)]
|
||||
false -> raise KeyError, key: key, term: keywords
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if two keywords are equal.
|
||||
|
||||
@@ -675,16 +581,12 @@ defmodule Keyword do
|
||||
fun = fn
|
||||
{key, _value} when is_atom(key) ->
|
||||
not has_key?(keywords2, key)
|
||||
|
||||
_ ->
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the first argument, got: #{inspect(keywords1)}"
|
||||
raise ArgumentError, message: "expected a keyword list as the first argument, got: #{inspect keywords1}"
|
||||
end
|
||||
|
||||
:lists.filter(fun, keywords1) ++ keywords2
|
||||
else
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the second argument, got: #{inspect(keywords2)}"
|
||||
raise ArgumentError, message: "expected a keyword list as the second argument, got: #{inspect keywords2}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -723,22 +625,19 @@ defmodule Keyword do
|
||||
|
||||
"""
|
||||
@spec merge(t, t, (key, value, value -> value)) :: t
|
||||
def merge(keywords1, keywords2, fun)
|
||||
when is_list(keywords1) and is_list(keywords2) and is_function(fun, 3) do
|
||||
def merge(keywords1, keywords2, fun) when is_list(keywords1) and is_list(keywords2) and is_function(fun, 3) do
|
||||
if keyword?(keywords1) do
|
||||
do_merge(keywords2, [], keywords1, keywords1, fun, keywords2)
|
||||
else
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the first argument, got: #{inspect(keywords1)}"
|
||||
raise ArgumentError, message: "expected a keyword list as the first argument, got: #{inspect keywords1}"
|
||||
end
|
||||
end
|
||||
|
||||
defp do_merge([{key, value2} | tail], acc, rest, original, fun, keywords2) when is_atom(key) do
|
||||
case :lists.keyfind(key, 1, original) do
|
||||
{^key, value1} ->
|
||||
acc = [{key, fun.(key, value1, value2)} | acc]
|
||||
original = :lists.keydelete(key, 1, original)
|
||||
do_merge(tail, acc, delete(rest, key), original, fun, keywords2)
|
||||
do_merge(tail, [{key, fun.(key, value1, value2)} | acc],
|
||||
delete(rest, key), :lists.keydelete(key, 1, original), fun, keywords2)
|
||||
|
||||
false ->
|
||||
do_merge(tail, [{key, value2} | acc], rest, original, fun, keywords2)
|
||||
@@ -750,8 +649,7 @@ defmodule Keyword do
|
||||
end
|
||||
|
||||
defp do_merge(_other, _acc, _rest, _original, _fun, keywords2) do
|
||||
raise ArgumentError,
|
||||
message: "expected a keyword list as the second argument, got: #{inspect(keywords2)}"
|
||||
raise ArgumentError, message: "expected a keyword list as the second argument, got: #{inspect keywords2}"
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -861,7 +759,7 @@ defmodule Keyword do
|
||||
def split(keywords, keys) when is_list(keywords) do
|
||||
fun = fn {k, v}, {take, drop} ->
|
||||
case k in keys do
|
||||
true -> {[{k, v} | take], drop}
|
||||
true -> {[{k, v} | take], drop}
|
||||
false -> {take, [{k, v} | drop]}
|
||||
end
|
||||
end
|
||||
@@ -905,7 +803,7 @@ defmodule Keyword do
|
||||
"""
|
||||
@spec drop(t, [key]) :: t
|
||||
def drop(keywords, keys) when is_list(keywords) do
|
||||
:lists.filter(fn {key, _} -> key not in keys end, keywords)
|
||||
:lists.filter(fn {k, _} -> not k in keys end, keywords)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -931,7 +829,6 @@ defmodule Keyword do
|
||||
case fetch(keywords, key) do
|
||||
{:ok, value} ->
|
||||
{value, delete(keywords, key)}
|
||||
|
||||
:error ->
|
||||
{default, keywords}
|
||||
end
|
||||
@@ -965,7 +862,6 @@ defmodule Keyword do
|
||||
case fetch(keywords, key) do
|
||||
{:ok, value} ->
|
||||
{value, delete(keywords, key)}
|
||||
|
||||
:error ->
|
||||
{fun.(), keywords}
|
||||
end
|
||||
@@ -1012,8 +908,8 @@ defmodule Keyword do
|
||||
|
||||
@doc false
|
||||
# TODO: Remove on 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
def size(keyword) do
|
||||
IO.warn "Keyword.size/1 is deprecated, please use Kernel.length/1"
|
||||
length(keyword)
|
||||
end
|
||||
end
|
||||
|
||||
+20
-141
@@ -78,13 +78,10 @@ defmodule List do
|
||||
|
||||
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
|
||||
codepoints with `ascii_printable?/2`.
|
||||
{: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'}]
|
||||
|
||||
## List and Enum modules
|
||||
|
||||
@@ -119,10 +116,9 @@ defmodule List do
|
||||
|
||||
"""
|
||||
@spec delete(list, any) :: list
|
||||
def delete(list, item)
|
||||
def delete([item | list], item), do: list
|
||||
def delete([other | list], item), do: [other | delete(list, item)]
|
||||
def delete([], _item), do: []
|
||||
def delete(list, item) do
|
||||
:lists.delete(item, list)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Duplicates the given element `n` times in a list.
|
||||
@@ -185,8 +181,8 @@ defmodule List do
|
||||
|
||||
"""
|
||||
@spec foldl([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
|
||||
def foldl(list, acc, fun) when is_list(list) and is_function(fun) do
|
||||
:lists.foldl(fun, acc, list)
|
||||
def foldl(list, acc, function) when is_list(list) and is_function(function) do
|
||||
:lists.foldl(function, acc, list)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -200,8 +196,8 @@ defmodule List do
|
||||
|
||||
"""
|
||||
@spec foldr([elem], acc, (elem, acc -> acc)) :: acc when elem: var, acc: var
|
||||
def foldr(list, acc, fun) when is_list(list) and is_function(fun) do
|
||||
:lists.foldr(fun, acc, list)
|
||||
def foldr(list, acc, function) when is_list(list) and is_function(function) do
|
||||
:lists.foldr(function, acc, list)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -220,7 +216,7 @@ defmodule List do
|
||||
|
||||
"""
|
||||
@spec first([elem]) :: nil | elem when elem: var
|
||||
def first([]), do: nil
|
||||
def first([]), do: nil
|
||||
def first([head | _]), do: head
|
||||
|
||||
@doc """
|
||||
@@ -385,7 +381,7 @@ defmodule List do
|
||||
def keytake(list, key, position) do
|
||||
case :lists.keytake(key, position + 1, list) do
|
||||
{:value, item, list} -> {item, list}
|
||||
false -> nil
|
||||
false -> nil
|
||||
end
|
||||
end
|
||||
|
||||
@@ -436,86 +432,10 @@ defmodule List do
|
||||
"""
|
||||
@spec zip([list]) :: [tuple]
|
||||
def zip([]), do: []
|
||||
|
||||
def zip(list_of_lists) when is_list(list_of_lists) do
|
||||
do_zip(list_of_lists, [])
|
||||
end
|
||||
|
||||
@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`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> List.ascii_printable?('abc')
|
||||
true
|
||||
|
||||
iex> List.ascii_printable?('abc' ++ [0])
|
||||
false
|
||||
|
||||
iex> List.ascii_printable?('abc' ++ [0], 2)
|
||||
true
|
||||
|
||||
Improper lists are not printable, even if made only of ascii characters:
|
||||
|
||||
iex> List.ascii_printable?('abc' ++ ?d)
|
||||
false
|
||||
|
||||
"""
|
||||
def ascii_printable?(list, counter \\ :infinity)
|
||||
|
||||
def ascii_printable?(_, 0) do
|
||||
true
|
||||
end
|
||||
|
||||
def ascii_printable?([char | rest], counter)
|
||||
when is_integer(char) and char >= 32 and char <= 126 do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\n | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\r | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\t | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\v | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\b | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\f | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\e | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
def ascii_printable?([?\a | rest], counter) do
|
||||
ascii_printable?(rest, decrement(counter))
|
||||
end
|
||||
|
||||
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 a list with `value` inserted at the specified `index`.
|
||||
|
||||
@@ -656,35 +576,6 @@ defmodule List do
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns `true` if `list` starts with the given `prefix` list; otherwise returns `false`.
|
||||
|
||||
If `prefix` is an empty list, it returns `true`.
|
||||
|
||||
### Examples
|
||||
|
||||
iex> List.starts_with?([1, 2, 3], [1, 2])
|
||||
true
|
||||
|
||||
iex> List.starts_with?([1, 2], [1, 2, 3])
|
||||
false
|
||||
|
||||
iex> List.starts_with?([:alpha], [])
|
||||
true
|
||||
|
||||
iex> List.starts_with?([], [:alpha])
|
||||
false
|
||||
|
||||
"""
|
||||
@spec starts_with?(list, list) :: boolean
|
||||
@spec starts_with?(list, []) :: true
|
||||
@spec starts_with?([], nonempty_list) :: false
|
||||
def starts_with?(list, prefix)
|
||||
|
||||
def starts_with?([head | tail], [head | prefix_tail]), do: starts_with?(tail, prefix_tail)
|
||||
def starts_with?(list, []) when is_list(list), do: true
|
||||
def starts_with?(list, [_ | _]) when is_list(list), do: false
|
||||
|
||||
@doc """
|
||||
Converts a charlist to an atom.
|
||||
|
||||
@@ -808,11 +699,8 @@ defmodule List do
|
||||
iex> List.to_string([0x0061, "bc"])
|
||||
"abc"
|
||||
|
||||
iex> List.to_string([0x0064, "ee", ['p']])
|
||||
"deep"
|
||||
|
||||
"""
|
||||
@spec to_string(:unicode.charlist()) :: String.t()
|
||||
@spec to_string(:unicode.charlist) :: String.t
|
||||
def to_string(list) when is_list(list) do
|
||||
try do
|
||||
:unicode.characters_to_binary(list)
|
||||
@@ -829,7 +717,7 @@ defmodule List do
|
||||
|
||||
Please check the given list or call inspect/1 to get the list representation, got:
|
||||
|
||||
#{inspect(list)}
|
||||
#{inspect list}
|
||||
"""
|
||||
else
|
||||
result when is_binary(result) ->
|
||||
@@ -885,24 +773,18 @@ defmodule List do
|
||||
compact_reverse(rest, [{kind, [elem | result]} | acc])
|
||||
end
|
||||
|
||||
defp compact_reverse(rest, [{:eq, elem}, {:ins, elem}, {:eq, other} | acc]) do
|
||||
compact_reverse(rest, [{:ins, elem}, {:eq, elem ++ other} | acc])
|
||||
end
|
||||
|
||||
defp compact_reverse([{kind, elem} | rest], acc) do
|
||||
compact_reverse(rest, [{kind, [elem]} | acc])
|
||||
end
|
||||
|
||||
defp each_diagonal(diag, limit, _paths, next_paths) when diag > limit do
|
||||
{:next, :lists.reverse(next_paths)}
|
||||
{:next, Enum.reverse(next_paths)}
|
||||
end
|
||||
|
||||
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])
|
||||
{:done, edits} -> {:done, edits}
|
||||
with {:cont, path} <- follow_snake(path) do
|
||||
each_diagonal(diag + 2, limit, rest, [path | next_paths])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1026,11 +908,8 @@ defmodule List do
|
||||
|
||||
defp do_zip(list, acc) do
|
||||
converter = fn x, acc -> do_zip_each(to_list(x), acc) end
|
||||
|
||||
case :lists.mapfoldl(converter, [], list) do
|
||||
{_, nil} ->
|
||||
:lists.reverse(acc)
|
||||
|
||||
{_, nil} -> :lists.reverse(acc)
|
||||
{mlist, heads} ->
|
||||
do_zip(mlist, [to_tuple(:lists.reverse(heads)) | acc])
|
||||
end
|
||||
@@ -1049,5 +928,5 @@ defmodule List do
|
||||
end
|
||||
|
||||
defp to_list(tuple) when is_tuple(tuple), do: Tuple.to_list(tuple)
|
||||
defp to_list(list) when is_list(list), do: list
|
||||
defp to_list(list) when is_list(list), do: list
|
||||
end
|
||||
|
||||
@@ -1,24 +1,18 @@
|
||||
defprotocol List.Chars do
|
||||
@moduledoc ~S"""
|
||||
The `List.Chars` protocol is responsible for
|
||||
converting a structure to a charlist (only if applicable).
|
||||
|
||||
The List.Chars protocol is responsible for
|
||||
converting a structure to a list (only if applicable).
|
||||
The only function required to be implemented is
|
||||
`to_charlist/1` which does the conversion.
|
||||
`to_charlist` which does the conversion.
|
||||
|
||||
The `to_charlist/1` function automatically imported
|
||||
by `Kernel` invokes this protocol.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Converts `term` to a charlist.
|
||||
"""
|
||||
@spec to_charlist(t) :: charlist
|
||||
def to_charlist(term)
|
||||
|
||||
# TODO: Deprecate by v1.5
|
||||
@doc false
|
||||
# TODO: Remove by 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
Kernel.def to_char_list(term) do
|
||||
__MODULE__.to_charlist(term)
|
||||
end
|
||||
@@ -38,9 +32,9 @@ defimpl List.Chars, for: BitString do
|
||||
|
||||
def to_charlist(term) do
|
||||
raise Protocol.UndefinedError,
|
||||
protocol: @protocol,
|
||||
value: term,
|
||||
description: "cannot convert a bitstring to a charlist"
|
||||
protocol: @protocol,
|
||||
value: term,
|
||||
description: "cannot convert a bitstring to a charlist"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
+289
-374
File diff suppressed because it is too large
Load Diff
+24
-59
@@ -36,20 +36,11 @@ defmodule Macro.Env do
|
||||
* `macros` - a list of macros imported from each module
|
||||
* `macro_aliases` - a list of aliases defined inside the current macro
|
||||
* `context_modules` - a list of modules defined in the current context
|
||||
* `lexical_tracker` - PID of the lexical tracker which is responsible for
|
||||
keeping user info
|
||||
* `vars` - a list keeping all defined variables as `{var, context}`
|
||||
|
||||
The following fields are private and must not be accessed or relied on:
|
||||
|
||||
* `export_vars` - a list keeping all variables to be exported in a
|
||||
construct (may be `nil`)
|
||||
* `match_vars` - controls how "new" variables are handled. Inside a
|
||||
match it is a list with all variables in a match. Outside of a match
|
||||
is either `:warn` or `:apply`
|
||||
* `prematch_vars` - a list of variables defined before a match (is
|
||||
`nil` when not inside a match)
|
||||
|
||||
* `lexical_tracker` - PID of the lexical tracker which is responsible for
|
||||
keeping user info
|
||||
"""
|
||||
|
||||
@type name_arity :: {atom, arity}
|
||||
@@ -63,36 +54,28 @@ defmodule Macro.Env do
|
||||
@type macros :: [{module, [name_arity]}]
|
||||
@type context_modules :: [module]
|
||||
@type vars :: [{atom, atom | non_neg_integer}]
|
||||
@type lexical_tracker :: pid | nil
|
||||
@type export_vars :: vars | nil
|
||||
@type lexical_tracker :: pid
|
||||
@type local :: atom | nil
|
||||
|
||||
@opaque export_vars :: vars | nil
|
||||
@opaque match_vars :: vars | :warn | :apply
|
||||
@opaque prematch_vars :: vars | nil
|
||||
|
||||
@type t :: %{
|
||||
__struct__: __MODULE__,
|
||||
module: atom,
|
||||
file: file,
|
||||
line: line,
|
||||
function: name_arity | nil,
|
||||
context: context,
|
||||
requires: requires,
|
||||
aliases: aliases,
|
||||
functions: functions,
|
||||
macros: macros,
|
||||
macro_aliases: aliases,
|
||||
context_modules: context_modules,
|
||||
vars: vars,
|
||||
export_vars: export_vars,
|
||||
match_vars: match_vars,
|
||||
prematch_vars: prematch_vars,
|
||||
lexical_tracker: lexical_tracker
|
||||
}
|
||||
@type t :: %{__struct__: __MODULE__,
|
||||
module: atom,
|
||||
file: file,
|
||||
line: line,
|
||||
function: name_arity | nil,
|
||||
context: context,
|
||||
requires: requires,
|
||||
aliases: aliases,
|
||||
functions: functions,
|
||||
macros: macros,
|
||||
macro_aliases: aliases,
|
||||
context_modules: context_modules,
|
||||
vars: vars,
|
||||
export_vars: export_vars,
|
||||
lexical_tracker: lexical_tracker}
|
||||
|
||||
def __struct__ do
|
||||
%{
|
||||
__struct__: __MODULE__,
|
||||
%{__struct__: __MODULE__,
|
||||
module: nil,
|
||||
file: "nofile",
|
||||
line: 0,
|
||||
@@ -105,40 +88,24 @@ defmodule Macro.Env do
|
||||
macro_aliases: [],
|
||||
context_modules: [],
|
||||
vars: [],
|
||||
lexical_tracker: nil,
|
||||
export_vars: nil,
|
||||
match_vars: :warn,
|
||||
prematch_vars: nil
|
||||
}
|
||||
lexical_tracker: nil}
|
||||
end
|
||||
|
||||
def __struct__(kv) do
|
||||
Enum.reduce(kv, __struct__(), fn {k, v}, acc -> :maps.update(k, v, acc) end)
|
||||
Enum.reduce kv, __struct__(), fn {k, v}, acc -> :maps.update(k, v, acc) end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a keyword list containing the file and line
|
||||
information as keys.
|
||||
"""
|
||||
@spec location(t) :: keyword
|
||||
@spec location(t) :: Keyword.t
|
||||
def location(env)
|
||||
|
||||
def location(%{__struct__: Macro.Env, file: file, line: line}) do
|
||||
[file: file, line: line]
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a `Macro.Env` in the match context.
|
||||
"""
|
||||
@spec to_match(t) :: t
|
||||
def to_match(%{__struct__: Macro.Env, context: :match} = env) do
|
||||
env
|
||||
end
|
||||
|
||||
def to_match(%{__struct__: Macro.Env, prematch_vars: nil, vars: vars} = env) do
|
||||
%{env | context: :match, match_vars: [], prematch_vars: vars}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns whether the compilation environment is currently
|
||||
inside a guard.
|
||||
@@ -163,10 +130,8 @@ defmodule Macro.Env do
|
||||
cond do
|
||||
is_nil(env.module) ->
|
||||
[{:elixir_compiler, :__FILE__, 1, relative_location(env)}]
|
||||
|
||||
is_nil(env.function) ->
|
||||
[{env.module, :__MODULE__, 0, relative_location(env)}]
|
||||
|
||||
true ->
|
||||
{name, arity} = env.function
|
||||
[{env.module, name, arity, relative_location(env)}]
|
||||
@@ -174,6 +139,6 @@ defmodule Macro.Env do
|
||||
end
|
||||
|
||||
defp relative_location(env) do
|
||||
[file: String.to_charlist(Path.relative_to_cwd(env.file)), line: env.line]
|
||||
[file: Path.relative_to_cwd(env.file), line: env.line]
|
||||
end
|
||||
end
|
||||
|
||||
+113
-196
@@ -14,7 +14,7 @@ defmodule Map do
|
||||
in the example above has a different order than the map that was created).
|
||||
|
||||
Maps do not impose any restriction on the key type: anything can be a key in a
|
||||
map. As a key-value structure, maps do not allow duplicated keys. Keys are
|
||||
map. As a key-value structure, maps do not allow duplicated keys; keys are
|
||||
compared using the exact-equality operator (`===`). If colliding keys are defined
|
||||
in a map literal, the last one prevails.
|
||||
|
||||
@@ -39,7 +39,7 @@ defmodule Map do
|
||||
|
||||
The alternative access syntax `map.key` is provided alongside `[]` when the
|
||||
map has a `:key` key; note that while `map[key]` will return `nil` if `map`
|
||||
doesn't contain `key`, `map.key` will raise if `map` doesn't contain
|
||||
doesn't contain the key `key`, `map.key` will raise if `map` doesn't contain
|
||||
the key `:key`.
|
||||
|
||||
iex> map = %{foo: "bar", baz: "bong"}
|
||||
@@ -94,7 +94,7 @@ defmodule Map do
|
||||
|
||||
@type key :: any
|
||||
@type value :: any
|
||||
@compile {:inline, fetch: 2, fetch!: 2, get: 2, put: 3, delete: 2, has_key?: 2, replace!: 3}
|
||||
@compile {:inline, fetch: 2, put: 3, delete: 2, has_key?: 2}
|
||||
|
||||
@doc """
|
||||
Returns all keys from `map`.
|
||||
@@ -162,17 +162,16 @@ defmodule Map do
|
||||
%{a: 3}
|
||||
|
||||
"""
|
||||
@spec new(Enumerable.t()) :: map
|
||||
@spec new(Enumerable.t) :: map
|
||||
def new(enumerable)
|
||||
def new(list) when is_list(list), do: :maps.from_list(list)
|
||||
def new(%_{} = struct), do: new_from_enum(struct)
|
||||
def new(%{__struct__: _} = struct), do: new_from_enum(struct)
|
||||
def new(%{} = map), do: map
|
||||
def new(enum), do: new_from_enum(enum)
|
||||
|
||||
defp new_from_enum(enumerable) do
|
||||
enumerable
|
||||
|> Enum.to_list()
|
||||
|> :maps.from_list()
|
||||
|> Enum.to_list
|
||||
|> :maps.from_list
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -186,17 +185,17 @@ defmodule Map do
|
||||
%{a: :a, b: :b}
|
||||
|
||||
"""
|
||||
@spec new(Enumerable.t(), (term -> {key, value})) :: map
|
||||
@spec new(Enumerable.t, (term -> {key, value})) :: map
|
||||
def new(enumerable, transform) when is_function(transform, 1) do
|
||||
enumerable
|
||||
|> Enum.to_list()
|
||||
|> Enum.to_list
|
||||
|> new_transform(transform, [])
|
||||
end
|
||||
|
||||
defp new_transform([], _fun, acc) do
|
||||
acc
|
||||
|> :lists.reverse()
|
||||
|> :maps.from_list()
|
||||
|> :lists.reverse
|
||||
|> :maps.from_list
|
||||
end
|
||||
|
||||
defp new_transform([item | rest], fun, acc) do
|
||||
@@ -213,7 +212,6 @@ defmodule Map do
|
||||
iex> Map.has_key?(%{a: 1}, :b)
|
||||
false
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec has_key?(map, key) :: boolean
|
||||
def has_key?(map, key), do: :maps.is_key(key, map)
|
||||
@@ -231,7 +229,6 @@ defmodule Map do
|
||||
iex> Map.fetch(%{a: 1}, :b)
|
||||
:error
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec fetch(map, key) :: {:ok, value} | :error
|
||||
def fetch(map, key), do: :maps.find(key, map)
|
||||
@@ -253,7 +250,10 @@ defmodule Map do
|
||||
"""
|
||||
@spec fetch!(map, key) :: value | no_return
|
||||
def fetch!(map, key) do
|
||||
:maps.get(key, map)
|
||||
case fetch(map, key) do
|
||||
{:ok, value} -> value
|
||||
:error -> raise KeyError, key: key, term: map
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -263,60 +263,19 @@ defmodule Map do
|
||||
## Examples
|
||||
|
||||
iex> Map.put_new(%{a: 1}, :b, 2)
|
||||
%{a: 1, b: 2}
|
||||
%{b: 2, a: 1}
|
||||
iex> Map.put_new(%{a: 1, b: 2}, :a, 3)
|
||||
%{a: 1, b: 2}
|
||||
|
||||
"""
|
||||
@spec put_new(map, key, value) :: map
|
||||
def put_new(map, key, value) do
|
||||
case map do
|
||||
%{^key => _value} ->
|
||||
map
|
||||
|
||||
%{} ->
|
||||
put(map, key, value)
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other})
|
||||
case has_key?(map, key) do
|
||||
true -> map
|
||||
false -> put(map, key, value)
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def replace(map, key, value) do
|
||||
case map do
|
||||
%{^key => _value} ->
|
||||
put(map, key, value)
|
||||
|
||||
%{} ->
|
||||
map
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other})
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Alters the value stored under `key` to `value`, but only
|
||||
if the entry `key` already exists in `map`.
|
||||
|
||||
If `key` is not present in `map`, a `KeyError` exception is raised.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Map.replace!(%{a: 1, b: 2}, :a, 3)
|
||||
%{a: 3, b: 2}
|
||||
|
||||
iex> Map.replace!(%{a: 1}, :b, 2)
|
||||
** (KeyError) key :b not found in: %{a: 1}
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec replace!(map, key, value) :: map
|
||||
def replace!(map, key, value) do
|
||||
:maps.update(key, value, map)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Evaluates `fun` and puts the result under `key`
|
||||
in `map` unless `key` is already present.
|
||||
@@ -340,15 +299,9 @@ defmodule Map do
|
||||
"""
|
||||
@spec put_new_lazy(map, key, (() -> value)) :: map
|
||||
def put_new_lazy(map, key, fun) when is_function(fun, 0) do
|
||||
case map do
|
||||
%{^key => _value} ->
|
||||
map
|
||||
|
||||
%{} ->
|
||||
put(map, key, fun.())
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other})
|
||||
case has_key?(map, key) do
|
||||
true -> map
|
||||
false -> put(map, key, fun.())
|
||||
end
|
||||
end
|
||||
|
||||
@@ -364,31 +317,26 @@ defmodule Map do
|
||||
%{a: 1, c: 3}
|
||||
|
||||
"""
|
||||
@spec take(map, Enumerable.t()) :: map
|
||||
@spec take(map, Enumerable.t) :: map
|
||||
def take(map, keys)
|
||||
|
||||
def take(map, keys) when is_map(map) do
|
||||
keys
|
||||
|> Enum.to_list()
|
||||
|> take(map, [])
|
||||
|> Enum.to_list
|
||||
|> do_take(map, [])
|
||||
end
|
||||
|
||||
def take(non_map, _keys) do
|
||||
:erlang.error({:badmap, non_map})
|
||||
end
|
||||
|
||||
defp take([], _map, acc) do
|
||||
:maps.from_list(acc)
|
||||
end
|
||||
|
||||
defp take([key | rest], map, acc) do
|
||||
acc =
|
||||
case map do
|
||||
%{^key => value} -> [{key, value} | acc]
|
||||
%{} -> acc
|
||||
end
|
||||
|
||||
take(rest, map, acc)
|
||||
defp do_take([], _map, acc), do: :maps.from_list(acc)
|
||||
defp do_take([key | rest], map, acc) do
|
||||
acc = case fetch(map, key) do
|
||||
{:ok, value} -> [{key, value} | acc]
|
||||
:error -> acc
|
||||
end
|
||||
do_take(rest, map, acc)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -410,17 +358,12 @@ defmodule Map do
|
||||
3
|
||||
|
||||
"""
|
||||
@spec get(map, key) :: value
|
||||
@spec get(map, key, value) :: value
|
||||
def get(map, key, default \\ nil) do
|
||||
case map do
|
||||
%{^key => value} ->
|
||||
value
|
||||
|
||||
%{} ->
|
||||
default
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other}, [map, key, default])
|
||||
case fetch(map, key) do
|
||||
{:ok, value} -> value
|
||||
:error -> default
|
||||
end
|
||||
end
|
||||
|
||||
@@ -448,15 +391,9 @@ defmodule Map do
|
||||
"""
|
||||
@spec get_lazy(map, key, (() -> value)) :: value
|
||||
def get_lazy(map, key, fun) when is_function(fun, 0) do
|
||||
case map do
|
||||
%{^key => value} ->
|
||||
value
|
||||
|
||||
%{} ->
|
||||
fun.()
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other}, [map, key, fun])
|
||||
case fetch(map, key) do
|
||||
{:ok, value} -> value
|
||||
:error -> fun.()
|
||||
end
|
||||
end
|
||||
|
||||
@@ -470,7 +407,6 @@ defmodule Map do
|
||||
iex> Map.put(%{a: 1, b: 2}, :a, 3)
|
||||
%{a: 3, b: 2}
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec put(map, key, value) :: map
|
||||
def put(map, key, value) do
|
||||
@@ -489,7 +425,6 @@ defmodule Map do
|
||||
iex> Map.delete(%{b: 2}, :a)
|
||||
%{b: 2}
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec delete(map, key) :: map
|
||||
def delete(map, key), do: :maps.remove(key, map)
|
||||
@@ -505,8 +440,6 @@ defmodule Map do
|
||||
side into the struct, even if the key is not part of the struct. Instead,
|
||||
use `Kernel.struct/2`.
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Map.merge(%{a: 1, b: 2}, %{a: 3, d: 4})
|
||||
@@ -517,12 +450,12 @@ defmodule Map do
|
||||
defdelegate merge(map1, map2), to: :maps
|
||||
|
||||
@doc """
|
||||
Merges two maps into one, resolving conflicts through the given `fun`.
|
||||
Merges two maps into one, resolving conflicts through the given `callback`.
|
||||
|
||||
All keys in `map2` will be added to `map1`. The given function will be invoked
|
||||
when there are duplicate keys; its arguments are `key` (the duplicate key),
|
||||
`value1` (the value of `key` in `map1`), and `value2` (the value of `key` in
|
||||
`map2`). The value returned by `fun` is used as the value under `key` in
|
||||
`map2`). The value returned by `callback` is used as the value under `key` in
|
||||
the resulting map.
|
||||
|
||||
## Examples
|
||||
@@ -534,20 +467,10 @@ defmodule Map do
|
||||
|
||||
"""
|
||||
@spec merge(map, map, (key, value, value -> value)) :: map
|
||||
def merge(map1, map2, fun) when is_function(fun, 3) do
|
||||
if map_size(map1) > map_size(map2) do
|
||||
folder = fn key, val2, acc ->
|
||||
update(acc, key, val2, fn val1 -> fun.(key, val1, val2) end)
|
||||
end
|
||||
|
||||
:maps.fold(folder, map1, map2)
|
||||
else
|
||||
folder = fn key, val2, acc ->
|
||||
update(acc, key, val2, fn val1 -> fun.(key, val2, val1) end)
|
||||
end
|
||||
|
||||
:maps.fold(folder, map2, map1)
|
||||
end
|
||||
def merge(map1, map2, callback) when is_function(callback, 3) do
|
||||
:maps.fold fn k, v2, acc ->
|
||||
update(acc, k, v2, fn(v1) -> callback.(k, v1, v2) end)
|
||||
end, map1, map2
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -555,8 +478,7 @@ defmodule Map do
|
||||
|
||||
If `key` is present in `map` with value `value`, `fun` is invoked with
|
||||
argument `value` and its result is used as the new value of `key`. If `key` is
|
||||
not present in `map`, `initial` is inserted as the value of `key`. The initial
|
||||
value will not be passed through the update function.
|
||||
not present in `map`, `initial` is inserted as the value of `key`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -568,15 +490,11 @@ defmodule Map do
|
||||
"""
|
||||
@spec update(map, key, value, (value -> value)) :: map
|
||||
def update(map, key, initial, fun) when is_function(fun, 1) do
|
||||
case map do
|
||||
%{^key => value} ->
|
||||
case fetch(map, key) do
|
||||
{:ok, value} ->
|
||||
put(map, key, fun.(value))
|
||||
|
||||
%{} ->
|
||||
:error ->
|
||||
put(map, key, initial)
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other}, [map, key, initial, fun])
|
||||
end
|
||||
end
|
||||
|
||||
@@ -599,9 +517,9 @@ defmodule Map do
|
||||
"""
|
||||
@spec pop(map, key, value) :: {value, map}
|
||||
def pop(map, key, default \\ nil) do
|
||||
case :maps.take(key, map) do
|
||||
{_, _} = tuple -> tuple
|
||||
:error -> {default, map}
|
||||
case map do
|
||||
%{^key => value} -> {value, delete(map, key)}
|
||||
%{} -> {default, map}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -631,15 +549,9 @@ defmodule Map do
|
||||
"""
|
||||
@spec pop_lazy(map, key, (() -> value)) :: {value, map}
|
||||
def pop_lazy(map, key, fun) when is_function(fun, 0) do
|
||||
case map do
|
||||
%{^key => value} ->
|
||||
{value, delete(map, key)}
|
||||
|
||||
%{} ->
|
||||
{fun.(), map}
|
||||
|
||||
other ->
|
||||
:erlang.error({:badmap, other}, [map, key, fun])
|
||||
case fetch(map, key) do
|
||||
{:ok, value} -> {value, delete(map, key)}
|
||||
:error -> {fun.(), map}
|
||||
end
|
||||
end
|
||||
|
||||
@@ -654,27 +566,26 @@ defmodule Map do
|
||||
%{a: 1, c: 3}
|
||||
|
||||
"""
|
||||
@spec drop(map, Enumerable.t()) :: map
|
||||
@spec drop(map, Enumerable.t) :: map
|
||||
def drop(map, keys)
|
||||
|
||||
def drop(map, keys) when is_map(map) do
|
||||
keys
|
||||
|> Enum.to_list()
|
||||
|> Enum.to_list
|
||||
|> drop_list(map)
|
||||
end
|
||||
|
||||
def drop(non_map, keys) do
|
||||
:erlang.error({:badmap, non_map}, [non_map, keys])
|
||||
def drop(non_map, _keys) do
|
||||
:erlang.error({:badmap, non_map})
|
||||
end
|
||||
|
||||
defp drop_list([], acc), do: acc
|
||||
|
||||
defp drop_list([key | rest], acc) do
|
||||
drop_list(rest, delete(acc, key))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Takes all entries corresponding to the given `keys` in `map` and extracts
|
||||
Takes all entries corresponding to the given `keys` in `maps` and extracts
|
||||
them into a separate map.
|
||||
|
||||
Returns a tuple with the new map and the old map with removed keys.
|
||||
@@ -687,30 +598,28 @@ defmodule Map do
|
||||
{%{a: 1, c: 3}, %{b: 2}}
|
||||
|
||||
"""
|
||||
@spec split(map, Enumerable.t()) :: {map, map}
|
||||
@spec split(map, Enumerable.t) :: {map, map}
|
||||
def split(map, keys)
|
||||
|
||||
def split(map, keys) when is_map(map) do
|
||||
keys
|
||||
|> Enum.to_list()
|
||||
|> split([], map)
|
||||
|> Enum.to_list
|
||||
|> do_split([], map)
|
||||
end
|
||||
|
||||
def split(non_map, keys) do
|
||||
:erlang.error({:badmap, non_map}, [non_map, keys])
|
||||
def split(non_map, _keys) do
|
||||
:erlang.error({:badmap, non_map})
|
||||
end
|
||||
|
||||
defp split([], included, excluded) do
|
||||
{:maps.from_list(included), excluded}
|
||||
defp do_split([], inc, exc) do
|
||||
{:maps.from_list(inc), exc}
|
||||
end
|
||||
|
||||
defp split([key | rest], included, excluded) do
|
||||
case excluded do
|
||||
%{^key => value} ->
|
||||
split(rest, [{key, value} | included], delete(excluded, key))
|
||||
|
||||
_other ->
|
||||
split(rest, included, excluded)
|
||||
defp do_split([key | rest], inc, exc) do
|
||||
case fetch(exc, key) do
|
||||
{:ok, value} ->
|
||||
do_split(rest, [{key, value} | inc], delete(exc, key))
|
||||
:error ->
|
||||
do_split(rest, inc, exc)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -730,12 +639,18 @@ defmodule Map do
|
||||
** (KeyError) key :b not found in: %{a: 1}
|
||||
|
||||
"""
|
||||
@spec update!(map, key, (value -> value)) :: map
|
||||
def update!(map, key, fun) when is_function(fun, 1) do
|
||||
value = fetch!(map, key)
|
||||
put(map, key, fun.(value))
|
||||
@spec update!(map, key, (value -> value)) :: map | no_return
|
||||
def update!(%{} = map, key, fun) when is_function(fun, 1) do
|
||||
case fetch(map, key) do
|
||||
{:ok, value} ->
|
||||
put(map, key, fun.(value))
|
||||
:error ->
|
||||
raise KeyError, term: map, key: key
|
||||
end
|
||||
end
|
||||
|
||||
def update!(map, _key, _fun), do: :erlang.error({:badmap, map})
|
||||
|
||||
@doc """
|
||||
Gets the value from `key` and updates it, all in one pass.
|
||||
|
||||
@@ -769,21 +684,25 @@ defmodule Map do
|
||||
|
||||
"""
|
||||
@spec get_and_update(map, key, (value -> {get, value} | :pop)) :: {get, map} when get: term
|
||||
def get_and_update(map, key, fun) when is_function(fun, 1) do
|
||||
current = get(map, key)
|
||||
def get_and_update(%{} = map, key, fun) when is_function(fun, 1) do
|
||||
current =
|
||||
case :maps.find(key, map) do
|
||||
{:ok, value} -> value
|
||||
:error -> nil
|
||||
end
|
||||
|
||||
case fun.(current) do
|
||||
{get, update} ->
|
||||
{get, put(map, key, update)}
|
||||
|
||||
{get, :maps.put(key, update, map)}
|
||||
:pop ->
|
||||
{current, delete(map, key)}
|
||||
|
||||
{current, :maps.remove(key, map)}
|
||||
other ->
|
||||
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
|
||||
end
|
||||
end
|
||||
|
||||
def get_and_update(map, _key, _fun), do: :erlang.error({:badmap, map})
|
||||
|
||||
@doc """
|
||||
Gets the value from `key` and updates it. Raises if there is no `key`.
|
||||
|
||||
@@ -808,23 +727,25 @@ defmodule Map do
|
||||
{1, %{}}
|
||||
|
||||
"""
|
||||
@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)
|
||||
|
||||
case fun.(value) do
|
||||
{get, update} ->
|
||||
{get, put(map, key, update)}
|
||||
|
||||
:pop ->
|
||||
{value, delete(map, key)}
|
||||
|
||||
other ->
|
||||
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
|
||||
@spec get_and_update!(map, key, (value -> {get, value})) :: {get, map} | no_return when get: term
|
||||
def get_and_update!(%{} = map, key, fun) when is_function(fun, 1) do
|
||||
case :maps.find(key, map) do
|
||||
{:ok, value} ->
|
||||
case fun.(value) do
|
||||
{get, update} ->
|
||||
{get, :maps.put(key, update, map)}
|
||||
:pop ->
|
||||
{value, :maps.remove(key, map)}
|
||||
other ->
|
||||
raise "the given function must return a two-element tuple or :pop, got: #{inspect(other)}"
|
||||
end
|
||||
:error ->
|
||||
raise KeyError, term: map, key: key
|
||||
end
|
||||
end
|
||||
|
||||
def get_and_update!(map, _key, _fun), do: :erlang.error({:badmap, map})
|
||||
|
||||
@doc """
|
||||
Converts a `struct` to map.
|
||||
|
||||
@@ -847,11 +768,11 @@ defmodule Map do
|
||||
"""
|
||||
@spec from_struct(atom | struct) :: map
|
||||
def from_struct(struct) when is_atom(struct) do
|
||||
delete(struct.__struct__(), :__struct__)
|
||||
:maps.remove(:__struct__, struct.__struct__)
|
||||
end
|
||||
|
||||
def from_struct(%_{} = struct) do
|
||||
delete(struct, :__struct__)
|
||||
def from_struct(%{__struct__: _} = struct) do
|
||||
:maps.remove(:__struct__, struct)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -869,16 +790,12 @@ defmodule Map do
|
||||
|
||||
"""
|
||||
@spec equal?(map, map) :: boolean
|
||||
def equal?(map1, map2)
|
||||
|
||||
def equal?(%{} = map1, %{} = map2), do: map1 === map2
|
||||
def equal?(%{} = map1, map2), do: :erlang.error({:badmap, map2}, [map1, map2])
|
||||
def equal?(term, other), do: :erlang.error({:badmap, term}, [term, other])
|
||||
|
||||
@doc false
|
||||
# TODO: Remove on 2.0
|
||||
# (hard-deprecated in elixir_dispatch)
|
||||
def size(map) do
|
||||
IO.warn "Map.size/1 is deprecated, please use Kernel.map_size/1"
|
||||
map_size(map)
|
||||
end
|
||||
end
|
||||
|
||||
+88
-118
@@ -8,15 +8,15 @@ defmodule MapSet do
|
||||
iex> MapSet.new
|
||||
#MapSet<[]>
|
||||
|
||||
A set can contain any kind of elements, and elements in a set don't have to be
|
||||
A set can contain any kind of elements and elements in a set don't have to be
|
||||
of the same type. By definition, sets can't contain duplicate elements: when
|
||||
inserting an element in a set where it's already present, the insertion is
|
||||
simply a no-op.
|
||||
|
||||
iex> map_set = MapSet.new
|
||||
iex> MapSet.put(map_set, "foo")
|
||||
iex> set = MapSet.new
|
||||
iex> MapSet.put(set, "foo")
|
||||
#MapSet<["foo"]>
|
||||
iex> map_set |> MapSet.put("foo") |> MapSet.put("foo")
|
||||
iex> set |> MapSet.put("foo") |> MapSet.put("foo")
|
||||
#MapSet<["foo"]>
|
||||
|
||||
A `MapSet` is represented internally using the `%MapSet{}` struct. This struct
|
||||
@@ -28,21 +28,16 @@ defmodule MapSet do
|
||||
Note that, however, the struct fields are private and must not be accessed
|
||||
directly; use the functions in this module to perform operations on sets.
|
||||
|
||||
`MapSet`s can also be constructed starting from other collection-type data
|
||||
Sets can also be constructed starting from other collection-type data
|
||||
structures: for example, see `MapSet.new/1` or `Enum.into/2`.
|
||||
"""
|
||||
|
||||
# MapSets have an underlying Map. MapSet elements are keys of said map,
|
||||
# and this empty list is their associated dummy value.
|
||||
@dummy_value []
|
||||
|
||||
@type value :: term
|
||||
|
||||
@opaque t(value) :: %__MODULE__{map: %{optional(value) => []}}
|
||||
@opaque t(value) :: %__MODULE__{map: %{optional(value) => true}}
|
||||
@type t :: t(term)
|
||||
|
||||
# TODO: Remove version key on Elixir 2.0
|
||||
defstruct map: %{}, version: 2
|
||||
defstruct map: %{}
|
||||
|
||||
@doc """
|
||||
Returns a new set.
|
||||
@@ -67,22 +62,19 @@ defmodule MapSet do
|
||||
#MapSet<[1, 2, 3]>
|
||||
|
||||
"""
|
||||
@spec new(Enum.t()) :: t
|
||||
def new(enumerable)
|
||||
|
||||
def new(%__MODULE__{} = map_set), do: map_set
|
||||
|
||||
@spec new(Enum.t) :: t
|
||||
def new(%__MODULE__{} = mapset), do: mapset
|
||||
def new(enumerable) do
|
||||
map =
|
||||
enumerable
|
||||
|> Enum.to_list()
|
||||
|> new_from_list([])
|
||||
|> Enum.to_list
|
||||
|> do_new([])
|
||||
|
||||
%MapSet{map: map}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a set from an enumerable via the transformation function.
|
||||
Creates a mapset from an enumerable via the transformation function.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -90,53 +82,55 @@ defmodule MapSet do
|
||||
#MapSet<[2, 4]>
|
||||
|
||||
"""
|
||||
@spec new(Enum.t(), (term -> val)) :: t(val) when val: value
|
||||
@spec new(Enum.t, (term -> val)) :: t(val) when val: value
|
||||
def new(enumerable, transform) when is_function(transform, 1) do
|
||||
map =
|
||||
enumerable
|
||||
|> Enum.to_list()
|
||||
|> new_from_list_transform(transform, [])
|
||||
|> Enum.to_list
|
||||
|> do_new_transform(transform, [])
|
||||
|
||||
%MapSet{map: map}
|
||||
end
|
||||
|
||||
defp new_from_list([], acc) do
|
||||
:maps.from_list(acc)
|
||||
defp do_new([], acc) do
|
||||
acc
|
||||
|> :lists.reverse
|
||||
|> :maps.from_list
|
||||
end
|
||||
defp do_new([item | rest], acc) do
|
||||
do_new(rest, [{item, true} | acc])
|
||||
end
|
||||
|
||||
defp new_from_list([item | rest], acc) do
|
||||
new_from_list(rest, [{item, @dummy_value} | acc])
|
||||
defp do_new_transform([], _fun, acc) do
|
||||
acc
|
||||
|> :lists.reverse
|
||||
|> :maps.from_list
|
||||
end
|
||||
|
||||
defp new_from_list_transform([], _fun, acc) do
|
||||
:maps.from_list(acc)
|
||||
end
|
||||
|
||||
defp new_from_list_transform([item | rest], fun, acc) do
|
||||
new_from_list_transform(rest, fun, [{fun.(item), @dummy_value} | acc])
|
||||
defp do_new_transform([item | rest], fun, acc) do
|
||||
do_new_transform(rest, fun, [{fun.(item), true} | acc])
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes `value` from `map_set`.
|
||||
Deletes `value` from `set`.
|
||||
|
||||
Returns a new set which is a copy of `map_set` but without `value`.
|
||||
Returns a new set which is a copy of `set` but without `value`.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> map_set = MapSet.new([1, 2, 3])
|
||||
iex> MapSet.delete(map_set, 4)
|
||||
iex> set = MapSet.new([1, 2, 3])
|
||||
iex> MapSet.delete(set, 4)
|
||||
#MapSet<[1, 2, 3]>
|
||||
iex> MapSet.delete(map_set, 2)
|
||||
iex> MapSet.delete(set, 2)
|
||||
#MapSet<[1, 3]>
|
||||
|
||||
"""
|
||||
@spec delete(t(val1), val2) :: t(val1) when val1: value, val2: value
|
||||
def delete(%MapSet{map: map} = map_set, value) do
|
||||
%{map_set | map: Map.delete(map, value)}
|
||||
def delete(%MapSet{map: map} = set, value) do
|
||||
%{set | map: Map.delete(map, value)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a set that is `map_set1` without the members of `map_set2`.
|
||||
Returns a set that is `set1` without the members of `set2`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -145,17 +139,16 @@ defmodule MapSet do
|
||||
|
||||
"""
|
||||
@spec difference(t(val1), t(val2)) :: t(val1) when val1: value, val2: value
|
||||
def difference(map_set1, map_set2)
|
||||
def difference(mapset1, mapset2)
|
||||
|
||||
# If the first set is less than twice the size of the second map,
|
||||
# it is fastest to re-accumulate items in the first set that are not
|
||||
# present in the second set.
|
||||
def difference(%MapSet{map: map1}, %MapSet{map: map2})
|
||||
when map_size(map1) < map_size(map2) * 2 do
|
||||
map =
|
||||
map1
|
||||
|> Map.keys()
|
||||
|> filter_not_in(map2, [])
|
||||
map = map1
|
||||
|> Map.keys
|
||||
|> filter_not_in(map2)
|
||||
|
||||
%MapSet{map: map}
|
||||
end
|
||||
@@ -163,21 +156,23 @@ defmodule MapSet do
|
||||
# If the second set is less than half the size of the first set, it's fastest
|
||||
# to simply iterate through each item in the second set, deleting them from
|
||||
# the first set.
|
||||
def difference(%MapSet{map: map1} = map_set, %MapSet{map: map2}) do
|
||||
%{map_set | map: Map.drop(map1, Map.keys(map2))}
|
||||
def difference(%MapSet{map: map1}, %MapSet{map: map2}) do
|
||||
%MapSet{map: Map.drop(map1, Map.keys(map2))}
|
||||
end
|
||||
|
||||
defp filter_not_in(keys, map2, acc \\ [])
|
||||
defp filter_not_in([], _map2, acc), do: :maps.from_list(acc)
|
||||
|
||||
defp filter_not_in([key | rest], map2, acc) do
|
||||
case map2 do
|
||||
%{^key => _} -> filter_not_in(rest, map2, acc)
|
||||
_ -> filter_not_in(rest, map2, [{key, @dummy_value} | acc])
|
||||
acc = if Map.has_key?(map2, key) do
|
||||
acc
|
||||
else
|
||||
[{key, true} | acc]
|
||||
end
|
||||
filter_not_in(rest, map2, acc)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if `map_set1` and `map_set2` have no members in common.
|
||||
Checks if `set1` and `set2` have no members in common.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -192,18 +187,17 @@ defmodule MapSet do
|
||||
{map1, map2} = order_by_size(map1, map2)
|
||||
|
||||
map1
|
||||
|> Map.keys()
|
||||
|> Map.keys
|
||||
|> none_in?(map2)
|
||||
end
|
||||
|
||||
defp none_in?([], _) do
|
||||
true
|
||||
end
|
||||
|
||||
defp none_in?([key | rest], map2) do
|
||||
case map2 do
|
||||
%{^key => _} -> false
|
||||
_ -> none_in?(rest, map2)
|
||||
case Map.has_key?(map2, key) do
|
||||
true -> false
|
||||
false -> none_in?(rest, map2)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -221,18 +215,12 @@ defmodule MapSet do
|
||||
|
||||
"""
|
||||
@spec equal?(t, t) :: boolean
|
||||
def equal?(%MapSet{map: map1, version: version}, %MapSet{map: map2, version: version}) do
|
||||
def equal?(%MapSet{map: map1}, %MapSet{map: map2}) do
|
||||
Map.equal?(map1, map2)
|
||||
end
|
||||
|
||||
# Elixir v1.5 change the map representation, so on
|
||||
# version mismatch we need to compare the keys directly.
|
||||
def equal?(%MapSet{map: map1}, %MapSet{map: map2}) do
|
||||
map_size(map1) == map_size(map2) and map_subset?(Map.keys(map1), map2)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a set containing only members that `map_set1` and `map_set2` have in common.
|
||||
Returns a set containing only members that `set1` and `set2` have in common.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -244,13 +232,14 @@ defmodule MapSet do
|
||||
|
||||
"""
|
||||
@spec intersection(t(val), t(val)) :: t(val) when val: value
|
||||
def intersection(%MapSet{map: map1} = map_set, %MapSet{map: map2}) do
|
||||
def intersection(%MapSet{map: map1}, %MapSet{map: map2}) do
|
||||
{map1, map2} = order_by_size(map1, map2)
|
||||
%{map_set | map: Map.take(map2, Map.keys(map1))}
|
||||
|
||||
%MapSet{map: Map.take(map2, Map.keys(map1))}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if `map_set` contains `value`.
|
||||
Checks if `set` contains `value`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -262,11 +251,11 @@ defmodule MapSet do
|
||||
"""
|
||||
@spec member?(t, value) :: boolean
|
||||
def member?(%MapSet{map: map}, value) do
|
||||
match?(%{^value => _}, map)
|
||||
Map.has_key?(map, value)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Inserts `value` into `map_set` if `map_set` doesn't already contain it.
|
||||
Inserts `value` into `set` if `set` doesn't already contain it.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -277,12 +266,12 @@ defmodule MapSet do
|
||||
|
||||
"""
|
||||
@spec put(t(val), new_val) :: t(val | new_val) when val: value, new_val: value
|
||||
def put(%MapSet{map: map} = map_set, value) do
|
||||
%{map_set | map: Map.put(map, value, @dummy_value)}
|
||||
def put(%MapSet{map: map} = set, value) do
|
||||
%{set | map: Map.put(map, value, true)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the number of elements in `map_set`.
|
||||
Returns the number of elements in `set`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -296,9 +285,9 @@ defmodule MapSet do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if `map_set1`'s members are all contained in `map_set2`.
|
||||
Checks if `set1`'s members are all contained in `set2`.
|
||||
|
||||
This function checks if `map_set1` is a subset of `map_set2`.
|
||||
This function checks if `set1` is a subset of `set2`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -312,21 +301,24 @@ defmodule MapSet do
|
||||
def subset?(%MapSet{map: map1}, %MapSet{map: map2}) do
|
||||
if map_size(map1) <= map_size(map2) do
|
||||
map1
|
||||
|> Map.keys()
|
||||
|> map_subset?(map2)
|
||||
|> Map.keys
|
||||
|> do_subset?(map2)
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
defp map_subset?([], _), do: true
|
||||
|
||||
defp map_subset?([key | rest], map2) do
|
||||
match?(%{^key => _}, map2) and map_subset?(rest, map2)
|
||||
defp do_subset?([], _), do: true
|
||||
defp do_subset?([key | rest], map2) do
|
||||
if Map.has_key?(map2, key) do
|
||||
do_subset?(rest, map2)
|
||||
else
|
||||
false
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Converts `map_set` to a list.
|
||||
Converts `set` to a list.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -340,7 +332,7 @@ defmodule MapSet do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a set containing all members of `map_set1` and `map_set2`.
|
||||
Returns a set containing all members of `set1` and `set2`.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -349,56 +341,34 @@ defmodule MapSet do
|
||||
|
||||
"""
|
||||
@spec union(t(val1), t(val2)) :: t(val1 | val2) when val1: value, val2: value
|
||||
def union(map_set1, map_set2)
|
||||
|
||||
def union(%MapSet{map: map1, version: version} = map_set, %MapSet{map: map2, version: version}) do
|
||||
%{map_set | map: Map.merge(map1, map2)}
|
||||
end
|
||||
|
||||
def union(%MapSet{map: map1}, %MapSet{map: map2}) do
|
||||
map = new_from_list(Map.keys(map1) ++ Map.keys(map2), [])
|
||||
%MapSet{map: map}
|
||||
%MapSet{map: Map.merge(map1, map2)}
|
||||
end
|
||||
|
||||
@compile {:inline, [order_by_size: 2]}
|
||||
defp order_by_size(map1, map2) when map_size(map1) > map_size(map2), do: {map2, map1}
|
||||
defp order_by_size(map1, map2), do: {map1, map2}
|
||||
|
||||
defimpl Enumerable do
|
||||
def count(map_set) do
|
||||
{:ok, MapSet.size(map_set)}
|
||||
end
|
||||
|
||||
def member?(map_set, val) do
|
||||
{:ok, MapSet.member?(map_set, val)}
|
||||
end
|
||||
|
||||
def slice(map_set) do
|
||||
{:ok, MapSet.size(map_set), &Enumerable.List.slice(MapSet.to_list(map_set), &1, &2)}
|
||||
end
|
||||
|
||||
def reduce(map_set, acc, fun) do
|
||||
Enumerable.List.reduce(MapSet.to_list(map_set), acc, fun)
|
||||
end
|
||||
def reduce(set, acc, fun), do: Enumerable.List.reduce(MapSet.to_list(set), acc, fun)
|
||||
def member?(set, val), do: {:ok, MapSet.member?(set, val)}
|
||||
def count(set), do: {:ok, MapSet.size(set)}
|
||||
end
|
||||
|
||||
defimpl Collectable do
|
||||
def into(map_set) do
|
||||
fun = fn
|
||||
list, {:cont, x} -> [{x, []} | list]
|
||||
list, :done -> %{map_set | map: Map.merge(map_set.map, Map.new(list))}
|
||||
def into(original) do
|
||||
{original, fn
|
||||
set, {:cont, x} -> MapSet.put(set, x)
|
||||
set, :done -> set
|
||||
_, :halt -> :ok
|
||||
end
|
||||
|
||||
{[], fun}
|
||||
end}
|
||||
end
|
||||
end
|
||||
|
||||
defimpl Inspect do
|
||||
import Inspect.Algebra
|
||||
|
||||
def inspect(map_set, opts) do
|
||||
concat(["#MapSet<", Inspect.List.inspect(MapSet.to_list(map_set), opts), ">"])
|
||||
def inspect(set, opts) do
|
||||
concat ["#MapSet<", Inspect.List.inspect(MapSet.to_list(set), opts), ">"]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
+286
-925
File diff suppressed because it is too large
Load Diff
@@ -4,229 +4,356 @@
|
||||
#
|
||||
# ## Implementation
|
||||
#
|
||||
# The implementation uses ets to track all dependencies
|
||||
# resembling a graph. The graph has the following vertices:
|
||||
# The implementation uses the digraph module to track
|
||||
# all dependencies. The graph starts with one main vertex:
|
||||
#
|
||||
# * `Module` - a module that was invoked via an import
|
||||
# * `{name, arity}` - a local function/arity pair
|
||||
# * `{:import, name, arity}` - an invoked function/arity import
|
||||
# * `:reattach` - points to reattached functions
|
||||
# * `:local` - points to local functions
|
||||
#
|
||||
# Those vertices can associate to other vertices as described
|
||||
# below:
|
||||
# We can also have the following vertices:
|
||||
#
|
||||
# * `{name, arity}`
|
||||
# * in neighbours: `:reattach`, `{name, arity}`
|
||||
# * out neighbours: `{:import, name, arity}`
|
||||
# * `Module` - a module that was invoked via an import
|
||||
# * `{name, arity}` - a local function/arity pair
|
||||
# * `{:import, name, arity}` - an invoked function/arity import
|
||||
#
|
||||
# * `{:import, name, arity}`
|
||||
# * in neighbours: `{name, arity}`
|
||||
# * out neighbours: `Module`
|
||||
# Each of those vertices can associate to other vertices
|
||||
# as described below:
|
||||
#
|
||||
# * `Module`
|
||||
# * in neighbours: `{:import, name, arity}`
|
||||
#
|
||||
# * `{name, arity}`
|
||||
# * in neighbours: `:local`, `{name, arity}`
|
||||
# * out neighbours: `{:import, name, arity}`
|
||||
#
|
||||
# * `{:import, name, arity}`
|
||||
# * in neighbours: `{name, arity}`
|
||||
# * out neighbours: `Module`
|
||||
#
|
||||
# Note that since this is required for bootstrap, we can't use
|
||||
# any of the `GenServer` conveniences.
|
||||
defmodule Module.LocalsTracker do
|
||||
@moduledoc false
|
||||
|
||||
@timeout 30_000
|
||||
@behaviour :gen_server
|
||||
|
||||
@type ref :: pid | module
|
||||
@type name :: atom
|
||||
@type name_arity :: {name, arity}
|
||||
|
||||
@type local :: {name, arity}
|
||||
@type import :: {:import, name, arity}
|
||||
|
||||
# Public API
|
||||
|
||||
@doc """
|
||||
Starts the tracker table.
|
||||
Returns all imported modules that had the given
|
||||
`{name, arity}` invoked.
|
||||
"""
|
||||
def init do
|
||||
:ets.new(__MODULE__, [:bag, :public])
|
||||
@spec imports_with_dispatch(ref, name_arity) :: [module]
|
||||
def imports_with_dispatch(ref, {name, arity}) do
|
||||
d = :gen_server.call(to_pid(ref), :digraph, @timeout)
|
||||
:digraph.out_neighbours(d, {:import, name, arity})
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes the tracker table.
|
||||
"""
|
||||
def delete(d) do
|
||||
:ets.delete(d)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds and tracks defaults for a definition into the tracker.
|
||||
"""
|
||||
def add_defaults(d, _kind, {name, arity}, defaults) do
|
||||
for i <- :lists.seq(arity - defaults, arity - 1) do
|
||||
put_edge(d, {name, i}, {name, arity})
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds a local dispatch from-to the given target.
|
||||
"""
|
||||
def add_local(d, from, to) when is_tuple(from) and is_tuple(to) do
|
||||
put_edge(d, from, to)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Adds an import dispatch to the given target.
|
||||
"""
|
||||
def add_import(d, function, module, {name, arity})
|
||||
when is_tuple(function) and is_atom(module) do
|
||||
tuple = {:import, name, arity}
|
||||
put_edge(d, tuple, module)
|
||||
put_edge(d, function, tuple)
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc """
|
||||
Yanks a local node. Returns its in and out vertices in a tuple.
|
||||
"""
|
||||
def yank(d, local) do
|
||||
{[], take_out_neighbours(d, local)}
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reattach a previously yanked node.
|
||||
"""
|
||||
def reattach(d, tuple, _kind, function, {in_neigh, out_neigh}) do
|
||||
# Reattach the old function
|
||||
for from <- in_neigh do
|
||||
put_edge(d, from, function)
|
||||
end
|
||||
|
||||
for to <- out_neigh do
|
||||
put_edge(d, function, to)
|
||||
end
|
||||
|
||||
# Make a call from the old function to the new one
|
||||
if function != tuple do
|
||||
put_edge(d, function, tuple)
|
||||
end
|
||||
|
||||
# Finally marked the new one as reattached
|
||||
put_edge(d, :reattach, tuple)
|
||||
:ok
|
||||
end
|
||||
|
||||
# Collecting all conflicting imports with the given functions
|
||||
@doc false
|
||||
def collect_imports_conflicts(d, all_defined) do
|
||||
for {{name, arity}, _, meta, _} <- all_defined,
|
||||
n = out_neighbours(d, {:import, name, arity}),
|
||||
n != [] do
|
||||
{meta, {n, name, arity}}
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Collect all unused definitions based on the private
|
||||
given, also accounting the expected number of default
|
||||
clauses a private function have.
|
||||
"""
|
||||
def collect_unused_locals(d, all_defined, private) do
|
||||
reachable =
|
||||
Enum.reduce(all_defined, %{}, fn {pair, kind, _, _}, acc ->
|
||||
if kind in [:def, :defmacro] do
|
||||
reachable_from(d, pair, acc)
|
||||
else
|
||||
acc
|
||||
end
|
||||
end)
|
||||
|
||||
reattached = out_neighbours(d, :reattach)
|
||||
{unreachable(reachable, reattached, private), collect_warnings(reachable, private)}
|
||||
end
|
||||
|
||||
defp unreachable(reachable, reattached, private) do
|
||||
for {tuple, kind, _, _} <- private,
|
||||
not reachable?(tuple, kind, reachable, reattached),
|
||||
do: tuple
|
||||
end
|
||||
|
||||
defp reachable?(tuple, :defmacrop, reachable, reattached) do
|
||||
# All private micros are unreachable unless they have been
|
||||
# reattached and they are reachable.
|
||||
:lists.member(tuple, reattached) and Map.has_key?(reachable, tuple)
|
||||
end
|
||||
|
||||
defp reachable?(tuple, :defp, reachable, _reattached) do
|
||||
Map.has_key?(reachable, tuple)
|
||||
end
|
||||
|
||||
defp collect_warnings(reachable, private) do
|
||||
:lists.foldl(&collect_warnings(&1, &2, reachable), [], private)
|
||||
end
|
||||
|
||||
defp collect_warnings({_, _, false, _}, acc, _reachable) do
|
||||
acc
|
||||
end
|
||||
|
||||
defp collect_warnings({tuple, kind, meta, 0}, acc, reachable) do
|
||||
if Map.has_key?(reachable, tuple) do
|
||||
acc
|
||||
else
|
||||
[{meta, {:unused_def, tuple, kind}} | acc]
|
||||
end
|
||||
end
|
||||
|
||||
defp collect_warnings({tuple, kind, meta, default}, acc, reachable) when default > 0 do
|
||||
{name, arity} = tuple
|
||||
min = arity - default
|
||||
max = arity
|
||||
|
||||
case min_reachable_default(max, min, :none, name, reachable) do
|
||||
:none -> [{meta, {:unused_def, tuple, kind}} | acc]
|
||||
^min -> acc
|
||||
^max -> [{meta, {:unused_args, tuple}} | acc]
|
||||
diff -> [{meta, {:unused_args, tuple, diff}} | acc]
|
||||
end
|
||||
end
|
||||
|
||||
defp min_reachable_default(max, min, last, name, reachable) when max >= min do
|
||||
case Map.has_key?(reachable, {name, max}) do
|
||||
true -> min_reachable_default(max - 1, min, max, name, reachable)
|
||||
false -> min_reachable_default(max - 1, min, last, name, reachable)
|
||||
end
|
||||
end
|
||||
|
||||
defp min_reachable_default(_max, _min, last, _name, _reachable) do
|
||||
last
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all local nodes reachable from `vertex`.
|
||||
Returns all locals that are reachable.
|
||||
|
||||
By default, all public functions are reachable.
|
||||
A private function is only reachable if it has
|
||||
a public function that it invokes directly.
|
||||
"""
|
||||
def reachable_from(d, vertex) do
|
||||
d
|
||||
|> reachable_from(vertex, %{})
|
||||
|> Map.keys()
|
||||
@spec reachable(ref) :: [local]
|
||||
def reachable(ref) do
|
||||
reachable_from(:gen_server.call(to_pid(ref), :digraph, @timeout), :local)
|
||||
end
|
||||
|
||||
defp reachable_from(d, vertex, vertices) do
|
||||
vertices = Map.put(vertices, vertex, true)
|
||||
|
||||
Enum.reduce(out_neighbours(d, vertex), vertices, fn
|
||||
{_, _} = local, acc ->
|
||||
case acc do
|
||||
%{^local => true} -> acc
|
||||
_ -> reachable_from(d, local, acc)
|
||||
end
|
||||
|
||||
_, acc ->
|
||||
acc
|
||||
end)
|
||||
defp reachable_from(d, starting) do
|
||||
:sets.to_list(reduce_reachable(d, starting, :sets.new))
|
||||
end
|
||||
|
||||
## Lightweight digraph implementation
|
||||
|
||||
defp put_edge(d, from, to) do
|
||||
:ets.insert(d, {from, to})
|
||||
defp reduce_reachable(d, vertex, vertices) do
|
||||
neighbours = :digraph.out_neighbours(d, vertex)
|
||||
neighbours = (for {_, _} = t <- neighbours, do: t) |> :sets.from_list
|
||||
remaining = :sets.subtract(neighbours, vertices)
|
||||
vertices = :sets.union(neighbours, vertices)
|
||||
:sets.fold(&reduce_reachable(d, &1, &2), vertices, remaining)
|
||||
end
|
||||
|
||||
defp out_neighbours(d, from) do
|
||||
try do
|
||||
:ets.lookup_element(d, from, 2)
|
||||
catch
|
||||
:error, :badarg -> []
|
||||
defp to_pid(pid) when is_pid(pid), do: pid
|
||||
defp to_pid(mod) when is_atom(mod) do
|
||||
table = :elixir_module.data_table(mod)
|
||||
:ets.lookup_element(table, {:elixir, :locals_tracker}, 2)
|
||||
end
|
||||
|
||||
# Internal API
|
||||
|
||||
# Starts the tracker and returns its PID.
|
||||
@doc false
|
||||
def start_link do
|
||||
:gen_server.start_link(__MODULE__, [], [])
|
||||
end
|
||||
|
||||
# Adds a definition into the tracker. A public
|
||||
# definition is connected with the :local node
|
||||
# while a private one is left unreachable until
|
||||
# a call is made to.
|
||||
@doc false
|
||||
def add_definition(pid, kind, tuple) when kind in [:def, :defp, :defmacro, :defmacrop] do
|
||||
:gen_server.cast(pid, {:add_definition, kind, tuple})
|
||||
end
|
||||
|
||||
# Adds and tracks defaults for a definition into the tracker.
|
||||
@doc false
|
||||
def add_defaults(pid, kind, tuple, defaults) when kind in [:def, :defp, :defmacro, :defmacrop] do
|
||||
:gen_server.cast(pid, {:add_defaults, kind, tuple, defaults})
|
||||
end
|
||||
|
||||
# Adds a local dispatch to the given target.
|
||||
def add_local(pid, to) when is_tuple(to) do
|
||||
:gen_server.cast(pid, {:add_local, :local, to})
|
||||
end
|
||||
|
||||
# Adds a local dispatch from-to the given target.
|
||||
@doc false
|
||||
def add_local(pid, from, to) when is_tuple(from) and is_tuple(to) do
|
||||
:gen_server.cast(pid, {:add_local, from, to})
|
||||
end
|
||||
|
||||
# Adds an import dispatch to the given target.
|
||||
@doc false
|
||||
def add_import(pid, function, module, target) when is_atom(module) and is_tuple(target) do
|
||||
:gen_server.cast(pid, {:add_import, function, module, target})
|
||||
end
|
||||
|
||||
# Yanks a local node. Returns its in and out vertices in a tuple.
|
||||
@doc false
|
||||
def yank(pid, local) do
|
||||
:gen_server.call(to_pid(pid), {:yank, local}, @timeout)
|
||||
end
|
||||
|
||||
# Reattach a previously yanked node
|
||||
@doc false
|
||||
def reattach(pid, kind, tuple, neighbours) do
|
||||
:gen_server.cast(to_pid(pid), {:reattach, kind, tuple, neighbours})
|
||||
end
|
||||
|
||||
# Collecting all conflicting imports with the given functions
|
||||
@doc false
|
||||
def collect_imports_conflicts(pid, all_defined) do
|
||||
d = :gen_server.call(pid, :digraph, @timeout)
|
||||
|
||||
for {name, arity} <- all_defined,
|
||||
:digraph.in_neighbours(d, {:import, name, arity}) != [],
|
||||
n = :digraph.out_neighbours(d, {:import, name, arity}),
|
||||
n != [] do
|
||||
{n, name, arity}
|
||||
end
|
||||
end
|
||||
|
||||
defp take_out_neighbours(d, from) do
|
||||
Keyword.values(:ets.take(d, from))
|
||||
# Collect all unused definitions based on the private
|
||||
# given also accounting the expected amount of default
|
||||
# clauses a private function have.
|
||||
@doc false
|
||||
def collect_unused_locals(ref, private) do
|
||||
d = :gen_server.call(to_pid(ref), :digraph, @timeout)
|
||||
{unreachable(d, private), collect_warnings(d, private)}
|
||||
end
|
||||
|
||||
defp unreachable(d, private) do
|
||||
unreachable = for {tuple, _, _} <- private, do: tuple
|
||||
|
||||
private =
|
||||
for {tuple, :defp, _} <- private do
|
||||
neighbours = :digraph.in_neighbours(d, tuple)
|
||||
neighbours = for {_, _} = t <- neighbours, do: t
|
||||
{tuple, :sets.from_list(neighbours)}
|
||||
end
|
||||
|
||||
reduce_unreachable(private, [], :sets.from_list(unreachable))
|
||||
end
|
||||
|
||||
defp reduce_unreachable([{vertex, callers} | t], acc, unreachable) do
|
||||
if :sets.is_subset(callers, unreachable) do
|
||||
reduce_unreachable(t, [{vertex, callers} | acc], unreachable)
|
||||
else
|
||||
reduce_unreachable(acc ++ t, [], :sets.del_element(vertex, unreachable))
|
||||
end
|
||||
end
|
||||
|
||||
defp reduce_unreachable([], _acc, unreachable) do
|
||||
:sets.to_list(unreachable)
|
||||
end
|
||||
|
||||
defp collect_warnings(d, private) do
|
||||
reachable = reachable_from(d, :local)
|
||||
:lists.foldl(&collect_warnings(&1, &2, reachable), [], private)
|
||||
end
|
||||
|
||||
defp collect_warnings({tuple, kind, 0}, acc, reachable) do
|
||||
if :lists.member(tuple, reachable) do
|
||||
acc
|
||||
else
|
||||
[{:unused_def, tuple, kind} | acc]
|
||||
end
|
||||
end
|
||||
|
||||
defp collect_warnings({tuple, kind, default}, acc, reachable) when default > 0 do
|
||||
{name, arity} = tuple
|
||||
min = arity - default
|
||||
max = arity
|
||||
|
||||
invoked = for {n, a} <- reachable, n == name, a in min..max, do: a
|
||||
|
||||
if invoked == [] do
|
||||
[{:unused_def, tuple, kind} | acc]
|
||||
else
|
||||
case :lists.min(invoked) - min do
|
||||
0 -> acc
|
||||
^default -> [{:unused_args, tuple} | acc]
|
||||
unused_args -> [{:unused_args, tuple, unused_args} | acc]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def cache_env(pid, env) do
|
||||
:gen_server.call(pid, {:cache_env, env}, @timeout)
|
||||
end
|
||||
|
||||
@doc false
|
||||
def get_cached_env(pid, ref) do
|
||||
:gen_server.call(pid, {:get_cached_env, ref}, @timeout)
|
||||
end
|
||||
|
||||
# Stops the gen server
|
||||
@doc false
|
||||
def stop(pid) do
|
||||
:gen_server.cast(pid, :stop)
|
||||
end
|
||||
|
||||
# Callbacks
|
||||
|
||||
def init([]) do
|
||||
d = :digraph.new([:protected])
|
||||
:digraph.add_vertex(d, :local)
|
||||
{:ok, {d, []}}
|
||||
end
|
||||
|
||||
@doc false
|
||||
def handle_call({:cache_env, env}, _from, {d, cache}) do
|
||||
case cache do
|
||||
[{i, ^env} | _] ->
|
||||
{:reply, i, {d, cache}}
|
||||
t ->
|
||||
i = length(t)
|
||||
{:reply, i, {d, [{i, env} | t]}}
|
||||
end
|
||||
end
|
||||
|
||||
def handle_call({:get_cached_env, ref}, _from, {_, cache} = state) do
|
||||
{^ref, env} = :lists.keyfind(ref, 1, cache)
|
||||
{:reply, env, state}
|
||||
end
|
||||
|
||||
def handle_call({:yank, local}, _from, {d, _} = state) do
|
||||
out_vertices = :digraph.out_neighbours(d, local)
|
||||
:digraph.del_edges(d, :digraph.out_edges(d, local))
|
||||
{:reply, {[], out_vertices}, state}
|
||||
end
|
||||
|
||||
def handle_call(:digraph, _from, {d, _} = state) do
|
||||
{:reply, d, state}
|
||||
end
|
||||
|
||||
@doc false
|
||||
def handle_info(_msg, state) do
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
def handle_cast({:add_local, from, to}, {d, _} = state) do
|
||||
handle_add_local(d, from, to)
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
def handle_cast({:add_import, function, module, {name, arity}}, {d, _} = state) do
|
||||
handle_import(d, function, module, name, arity)
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
def handle_cast({:add_definition, kind, tuple}, {d, _} = state) do
|
||||
handle_add_definition(d, kind, tuple)
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
def handle_cast({:add_defaults, kind, {name, arity}, defaults}, {d, _} = state) do
|
||||
for i <- :lists.seq(arity - defaults, arity - 1) do
|
||||
handle_add_definition(d, kind, {name, i})
|
||||
handle_add_local(d, {name, i}, {name, i + 1})
|
||||
end
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
def handle_cast({:reattach, _kind, tuple, {in_neigh, out_neigh}}, {d, _} = state) do
|
||||
for from <- in_neigh do
|
||||
:digraph.add_vertex(d, from)
|
||||
replace_edge!(d, from, tuple)
|
||||
end
|
||||
|
||||
for to <- out_neigh do
|
||||
:digraph.add_vertex(d, to)
|
||||
replace_edge!(d, tuple, to)
|
||||
end
|
||||
|
||||
{:noreply, state}
|
||||
end
|
||||
|
||||
def handle_cast(:stop, state) do
|
||||
{:stop, :normal, state}
|
||||
end
|
||||
|
||||
@doc false
|
||||
def terminate(_reason, _state) do
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc false
|
||||
def code_change(_old, state, _extra) do
|
||||
{:ok, state}
|
||||
end
|
||||
|
||||
defp handle_import(d, function, module, name, arity) do
|
||||
:digraph.add_vertex(d, module)
|
||||
|
||||
tuple = {:import, name, arity}
|
||||
:digraph.add_vertex(d, tuple)
|
||||
replace_edge!(d, tuple, module)
|
||||
|
||||
if function != nil do
|
||||
replace_edge!(d, function, tuple)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp handle_add_local(d, from, to) do
|
||||
:digraph.add_vertex(d, to)
|
||||
replace_edge!(d, from, to)
|
||||
end
|
||||
|
||||
defp handle_add_definition(d, public, tuple) when public in [:def, :defmacro] do
|
||||
:digraph.add_vertex(d, tuple)
|
||||
replace_edge!(d, :local, tuple)
|
||||
end
|
||||
|
||||
defp handle_add_definition(d, private, tuple) when private in [:defp, :defmacrop] do
|
||||
:digraph.add_vertex(d, tuple)
|
||||
end
|
||||
|
||||
defp replace_edge!(d, from, to) do
|
||||
_ = unless :lists.member(to, :digraph.out_neighbours(d, from)) do
|
||||
[:"$e" | _] = :digraph.add_edge(d, from, to)
|
||||
end
|
||||
:ok
|
||||
end
|
||||
end
|
||||
|
||||
+24
-18
@@ -16,7 +16,8 @@ defmodule Node do
|
||||
This functionality starts the `:net_kernel` and other
|
||||
related processes.
|
||||
"""
|
||||
@spec start(node, :longnames | :shortnames, non_neg_integer) :: {:ok, pid} | {:error, term}
|
||||
@spec start(node, :longnames | :shortnames, non_neg_integer) ::
|
||||
{:ok, pid} | {:error, term}
|
||||
def start(name, type \\ :longnames, tick_time \\ 15000) do
|
||||
:net_kernel.start([name, type, tick_time])
|
||||
end
|
||||
@@ -71,9 +72,10 @@ defmodule Node do
|
||||
The result returned when the argument is a list, is the list of nodes
|
||||
satisfying the disjunction(s) of the list elements.
|
||||
|
||||
For more information, see `:erlang.nodes/1`.
|
||||
For more information, see
|
||||
[`:erlang.nodes/1`](http://www.erlang.org/doc/man/erlang.html#nodes-1).
|
||||
"""
|
||||
@type state :: :visible | :hidden | :connected | :this | :known
|
||||
@typep state :: :visible | :hidden | :connected | :this | :known
|
||||
@spec list(state | [state]) :: [t]
|
||||
def list(args) do
|
||||
:erlang.nodes(args)
|
||||
@@ -85,9 +87,8 @@ defmodule Node do
|
||||
If `flag` is `true`, monitoring is turned on.
|
||||
If `flag` is `false`, monitoring is turned off.
|
||||
|
||||
For more information, see `:erlang.monitor_node/2`.
|
||||
|
||||
For monitoring status changes of all nodes, see `:net_kernel.monitor_nodes/3`.
|
||||
For more information, see
|
||||
[`:erlang.monitor_node/2`](http://www.erlang.org/doc/man/erlang.html#monitor_node-2).
|
||||
"""
|
||||
@spec monitor(t, boolean) :: true
|
||||
def monitor(node, flag) do
|
||||
@@ -98,9 +99,8 @@ defmodule Node do
|
||||
Behaves as `monitor/2` except that it allows an extra
|
||||
option to be given, namely `:allow_passive_connect`.
|
||||
|
||||
For more information, see `:erlang.monitor_node/3`.
|
||||
|
||||
For monitoring status changes of all nodes, see `:net_kernel.monitor_nodes/3`.
|
||||
For more information, see
|
||||
[`:erlang.monitor_node/3`](http://www.erlang.org/doc/man/erlang.html#monitor_node-3).
|
||||
"""
|
||||
@spec monitor(t, boolean, [:allow_passive_connect]) :: true
|
||||
def monitor(node, flag, options) do
|
||||
@@ -131,7 +131,8 @@ defmodule Node do
|
||||
protocols. Returns `true` if disconnection succeeds, otherwise `false`.
|
||||
If the local node is not alive, the function returns `:ignored`.
|
||||
|
||||
For more information, see `:erlang.disconnect_node/1`.
|
||||
For more information, see
|
||||
[`:erlang.disconnect_node/1`](http://www.erlang.org/doc/man/erlang.html#disconnect_node-1).
|
||||
"""
|
||||
@spec disconnect(t) :: boolean | :ignored
|
||||
def disconnect(node) do
|
||||
@@ -144,7 +145,8 @@ defmodule Node do
|
||||
Returns `true` if successful, `false` if not, and the atom
|
||||
`:ignored` if the local node is not alive.
|
||||
|
||||
For more information, see `:net_kernel.connect_node/1`.
|
||||
For more information, see
|
||||
[`:net_kernel.connect_node/1`](http://www.erlang.org/doc/man/net_kernel.html#connect_node-1).
|
||||
"""
|
||||
@spec connect(t) :: boolean | :ignored
|
||||
def connect(node) do
|
||||
@@ -155,7 +157,8 @@ defmodule Node do
|
||||
Returns the PID of a new process started by the application of `fun`
|
||||
on `node`. If `node` does not exist, a useless PID is returned.
|
||||
|
||||
For the list of available options, see `:erlang.spawn/2`.
|
||||
For the list of available options, see
|
||||
[`:erlang.spawn/2`](http://www.erlang.org/doc/man/erlang.html#spawn-2).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -170,11 +173,12 @@ defmodule Node do
|
||||
|
||||
If `node` does not exist, a useless PID is returned.
|
||||
|
||||
For the list of available options, see `:erlang.spawn_opt/3`.
|
||||
For the list of available options, see
|
||||
[`:erlang.spawn_opt/3`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-3).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec spawn(t, (() -> any), Process.spawn_opts()) :: pid | {pid, reference}
|
||||
@spec spawn(t, (() -> any), Process.spawn_opts) :: pid | {pid, reference}
|
||||
def spawn(node, fun, opts) do
|
||||
:erlang.spawn_opt(node, fun, opts)
|
||||
end
|
||||
@@ -185,7 +189,8 @@ defmodule Node do
|
||||
|
||||
If `node` does not exist, a useless PID is returned.
|
||||
|
||||
For the list of available options, see `:erlang.spawn/4`.
|
||||
For the list of available options, see
|
||||
[`:erlang.spawn/4`](http://www.erlang.org/doc/man/erlang.html#spawn-4).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -200,11 +205,12 @@ defmodule Node do
|
||||
|
||||
If `node` does not exist, a useless PID is returned.
|
||||
|
||||
For the list of available options, see `:erlang.spawn/5`.
|
||||
For the list of available options, see
|
||||
[`:erlang.spawn/5`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-5).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec spawn(t, module, atom, [any], Process.spawn_opts()) :: pid | {pid, reference}
|
||||
@spec spawn(t, module, atom, [any], Process.spawn_opts) :: pid | {pid, reference}
|
||||
def spawn(node, module, fun, args, opts) do
|
||||
:erlang.spawn_opt(node, module, fun, args, opts)
|
||||
end
|
||||
@@ -246,7 +252,7 @@ defmodule Node do
|
||||
|
||||
This function will raise `FunctionClauseError` if the given `node` is not alive.
|
||||
"""
|
||||
def set_cookie(node \\ Node.self(), cookie) when is_atom(cookie) do
|
||||
def set_cookie(node \\ Node.self, cookie) when is_atom(cookie) do
|
||||
:erlang.set_cookie(node, cookie)
|
||||
end
|
||||
|
||||
|
||||
+83
-110
@@ -3,10 +3,10 @@ defmodule OptionParser do
|
||||
This module contains functions to parse command line options.
|
||||
"""
|
||||
|
||||
@type argv :: [String.t()]
|
||||
@type parsed :: keyword
|
||||
@type errors :: [{String.t(), String.t() | nil}]
|
||||
@type options :: [switches: keyword, strict: keyword, aliases: keyword]
|
||||
@type argv :: [String.t]
|
||||
@type parsed :: Keyword.t
|
||||
@type errors :: [{String.t, String.t | nil}]
|
||||
@type options :: [switches: Keyword.t, strict: Keyword.t, aliases: Keyword.t]
|
||||
|
||||
defmodule ParseError do
|
||||
defexception [:message]
|
||||
@@ -119,17 +119,18 @@ defmodule OptionParser do
|
||||
iex> OptionParser.parse(["--debug"])
|
||||
{[debug: true], [], []}
|
||||
|
||||
|
||||
Switches followed by a value will be assigned the value, as a string. Switches
|
||||
without an argument, like `--debug` in the examples above, will automatically be
|
||||
set to `true`.
|
||||
|
||||
Since Elixir converts switches to atoms, the dynamic mode will only parse
|
||||
switches that translate to atoms used by the runtime. Therefore, the code below
|
||||
switches that translates to atoms used by the runtime. Therefore, the code below
|
||||
likely won't parse the given option since the `:option_parser_example` atom is
|
||||
never used anywhere:
|
||||
|
||||
OptionParser.parse(["--option-parser-example"])
|
||||
# The :option_parser_example atom is not used anywhere below
|
||||
# Does nothing more...
|
||||
|
||||
However, the code below does since the `:option_parser_example` atom is used
|
||||
at some point later (or earlier) on:
|
||||
@@ -192,7 +193,7 @@ defmodule OptionParser do
|
||||
"""
|
||||
@spec parse(argv, options) :: {parsed, argv, errors}
|
||||
def parse(argv, opts \\ []) when is_list(argv) and is_list(opts) do
|
||||
do_parse(argv, build_config(opts), [], [], [], true)
|
||||
do_parse(argv, compile_config(opts), [], [], [], true)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -251,7 +252,7 @@ defmodule OptionParser do
|
||||
"""
|
||||
@spec parse_head(argv, options) :: {parsed, argv, errors}
|
||||
def parse_head(argv, opts \\ []) when is_list(argv) and is_list(opts) do
|
||||
do_parse(argv, build_config(opts), [], [], [], false)
|
||||
do_parse(argv, compile_config(opts), [], [], [], false)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -292,11 +293,11 @@ defmodule OptionParser do
|
||||
{Enum.reverse(opts), Enum.reverse(args), Enum.reverse(invalid)}
|
||||
end
|
||||
|
||||
defp do_parse(argv, %{switches: switches} = config, opts, args, invalid, all?) do
|
||||
case next_with_config(argv, config) do
|
||||
defp do_parse(argv, {aliases, switches, strict?, allow_nonexistent_atoms?} = config, opts, args, invalid, all?) do
|
||||
case next(argv, aliases, switches, strict?, allow_nonexistent_atoms?) do
|
||||
{:ok, option, value, rest} ->
|
||||
# the option exists and it was successfully parsed
|
||||
kinds = List.wrap(Keyword.get(switches, option))
|
||||
kinds = List.wrap Keyword.get(switches, option)
|
||||
new_opts = store_option(opts, option, value, kinds)
|
||||
do_parse(rest, config, new_opts, args, invalid, all?)
|
||||
|
||||
@@ -341,83 +342,78 @@ defmodule OptionParser do
|
||||
|
||||
"""
|
||||
@spec next(argv, options) ::
|
||||
{:ok, key :: atom, value :: term, argv}
|
||||
| {:invalid, String.t(), String.t() | nil, argv}
|
||||
| {:undefined, String.t(), String.t() | nil, argv}
|
||||
| {:error, argv}
|
||||
{:ok, key :: atom, value :: term, argv} |
|
||||
{:invalid, String.t, String.t | nil, argv} |
|
||||
{:undefined, String.t, String.t | nil, argv} |
|
||||
{:error, argv}
|
||||
|
||||
def next(argv, opts \\ []) when is_list(argv) and is_list(opts) do
|
||||
next_with_config(argv, build_config(opts))
|
||||
{aliases, switches, strict?, allow_nonexistent_atoms?} = compile_config(opts)
|
||||
next(argv, aliases, switches, strict?, allow_nonexistent_atoms?)
|
||||
end
|
||||
|
||||
defp next_with_config([], _config) do
|
||||
defp next([], _aliases, _switches, _strict?, _allow_nonexistent_atoms?) do
|
||||
{:error, []}
|
||||
end
|
||||
|
||||
defp next_with_config(["--" | _] = argv, _config) do
|
||||
defp next(["--" | _] = argv, _aliases, _switches, _strict?, _allow_nonexistent_atoms?) do
|
||||
{:error, argv}
|
||||
end
|
||||
|
||||
defp next_with_config(["-" | _] = argv, _config) do
|
||||
defp next(["-" | _] = argv, _aliases, _switches, _strict?, _allow_nonexistent_atoms?) do
|
||||
{:error, argv}
|
||||
end
|
||||
|
||||
defp next_with_config(["- " <> _ | _] = argv, _config) do
|
||||
defp next(["- " <> _ | _] = argv, _aliases, _switches, _strict?, _allow_nonexistent_atoms?) do
|
||||
{:error, argv}
|
||||
end
|
||||
|
||||
# Handles --foo or --foo=bar
|
||||
defp next_with_config(["--" <> option | rest], config) do
|
||||
defp next(["--" <> option | rest], _aliases, switches, strict?, allow_nonexistent_atoms?) do
|
||||
{option, value} = split_option(option)
|
||||
tagged = tag_option(option, config)
|
||||
next_tagged(tagged, value, "--" <> option, rest, config)
|
||||
tagged = tag_option(option, switches, allow_nonexistent_atoms?)
|
||||
do_next(tagged, value, "--" <> option, rest, switches, strict?, allow_nonexistent_atoms?)
|
||||
end
|
||||
|
||||
# Handles -a, -abc, -abc=something
|
||||
defp next_with_config(["-" <> option | rest] = argv, config) do
|
||||
%{aliases: aliases, allow_nonexistent_atoms?: allow_nonexistent_atoms?} = config
|
||||
defp next(["-" <> option | rest] = argv, aliases, switches, strict?, allow_nonexistent_atoms?) do
|
||||
{option, value} = split_option(option)
|
||||
original = "-" <> option
|
||||
|
||||
cond do
|
||||
is_nil(value) and negative_number?(original) ->
|
||||
{:error, argv}
|
||||
|
||||
String.contains?(option, ["-", "_"]) ->
|
||||
{:undefined, original, value, rest}
|
||||
|
||||
String.length(option) > 1 ->
|
||||
key = get_option_key(option, allow_nonexistent_atoms?)
|
||||
option_key = aliases[key]
|
||||
|
||||
if key && option_key do
|
||||
IO.warn("multi-letter aliases are deprecated, got: #{inspect(key)}")
|
||||
next_tagged({:default, option_key}, value, original, rest, config)
|
||||
IO.warn "multi-letter aliases are deprecated, got: #{inspect(key)}"
|
||||
do_next({:default, option_key}, value, original, rest, switches, strict?, allow_nonexistent_atoms?)
|
||||
else
|
||||
next_with_config(expand_multiletter_alias(option, value) ++ rest, config)
|
||||
next(expand_multiletter_alias(option, value) ++ rest, aliases, switches, strict?, allow_nonexistent_atoms?)
|
||||
end
|
||||
|
||||
true ->
|
||||
# We have a regular one-letter alias here
|
||||
tagged = tag_oneletter_alias(option, config)
|
||||
next_tagged(tagged, value, original, rest, config)
|
||||
tagged = tag_oneletter_alias(option, aliases, allow_nonexistent_atoms?)
|
||||
do_next(tagged, value, original, rest, switches, strict?, allow_nonexistent_atoms?)
|
||||
end
|
||||
end
|
||||
|
||||
defp next_with_config(argv, _config) do
|
||||
defp next(argv, _aliases, _switches, _strict?, _allow_nonexistent_atoms?) do
|
||||
{:error, argv}
|
||||
end
|
||||
|
||||
defp next_tagged(tagged, value, original, rest, %{switches: switches, strict?: strict?}) do
|
||||
defp do_next(tagged, value, original, rest, switches, strict?, allow_nonexistent_atoms?) do
|
||||
if strict? and not option_defined?(tagged, switches) do
|
||||
{:undefined, original, value, rest}
|
||||
else
|
||||
{option, kinds, value} = normalize_option(tagged, value, switches)
|
||||
{value, kinds, rest} = normalize_value(value, kinds, rest, strict?)
|
||||
|
||||
case validate_option(value, kinds) do
|
||||
{:ok, new_value} -> {:ok, option, new_value, rest}
|
||||
:invalid -> {:invalid, original, value, rest}
|
||||
:invalid -> {:invalid, original, value, rest}
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -450,13 +446,12 @@ defmodule OptionParser do
|
||||
["--number", "--number"]
|
||||
|
||||
"""
|
||||
@spec to_argv(Enumerable.t(), options) :: argv
|
||||
@spec to_argv(Enumerable.t, options) :: argv
|
||||
def to_argv(enum, opts \\ []) do
|
||||
switches = Keyword.get(opts, :switches, [])
|
||||
|
||||
Enum.flat_map(enum, fn
|
||||
{_key, nil} -> []
|
||||
{key, true} -> [to_switch(key)]
|
||||
{_key, nil} -> []
|
||||
{key, true} -> [to_switch(key)]
|
||||
{key, false} -> [to_switch(key, "--no-")]
|
||||
{key, value} -> to_argv(key, value, switches)
|
||||
end)
|
||||
@@ -489,8 +484,8 @@ defmodule OptionParser do
|
||||
["foo", "bar baz"]
|
||||
|
||||
"""
|
||||
@spec split(String.t()) :: argv
|
||||
def split(string) when is_binary(string) do
|
||||
@spec split(String.t) :: argv
|
||||
def split(string) do
|
||||
do_split(String.trim_leading(string, " "), "", [], nil)
|
||||
end
|
||||
|
||||
@@ -503,7 +498,8 @@ defmodule OptionParser do
|
||||
do: do_split(t, buffer, acc, quote)
|
||||
|
||||
# If we have a quote and we were inside it, close it
|
||||
defp do_split(<<quote, t::binary>>, buffer, acc, quote), do: do_split(t, buffer, acc, nil)
|
||||
defp do_split(<<quote, t::binary>>, buffer, acc, quote),
|
||||
do: do_split(t, buffer, acc, nil)
|
||||
|
||||
# If we have an escaped quote/space, simply remove the escape as long as we are not inside a quote
|
||||
defp do_split(<<?\\, h, t::binary>>, buffer, acc, nil) when h in [?\s, ?', ?"],
|
||||
@@ -519,9 +515,11 @@ defmodule OptionParser do
|
||||
end
|
||||
|
||||
# Finish the string expecting a nil marker
|
||||
defp do_split(<<>>, "", acc, nil), do: Enum.reverse(acc)
|
||||
defp do_split(<<>>, "", acc, nil),
|
||||
do: Enum.reverse(acc)
|
||||
|
||||
defp do_split(<<>>, buffer, acc, nil), do: Enum.reverse([buffer | acc])
|
||||
defp do_split(<<>>, buffer, acc, nil),
|
||||
do: Enum.reverse([buffer | acc])
|
||||
|
||||
# Otherwise raise
|
||||
defp do_split(<<>>, _, _acc, marker) do
|
||||
@@ -530,28 +528,22 @@ defmodule OptionParser do
|
||||
|
||||
## Helpers
|
||||
|
||||
defp build_config(opts) do
|
||||
{switches, strict?} =
|
||||
cond do
|
||||
opts[:switches] && opts[:strict] ->
|
||||
raise ArgumentError, ":switches and :strict cannot be given together"
|
||||
defp compile_config(opts) do
|
||||
aliases = opts[:aliases] || []
|
||||
allow_nonexistent_atoms? = opts[:allow_nonexistent_atoms] || false
|
||||
|
||||
switches = opts[:switches] ->
|
||||
{switches, false}
|
||||
{switches, strict?} = cond do
|
||||
opts[:switches] && opts[:strict] ->
|
||||
raise ArgumentError, ":switches and :strict cannot be given together"
|
||||
switches = opts[:switches] ->
|
||||
{switches, false}
|
||||
strict = opts[:strict] ->
|
||||
{strict, true}
|
||||
true ->
|
||||
{[], false}
|
||||
end
|
||||
|
||||
strict = opts[:strict] ->
|
||||
{strict, true}
|
||||
|
||||
true ->
|
||||
{[], false}
|
||||
end
|
||||
|
||||
%{
|
||||
aliases: opts[:aliases] || [],
|
||||
allow_nonexistent_atoms?: opts[:allow_nonexistent_atoms] || false,
|
||||
strict?: strict?,
|
||||
switches: switches
|
||||
}
|
||||
{aliases, switches, strict?, allow_nonexistent_atoms?}
|
||||
end
|
||||
|
||||
defp validate_option(value, kinds) do
|
||||
@@ -559,32 +551,27 @@ defmodule OptionParser do
|
||||
cond do
|
||||
:invalid in kinds ->
|
||||
{true, value}
|
||||
|
||||
:boolean in kinds ->
|
||||
case value do
|
||||
t when t in [true, "true"] -> {false, true}
|
||||
f when f in [false, "false"] -> {false, false}
|
||||
_ -> {true, value}
|
||||
end
|
||||
|
||||
:count in kinds ->
|
||||
case value do
|
||||
1 -> {false, value}
|
||||
_ -> {true, value}
|
||||
end
|
||||
|
||||
:integer in kinds ->
|
||||
case Integer.parse(value) do
|
||||
{value, ""} -> {false, value}
|
||||
_ -> {true, value}
|
||||
end
|
||||
|
||||
:float in kinds ->
|
||||
case Float.parse(value) do
|
||||
{value, ""} -> {false, value}
|
||||
_ -> {true, value}
|
||||
end
|
||||
|
||||
true ->
|
||||
{false, value}
|
||||
end
|
||||
@@ -599,34 +586,26 @@ defmodule OptionParser do
|
||||
defp store_option(dict, option, value, kinds) do
|
||||
cond do
|
||||
:count in kinds ->
|
||||
Keyword.update(dict, option, value, &(&1 + 1))
|
||||
|
||||
Keyword.update(dict, option, value, & &1 + 1)
|
||||
:keep in kinds ->
|
||||
[{option, value} | dict]
|
||||
|
||||
true ->
|
||||
[{option, value} | Keyword.delete(dict, option)]
|
||||
end
|
||||
end
|
||||
|
||||
defp tag_option("no-" <> option = original, %{
|
||||
switches: switches,
|
||||
allow_nonexistent_atoms?: allow_nonexistent_atoms?
|
||||
}) do
|
||||
defp tag_option("no-" <> option = original, switches, allow_nonexistent_atoms?) do
|
||||
cond do
|
||||
(negated = get_option_key(option, allow_nonexistent_atoms?)) &&
|
||||
:boolean in List.wrap(switches[negated]) ->
|
||||
(negated = get_option_key(option, allow_nonexistent_atoms?)) && :boolean in List.wrap(switches[negated]) ->
|
||||
{:negated, negated}
|
||||
|
||||
option_key = get_option_key(original, allow_nonexistent_atoms?) ->
|
||||
{:default, option_key}
|
||||
|
||||
true ->
|
||||
:unknown
|
||||
end
|
||||
end
|
||||
|
||||
defp tag_option(option, %{allow_nonexistent_atoms?: allow_nonexistent_atoms?}) do
|
||||
defp tag_option(option, _switches, allow_nonexistent_atoms?) do
|
||||
if option_key = get_option_key(option, allow_nonexistent_atoms?) do
|
||||
{:default, option_key}
|
||||
else
|
||||
@@ -634,11 +613,7 @@ defmodule OptionParser do
|
||||
end
|
||||
end
|
||||
|
||||
defp tag_oneletter_alias(alias, %{
|
||||
aliases: aliases,
|
||||
allow_nonexistent_atoms?: allow_nonexistent_atoms?
|
||||
})
|
||||
when is_binary(alias) do
|
||||
defp tag_oneletter_alias(alias, aliases, allow_nonexistent_atoms?) when is_binary(alias) do
|
||||
if option_key = aliases[to_existing_key(alias, allow_nonexistent_atoms?)] do
|
||||
{:default, option_key}
|
||||
else
|
||||
@@ -652,7 +627,6 @@ defmodule OptionParser do
|
||||
|> String.codepoints()
|
||||
|> Enum.map(&("-" <> &1))
|
||||
|> List.pop_at(-1)
|
||||
|
||||
expanded ++ [last <> if(value, do: "=" <> value, else: "")]
|
||||
end
|
||||
|
||||
@@ -688,20 +662,15 @@ defmodule OptionParser do
|
||||
cond do
|
||||
:boolean in kinds ->
|
||||
{true, kinds, t}
|
||||
|
||||
:count in kinds ->
|
||||
{1, kinds, t}
|
||||
|
||||
value_in_tail?(t) ->
|
||||
[h | t] = t
|
||||
{h, kinds, t}
|
||||
|
||||
kinds == [] and strict? ->
|
||||
{nil, kinds, t}
|
||||
|
||||
kinds == [] ->
|
||||
{true, kinds, t}
|
||||
|
||||
true ->
|
||||
{nil, [:invalid], t}
|
||||
end
|
||||
@@ -711,33 +680,38 @@ defmodule OptionParser do
|
||||
{value, kinds, t}
|
||||
end
|
||||
|
||||
defp value_in_tail?(["-" | _]), do: true
|
||||
defp value_in_tail?(["- " <> _ | _]), do: true
|
||||
defp value_in_tail?(["-" | _]), do: true
|
||||
defp value_in_tail?(["- " <> _ | _]), do: true
|
||||
defp value_in_tail?(["-" <> arg | _]), do: negative_number?("-" <> arg)
|
||||
defp value_in_tail?([]), do: false
|
||||
defp value_in_tail?(_), do: true
|
||||
defp value_in_tail?([]), do: false
|
||||
defp value_in_tail?(_), do: true
|
||||
|
||||
defp split_option(option) do
|
||||
case :binary.split(option, "=") do
|
||||
[h] -> {h, nil}
|
||||
[h] -> {h, nil}
|
||||
[h, t] -> {h, t}
|
||||
end
|
||||
end
|
||||
|
||||
defp to_underscore(option), do: to_underscore(option, <<>>)
|
||||
defp to_underscore("_" <> _rest, _acc), do: nil
|
||||
defp to_underscore("-" <> rest, acc), do: to_underscore(rest, acc <> "_")
|
||||
defp to_underscore(<<c>> <> rest, acc), do: to_underscore(rest, <<acc::binary, c>>)
|
||||
defp to_underscore(<<>>, acc), do: acc
|
||||
defp to_underscore(option),
|
||||
do: to_underscore(option, <<>>)
|
||||
defp to_underscore("_" <> _rest, _acc),
|
||||
do: nil
|
||||
defp to_underscore("-" <> rest, acc),
|
||||
do: to_underscore(rest, acc <> "_")
|
||||
defp to_underscore(<<c>> <> rest, acc),
|
||||
do: to_underscore(rest, <<acc::binary, c>>)
|
||||
defp to_underscore(<<>>, acc),
|
||||
do: acc
|
||||
|
||||
defp get_option_key(option, allow_nonexistent_atoms?) do
|
||||
def get_option_key(option, allow_nonexistent_atoms?) do
|
||||
if string = to_underscore(option) do
|
||||
to_existing_key(string, allow_nonexistent_atoms?)
|
||||
end
|
||||
end
|
||||
|
||||
defp to_existing_key(option, true), do: String.to_atom(option)
|
||||
|
||||
defp to_existing_key(option, true),
|
||||
do: String.to_atom(option)
|
||||
defp to_existing_key(option, false) do
|
||||
try do
|
||||
String.to_existing_atom(option)
|
||||
@@ -754,7 +728,6 @@ defmodule OptionParser do
|
||||
types = opts[:switches] || opts[:strict]
|
||||
error_count = length(errors)
|
||||
error = if error_count == 1, do: "error", else: "errors"
|
||||
|
||||
"#{error_count} #{error} found!\n" <>
|
||||
Enum.map_join(errors, "\n", &format_error(&1, opts, types))
|
||||
end
|
||||
@@ -769,7 +742,7 @@ defmodule OptionParser do
|
||||
|
||||
defp format_error({option, value}, opts, types) do
|
||||
type = get_type(option, opts, types)
|
||||
"#{option} : Expected type #{type}, got #{inspect(value)}"
|
||||
"#{option} : Expected type #{type}, got #{inspect value}"
|
||||
end
|
||||
|
||||
defp get_type(option, opts, types) do
|
||||
|
||||
+144
-191
@@ -12,15 +12,14 @@ defmodule Path do
|
||||
that require it (like `wildcard/2` and `expand/1`).
|
||||
"""
|
||||
|
||||
alias :filename, as: FN
|
||||
@type t :: :unicode.chardata()
|
||||
|
||||
@doc """
|
||||
Converts the given path to an absolute one. Unlike
|
||||
`expand/1`, no attempt is made to resolve `..`, `.` or `~`.
|
||||
|
||||
## Examples
|
||||
|
||||
### Unix
|
||||
## Unix examples
|
||||
|
||||
Path.absname("foo")
|
||||
#=> "/usr/local/foo"
|
||||
@@ -28,24 +27,22 @@ defmodule Path do
|
||||
Path.absname("../x")
|
||||
#=> "/usr/local/../x"
|
||||
|
||||
### Windows
|
||||
## Windows
|
||||
|
||||
Path.absname("foo").
|
||||
#=> "D:/usr/local/foo"
|
||||
"D:/usr/local/foo"
|
||||
Path.absname("../x").
|
||||
#=> "D:/usr/local/../x"
|
||||
"D:/usr/local/../x"
|
||||
|
||||
"""
|
||||
@spec absname(t) :: binary
|
||||
def absname(path) do
|
||||
absname(path, System.cwd!())
|
||||
absname(path, System.cwd!)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Builds a path from `relative_to` to `path`.
|
||||
|
||||
If `path` is already an absolute path, `relative_to` is ignored. See also
|
||||
`relative_to/2`.
|
||||
Builds a path from `relative_to` to `path`. If `path` is already
|
||||
an absolute path, `relative_to` is ignored. See also `relative_to/2`.
|
||||
|
||||
Unlike `expand/2`, no attempt is made to
|
||||
resolve `..`, `.` or `~`.
|
||||
@@ -62,14 +59,9 @@ defmodule Path do
|
||||
@spec absname(t, t) :: binary
|
||||
def absname(path, relative_to) do
|
||||
path = IO.chardata_to_string(path)
|
||||
|
||||
case type(path) do
|
||||
:relative ->
|
||||
absname_join(relative_to, path)
|
||||
|
||||
:absolute ->
|
||||
absname_join([path])
|
||||
|
||||
:relative -> absname_join(relative_to, path)
|
||||
:absolute -> absname_join([path])
|
||||
:volumerelative ->
|
||||
relative_to = IO.chardata_to_string(relative_to)
|
||||
absname_vr(split(path), split(relative_to), relative_to)
|
||||
@@ -77,7 +69,8 @@ defmodule Path do
|
||||
end
|
||||
|
||||
# Absolute path on current drive
|
||||
defp absname_vr(["/" | rest], [volume | _], _relative), do: absname_join([volume | rest])
|
||||
defp absname_vr(["/" | rest], [volume | _], _relative),
|
||||
do: absname_join([volume | rest])
|
||||
|
||||
# Relative to current directory on current drive.
|
||||
defp absname_vr([<<x, ?:>> | rest], [<<x, _::binary>> | _], relative),
|
||||
@@ -87,56 +80,49 @@ defmodule Path do
|
||||
defp absname_vr([<<x, ?:>> | name], _, _relative) do
|
||||
cwd =
|
||||
case :file.get_cwd([x, ?:]) do
|
||||
{:ok, dir} -> IO.chardata_to_string(dir)
|
||||
{:ok, dir} -> IO.chardata_to_string(dir)
|
||||
{:error, _} -> <<x, ?:, ?/>>
|
||||
end
|
||||
|
||||
absname(absname_join(name), cwd)
|
||||
end
|
||||
|
||||
# Joins a list
|
||||
defp absname_join([name1, name2 | rest]), do: absname_join([absname_join(name1, name2) | rest])
|
||||
|
||||
defp absname_join([name]),
|
||||
do: do_absname_join(IO.chardata_to_string(name), <<>>, [], major_os_type())
|
||||
defp absname_join([name1, name2 | rest]), do:
|
||||
absname_join([absname_join(name1, name2) | rest])
|
||||
defp absname_join([name]), do:
|
||||
do_absname_join(IO.chardata_to_string(name), <<>>, [], major_os_type())
|
||||
|
||||
# Joins two paths
|
||||
defp absname_join(left, right),
|
||||
do: do_absname_join(IO.chardata_to_string(left), relative(right), [], major_os_type())
|
||||
|
||||
defp do_absname_join(<<uc_letter, ?:, rest::binary>>, relativename, [], :win32)
|
||||
when uc_letter in ?A..?Z do
|
||||
do_absname_join(rest, relativename, [?:, uc_letter + ?a - ?A], :win32)
|
||||
end
|
||||
defp do_absname_join(<<uc_letter, ?:, rest::binary>>, relativename, [], :win32) when uc_letter in ?A..?Z, do:
|
||||
do_absname_join(rest, relativename, [?:, uc_letter+?a-?A], :win32)
|
||||
defp do_absname_join(<<?\\, rest::binary>>, relativename, result, :win32), do:
|
||||
do_absname_join(<<?/, rest::binary>>, relativename, result, :win32)
|
||||
defp do_absname_join(<<?/, rest::binary>>, relativename, [?., ?/ | result], os_type), do:
|
||||
do_absname_join(rest, relativename, [?/ | result], os_type)
|
||||
defp do_absname_join(<<?/, rest::binary>>, relativename, [?/ | result], os_type), do:
|
||||
do_absname_join(rest, relativename, [?/ | result], os_type)
|
||||
defp do_absname_join(<<>>, <<>>, result, os_type), do:
|
||||
IO.iodata_to_binary(reverse_maybe_remove_dir_sep(result, os_type))
|
||||
defp do_absname_join(<<>>, relativename, [?: | rest], :win32), do:
|
||||
do_absname_join(relativename, <<>>, [?: | rest], :win32)
|
||||
defp do_absname_join(<<>>, relativename, [?/ | result], os_type), do:
|
||||
do_absname_join(relativename, <<>>, [?/ | result], os_type)
|
||||
defp do_absname_join(<<>>, relativename, result, os_type), do:
|
||||
do_absname_join(relativename, <<>>, [?/ | result], os_type)
|
||||
defp do_absname_join(<<char, rest::binary>>, relativename, result, os_type), do:
|
||||
do_absname_join(rest, relativename, [char | result], os_type)
|
||||
|
||||
defp do_absname_join(<<?\\, rest::binary>>, relativename, result, :win32),
|
||||
do: do_absname_join(<<?/, rest::binary>>, relativename, result, :win32)
|
||||
|
||||
defp do_absname_join(<<?/, rest::binary>>, relativename, [?., ?/ | result], os_type),
|
||||
do: do_absname_join(rest, relativename, [?/ | result], os_type)
|
||||
|
||||
defp do_absname_join(<<?/, rest::binary>>, relativename, [?/ | result], os_type),
|
||||
do: do_absname_join(rest, relativename, [?/ | result], os_type)
|
||||
|
||||
defp do_absname_join(<<>>, <<>>, result, os_type),
|
||||
do: IO.iodata_to_binary(reverse_maybe_remove_dir_sep(result, os_type))
|
||||
|
||||
defp do_absname_join(<<>>, relativename, [?: | rest], :win32),
|
||||
do: do_absname_join(relativename, <<>>, [?: | rest], :win32)
|
||||
|
||||
defp do_absname_join(<<>>, relativename, [?/ | result], os_type),
|
||||
do: do_absname_join(relativename, <<>>, [?/ | result], os_type)
|
||||
|
||||
defp do_absname_join(<<>>, relativename, result, os_type),
|
||||
do: do_absname_join(relativename, <<>>, [?/ | result], os_type)
|
||||
|
||||
defp do_absname_join(<<char, rest::binary>>, relativename, result, os_type),
|
||||
do: do_absname_join(rest, relativename, [char | result], os_type)
|
||||
|
||||
defp reverse_maybe_remove_dir_sep([?/, ?:, letter], :win32), do: [letter, ?:, ?/]
|
||||
defp reverse_maybe_remove_dir_sep([?/], _), do: [?/]
|
||||
defp reverse_maybe_remove_dir_sep([?/ | name], _), do: :lists.reverse(name)
|
||||
defp reverse_maybe_remove_dir_sep(name, _), do: :lists.reverse(name)
|
||||
defp reverse_maybe_remove_dir_sep([?/, ?:, letter], :win32), do:
|
||||
[letter, ?:, ?/]
|
||||
defp reverse_maybe_remove_dir_sep([?/], _), do:
|
||||
[?/]
|
||||
defp reverse_maybe_remove_dir_sep([?/ | name], _), do:
|
||||
:lists.reverse(name)
|
||||
defp reverse_maybe_remove_dir_sep(name, _), do:
|
||||
:lists.reverse(name)
|
||||
|
||||
@doc """
|
||||
Converts the path to an absolute one and expands
|
||||
@@ -150,16 +136,15 @@ defmodule Path do
|
||||
"""
|
||||
@spec expand(t) :: binary
|
||||
def expand(path) do
|
||||
expand_dot(absname(expand_home(path), System.cwd!()))
|
||||
expand_dot absname(expand_home(path), System.cwd!)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Expands the path relative to the path given as the second argument
|
||||
expanding any `.` and `..` characters.
|
||||
expanding any `.` and `..` characters. If the path is already an
|
||||
absolute path, `relative_to` is ignored.
|
||||
|
||||
If the path is already an absolute path, `relative_to` is ignored.
|
||||
|
||||
Note that this function treats a `path` with a leading `~` as
|
||||
Note, that this function treats `path` with a leading `~` as
|
||||
an absolute one.
|
||||
|
||||
The second argument is first expanded to an absolute path.
|
||||
@@ -178,15 +163,13 @@ defmodule Path do
|
||||
"""
|
||||
@spec expand(t, t) :: binary
|
||||
def expand(path, relative_to) do
|
||||
expand_dot(absname(absname(expand_home(path), expand_home(relative_to)), System.cwd!()))
|
||||
expand_dot absname(absname(expand_home(path), expand_home(relative_to)), System.cwd!)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the path type.
|
||||
|
||||
## Examples
|
||||
|
||||
### Unix
|
||||
## Unix examples
|
||||
|
||||
Path.type("/") #=> :absolute
|
||||
Path.type("/usr/local/bin") #=> :absolute
|
||||
@@ -194,7 +177,7 @@ defmodule Path do
|
||||
Path.type("../usr/local/bin") #=> :relative
|
||||
Path.type("~/file") #=> :relative
|
||||
|
||||
### Windows
|
||||
## Windows examples
|
||||
|
||||
Path.type("D:/usr/local/bin") #=> :absolute
|
||||
Path.type("usr/local/bin") #=> :relative
|
||||
@@ -203,24 +186,20 @@ defmodule Path do
|
||||
|
||||
"""
|
||||
@spec type(t) :: :absolute | :relative | :volumerelative
|
||||
def type(name)
|
||||
when is_list(name)
|
||||
when is_binary(name) do
|
||||
def type(name) when is_list(name) or is_binary(name) do
|
||||
pathtype(name, major_os_type()) |> elem(0)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Forces the path to be a relative path.
|
||||
|
||||
## Examples
|
||||
|
||||
### Unix
|
||||
## Unix examples
|
||||
|
||||
Path.relative("/usr/local/bin") #=> "usr/local/bin"
|
||||
Path.relative("usr/local/bin") #=> "usr/local/bin"
|
||||
Path.relative("../usr/local/bin") #=> "../usr/local/bin"
|
||||
|
||||
### Windows
|
||||
## Windows examples
|
||||
|
||||
Path.relative("D:/usr/local/bin") #=> "usr/local/bin"
|
||||
Path.relative("usr/local/bin") #=> "usr/local/bin"
|
||||
@@ -236,58 +215,56 @@ defmodule Path do
|
||||
defp relative(name, os_type) do
|
||||
pathtype(name, os_type)
|
||||
|> elem(1)
|
||||
|> IO.chardata_to_string()
|
||||
|> IO.chardata_to_string
|
||||
end
|
||||
|
||||
defp pathtype(name, os_type) do
|
||||
case os_type do
|
||||
:win32 -> win32_pathtype(name)
|
||||
_ -> unix_pathtype(name)
|
||||
_ -> unix_pathtype(name)
|
||||
end
|
||||
end
|
||||
|
||||
defp unix_pathtype(path) when path in ["/", '/'], do: {:absolute, "."}
|
||||
defp unix_pathtype(<<?/, relative::binary>>), do: {:absolute, relative}
|
||||
defp unix_pathtype([?/ | relative]), do: {:absolute, relative}
|
||||
defp unix_pathtype([list | rest]) when is_list(list), do: unix_pathtype(list ++ rest)
|
||||
defp unix_pathtype(relative), do: {:relative, relative}
|
||||
defp unix_pathtype(<<?/, relative::binary>>), do:
|
||||
{:absolute, relative}
|
||||
defp unix_pathtype([?/ | relative]), do:
|
||||
{:absolute, relative}
|
||||
defp unix_pathtype([list | rest]) when is_list(list), do:
|
||||
unix_pathtype(list ++ rest)
|
||||
defp unix_pathtype(relative), do:
|
||||
{:relative, relative}
|
||||
|
||||
@slash [?/, ?\\]
|
||||
|
||||
defp win32_pathtype([list | rest]) when is_list(list), do: win32_pathtype(list ++ rest)
|
||||
defp win32_pathtype([list | rest]) when is_list(list), do:
|
||||
win32_pathtype(list++rest)
|
||||
defp win32_pathtype([char, list | rest]) when is_list(list), do:
|
||||
win32_pathtype([char | list++rest])
|
||||
defp win32_pathtype(<<c1, c2, relative::binary>>) when c1 in @slash and c2 in @slash, do:
|
||||
{:absolute, relative}
|
||||
defp win32_pathtype(<<c, relative::binary>>) when c in @slash, do:
|
||||
{:volumerelative, relative}
|
||||
defp win32_pathtype(<<_letter, ?:, c, relative::binary>>) when c in @slash, do:
|
||||
{:absolute, relative}
|
||||
defp win32_pathtype(<<_letter, ?:, relative::binary>>), do:
|
||||
{:volumerelative, relative}
|
||||
|
||||
defp win32_pathtype([char, list | rest]) when is_list(list),
|
||||
do: win32_pathtype([char | list ++ rest])
|
||||
|
||||
defp win32_pathtype(<<c1, c2, relative::binary>>) when c1 in @slash and c2 in @slash,
|
||||
do: {:absolute, relative}
|
||||
|
||||
defp win32_pathtype(<<char, relative::binary>>) when char in @slash,
|
||||
do: {:volumerelative, relative}
|
||||
|
||||
defp win32_pathtype(<<_letter, ?:, char, relative::binary>>) when char in @slash,
|
||||
do: {:absolute, relative}
|
||||
|
||||
defp win32_pathtype(<<_letter, ?:, relative::binary>>), do: {:volumerelative, relative}
|
||||
|
||||
defp win32_pathtype([c1, c2 | relative]) when c1 in @slash and c2 in @slash,
|
||||
do: {:absolute, relative}
|
||||
|
||||
defp win32_pathtype([char | relative]) when char in @slash, do: {:volumerelative, relative}
|
||||
|
||||
defp win32_pathtype([c1, c2, list | rest]) when is_list(list),
|
||||
do: win32_pathtype([c1, c2 | list ++ rest])
|
||||
|
||||
defp win32_pathtype([_letter, ?:, char | relative]) when char in @slash,
|
||||
do: {:absolute, relative}
|
||||
|
||||
defp win32_pathtype([_letter, ?: | relative]), do: {:volumerelative, relative}
|
||||
defp win32_pathtype(relative), do: {:relative, relative}
|
||||
defp win32_pathtype([c1, c2 | relative]) when c1 in @slash and c2 in @slash, do:
|
||||
{:absolute, relative}
|
||||
defp win32_pathtype([c | relative]) when c in @slash, do:
|
||||
{:volumerelative, relative}
|
||||
defp win32_pathtype([c1, c2, list | rest]) when is_list(list), do:
|
||||
win32_pathtype([c1, c2 | list++rest])
|
||||
defp win32_pathtype([_letter, ?:, c | relative]) when c in @slash, do:
|
||||
{:absolute, relative}
|
||||
defp win32_pathtype([_letter, ?: | relative]), do:
|
||||
{:volumerelative, relative}
|
||||
defp win32_pathtype(relative), do:
|
||||
{:relative, relative}
|
||||
|
||||
@doc """
|
||||
Returns the given `path` relative to the given `from` path.
|
||||
|
||||
In other words, this function tries to strip the `from` prefix from `path`.
|
||||
In other words, it tries to strip the `from` prefix from `path`.
|
||||
|
||||
This function does not query the file system, so it assumes
|
||||
no symlinks between the paths.
|
||||
@@ -327,14 +304,12 @@ defmodule Path do
|
||||
|
||||
@doc """
|
||||
Convenience to get the path relative to the current working
|
||||
directory.
|
||||
|
||||
If, for some reason, the current working directory
|
||||
cannot be retrieved, this function returns the given `path`.
|
||||
directory. If, for some reason, the current working directory
|
||||
cannot be retrieved, returns the full path.
|
||||
"""
|
||||
@spec relative_to_cwd(t) :: binary
|
||||
def relative_to_cwd(path) do
|
||||
case :file.get_cwd() do
|
||||
case :file.get_cwd do
|
||||
{:ok, base} -> relative_to(path, IO.chardata_to_string(base))
|
||||
_ -> path
|
||||
end
|
||||
@@ -358,15 +333,13 @@ defmodule Path do
|
||||
"""
|
||||
@spec basename(t) :: binary
|
||||
def basename(path) do
|
||||
:filename.basename(IO.chardata_to_string(path))
|
||||
FN.basename(IO.chardata_to_string(path))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the last component of `path` with the `extension`
|
||||
stripped.
|
||||
|
||||
This function should be used to remove a specific
|
||||
extension which may or may not be there.
|
||||
stripped. This function should be used to remove a specific
|
||||
extension which may, or may not, be there.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -382,7 +355,7 @@ defmodule Path do
|
||||
"""
|
||||
@spec basename(t, t) :: binary
|
||||
def basename(path, extension) do
|
||||
:filename.basename(IO.chardata_to_string(path), IO.chardata_to_string(extension))
|
||||
FN.basename(IO.chardata_to_string(path), IO.chardata_to_string(extension))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -396,13 +369,10 @@ defmodule Path do
|
||||
iex> Path.dirname("/foo/bar/baz.ex")
|
||||
"/foo/bar"
|
||||
|
||||
iex> Path.dirname("/foo/bar/")
|
||||
"/foo/bar"
|
||||
|
||||
"""
|
||||
@spec dirname(t) :: binary
|
||||
def dirname(path) do
|
||||
:filename.dirname(IO.chardata_to_string(path))
|
||||
FN.dirname(IO.chardata_to_string(path))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -419,7 +389,7 @@ defmodule Path do
|
||||
"""
|
||||
@spec extname(t) :: binary
|
||||
def extname(path) do
|
||||
:filename.extension(IO.chardata_to_string(path))
|
||||
FN.extension(IO.chardata_to_string(path))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -436,14 +406,12 @@ defmodule Path do
|
||||
"""
|
||||
@spec rootname(t) :: binary
|
||||
def rootname(path) do
|
||||
:filename.rootname(IO.chardata_to_string(path))
|
||||
FN.rootname(IO.chardata_to_string(path))
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the `path` with the `extension` stripped.
|
||||
|
||||
This function should be used to remove a specific extension which may
|
||||
or may not be there.
|
||||
Returns the `path` with the `extension` stripped. This function should be used to
|
||||
remove a specific extension which might, or might not, be there.
|
||||
|
||||
## Examples
|
||||
|
||||
@@ -456,7 +424,7 @@ defmodule Path do
|
||||
"""
|
||||
@spec rootname(t, t) :: binary
|
||||
def rootname(path, extension) do
|
||||
:filename.rootname(IO.chardata_to_string(path), IO.chardata_to_string(extension))
|
||||
FN.rootname(IO.chardata_to_string(path), IO.chardata_to_string(extension))
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -478,52 +446,38 @@ defmodule Path do
|
||||
|
||||
"""
|
||||
@spec join(nonempty_list(t)) :: binary
|
||||
def join([name1, name2 | rest]), do: join([join(name1, name2) | rest])
|
||||
def join([name]), do: IO.chardata_to_string(name)
|
||||
def join([name1, name2 | rest]), do:
|
||||
join([join(name1, name2) | rest])
|
||||
def join([name]), do:
|
||||
IO.chardata_to_string(name)
|
||||
|
||||
@doc """
|
||||
Joins two paths.
|
||||
|
||||
The right path will always be expanded to its relative format
|
||||
and any trailing slash will be removed when joining.
|
||||
and any trailing slash is removed on join.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Path.join("foo", "bar")
|
||||
"foo/bar"
|
||||
|
||||
iex> Path.join("/foo", "/bar/")
|
||||
"/foo/bar"
|
||||
|
||||
The functions in this module support chardata, so giving a list will
|
||||
treat it as a single entity:
|
||||
|
||||
iex> Path.join("foo", ["bar", "fiz"])
|
||||
"foo/barfiz"
|
||||
|
||||
iex> Path.join(["foo", "bar"], "fiz")
|
||||
"foobar/fiz"
|
||||
|
||||
"""
|
||||
@spec join(t, t) :: binary
|
||||
def join(left, right) do
|
||||
left = IO.chardata_to_string(left)
|
||||
left = IO.chardata_to_string(left)
|
||||
os_type = major_os_type()
|
||||
do_join(left, right, os_type) |> remove_dir_sep(os_type)
|
||||
end
|
||||
|
||||
defp do_join("", right, os_type), do: relative(right, os_type)
|
||||
defp do_join("/", right, os_type), do: "/" <> relative(right, os_type)
|
||||
|
||||
defp do_join(left, right, os_type),
|
||||
do: remove_dir_sep(left, os_type) <> "/" <> relative(right, os_type)
|
||||
defp do_join("", right, os_type), do: relative(right, os_type)
|
||||
defp do_join("/", right, os_type), do: "/" <> relative(right, os_type)
|
||||
defp do_join(left, right, os_type), do: remove_dir_sep(left, os_type) <> "/" <> relative(right, os_type)
|
||||
|
||||
defp remove_dir_sep("", _os_type), do: ""
|
||||
defp remove_dir_sep("/", _os_type), do: "/"
|
||||
|
||||
defp remove_dir_sep(bin, os_type) do
|
||||
last = :binary.last(bin)
|
||||
|
||||
if last == ?/ or (last == ?\\ and os_type == :win32) do
|
||||
binary_part(bin, 0, byte_size(bin) - 1)
|
||||
else
|
||||
@@ -558,7 +512,7 @@ defmodule Path do
|
||||
def split(""), do: []
|
||||
|
||||
def split(path) do
|
||||
:filename.split(IO.chardata_to_string(path))
|
||||
FN.split(IO.chardata_to_string(path))
|
||||
end
|
||||
|
||||
defmodule Wildcard do
|
||||
@@ -572,7 +526,6 @@ defmodule Path do
|
||||
case call({:list_dir, dir}) do
|
||||
{:ok, files} ->
|
||||
{:ok, for(file <- files, hd(file) != ?., do: file)}
|
||||
|
||||
other ->
|
||||
other
|
||||
end
|
||||
@@ -589,7 +542,7 @@ defmodule Path do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Traverses paths according to the given `glob` expression and returns a
|
||||
Traverses paths according to the given `glob` expression, and returns a
|
||||
list of matches.
|
||||
|
||||
The wildcard looks like an ordinary path, except that certain
|
||||
@@ -615,7 +568,7 @@ defmodule Path do
|
||||
|
||||
Other characters represent themselves. Only paths that have
|
||||
exactly the same character in the same position will match. Note
|
||||
that matching is case-sensitive: `"a"` will not match `"A"`.
|
||||
that matching is case-sensitive; i.e. "a" will not match "A".
|
||||
|
||||
By default, the patterns `*` and `?` do not match files starting
|
||||
with a dot `.` unless `match_dot: true` is given in `opts`.
|
||||
@@ -623,7 +576,7 @@ defmodule Path do
|
||||
## Examples
|
||||
|
||||
Imagine you have a directory called `projects` with three Elixir projects
|
||||
inside of it: `elixir`, `ex_doc`, and `plug`. You can find all `.beam` files
|
||||
inside of it: `elixir`, `ex_doc` and `dynamo`. You can find all `.beam` files
|
||||
inside the `ebin` directory of each project as follows:
|
||||
|
||||
Path.wildcard("projects/*/ebin/**/*.beam")
|
||||
@@ -633,25 +586,21 @@ defmodule Path do
|
||||
Path.wildcard("projects/*/ebin/**/*.{beam,app}")
|
||||
|
||||
"""
|
||||
@spec wildcard(t, keyword) :: [binary]
|
||||
@spec wildcard(t, Keyword.t) :: [binary]
|
||||
def wildcard(glob, opts \\ []) do
|
||||
mod = if Keyword.get(opts, :match_dot), do: :file, else: Path.Wildcard
|
||||
|
||||
glob
|
||||
|> chardata_to_list!()
|
||||
|> chardata_to_list()
|
||||
|> :filelib.wildcard(mod)
|
||||
|> Enum.map(&IO.chardata_to_string/1)
|
||||
end
|
||||
|
||||
defp chardata_to_list!(chardata) do
|
||||
# expand_dot the given path by expanding "..", "." and "~".
|
||||
|
||||
defp chardata_to_list(chardata) do
|
||||
case :unicode.characters_to_list(chardata) do
|
||||
result when is_list(result) ->
|
||||
if 0 in result do
|
||||
raise ArgumentError,
|
||||
"cannot execute Path.wildcard/2 for path with null byte, got: #{inspect(chardata)}"
|
||||
else
|
||||
result
|
||||
end
|
||||
result
|
||||
|
||||
{:error, encoded, rest} ->
|
||||
raise UnicodeConversionError, encoded: encoded, rest: rest, kind: :invalid
|
||||
@@ -664,42 +613,46 @@ defmodule Path do
|
||||
defp expand_home(type) do
|
||||
case IO.chardata_to_string(type) do
|
||||
"~" <> rest -> resolve_home(rest)
|
||||
rest -> rest
|
||||
rest -> rest
|
||||
end
|
||||
end
|
||||
|
||||
defp resolve_home(""), do: System.user_home!()
|
||||
defp resolve_home(""), do: System.user_home!
|
||||
|
||||
defp resolve_home(rest) do
|
||||
case {rest, major_os_type()} do
|
||||
{"\\" <> _, :win32} ->
|
||||
System.user_home!() <> rest
|
||||
|
||||
System.user_home! <> rest
|
||||
{"/" <> _, _} ->
|
||||
System.user_home!() <> rest
|
||||
|
||||
_ ->
|
||||
rest
|
||||
System.user_home! <> rest
|
||||
_ -> rest
|
||||
end
|
||||
end
|
||||
|
||||
# expand_dot the given path by expanding "..", "." and "~".
|
||||
defp expand_dot(<<"/", rest::binary>>), do: "/" <> do_expand_dot(rest)
|
||||
|
||||
defp expand_dot(<<"/", rest::binary>>),
|
||||
do: "/" <> do_expand_dot(rest)
|
||||
defp expand_dot(<<letter, ":/", rest::binary>>) when letter in ?a..?z,
|
||||
do: <<letter, ":/">> <> do_expand_dot(rest)
|
||||
defp expand_dot(path),
|
||||
do: do_expand_dot(path)
|
||||
|
||||
defp expand_dot(path), do: do_expand_dot(path)
|
||||
defp do_expand_dot(path),
|
||||
do: do_expand_dot(:binary.split(path, "/", [:global]), [])
|
||||
|
||||
defp do_expand_dot(path), do: do_expand_dot(:binary.split(path, "/", [:global]), [])
|
||||
defp do_expand_dot([".." | t], [_, _ | acc]), do: do_expand_dot(t, acc)
|
||||
defp do_expand_dot([".." | t], []), do: do_expand_dot(t, [])
|
||||
defp do_expand_dot(["." | t], acc), do: do_expand_dot(t, acc)
|
||||
defp do_expand_dot([h | t], acc), do: do_expand_dot(t, ["/", h | acc])
|
||||
defp do_expand_dot([], []), do: ""
|
||||
defp do_expand_dot([], ["/" | acc]), do: IO.iodata_to_binary(:lists.reverse(acc))
|
||||
defp do_expand_dot([".." | t], [_, _ | acc]),
|
||||
do: do_expand_dot(t, acc)
|
||||
defp do_expand_dot([".." | t], []),
|
||||
do: do_expand_dot(t, [])
|
||||
defp do_expand_dot(["." | t], acc),
|
||||
do: do_expand_dot(t, acc)
|
||||
defp do_expand_dot([h | t], acc),
|
||||
do: do_expand_dot(t, ["/", h | acc])
|
||||
defp do_expand_dot([], []),
|
||||
do: ""
|
||||
defp do_expand_dot([], ["/" | acc]),
|
||||
do: IO.iodata_to_binary(:lists.reverse(acc))
|
||||
|
||||
defp major_os_type do
|
||||
:os.type() |> elem(0)
|
||||
:os.type |> elem(0)
|
||||
end
|
||||
end
|
||||
|
||||
+33
-64
@@ -63,12 +63,11 @@ defmodule Port do
|
||||
|
||||
On its turn, the port will send the connected process the following messages:
|
||||
|
||||
* `{port, {:data, data}}` - data sent by the port
|
||||
* `{port, {:port, data}}` - data sent by the port
|
||||
* `{port, :closed}` - reply to the `{pid, :close}` message
|
||||
* `{port, :connected}` - reply to the `{pid, {:connect, new_pid}}` message
|
||||
* `{:EXIT, port, reason}` - exit signals in case the port crashes. If reason
|
||||
is not `:normal`, this message will only be received if the owner process
|
||||
is trapping exits
|
||||
* `{:EXIT, port, reason}` - exit signals in case the port crashes and the
|
||||
owner process is trapping exits
|
||||
|
||||
## Open mechanisms
|
||||
|
||||
@@ -84,16 +83,16 @@ defmodule Port do
|
||||
The `:spawn` tuple receives a binary that is going to be executed as a
|
||||
full invocation. For example, we can use it to invoke "echo hello" directly:
|
||||
|
||||
iex> port = Port.open({:spawn, "echo hello"}, [:binary])
|
||||
iex> port = Port.open({:spawn, "echo oops"}, [:binary])
|
||||
iex> flush()
|
||||
{#Port<0.1444>, {:data, "hello\n"}}
|
||||
{#Port<0.1444>, {:data, "oops\n"}}
|
||||
|
||||
`:spawn` will retrieve the program name from the argument and traverse your
|
||||
OS `$PATH` environment variable looking for a matching program.
|
||||
|
||||
Although the above is handy, it means it is impossible to invoke an executable
|
||||
that has whitespaces on its name or in any of its arguments. For those reasons,
|
||||
most times it is preferable to execute `:spawn_executable`.
|
||||
most times it is preferrable to execute `:spawn_executable`.
|
||||
|
||||
### spawn_executable
|
||||
|
||||
@@ -110,6 +109,14 @@ defmodule Port do
|
||||
the `:args` option as done above. For the full list of options, see the
|
||||
documentation for the Erlang function `:erlang.open_port/2`.
|
||||
|
||||
### spawn_driver
|
||||
|
||||
Spawn driver is used to start Port Drivers, which are programs written in
|
||||
C that implements a specific communication protocols and are dynamically
|
||||
linked to the Erlang VM. Port drivers are an advanced topic and one of the
|
||||
mechanisms for integrating C code, alongside NIFs. For more information,
|
||||
[please check the Erlang docs](http://erlang.org/doc/reference_manual/ports.html).
|
||||
|
||||
### fd
|
||||
|
||||
The `:fd` name option allows developers to access `in` and `out` file
|
||||
@@ -117,7 +124,7 @@ defmodule Port do
|
||||
reimplementing core part of the Runtime System, such as the `:user` and
|
||||
`:shell` processes.
|
||||
|
||||
## Zombie OS processes
|
||||
## Zombie processes
|
||||
|
||||
A port can be closed via the `close/1` function or by sending a `{pid, :close}`
|
||||
message. However, if the VM crashes, a long-running program started by the port
|
||||
@@ -132,13 +139,14 @@ defmodule Port do
|
||||
script in bash:
|
||||
|
||||
#!/bin/sh
|
||||
"$@" &
|
||||
"$@"
|
||||
pid=$!
|
||||
while read line ; do
|
||||
:
|
||||
done
|
||||
kill -KILL $pid
|
||||
|
||||
|
||||
Now instead of:
|
||||
|
||||
Port.open({:spawn_executable, "/path/to/program"},
|
||||
@@ -151,11 +159,10 @@ defmodule Port do
|
||||
|
||||
"""
|
||||
|
||||
@type name ::
|
||||
{:spawn, charlist | binary}
|
||||
| {:spawn_driver, charlist | binary}
|
||||
| {:spawn_executable, charlist | atom}
|
||||
| {:fd, non_neg_integer, non_neg_integer}
|
||||
@type name :: {:spawn, charlist | binary} |
|
||||
{:spawn_driver, charlist | binary} |
|
||||
{:spawn_executable, charlist | atom} |
|
||||
{:fd, non_neg_integer, non_neg_integer}
|
||||
|
||||
@doc """
|
||||
Opens a port given a tuple `name` and a list of `options`.
|
||||
@@ -172,7 +179,8 @@ defmodule Port do
|
||||
* `{:fd, fd_in, fd_out}` - accesses file descriptors, `fd_in` and `fd_out`
|
||||
opened by the VM.
|
||||
|
||||
For more information and the list of options, see `:erlang.open_port/2`.
|
||||
For more information and the list of options, see
|
||||
[`:erlang.open_port/2`](http://www.erlang.org/doc/man/erlang.html#open_port-2).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -184,7 +192,7 @@ defmodule Port do
|
||||
@doc """
|
||||
Closes the `port`.
|
||||
|
||||
For more information, see `:erlang.port_close/1`.
|
||||
For more information, see [`:erlang.port_close/1`](http://www.erlang.org/doc/man/erlang.html#port_close-1).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -196,7 +204,7 @@ defmodule Port do
|
||||
@doc """
|
||||
Sends `data` to the port driver `port`.
|
||||
|
||||
For more information, see `:erlang.port_command/2`.
|
||||
For more information, see [`:erlang.port_command/2`](http://www.erlang.org/doc/man/erlang.html#port_command-2).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -208,7 +216,7 @@ defmodule Port do
|
||||
@doc """
|
||||
Associates the `port` identifier with a `pid`.
|
||||
|
||||
For more information, see `:erlang.port_connect/2`.
|
||||
For more information, see [`:erlang.port_connect/2`](http://www.erlang.org/doc/man/erlang.html#port_connect-2).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@@ -220,70 +228,31 @@ defmodule Port do
|
||||
@doc """
|
||||
Returns information about the `port` or `nil` if the port is closed.
|
||||
|
||||
For more information, see `:erlang.port_info/1`.
|
||||
For more information, see [`:erlang.port_info/1`](http://www.erlang.org/doc/man/erlang.html#port_info-1).
|
||||
"""
|
||||
def info(port) do
|
||||
nillify(:erlang.port_info(port))
|
||||
nillify :erlang.port_info(port)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns information about the `port` or `nil` if the port is closed.
|
||||
|
||||
For more information, see `:erlang.port_info/2`.
|
||||
For more information, see [`:erlang.port_info/2`](http://www.erlang.org/doc/man/erlang.html#port_info-2).
|
||||
"""
|
||||
@spec info(port, atom) :: {atom, term} | nil
|
||||
def info(port, spec)
|
||||
|
||||
def info(port, :registered_name) do
|
||||
case :erlang.port_info(port, :registered_name) do
|
||||
:undefined -> nil
|
||||
[] -> {:registered_name, []}
|
||||
other -> other
|
||||
other -> nillify(other)
|
||||
end
|
||||
end
|
||||
|
||||
def info(port, item) do
|
||||
nillify(:erlang.port_info(port, item))
|
||||
nillify :erlang.port_info(port, item)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts monitoring the given `port` from the calling process.
|
||||
|
||||
Once the monitored port process dies, a message is delivered to the
|
||||
monitoring process in the shape of:
|
||||
|
||||
{:DOWN, ref, :port, object, reason}
|
||||
|
||||
where:
|
||||
|
||||
* `ref` is a monitor reference returned by this function;
|
||||
* `object` is either the `port` being monitored (when monitoring by port id)
|
||||
or `{name, node}` (when monitoring by a port name);
|
||||
* `reason` is the exit reason.
|
||||
|
||||
See `:erlang.monitor/2` for more info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec monitor(port | {name :: atom, node :: atom} | name :: atom) :: reference
|
||||
def monitor(port) do
|
||||
:erlang.monitor(:port, port)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Demonitors the monitor identified by the given `reference`.
|
||||
|
||||
If `monitor_ref` is a reference which the calling process
|
||||
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 info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec demonitor(reference, options :: [:flush | :info]) :: boolean
|
||||
defdelegate demonitor(monitor_ref, options \\ []), to: :erlang
|
||||
|
||||
@doc """
|
||||
Returns a list of all ports in the current node.
|
||||
|
||||
@@ -291,10 +260,10 @@ defmodule Port do
|
||||
"""
|
||||
@spec list :: [port]
|
||||
def list do
|
||||
:erlang.ports()
|
||||
:erlang.ports
|
||||
end
|
||||
|
||||
@compile {:inline, nillify: 1}
|
||||
defp nillify(:undefined), do: nil
|
||||
defp nillify(other), do: other
|
||||
defp nillify(other), do: other
|
||||
end
|
||||
|
||||
+187
-286
@@ -4,7 +4,7 @@ defmodule Process do
|
||||
|
||||
Besides the functions available in this module, the `Kernel` module
|
||||
exposes and auto-imports some basic functionality related to processes
|
||||
available through the following functions:
|
||||
available through the functions:
|
||||
|
||||
* `Kernel.spawn/1` and `Kernel.spawn/3`
|
||||
* `Kernel.spawn_link/1` and `Kernel.spawn_link/3`
|
||||
@@ -12,44 +12,42 @@ defmodule Process do
|
||||
* `Kernel.self/0`
|
||||
* `Kernel.send/2`
|
||||
|
||||
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
|
||||
resort to this module for gathering information, trapping exits, links
|
||||
and monitoring.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Tells whether the given process is alive.
|
||||
Returns `true` if the process exists and is alive (i.e. it is not exiting
|
||||
and has not exited yet). Otherwise, returns `false`.
|
||||
|
||||
If the process identified by `pid` is alive (that is, it's not exiting and has
|
||||
not exited yet) than this function returns `true`. Otherwise, it returns
|
||||
`false`.
|
||||
|
||||
`pid` must refer to a process running on the local node.
|
||||
`pid` must refer to a process at the local node.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec alive?(pid) :: boolean
|
||||
defdelegate alive?(pid), to: :erlang, as: :is_process_alive
|
||||
def alive?(pid) do
|
||||
:erlang.is_process_alive(pid)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all key-value pairs in the process dictionary.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec get() :: [{term, term}]
|
||||
defdelegate get(), to: :erlang
|
||||
@spec get :: [{term, term}]
|
||||
def get do
|
||||
:erlang.get()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the value for the given `key` in the process dictionary,
|
||||
or `default` if `key` is not set.
|
||||
Returns the value for the given `key` or `default` if `key` is not set.
|
||||
"""
|
||||
@spec get(term) :: term
|
||||
@spec get(term, default :: term) :: term
|
||||
def get(key, default \\ nil) do
|
||||
case :erlang.get(key) do
|
||||
:undefined -> default
|
||||
value -> value
|
||||
:undefined ->
|
||||
default
|
||||
value ->
|
||||
value
|
||||
end
|
||||
end
|
||||
|
||||
@@ -59,58 +57,41 @@ defmodule Process do
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec get_keys() :: [term]
|
||||
defdelegate get_keys(), to: :erlang
|
||||
def get_keys() do
|
||||
:erlang.get_keys()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns all keys in the process dictionary that have the given `value`.
|
||||
Returns all keys that have the given `value`.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec get_keys(term) :: [term]
|
||||
defdelegate get_keys(value), to: :erlang
|
||||
def get_keys(value) do
|
||||
:erlang.get_keys(value)
|
||||
end
|
||||
|
||||
@doc """
|
||||
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 `key`.
|
||||
|
||||
## Examples
|
||||
|
||||
# Assuming :locale was not set
|
||||
Process.put(:locale, "en")
|
||||
#=> nil
|
||||
Process.put(:locale, "fr")
|
||||
#=> "en"
|
||||
|
||||
The return value is the value that was previously stored under the key `key`
|
||||
(or `nil` in case no value was stored under `key`).
|
||||
"""
|
||||
@spec put(term, term) :: term | nil
|
||||
def put(key, value) do
|
||||
nillify(:erlang.put(key, value))
|
||||
nillify :erlang.put(key, value)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Deletes the given `key` from the process dictionary.
|
||||
|
||||
Returns the value that was under `key` in the process dictionary,
|
||||
or `nil` if `key` was not stored in the process dictionary.
|
||||
|
||||
## Examples
|
||||
|
||||
Process.put(:comments, ["comment", "other comment"])
|
||||
Process.delete(:comments)
|
||||
#=> ["comment", "other comment"]
|
||||
Process.delete(:comments)
|
||||
#=> nil
|
||||
|
||||
"""
|
||||
@spec delete(term) :: term | nil
|
||||
def delete(key) do
|
||||
nillify(:erlang.erase(key))
|
||||
nillify :erlang.erase(key)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sends an exit signal with the given `reason` to `pid`.
|
||||
Sends an exit signal with the given `reason` to the `pid`.
|
||||
|
||||
The following behaviour applies if `reason` is any term except `:normal`
|
||||
or `:kill`:
|
||||
@@ -127,7 +108,7 @@ defmodule Process do
|
||||
If it is trapping exits, the exit signal is transformed into a message
|
||||
`{:EXIT, from, :normal}` and delivered to its message queue.
|
||||
|
||||
If `reason` is the atom `:kill`, that is if `Process.exit(pid, :kill)` is called,
|
||||
If `reason` is the atom `:kill`, that is if `exit(pid, :kill)` is called,
|
||||
an untrappable exit signal is sent to `pid` which will unconditionally exit
|
||||
with reason `:killed`.
|
||||
|
||||
@@ -136,28 +117,27 @@ defmodule Process do
|
||||
## Examples
|
||||
|
||||
Process.exit(pid, :kill)
|
||||
#=> true
|
||||
|
||||
"""
|
||||
@spec exit(pid, term) :: true
|
||||
defdelegate exit(pid, reason), to: :erlang
|
||||
def exit(pid, reason) do
|
||||
:erlang.exit(pid, reason)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sleeps the current process for the given `timeout`.
|
||||
Sleeps the current process by `timeout`.
|
||||
|
||||
`timeout` is either the number of milliseconds to sleep as an
|
||||
integer or the atom `:infinity`. When `:infinity` is given,
|
||||
the current process will sleep forever, and not
|
||||
consume or reply to messages.
|
||||
the current process will suspend forever.
|
||||
|
||||
**Use this function with extreme care**. For almost all situations
|
||||
where you would use `sleep/1` in Elixir, there is likely a
|
||||
more correct, faster and precise way of achieving the same with
|
||||
more correct, faster and precise way of achieving it with
|
||||
message passing.
|
||||
|
||||
For example, if you are waiting for a process to perform some
|
||||
action, it is better to communicate the progress of such action
|
||||
with messages.
|
||||
For example, if you are waiting a process to perform some
|
||||
action, it is better to communicate.
|
||||
|
||||
In other words, **do not**:
|
||||
|
||||
@@ -184,11 +164,11 @@ defmodule Process do
|
||||
30_000 -> :timeout # Optional timeout
|
||||
end
|
||||
|
||||
For cases like the one above, `Task.async/1` and `Task.await/2` are
|
||||
preferred.
|
||||
Or even use `Task.async/1` and `Task.await/2` in the example
|
||||
above.
|
||||
|
||||
Similarly, if you are waiting for a process to terminate,
|
||||
monitor that process instead of sleeping. **Do not**:
|
||||
use monitor instead of sleep. **Do not**:
|
||||
|
||||
Task.start_link fn ->
|
||||
...
|
||||
@@ -212,7 +192,6 @@ defmodule Process do
|
||||
end
|
||||
|
||||
"""
|
||||
@spec sleep(timeout) :: :ok
|
||||
def sleep(timeout)
|
||||
when is_integer(timeout) and timeout >= 0
|
||||
when timeout == :infinity do
|
||||
@@ -222,48 +201,45 @@ defmodule Process do
|
||||
@doc """
|
||||
Sends a message to the given process.
|
||||
|
||||
## Options
|
||||
If the option `:noconnect` is used and sending the message would require an
|
||||
auto-connection to another node the message is not sent and `:noconnect` is
|
||||
returned.
|
||||
|
||||
* `:noconnect` - when used, if sending the message would require an
|
||||
auto-connection to another node the message is not sent and `:noconnect` is
|
||||
returned.
|
||||
|
||||
* `:nosuspend` - when used, if sending the message would cause the sender to
|
||||
be suspended the message is not sent and `:nosuspend` is returned.
|
||||
If the option `:nosuspend` is used and sending the message would cause the
|
||||
sender to be suspended the message is not sent and `:nosuspend` is returned.
|
||||
|
||||
Otherwise the message is sent and `:ok` is returned.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Process.send({:name, :node_that_does_not_exist}, :hi, [:noconnect])
|
||||
iex> Process.send({:name, :node_does_not_exist}, :hi, [:noconnect])
|
||||
:noconnect
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec send(dest, msg, [option]) :: :ok | :noconnect | :nosuspend
|
||||
when dest: pid | port | atom | {atom, node},
|
||||
msg: any,
|
||||
option: :noconnect | :nosuspend
|
||||
defdelegate send(dest, msg, options), to: :erlang
|
||||
def send(dest, msg, options) do
|
||||
:erlang.send(dest, msg, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sends `msg` to `dest` after `time` milliseconds.
|
||||
|
||||
If `dest` is a PID, it must be the PID of a local process, dead or alive.
|
||||
If `dest` is an atom, it must be the name of a registered process
|
||||
which is looked up at the time of delivery. No error is produced if the name does
|
||||
which is looked up at the time of delivery. No error is given if the name does
|
||||
not refer to a process.
|
||||
|
||||
This function returns a timer reference, which can be read with `read_timer/1`
|
||||
or canceled with `cancel_timer/1`.
|
||||
This function returns a timer reference, which can be read or canceled with
|
||||
`read_timer/1` and `cancel_timer/1`.
|
||||
|
||||
The timer will be automatically canceled if the given `dest` is a PID
|
||||
Finally, the timer will be automatically canceled if the given `dest` is a PID
|
||||
which is not alive or when the given PID exits. Note that timers will not be
|
||||
automatically canceled when `dest` is an atom (as the atom resolution is done
|
||||
on delivery).
|
||||
|
||||
Inlined by the compiler.
|
||||
|
||||
## Options
|
||||
|
||||
* `:abs` - (boolean) when `false`, `time` is treated as relative to the
|
||||
@@ -272,10 +248,6 @@ defmodule Process do
|
||||
To read more about Erlang monotonic time and other time-related concepts,
|
||||
look at the documentation for the `System` module. Defaults to `false`.
|
||||
|
||||
## Examples
|
||||
|
||||
timer_ref = Process.send_after(pid, :hi, 1000)
|
||||
|
||||
"""
|
||||
@spec send_after(pid | atom, term, non_neg_integer, [option]) :: reference
|
||||
when option: {:abs, boolean}
|
||||
@@ -284,40 +256,24 @@ defmodule Process do
|
||||
end
|
||||
|
||||
@doc """
|
||||
Cancels a timer returned by `send_after/3`.
|
||||
Cancels a timer created by `send_after/3`.
|
||||
|
||||
When the result is an integer, it represents the time in milliseconds
|
||||
left until the timer would have expired.
|
||||
|
||||
When the result is `false`, a timer corresponding to `timer_ref` could not be
|
||||
found. This can happen either because the timer expired, because it has
|
||||
already been canceled, or because `timer_ref` never corresponded to a timer.
|
||||
When the result is `false`, a timer corresponding to `timer_ref` could
|
||||
not be found. This can be either because the timer expired, already has
|
||||
been canceled, or because `timer_ref` never corresponded to a timer.
|
||||
|
||||
Even if the timer had expired and the message was sent, this function does not
|
||||
tell you if the timeout message has arrived at its destination yet.
|
||||
|
||||
## Options
|
||||
|
||||
* `:async` - (boolean) when `false`, the request for cancellation is
|
||||
synchronous. When `true`, the request for cancellation is asynchronous,
|
||||
meaning that the request to cancel the timer is issued and `:ok` is
|
||||
returned right away. Defaults to `false`.
|
||||
|
||||
* `:info` - (boolean) whether to return information about the timer being
|
||||
cancelled. When the `:async` option is `false` and `:info` is `true`, then
|
||||
either an integer or `false` (like described above) is returned. If
|
||||
`:async` is `false` and `:info` is `false`, `:ok` is returned. If `:async`
|
||||
is `true` and `:info` is `true`, a message in the form `{:cancel_timer,
|
||||
timer_ref, result}` (where `result` is an integer or `false` like
|
||||
described above) is sent to the caller of this function when the
|
||||
cancellation has been performed. If `:async` is `true` and `:info` is
|
||||
`false`, no message is sent. Defaults to `true`.
|
||||
If the timer has expired, the timeout message has been sent, but it does
|
||||
not tell you whether or not it has arrived at its destination yet.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec cancel_timer(reference, options) :: non_neg_integer | false | :ok
|
||||
when options: [async: boolean, info: boolean]
|
||||
defdelegate cancel_timer(timer_ref, options \\ []), to: :erlang
|
||||
@spec cancel_timer(reference) :: non_neg_integer | false
|
||||
def cancel_timer(timer_ref) do
|
||||
:erlang.cancel_timer(timer_ref)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Reads a timer created by `send_after/3`.
|
||||
@@ -325,25 +281,24 @@ defmodule Process do
|
||||
When the result is an integer, it represents the time in milliseconds
|
||||
left until the timer will expire.
|
||||
|
||||
When the result is `false`, a timer corresponding to `timer_ref` could not be
|
||||
found. This can be either because the timer expired, because it has already
|
||||
When the result is `false`, a timer corresponding to `timer_ref` could
|
||||
not be found. This can be either because the timer expired, already has
|
||||
been canceled, or because `timer_ref` never corresponded to a timer.
|
||||
|
||||
Even if the timer had expired and the message was sent, this function does not
|
||||
tell you if the timeout message has arrived at its destination yet.
|
||||
If the timer has expired, the timeout message has been sent, but it does
|
||||
not tell you whether or not it has arrived at its destination yet.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec read_timer(reference) :: non_neg_integer | false
|
||||
defdelegate read_timer(timer_ref), to: :erlang
|
||||
def read_timer(timer_ref) do
|
||||
:erlang.read_timer(timer_ref)
|
||||
end
|
||||
|
||||
@type spawn_opt ::
|
||||
:link
|
||||
| :monitor
|
||||
| {:priority, :low | :normal | :high}
|
||||
| {:fullsweep_after, non_neg_integer}
|
||||
| {:min_heap_size, non_neg_integer}
|
||||
| {:min_bin_vheap_size, non_neg_integer}
|
||||
@type spawn_opt :: :link | :monitor | {:priority, :low | :normal | :high} |
|
||||
{:fullsweep_after, non_neg_integer} |
|
||||
{:min_heap_size, non_neg_integer} |
|
||||
{:min_bin_vheap_size, non_neg_integer}
|
||||
@type spawn_opts :: [spawn_opt]
|
||||
|
||||
@doc """
|
||||
@@ -354,16 +309,18 @@ defmodule Process do
|
||||
containing the PID and the monitoring reference, otherwise
|
||||
just the spawned process PID.
|
||||
|
||||
More options are available; for the comprehensive list of available options
|
||||
check `:erlang.spawn_opt/4`.
|
||||
It also accepts extra options, for the list of available options
|
||||
check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec spawn((() -> any), spawn_opts) :: pid | {pid, reference}
|
||||
defdelegate spawn(fun, opts), to: :erlang, as: :spawn_opt
|
||||
def spawn(fun, opts) do
|
||||
:erlang.spawn_opt(fun, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Spawns the given function `fun` from module `mod`, passing the given `args`
|
||||
Spawns the given function from module `mod`, passing the given `args`
|
||||
according to the given options.
|
||||
|
||||
The result depends on the given options. In particular,
|
||||
@@ -372,107 +329,86 @@ defmodule Process do
|
||||
just the spawned process PID.
|
||||
|
||||
It also accepts extra options, for the list of available options
|
||||
check `:erlang.spawn_opt/4`.
|
||||
check [`:erlang.spawn_opt/4`](http://www.erlang.org/doc/man/erlang.html#spawn_opt-4).
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec spawn(module, atom, list, spawn_opts) :: pid | {pid, reference}
|
||||
defdelegate spawn(mod, fun, args, opts), to: :erlang, as: :spawn_opt
|
||||
def spawn(mod, fun, args, opts) do
|
||||
:erlang.spawn_opt(mod, fun, args, opts)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts monitoring the given `item` from the calling process.
|
||||
|
||||
Once the monitored process dies, a message is delivered to the
|
||||
monitoring process in the shape of:
|
||||
|
||||
{:DOWN, ref, :process, object, reason}
|
||||
|
||||
where:
|
||||
|
||||
* `ref` is a monitor reference returned by this function;
|
||||
* `object` is either a `pid` of the monitored process (if monitoring
|
||||
a PID) or `{name, node}` (if monitoring a remote or local name);
|
||||
* `reason` is the exit reason.
|
||||
The calling process starts monitoring the given `item`.
|
||||
It returns the monitor reference.
|
||||
|
||||
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.
|
||||
for an example.
|
||||
See [`:erlang.monitor/2`](http://www.erlang.org/doc/man/erlang.html#monitor-2) for more info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec monitor(pid | {name :: atom, node :: atom} | name :: atom) :: reference
|
||||
@spec monitor(pid | {reg_name :: atom, node :: atom} | reg_name :: atom) :: reference
|
||||
def monitor(item) do
|
||||
:erlang.monitor(:process, item)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Demonitors the monitor identified by the given `reference`.
|
||||
|
||||
If `monitor_ref` is a reference which the calling process
|
||||
obtained by calling `monitor/1`, that monitoring is turned off.
|
||||
obtained by calling `monitor/1`, this monitoring is turned off.
|
||||
If the monitoring is already turned off, nothing happens.
|
||||
|
||||
See `:erlang.demonitor/2` for more info.
|
||||
See [`:erlang.demonitor/2`](http://www.erlang.org/doc/man/erlang.html#demonitor-2) for more info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec demonitor(reference) :: true
|
||||
@spec demonitor(reference, options :: [:flush | :info]) :: boolean
|
||||
defdelegate demonitor(monitor_ref, options \\ []), to: :erlang
|
||||
def demonitor(monitor_ref, options \\ []) do
|
||||
:erlang.demonitor(monitor_ref, options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a list of PIDs corresponding to all the
|
||||
Returns a list of process identifiers corresponding to all the
|
||||
processes currently existing on the local node.
|
||||
|
||||
Note that if a process is exiting, it is considered to exist but not be
|
||||
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.
|
||||
Note that a process that is exiting, exists but is not alive, i.e.,
|
||||
`alive?/1` will return `false` for a process that is exiting,
|
||||
but its process identifier will be part of the result returned.
|
||||
|
||||
See `:erlang.processes/0` for more info.
|
||||
|
||||
Inlined by the compiler.
|
||||
See [`:erlang.processes/0`](http://www.erlang.org/doc/man/erlang.html#processes-0) for more info.
|
||||
"""
|
||||
@spec list() :: [pid]
|
||||
defdelegate list(), to: :erlang, as: :processes
|
||||
@spec list :: [pid]
|
||||
def list do
|
||||
:erlang.processes()
|
||||
end
|
||||
|
||||
@doc """
|
||||
Creates a link between the calling process and the given item (process or
|
||||
port).
|
||||
Creates a link between the calling process and another process
|
||||
(or port) `pid`, if there is not such a link already.
|
||||
|
||||
Links are bidirectional. Linked processes can be unlinked by using `unlink/1`.
|
||||
|
||||
If such a link exists already, this function does nothing since there can only
|
||||
be one link between two given processes. If a process tries to create a link
|
||||
to itself, nothing will happen.
|
||||
|
||||
When two processes are linked, each one receives exit signals from the other
|
||||
(see also `exit/2`). Let's assume `pid1` and `pid2` are linked. If `pid2`
|
||||
exits with a reason other than `:normal` (which is also the exit reason used
|
||||
when a process finishes its job) and `pid1` is not trapping exits (see
|
||||
`flag/2`), then `pid1` will exit with the same reason as `pid2` and in turn
|
||||
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 info.
|
||||
See [`:erlang.link/1`](http://www.erlang.org/doc/man/erlang.html#link-1) for more info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec link(pid | port) :: true
|
||||
defdelegate link(pid_or_port), to: :erlang
|
||||
def link(pid) do
|
||||
:erlang.link(pid)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Removes the link between the calling process and the given item (process or
|
||||
port).
|
||||
Removes the link, if there is one, between the calling process and
|
||||
the process or port referred to by `pid`. Returns `true` and does not
|
||||
fail, even if there is no link or `id` does not exist
|
||||
|
||||
If there is no such link, this function does nothing. If `pid_or_port` does
|
||||
not exist, this function does not produce any errors and simply does nothing.
|
||||
|
||||
The return value of this function is always `true`.
|
||||
|
||||
See `:erlang.unlink/1` for more info.
|
||||
See [`:erlang.unlink/1`](http://www.erlang.org/doc/man/erlang.html#unlink-1) for more info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec unlink(pid | port) :: true
|
||||
defdelegate unlink(pid_or_port), to: :erlang
|
||||
def unlink(pid) do
|
||||
:erlang.unlink(pid)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Registers the given `pid_or_port` under the given `name`.
|
||||
@@ -480,77 +416,64 @@ defmodule Process do
|
||||
`name` must be an atom and can then be used instead of the
|
||||
PID/port identifier when sending messages with `Kernel.send/2`.
|
||||
|
||||
`register/2` will fail with `ArgumentError` in any of the following cases:
|
||||
|
||||
* the PID/Port is not existing locally and alive
|
||||
* the name is already registered
|
||||
* the `pid_or_port` is already registered under a different `name`
|
||||
`register/2` will fail with `ArgumentError` if the PID/Port is
|
||||
not existing locally and alive, if the name is already registered
|
||||
or if the `pid_or_port` is already registered to a different `name`.
|
||||
|
||||
The following names are reserved and cannot be assigned to
|
||||
processes nor ports:
|
||||
|
||||
* `nil`
|
||||
* `false`
|
||||
* `true`
|
||||
* `:undefined`
|
||||
|
||||
processes nor ports: `nil`, `false`, `true` or `:undefined`.
|
||||
"""
|
||||
@spec register(pid | port, atom) :: true
|
||||
def register(pid_or_port, name)
|
||||
when is_atom(name) and name not in [nil, false, true, :undefined] do
|
||||
def register(pid_or_port, name) when is_atom(name) and not name in [nil, false, true, :undefined] do
|
||||
:erlang.register(name, pid_or_port)
|
||||
catch
|
||||
:error, :badarg when node(pid_or_port) != node() ->
|
||||
message = "could not register #{inspect(pid_or_port)} because it belongs to another node"
|
||||
:erlang.error(ArgumentError.exception(message), [pid_or_port, name])
|
||||
|
||||
:error, :badarg when node(pid_or_port) != node() ->
|
||||
message = "could not register the #{pid_or_port pid_or_port} because it belongs to another node"
|
||||
:erlang.error ArgumentError.exception(message), [pid_or_port, name]
|
||||
:error, :badarg ->
|
||||
message =
|
||||
"could not register #{inspect(pid_or_port)} with " <>
|
||||
"name #{inspect(name)} because it is not alive, the name is already " <>
|
||||
"taken, or it has already been given another name"
|
||||
|
||||
:erlang.error(ArgumentError.exception(message), [pid_or_port, name])
|
||||
message = "could not register the #{pid_or_port pid_or_port} with " <>
|
||||
"name #{inspect name}. Or it is not alive, or the name is already " <>
|
||||
"taken, or it has already been given another name"
|
||||
:erlang.error ArgumentError.exception(message), [pid_or_port, name]
|
||||
end
|
||||
|
||||
defp pid_or_port(pid) when is_pid(pid), do: "pid #{inspect pid}"
|
||||
defp pid_or_port(port) when is_port(port), do: "port #{inspect port}"
|
||||
|
||||
@doc """
|
||||
Removes the registered `name`, associated with a PID
|
||||
or a port identifier.
|
||||
|
||||
Fails with `ArgumentError` if the name is not registered
|
||||
to any PID or port.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec unregister(atom) :: true
|
||||
defdelegate unregister(name), to: :erlang
|
||||
|
||||
@doc """
|
||||
Returns the PID or port identifier registered under `name` or `nil` if the
|
||||
name is not registered.
|
||||
|
||||
See `:erlang.whereis/1` for more info.
|
||||
"""
|
||||
@spec whereis(atom) :: pid | port | nil
|
||||
def whereis(name) do
|
||||
nillify(:erlang.whereis(name))
|
||||
def unregister(name) do
|
||||
:erlang.unregister(name)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the PID of the group leader for the calling process.
|
||||
Returns the PID or port identifier with the registered `name`.
|
||||
Returns `nil` if the name is not registered.
|
||||
|
||||
Inlined by the compiler.
|
||||
See [`:erlang.whereis/1`](http://www.erlang.org/doc/man/erlang.html#whereis-1) for more info.
|
||||
"""
|
||||
@spec group_leader() :: pid
|
||||
defdelegate group_leader(), to: :erlang
|
||||
@spec whereis(atom) :: pid | port | nil
|
||||
def whereis(name) do
|
||||
nillify :erlang.whereis(name)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sets the group leader of the given `pid` to `leader`.
|
||||
Returns the PID of the group leader for the process which evaluates the function.
|
||||
"""
|
||||
@spec group_leader :: pid
|
||||
def group_leader do
|
||||
:erlang.group_leader
|
||||
end
|
||||
|
||||
Typically, this is used when a process started from a certain shell should
|
||||
have a group leader other than `:init`.
|
||||
|
||||
Inlined by the compiler.
|
||||
@doc """
|
||||
Sets the group leader of `pid` to `leader`. Typically, this is used when a processes
|
||||
started from a certain shell should have a group leader other than `:init`.
|
||||
"""
|
||||
@spec group_leader(pid, leader :: pid) :: true
|
||||
def group_leader(pid, leader) do
|
||||
@@ -559,79 +482,57 @@ defmodule Process do
|
||||
|
||||
@doc """
|
||||
Returns a list of names which have been registered using `register/2`.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec registered() :: [atom]
|
||||
defdelegate registered(), to: :erlang
|
||||
@spec registered :: [atom]
|
||||
def registered do
|
||||
:erlang.registered()
|
||||
end
|
||||
|
||||
@typep heap_size ::
|
||||
non_neg_integer
|
||||
| %{size: non_neg_integer, kill: boolean, error_logger: boolean}
|
||||
@typep process_flag :: :trap_exit | :error_handler | :min_heap_size |
|
||||
:min_bin_vheap_size | :priority | :save_calls |
|
||||
:sensitive
|
||||
@doc """
|
||||
Sets certain flags for the process which calls this function.
|
||||
Returns the old value of the `flag`.
|
||||
|
||||
@typep priority_level :: :low | :normal | :high | :max
|
||||
See [`:erlang.process_flag/2`](http://www.erlang.org/doc/man/erlang.html#process_flag-2) for more info.
|
||||
"""
|
||||
@spec flag(process_flag, term) :: term
|
||||
def flag(flag, value) do
|
||||
:erlang.process_flag(flag, value)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Sets the given `flag` to `value` for the calling process.
|
||||
Sets certain flags for the process `pid`, in the same manner as `flag/2`.
|
||||
Returns the old value of the `flag`. The allowed values for `flag` are
|
||||
only a subset of those allowed in `flag/2`, namely `:save_calls`.
|
||||
|
||||
Returns the old value of `flag`.
|
||||
|
||||
See `:erlang.process_flag/2` for more info.
|
||||
|
||||
Note that `flag` values `:max_heap_size` and `:message_queue_data` are only available since OTP 19.
|
||||
|
||||
Inlined by the compiler.
|
||||
See [`:erlang.process_flag/3`](http://www.erlang.org/doc/man/erlang.html#process_flag-3) for more info.
|
||||
"""
|
||||
@spec flag(:error_handler, module) :: module
|
||||
@spec flag(:max_heap_size, heap_size) :: heap_size
|
||||
@spec flag(:message_queue_data, :erlang.message_queue_data()) :: :erlang.message_queue_data()
|
||||
@spec flag(:min_bin_vheap_size, non_neg_integer) :: non_neg_integer
|
||||
@spec flag(:min_heap_size, non_neg_integer) :: non_neg_integer
|
||||
@spec flag(:monitor_nodes, term) :: term
|
||||
@spec flag({:monitor_nodes, term()}, term) :: term
|
||||
@spec flag(:priority, priority_level) :: priority_level
|
||||
@spec flag(:save_calls, 0..10000) :: 0..10000
|
||||
@spec flag(:sensitive, boolean) :: boolean
|
||||
@spec flag(:trap_exit, boolean) :: boolean
|
||||
defdelegate flag(flag, value), to: :erlang, as: :process_flag
|
||||
|
||||
@doc """
|
||||
Sets the given `flag` to `value` for the given process `pid`.
|
||||
|
||||
Returns the old value of `flag`.
|
||||
|
||||
It raises `ArgumentError` if `pid` is not a local process.
|
||||
|
||||
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 info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec flag(pid, :save_calls, 0..10000) :: 0..10000
|
||||
defdelegate flag(pid, flag, value), to: :erlang, as: :process_flag
|
||||
@spec flag(pid, :save_calls, non_neg_integer) :: non_neg_integer
|
||||
def flag(pid, flag, value) do
|
||||
:erlang.process_flag(pid, flag, value)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns information about the process identified by `pid`, or returns `nil` if the process
|
||||
is not alive.
|
||||
|
||||
Use this only for debugging information.
|
||||
|
||||
See `:erlang.process_info/1` for more info.
|
||||
See [`:erlang.process_info/1`](http://www.erlang.org/doc/man/erlang.html#process_info-1) for more info.
|
||||
"""
|
||||
@spec info(pid) :: keyword
|
||||
@spec info(pid) :: Keyword.t
|
||||
def info(pid) do
|
||||
nillify(:erlang.process_info(pid))
|
||||
nillify :erlang.process_info(pid)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns information about the process identified by `pid`,
|
||||
or returns `nil` if the process is not alive.
|
||||
|
||||
See `:erlang.process_info/2` for more info.
|
||||
See [`:erlang.process_info/2`](http://www.erlang.org/doc/man/erlang.html#process_info-2) for more info.
|
||||
"""
|
||||
@spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil
|
||||
@spec info(pid, atom | [atom]) :: {atom, term} | [{atom, term}] | nil
|
||||
def info(pid, spec)
|
||||
|
||||
def info(pid, :registered_name) do
|
||||
@@ -643,25 +544,25 @@ defmodule Process do
|
||||
end
|
||||
|
||||
def info(pid, spec) when is_atom(spec) or is_list(spec) do
|
||||
nillify(:erlang.process_info(pid, spec))
|
||||
nillify :erlang.process_info(pid, spec)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Puts the calling process into a "hibernation" state.
|
||||
|
||||
The calling process is put into a waiting state
|
||||
Puts the calling process into a wait state
|
||||
where its memory allocation has been reduced as much as possible,
|
||||
which is useful if the process does not expect to receive any messages
|
||||
in the near future.
|
||||
|
||||
See `:erlang.hibernate/3` for more info.
|
||||
See [`:erlang.hibernate/3`](http://www.erlang.org/doc/man/erlang.html#hibernate-3) for more info.
|
||||
|
||||
Inlined by the compiler.
|
||||
"""
|
||||
@spec hibernate(module, atom, list) :: no_return
|
||||
defdelegate hibernate(mod, fun_name, args), to: :erlang
|
||||
def hibernate(mod, fun, args) do
|
||||
:erlang.hibernate(mod, fun, args)
|
||||
end
|
||||
|
||||
@compile {:inline, nillify: 1}
|
||||
defp nillify(:undefined), do: nil
|
||||
defp nillify(other), do: other
|
||||
defp nillify(other), do: other
|
||||
end
|
||||
|
||||
+205
-337
@@ -19,27 +19,27 @@ defmodule Protocol do
|
||||
defmacro def({name, _, args}) when is_atom(name) and is_list(args) do
|
||||
arity = length(args)
|
||||
|
||||
type_args = :lists.map(fn _ -> quote(do: term) end, :lists.seq(2, arity))
|
||||
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("var" <> Integer.to_string(pos)), __MODULE__) end
|
||||
|
||||
call_args = :lists.map(varify, :lists.seq(2, arity))
|
||||
call_args = [quote(do: term) | call_args]
|
||||
call_args = :lists.map(fn i -> {String.to_atom(<<?x, i + 64>>), [], __MODULE__} end,
|
||||
:lists.seq(2, arity))
|
||||
call_args = [quote(do: t) | call_args]
|
||||
|
||||
quote do
|
||||
name = unquote(name)
|
||||
name = unquote(name)
|
||||
arity = unquote(arity)
|
||||
|
||||
@functions [{name, arity} | @functions]
|
||||
|
||||
# Generate a fake definition with the user
|
||||
# signature that will be used by docs
|
||||
Kernel.def(unquote(name)(unquote_splicing(args)))
|
||||
Kernel.def unquote(name)(unquote_splicing(args))
|
||||
|
||||
# Generate the actual implementation
|
||||
Kernel.def unquote(name)(unquote_splicing(call_args)) do
|
||||
impl_for!(term).unquote(name)(unquote_splicing(call_args))
|
||||
impl_for!(t).unquote(name)(unquote_splicing(call_args))
|
||||
end
|
||||
|
||||
# Convert the spec to callback if possible,
|
||||
@@ -50,7 +50,7 @@ defmodule Protocol do
|
||||
end
|
||||
|
||||
defmacro def(_) do
|
||||
raise ArgumentError, "invalid arguments for def inside defprotocol"
|
||||
raise ArgumentError, "invalid args for def inside defprotocol"
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -66,14 +66,14 @@ defmodule Protocol do
|
||||
defp assert_protocol!(module, extra) do
|
||||
case Code.ensure_compiled(module) do
|
||||
{:module, ^module} -> :ok
|
||||
_ -> raise ArgumentError, "#{inspect(module)} is not available" <> extra
|
||||
_ -> raise ArgumentError, "#{inspect module} is not available" <> extra
|
||||
end
|
||||
|
||||
try do
|
||||
module.__protocol__(:module)
|
||||
rescue
|
||||
UndefinedFunctionError ->
|
||||
raise ArgumentError, "#{inspect(module)} is not a protocol" <> extra
|
||||
raise ArgumentError, "#{inspect module} is not a protocol" <> extra
|
||||
end
|
||||
|
||||
:ok
|
||||
@@ -95,76 +95,27 @@ defmodule Protocol do
|
||||
|
||||
case Code.ensure_compiled(impl) do
|
||||
{:module, ^impl} -> :ok
|
||||
_ -> raise ArgumentError, "#{inspect(impl)} is not available" <> extra
|
||||
_ -> raise ArgumentError,
|
||||
"#{inspect impl} is not available" <> extra
|
||||
end
|
||||
|
||||
try do
|
||||
impl.__impl__(:protocol)
|
||||
rescue
|
||||
UndefinedFunctionError ->
|
||||
raise ArgumentError, "#{inspect(impl)} is not an implementation of a protocol" <> extra
|
||||
raise ArgumentError,
|
||||
"#{inspect impl} is not an implementation of a protocol" <> extra
|
||||
else
|
||||
^protocol ->
|
||||
:ok
|
||||
|
||||
other ->
|
||||
raise ArgumentError,
|
||||
"expected #{inspect(impl)} to be an implementation of #{inspect(protocol)}" <>
|
||||
", got: #{inspect(other)}" <> extra
|
||||
"expected #{inspect impl} to be an implementation of #{inspect protocol}, got: #{inspect other}" <> extra
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Derives the `protocol` for `module` with the given options.
|
||||
|
||||
If your implementation passes options or if you are generating
|
||||
custom code based on the struct, you will also need to implement
|
||||
a macro defined as `__deriving__(module, struct, options)`
|
||||
to get the options that were passed.
|
||||
|
||||
## Examples
|
||||
|
||||
defprotocol Derivable do
|
||||
def ok(a)
|
||||
end
|
||||
|
||||
defimpl Derivable, for: Any do
|
||||
defmacro __deriving__(module, struct, options) do
|
||||
quote do
|
||||
defimpl Derivable, for: unquote(module) do
|
||||
def ok(arg) do
|
||||
{:ok, arg, unquote(Macro.escape(struct)), unquote(options)}
|
||||
end
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
def ok(arg) do
|
||||
{:ok, arg}
|
||||
end
|
||||
end
|
||||
|
||||
defmodule ImplStruct do
|
||||
@derive [Derivable]
|
||||
defstruct a: 0, b: 0
|
||||
|
||||
defimpl Sample do
|
||||
def ok(struct) do
|
||||
Unknown.undefined(struct)
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
Explicit derivations can now be called via `__deriving__`:
|
||||
|
||||
# Explicitly derived via `__deriving__`
|
||||
Derivable.ok(%ImplStruct{a: 1, b: 1})
|
||||
|
||||
# Explicitly derived by API via `__deriving__`
|
||||
require Protocol
|
||||
Protocol.derive(Derivable, ImplStruct, :oops)
|
||||
Derivable.ok(%ImplStruct{a: 1, b: 1})
|
||||
|
||||
"""
|
||||
defmacro derive(protocol, module, options \\ []) do
|
||||
quote do
|
||||
@@ -193,14 +144,15 @@ defmodule Protocol do
|
||||
true
|
||||
|
||||
"""
|
||||
@spec extract_protocols([charlist | String.t()]) :: [atom]
|
||||
@spec extract_protocols([charlist | String.t]) :: [atom]
|
||||
def extract_protocols(paths) do
|
||||
extract_matching_by_attribute(paths, 'Elixir.', fn module, attributes ->
|
||||
case attributes[:protocol] do
|
||||
[fallback_to_any: _] -> module
|
||||
_ -> nil
|
||||
extract_matching_by_attribute paths, 'Elixir.',
|
||||
fn module, attributes ->
|
||||
case attributes[:protocol] do
|
||||
[fallback_to_any: _] -> module
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -222,23 +174,23 @@ defmodule Protocol do
|
||||
true
|
||||
|
||||
"""
|
||||
@spec extract_impls(module, [charlist | String.t()]) :: [atom]
|
||||
@spec extract_impls(module, [charlist | String.t]) :: [atom]
|
||||
def extract_impls(protocol, paths) when is_atom(protocol) do
|
||||
prefix = Atom.to_charlist(protocol) ++ '.'
|
||||
|
||||
extract_matching_by_attribute(paths, prefix, fn _mod, attributes ->
|
||||
case attributes[:protocol_impl] do
|
||||
[protocol: ^protocol, for: for] -> for
|
||||
_ -> nil
|
||||
end
|
||||
end)
|
||||
extract_matching_by_attribute paths, prefix, fn
|
||||
_mod, attributes ->
|
||||
case attributes[:impl] do
|
||||
[protocol: ^protocol, for: for] -> for
|
||||
_ -> nil
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
defp extract_matching_by_attribute(paths, prefix, callback) do
|
||||
for path <- paths,
|
||||
file <- list_dir(path),
|
||||
mod = extract_from_file(path, file, prefix, callback),
|
||||
do: mod
|
||||
file <- list_dir(path),
|
||||
mod = extract_from_file(path, file, prefix, callback),
|
||||
do: mod
|
||||
end
|
||||
|
||||
defp list_dir(path) when is_list(path) do
|
||||
@@ -260,9 +212,8 @@ defmodule Protocol do
|
||||
case :beam_lib.chunks(file, [:attributes]) do
|
||||
{:ok, {module, [attributes: attributes]}} ->
|
||||
callback.(module, attributes)
|
||||
|
||||
_ ->
|
||||
nil
|
||||
_ ->
|
||||
nil
|
||||
end
|
||||
end
|
||||
|
||||
@@ -299,39 +250,30 @@ defmodule Protocol do
|
||||
it will be loaded.
|
||||
"""
|
||||
@spec consolidate(module, [module]) ::
|
||||
{:ok, binary}
|
||||
| {:error, :not_a_protocol}
|
||||
| {:error, :no_beam_info}
|
||||
{:ok, binary} |
|
||||
{:error, :not_a_protocol} |
|
||||
{:error, :no_beam_info}
|
||||
def consolidate(protocol, types) when is_atom(protocol) do
|
||||
with {:ok, ast_info, chunks_info} <- beam_protocol(protocol),
|
||||
{:ok, code} <- change_debug_info(ast_info, types),
|
||||
do: compile(protocol, code, chunks_info)
|
||||
with {:ok, info} <- beam_protocol(protocol),
|
||||
{:ok, code, docs} <- change_debug_info(info, types),
|
||||
do: compile(code, docs)
|
||||
end
|
||||
|
||||
@docs_chunk 'ExDc'
|
||||
|
||||
defp beam_protocol(protocol) do
|
||||
chunk_ids = [:abstract_code, :attributes, :compile_info, 'ExDc', 'ExDp']
|
||||
chunk_ids = [:abstract_code, :attributes, @docs_chunk]
|
||||
opts = [:allow_missing_chunks]
|
||||
|
||||
case :beam_lib.chunks(beam_file(protocol), chunk_ids, opts) do
|
||||
{: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}
|
||||
|
||||
{:ok, {^protocol, [{:abstract_code, {_raw, abstract_code}},
|
||||
{:attributes, attributes},
|
||||
{@docs_chunk, docs}]}} ->
|
||||
case attributes[:protocol] do
|
||||
[fallback_to_any: any] ->
|
||||
{:ok, {protocol, any, abstract_code}, {compile_info, extra_chunks}}
|
||||
|
||||
{:ok, {protocol, any, abstract_code, docs}}
|
||||
_ ->
|
||||
{:error, :not_a_protocol}
|
||||
end
|
||||
|
||||
_ ->
|
||||
{:error, :no_beam_info}
|
||||
end
|
||||
@@ -339,155 +281,102 @@ defmodule Protocol do
|
||||
|
||||
defp beam_file(module) when is_atom(module) do
|
||||
case :code.which(module) do
|
||||
[_ | _] = file -> file
|
||||
_ -> module
|
||||
atom when is_atom(atom) -> module
|
||||
file -> file
|
||||
end
|
||||
end
|
||||
|
||||
# Change the debug information to the optimized
|
||||
# impl_for/1 dispatch version.
|
||||
defp change_debug_info({protocol, any, code}, types) do
|
||||
types = if any, do: types, else: List.delete(types, Any)
|
||||
all = [Any] ++ for {_guard, mod} <- __builtin__(), do: mod
|
||||
defp change_debug_info({protocol, any, code, docs}, types) do
|
||||
types = if any, do: types, else: List.delete(types, Any)
|
||||
all = [Any] ++ for {_guard, mod} <- __builtin__(), do: mod
|
||||
structs = types -- all
|
||||
|
||||
case change_impl_for(code, protocol, types, structs, false, []) do
|
||||
{:ok, ret} -> {:ok, ret}
|
||||
other -> other
|
||||
{:ok, ret} -> {:ok, ret, docs}
|
||||
other -> other
|
||||
end
|
||||
end
|
||||
|
||||
defp change_impl_for(
|
||||
[{:function, line, :__protocol__, 1, clauses} | tail],
|
||||
protocol,
|
||||
types,
|
||||
structs,
|
||||
_,
|
||||
acc
|
||||
) do
|
||||
abstract_types = :erl_parse.abstract(:lists.usort(types))
|
||||
defp change_impl_for([{:function, line, :__protocol__, 1, clauses} | t], protocol, types, structs, _, acc) do
|
||||
clauses = :lists.map(fn
|
||||
{:clause, l, [{:atom, _, :consolidated?}], [], [{:atom, _, _}]} ->
|
||||
{:clause, l, [{:atom, 0, :consolidated?}], [], [{:atom, 0, true}]}
|
||||
{:clause, _, _, _, _} = c ->
|
||||
c
|
||||
end, clauses)
|
||||
|
||||
clauses =
|
||||
Enum.map(clauses, fn
|
||||
{: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)
|
||||
|
||||
acc = [{:function, line, :__protocol__, 1, clauses} | acc]
|
||||
change_impl_for(tail, protocol, types, structs, true, acc)
|
||||
change_impl_for(t, protocol, types, structs, true,
|
||||
[{:function, line, :__protocol__, 1, clauses} | acc])
|
||||
end
|
||||
|
||||
defp change_impl_for(
|
||||
[{:function, line, :impl_for, 1, _} | tail],
|
||||
protocol,
|
||||
types,
|
||||
structs,
|
||||
protocol?,
|
||||
acc
|
||||
) do
|
||||
defp change_impl_for([{:function, line, :impl_for, 1, _} | t], protocol, types, structs, is_protocol, acc) do
|
||||
fallback = if Any in types, do: load_impl(protocol, Any)
|
||||
|
||||
clauses =
|
||||
for {guard, mod} <- __builtin__(),
|
||||
mod in types,
|
||||
do: builtin_clause_for(mod, guard, protocol, line)
|
||||
clauses = for {guard, mod} <- __builtin__(),
|
||||
mod in types,
|
||||
do: builtin_clause_for(mod, guard, protocol, line)
|
||||
|
||||
clauses =
|
||||
[struct_clause_for(line) | clauses] ++ [fallback_clause_for(fallback, protocol, line)]
|
||||
clauses = [struct_clause_for(line) | clauses] ++
|
||||
[fallback_clause_for(fallback, protocol, line)]
|
||||
|
||||
acc = [{:function, line, :impl_for, 1, clauses} | acc]
|
||||
change_impl_for(tail, protocol, types, structs, protocol?, acc)
|
||||
change_impl_for(t, protocol, types, structs, is_protocol,
|
||||
[{:function, line, :impl_for, 1, clauses} | acc])
|
||||
end
|
||||
|
||||
defp change_impl_for(
|
||||
[{:function, line, :struct_impl_for, 1, _} | tail],
|
||||
protocol,
|
||||
types,
|
||||
structs,
|
||||
protocol?,
|
||||
acc
|
||||
) do
|
||||
defp change_impl_for([{:function, line, :struct_impl_for, 1, _} | t], protocol, types, structs, is_protocol, acc) do
|
||||
fallback = if Any in types, do: load_impl(protocol, Any)
|
||||
clauses = for struct <- structs, do: each_struct_clause_for(struct, protocol, line)
|
||||
clauses = clauses ++ [fallback_clause_for(fallback, protocol, line)]
|
||||
|
||||
acc = [{:function, line, :struct_impl_for, 1, clauses} | acc]
|
||||
change_impl_for(tail, protocol, types, structs, protocol?, acc)
|
||||
change_impl_for(t, protocol, types, structs, is_protocol,
|
||||
[{:function, line, :struct_impl_for, 1, clauses} | acc])
|
||||
end
|
||||
|
||||
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)
|
||||
defp change_impl_for([h | t], protocol, info, types, is_protocol, acc) do
|
||||
change_impl_for(t, protocol, info, types, is_protocol, [h | acc])
|
||||
end
|
||||
|
||||
defp change_impl_for([head | tail], protocol, info, types, protocol?, acc) do
|
||||
change_impl_for(tail, protocol, info, types, protocol?, [head | acc])
|
||||
end
|
||||
|
||||
defp change_impl_for([], _protocol, _info, _types, protocol?, acc) do
|
||||
if protocol? do
|
||||
{:ok, Enum.reverse(acc)}
|
||||
defp change_impl_for([], protocol, _info, _types, is_protocol, acc) do
|
||||
if is_protocol do
|
||||
{:ok, {protocol, Enum.reverse(acc)}}
|
||||
else
|
||||
{:error, :not_a_protocol}
|
||||
end
|
||||
end
|
||||
|
||||
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]}
|
||||
{:clause, line,
|
||||
[{:var, line, :x}],
|
||||
[[{:call, line,
|
||||
{:remote, line, {:atom, line, :erlang}, {:atom, line, guard}},
|
||||
[{:var, line, :x}],
|
||||
}]],
|
||||
[{:atom, line, load_impl(protocol, mod)}]}
|
||||
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]}
|
||||
{:clause, line,
|
||||
[{:map, line, [
|
||||
{:map_field_exact, line, {:atom, line, :__struct__}, {:var, line, :x}}
|
||||
]}],
|
||||
[[{:call, line,
|
||||
{:remote, line, {:atom, line, :erlang}, {:atom, line, :is_atom}},
|
||||
[{:var, line, :x}],
|
||||
}]],
|
||||
[{:call, line,
|
||||
{:atom, line, :struct_impl_for},
|
||||
[{:var, line, :x}]}]}
|
||||
end
|
||||
|
||||
defp each_struct_clause_for(struct, protocol, line) do
|
||||
{:clause, line, [{:atom, line, struct}], [], [{:atom, line, load_impl(protocol, struct)}]}
|
||||
defp each_struct_clause_for(other, protocol, line) do
|
||||
{:clause, line, [{:atom, line, other}], [],
|
||||
[{:atom, line, load_impl(protocol, other)}]}
|
||||
end
|
||||
|
||||
defp fallback_clause_for(value, _protocol, line) do
|
||||
{:clause, line, [{:var, line, :_}], [], [{:atom, line, value}]}
|
||||
{:clause, line, [{:var, line, :_}], [],
|
||||
[{:atom, line, value}]}
|
||||
end
|
||||
|
||||
defp load_impl(protocol, for) do
|
||||
@@ -495,31 +384,27 @@ defmodule Protocol do
|
||||
end
|
||||
|
||||
# Finally compile the module and emit its bytecode.
|
||||
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
|
||||
defp compile({protocol, code}, docs) do
|
||||
opts = if Code.compiler_options[:debug_info], do: [:debug_info], else: []
|
||||
{:ok, ^protocol, binary, _warnings} = :compile.forms(code, [:return | opts])
|
||||
{:ok, :elixir_erl.add_beam_chunks(binary, extra_chunks)}
|
||||
{:ok,
|
||||
case docs do
|
||||
:missing_chunk -> binary
|
||||
_ -> :elixir_module.add_beam_chunk(binary, @docs_chunk, docs)
|
||||
end}
|
||||
end
|
||||
|
||||
## Definition callbacks
|
||||
|
||||
@doc false
|
||||
def __protocol__(name, do: block) do
|
||||
def __protocol__(name, [do: block]) do
|
||||
quote do
|
||||
defmodule unquote(name) do
|
||||
# We don't allow function definition inside protocols
|
||||
import Kernel,
|
||||
except: [
|
||||
defmacrop: 1,
|
||||
defmacrop: 2,
|
||||
defmacro: 1,
|
||||
defmacro: 2,
|
||||
defp: 1,
|
||||
defp: 2,
|
||||
def: 1,
|
||||
def: 2
|
||||
]
|
||||
import Kernel, except: [
|
||||
defmacrop: 1, defmacrop: 2, defmacro: 1, defmacro: 2,
|
||||
defp: 1, defp: 2, def: 1, def: 2
|
||||
]
|
||||
|
||||
# Import the new dsl that holds the new def
|
||||
import Protocol, only: [def: 1]
|
||||
@@ -542,16 +427,9 @@ defmodule Protocol do
|
||||
|
||||
defp after_defprotocol do
|
||||
quote bind_quoted: [builtin: __builtin__()] do
|
||||
any_impl_for =
|
||||
if @fallback_to_any do
|
||||
quote do: unquote(__MODULE__.Any).__impl__(:target)
|
||||
else
|
||||
nil
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec impl_for(term) :: atom | nil
|
||||
Kernel.def(impl_for(data))
|
||||
Kernel.def impl_for(data)
|
||||
|
||||
# Define the implementation for structs.
|
||||
#
|
||||
@@ -562,20 +440,16 @@ defmodule Protocol do
|
||||
end
|
||||
|
||||
# Define the implementation for built-ins
|
||||
:lists.foreach(
|
||||
fn {guard, mod} ->
|
||||
target = Module.concat(__MODULE__, mod)
|
||||
:lists.foreach(fn {guard, mod} ->
|
||||
target = Module.concat(__MODULE__, mod)
|
||||
|
||||
Kernel.def impl_for(data) when :erlang.unquote(guard)(data) do
|
||||
case Code.ensure_compiled?(unquote(target)) and
|
||||
function_exported?(unquote(target), :__impl__, 1) do
|
||||
true -> unquote(target).__impl__(:target)
|
||||
false -> unquote(any_impl_for)
|
||||
end
|
||||
Kernel.def impl_for(data) when :erlang.unquote(guard)(data) do
|
||||
case impl_for?(unquote(target)) do
|
||||
true -> unquote(target).__impl__(:target)
|
||||
false -> any_impl_for()
|
||||
end
|
||||
end,
|
||||
builtin
|
||||
)
|
||||
end
|
||||
end, builtin)
|
||||
|
||||
# Define a catch-all impl_for/1 clause to pacify Dialyzer (since
|
||||
# destructuring opaque types is illegal, Dialyzer will think none of the
|
||||
@@ -584,33 +458,39 @@ defmodule Protocol do
|
||||
# since it relies on Dialyzer not being smart enough to conclude that all
|
||||
# opaque types will get the any_impl_for/0 implementation.
|
||||
Kernel.def impl_for(_) do
|
||||
unquote(any_impl_for)
|
||||
any_impl_for()
|
||||
end
|
||||
|
||||
@doc false
|
||||
@spec impl_for!(term) :: atom
|
||||
if any_impl_for do
|
||||
Kernel.def impl_for!(data) do
|
||||
impl_for(data)
|
||||
end
|
||||
@spec impl_for!(term) :: atom | no_return
|
||||
Kernel.def impl_for!(data) do
|
||||
impl_for(data) || raise(Protocol.UndefinedError, protocol: __MODULE__, value: data)
|
||||
end
|
||||
|
||||
# Internal handler for Any
|
||||
if @fallback_to_any do
|
||||
Kernel.defp any_impl_for(), do: __MODULE__.Any.__impl__(:target)
|
||||
else
|
||||
Kernel.def impl_for!(data) do
|
||||
impl_for(data) || raise(Protocol.UndefinedError, protocol: __MODULE__, value: data)
|
||||
end
|
||||
Kernel.defp any_impl_for(), do: nil
|
||||
end
|
||||
|
||||
# Internal handler for Structs
|
||||
Kernel.defp struct_impl_for(struct) do
|
||||
target = Module.concat(__MODULE__, struct)
|
||||
|
||||
case Code.ensure_compiled?(target) and function_exported?(target, :__impl__, 1) do
|
||||
true -> target.__impl__(:target)
|
||||
false -> unquote(any_impl_for)
|
||||
case impl_for?(target) do
|
||||
true -> target.__impl__(:target)
|
||||
false -> any_impl_for()
|
||||
end
|
||||
end
|
||||
|
||||
# Inline struct implementation for performance
|
||||
@compile {:inline, struct_impl_for: 1}
|
||||
# Check if compilation is available internally
|
||||
Kernel.defp impl_for?(target) do
|
||||
Code.ensure_compiled?(target) and
|
||||
function_exported?(target, :__impl__, 1)
|
||||
end
|
||||
|
||||
# Inline any and struct implementations
|
||||
@compile {:inline, any_impl_for: 0, struct_impl_for: 1, impl_for?: 1}
|
||||
|
||||
unless Kernel.Typespec.defines_type?(__MODULE__, :t, 0) do
|
||||
@type t :: term
|
||||
@@ -624,31 +504,29 @@ defmodule Protocol do
|
||||
@doc false
|
||||
@spec __protocol__(:module) :: __MODULE__
|
||||
@spec __protocol__(:functions) :: unquote(Protocol.__functions_spec__(@functions))
|
||||
@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)
|
||||
Kernel.def(__protocol__(:impls), do: :not_consolidated)
|
||||
@spec __protocol__(:consolidated?) :: boolean
|
||||
Kernel.def __protocol__(:module), do: __MODULE__
|
||||
Kernel.def __protocol__(:functions), do: unquote(:lists.sort(@functions))
|
||||
Kernel.def __protocol__(:consolidated?), do: false
|
||||
end
|
||||
end
|
||||
|
||||
@doc false
|
||||
def __functions_spec__([]), do: []
|
||||
|
||||
def __functions_spec__([head | tail]),
|
||||
do: [:lists.foldl(&{:|, [], [&1, &2]}, head, tail), quote(do: ...)]
|
||||
def __functions_spec__([]),
|
||||
do: []
|
||||
def __functions_spec__([h | t]),
|
||||
do: [:lists.foldl(&{:|, [], [&1, &2]}, h, t), quote(do: ...)]
|
||||
|
||||
@doc false
|
||||
def __impl__(protocol, opts) do
|
||||
do_defimpl(protocol, :lists.keysort(1, opts))
|
||||
end
|
||||
|
||||
defp do_defimpl(protocol, do: block, for: for) when is_list(for) do
|
||||
for f <- for, do: do_defimpl(protocol, do: block, for: f)
|
||||
defp do_defimpl(protocol, [do: block, for: for]) when is_list(for) do
|
||||
for f <- for, do: do_defimpl(protocol, [do: block, for: f])
|
||||
end
|
||||
|
||||
defp do_defimpl(protocol, do: block, for: for) do
|
||||
defp do_defimpl(protocol, [do: block, for: for]) do
|
||||
# Unquote the implementation just later
|
||||
# when all variables will already be injected
|
||||
# into the module body.
|
||||
@@ -658,28 +536,28 @@ defmodule Protocol do
|
||||
@spec __impl__(:for) :: unquote(for)
|
||||
@spec __impl__(:target) :: __MODULE__
|
||||
@spec __impl__(:protocol) :: unquote(protocol)
|
||||
def __impl__(:for), do: unquote(for)
|
||||
def __impl__(:target), do: __MODULE__
|
||||
def __impl__(:for), do: unquote(for)
|
||||
def __impl__(:target), do: __MODULE__
|
||||
def __impl__(:protocol), do: unquote(protocol)
|
||||
end
|
||||
|
||||
quote do
|
||||
protocol = unquote(protocol)
|
||||
for = unquote(for)
|
||||
name = Module.concat(protocol, for)
|
||||
for = unquote(for)
|
||||
name = Module.concat(protocol, for)
|
||||
|
||||
Protocol.assert_protocol!(protocol)
|
||||
Protocol.__ensure_defimpl__(protocol, for, __ENV__)
|
||||
|
||||
defmodule name do
|
||||
@behaviour protocol
|
||||
@protocol protocol
|
||||
@for for
|
||||
@protocol protocol
|
||||
@for for
|
||||
|
||||
unquote(block)
|
||||
|
||||
Module.register_attribute(__MODULE__, :protocol_impl, persist: true)
|
||||
@protocol_impl [protocol: @protocol, for: @for]
|
||||
Module.register_attribute(__MODULE__, :impl, persist: true)
|
||||
@impl [protocol: @protocol, for: @for]
|
||||
|
||||
unquote(impl)
|
||||
end
|
||||
@@ -690,55 +568,51 @@ defmodule Protocol do
|
||||
def __derive__(derives, for, %Macro.Env{} = env) when is_atom(for) do
|
||||
struct =
|
||||
if for == env.module do
|
||||
Module.get_attribute(for, :struct) || raise "struct is not defined for #{inspect(for)}"
|
||||
Module.get_attribute(for, :struct) ||
|
||||
raise "struct is not defined for #{inspect for}"
|
||||
else
|
||||
for.__struct__
|
||||
end
|
||||
|
||||
foreach = fn
|
||||
:lists.foreach(fn
|
||||
proto when is_atom(proto) ->
|
||||
derive(proto, for, struct, [], env)
|
||||
|
||||
{proto, opts} when is_atom(proto) ->
|
||||
derive(proto, for, struct, opts, env)
|
||||
end
|
||||
|
||||
:lists.foreach(foreach, :lists.flatten(derives))
|
||||
end, :lists.flatten(derives))
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp derive(protocol, for, struct, opts, env) do
|
||||
extra = ", cannot derive #{inspect(protocol)} for #{inspect(for)}"
|
||||
extra = ", cannot derive #{inspect protocol} for #{inspect for}"
|
||||
assert_protocol!(protocol, extra)
|
||||
__ensure_defimpl__(protocol, for, env)
|
||||
assert_impl!(protocol, Any, extra)
|
||||
|
||||
# Clean up variables from eval context
|
||||
env = %{env | vars: [], export_vars: nil}
|
||||
env = %{env | vars: [], export_vars: nil}
|
||||
args = [for, struct, opts]
|
||||
impl = Module.concat(protocol, Any)
|
||||
|
||||
:elixir_module.expand_callback(env.line, impl, :__deriving__, args, env, fn mod, fun, args ->
|
||||
if function_exported?(mod, fun, length(args)) do
|
||||
apply(mod, fun, args)
|
||||
else
|
||||
quoted =
|
||||
quote do
|
||||
Module.register_attribute(__MODULE__, :protocol_impl, persist: true)
|
||||
@protocol_impl [protocol: unquote(protocol), for: unquote(for)]
|
||||
:elixir_module.expand_callback(env.line, impl, :__deriving__, args, env, fn
|
||||
mod, fun, args ->
|
||||
if function_exported?(mod, fun, length(args)) do
|
||||
apply(mod, fun, args)
|
||||
else
|
||||
Module.create(Module.concat(protocol, for), quote do
|
||||
Module.register_attribute(__MODULE__, :impl, persist: true)
|
||||
@impl [protocol: unquote(protocol), for: unquote(for)]
|
||||
|
||||
@doc false
|
||||
@spec __impl__(:target) :: unquote(impl)
|
||||
@spec __impl__(:protocol) :: unquote(protocol)
|
||||
@spec __impl__(:for) :: unquote(for)
|
||||
def __impl__(:target), do: unquote(impl)
|
||||
def __impl__(:target), do: unquote(impl)
|
||||
def __impl__(:protocol), do: unquote(protocol)
|
||||
def __impl__(:for), do: unquote(for)
|
||||
end
|
||||
|
||||
Module.create(Module.concat(protocol, for), quoted, Macro.Env.location(env))
|
||||
end
|
||||
def __impl__(:for), do: unquote(for)
|
||||
end, Macro.Env.location(env))
|
||||
end
|
||||
end)
|
||||
end
|
||||
|
||||
@@ -746,14 +620,10 @@ defmodule Protocol do
|
||||
def __ensure_defimpl__(protocol, for, env) do
|
||||
if Protocol.consolidated?(protocol) do
|
||||
message =
|
||||
"the #{inspect(protocol)} protocol has already been consolidated, an " <>
|
||||
"implementation for #{inspect(for)} has no effect. If you want to " <>
|
||||
"implement protocols after compilation or during tests, check the " <>
|
||||
"\"Consolidation\" section in the documentation for Kernel.defprotocol/2"
|
||||
|
||||
"the #{inspect protocol} protocol has already been consolidated" <>
|
||||
", an implementation for #{inspect for} has no effect"
|
||||
:elixir_errors.warn(env.line, env.file, message)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
@@ -761,34 +631,32 @@ defmodule Protocol do
|
||||
def __spec__?(module, name, arity) do
|
||||
signature = {name, arity}
|
||||
|
||||
mapper = fn {:spec, expr, pos} ->
|
||||
if Kernel.Typespec.spec_to_signature(expr) == signature do
|
||||
Module.store_typespec(module, :callback, {:callback, expr, pos})
|
||||
true
|
||||
end
|
||||
end
|
||||
|
||||
specs = Module.get_attribute(module, :spec)
|
||||
found = :lists.map(mapper, specs)
|
||||
:lists.any(&(&1 == true), found)
|
||||
found =
|
||||
:lists.map(fn {:spec, expr, caller} ->
|
||||
if Kernel.Typespec.spec_to_signature(expr) == signature do
|
||||
Kernel.Typespec.define_spec(:callback, expr, caller)
|
||||
true
|
||||
end
|
||||
end, specs)
|
||||
|
||||
:lists.any(& &1 == true, found)
|
||||
end
|
||||
|
||||
## Helpers
|
||||
|
||||
@doc false
|
||||
def __builtin__ do
|
||||
[
|
||||
is_tuple: Tuple,
|
||||
is_atom: Atom,
|
||||
is_list: List,
|
||||
is_map: Map,
|
||||
is_bitstring: BitString,
|
||||
is_integer: Integer,
|
||||
is_float: Float,
|
||||
is_function: Function,
|
||||
is_pid: PID,
|
||||
is_port: Port,
|
||||
is_reference: Reference
|
||||
]
|
||||
[is_tuple: Tuple,
|
||||
is_atom: Atom,
|
||||
is_list: List,
|
||||
is_map: Map,
|
||||
is_bitstring: BitString,
|
||||
is_integer: Integer,
|
||||
is_float: Float,
|
||||
is_function: Function,
|
||||
is_pid: PID,
|
||||
is_port: Port,
|
||||
is_reference: Reference]
|
||||
end
|
||||
end
|
||||
|
||||
+29
-33
@@ -5,11 +5,11 @@ defmodule Range do
|
||||
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
|
||||
Ranges can be either increasing (first <= last) or
|
||||
decreasing (first > last). Ranges are also always
|
||||
inclusive.
|
||||
|
||||
A range is represented internally as a struct. However,
|
||||
A Range is represented internally as a struct. However,
|
||||
the most common form of creating and matching on ranges
|
||||
is via the `../2` macro, auto-imported from `Kernel`:
|
||||
|
||||
@@ -21,9 +21,8 @@ defmodule Range do
|
||||
iex> last
|
||||
3
|
||||
|
||||
A range implements the `Enumerable` protocol, which means
|
||||
functions in the `Enum` module can be used to work with
|
||||
ranges:
|
||||
A Range implements the Enumerable protocol, which means
|
||||
all of the functions in the Enum module is available:
|
||||
|
||||
iex> range = 1..10
|
||||
1..10
|
||||
@@ -43,6 +42,7 @@ defmodule Range do
|
||||
@type t :: %Range{first: integer, last: integer}
|
||||
@type t(first, last) :: %Range{first: first, last: last}
|
||||
|
||||
|
||||
@doc """
|
||||
Creates a new range.
|
||||
"""
|
||||
@@ -53,12 +53,22 @@ defmodule Range do
|
||||
|
||||
def new(first, last) do
|
||||
raise ArgumentError,
|
||||
"ranges (first..last) expect both sides to be integers, " <>
|
||||
"got: #{inspect(first)}..#{inspect(last)}"
|
||||
"ranges (first..last) expect both sides to be integers, " <>
|
||||
"got: #{inspect first}..#{inspect last}"
|
||||
end
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
@doc false
|
||||
@doc """
|
||||
Returns `true` if the given `term` is a valid range.
|
||||
|
||||
## Examples
|
||||
|
||||
iex> Range.range?(1..3)
|
||||
true
|
||||
|
||||
iex> Range.range?(0)
|
||||
false
|
||||
|
||||
"""
|
||||
@spec range?(term) :: boolean
|
||||
def range?(term)
|
||||
def range?(first..last) when is_integer(first) and is_integer(last), do: true
|
||||
@@ -67,23 +77,23 @@ end
|
||||
|
||||
defimpl Enumerable, for: Range do
|
||||
def reduce(first..last, acc, fun) do
|
||||
reduce(first, last, acc, fun, _up? = last >= first)
|
||||
reduce(first, last, acc, fun, last >= first)
|
||||
end
|
||||
|
||||
defp reduce(_x, _y, {:halt, acc}, _fun, _up?) do
|
||||
defp reduce(_x, _y, {:halt, acc}, _fun, _up) do
|
||||
{:halted, acc}
|
||||
end
|
||||
|
||||
defp reduce(x, y, {:suspend, acc}, fun, up?) do
|
||||
{:suspended, acc, &reduce(x, y, &1, fun, up?)}
|
||||
defp reduce(x, y, {:suspend, acc}, fun, up) do
|
||||
{:suspended, acc, &reduce(x, y, &1, fun, up)}
|
||||
end
|
||||
|
||||
defp reduce(x, y, {:cont, acc}, fun, _up? = true) when x <= y do
|
||||
reduce(x + 1, y, fun.(x, acc), fun, _up? = true)
|
||||
defp reduce(x, y, {:cont, acc}, fun, true) when x <= y do
|
||||
reduce(x + 1, y, fun.(x, acc), fun, true)
|
||||
end
|
||||
|
||||
defp reduce(x, y, {:cont, acc}, fun, _up? = false) when x >= y do
|
||||
reduce(x - 1, y, fun.(x, acc), fun, _up? = false)
|
||||
defp reduce(x, y, {:cont, acc}, fun, false) when x >= y do
|
||||
reduce(x - 1, y, fun.(x, acc), fun, false)
|
||||
end
|
||||
|
||||
defp reduce(_, _, {:cont, acc}, _fun, _up) do
|
||||
@@ -109,26 +119,12 @@ defimpl Enumerable, for: Range do
|
||||
{:ok, first - last + 1}
|
||||
end
|
||||
end
|
||||
|
||||
def slice(first..last) do
|
||||
if first <= last do
|
||||
{:ok, last - first + 1, &slice_asc(first + &1, &2)}
|
||||
else
|
||||
{:ok, first - last + 1, &slice_desc(first - &1, &2)}
|
||||
end
|
||||
end
|
||||
|
||||
defp slice_asc(current, 1), do: [current]
|
||||
defp slice_asc(current, remaining), do: [current | slice_asc(current + 1, remaining - 1)]
|
||||
|
||||
defp slice_desc(current, 1), do: [current]
|
||||
defp slice_desc(current, remaining), do: [current | slice_desc(current - 1, remaining - 1)]
|
||||
end
|
||||
|
||||
defimpl Inspect, for: Range do
|
||||
import Inspect.Algebra
|
||||
|
||||
def inspect(first..last, opts) do
|
||||
concat([to_doc(first, opts), "..", to_doc(last, opts)])
|
||||
concat [to_doc(first, opts), "..", to_doc(last, opts)]
|
||||
end
|
||||
end
|
||||
|
||||
+82
-91
@@ -54,20 +54,11 @@ defmodule Record do
|
||||
that contains the record definition 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 definition to extract; with this option,
|
||||
this function uses the same path lookup used by the `-include_lib`
|
||||
attribute used in Erlang modules.
|
||||
|
||||
* `:includes` - (a list of directories as binaries) if the record being
|
||||
extracted depends on relative includes, this option allows developers
|
||||
to specify the directory those relative includes exist
|
||||
|
||||
* `:macros` - (keyword list of macro names and values) if the record
|
||||
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.
|
||||
|
||||
@@ -80,7 +71,6 @@ defmodule Record do
|
||||
uid: :undefined, gid: :undefined]
|
||||
|
||||
"""
|
||||
@spec extract(name :: atom, keyword) :: keyword
|
||||
def extract(name, opts) when is_atom(name) and is_list(opts) do
|
||||
Record.Extractor.extract(name, opts)
|
||||
end
|
||||
@@ -109,7 +99,6 @@ defmodule Record do
|
||||
These options are expected to be literals (including the binary values) at
|
||||
compile time.
|
||||
"""
|
||||
@spec extract_all(keyword) :: [{name :: atom, keyword}]
|
||||
def extract_all(opts) when is_list(opts) do
|
||||
Record.Extractor.extract_all(opts)
|
||||
end
|
||||
@@ -126,9 +115,21 @@ defmodule Record do
|
||||
true
|
||||
|
||||
"""
|
||||
defguard is_record(data, kind)
|
||||
when is_atom(kind) and is_tuple(data) and tuple_size(data) > 0 and
|
||||
elem(data, 0) == kind
|
||||
defmacro is_record(data, kind) do
|
||||
case Macro.Env.in_guard?(__CALLER__) do
|
||||
true ->
|
||||
quote do
|
||||
is_atom(unquote(kind)) and is_tuple(unquote(data)) and tuple_size(unquote(data)) > 0 and
|
||||
elem(unquote(data), 0) == unquote(kind)
|
||||
end
|
||||
false ->
|
||||
quote do
|
||||
result = unquote(data)
|
||||
kind = unquote(kind)
|
||||
is_atom(kind) and is_tuple(result) and tuple_size(result) > 0 and elem(result, 0) == kind
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Checks if the given `data` is a record.
|
||||
@@ -145,8 +146,20 @@ defmodule Record do
|
||||
false
|
||||
|
||||
"""
|
||||
defguard is_record(data)
|
||||
when is_tuple(data) and tuple_size(data) > 0 and is_atom(elem(data, 0))
|
||||
defmacro is_record(data) do
|
||||
case Macro.Env.in_guard?(__CALLER__) do
|
||||
true ->
|
||||
quote do
|
||||
is_tuple(unquote(data)) and tuple_size(unquote(data)) > 0 and
|
||||
is_atom(elem(unquote(data), 0))
|
||||
end
|
||||
false ->
|
||||
quote do
|
||||
result = unquote(data)
|
||||
is_tuple(result) and tuple_size(result) > 0 and is_atom(elem(result, 0))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Defines a set of macros to create, access, and pattern match
|
||||
@@ -209,17 +222,16 @@ defmodule Record do
|
||||
user(name: name) = record
|
||||
name #=> "meg"
|
||||
|
||||
By default, Elixir uses the record name as the first element of the tuple (the "tag").
|
||||
However, a different tag can be specified when defining a record,
|
||||
as in the following example, in which we use `Customer` as the second argument of `defrecord/3`:
|
||||
By default, Elixir uses the record name as the first element of the tuple (the
|
||||
"tag"). However, a different tag can be specified when defining a record:
|
||||
|
||||
defmodule User do
|
||||
require Record
|
||||
Record.defrecord :user, Customer, name: nil
|
||||
Record.defrecord :user, User, name: nil
|
||||
end
|
||||
|
||||
require User
|
||||
User.user() #=> {Customer, nil}
|
||||
User.user() #=> {User, nil}
|
||||
|
||||
## Defining extracted records with anonymous functions in the values
|
||||
|
||||
@@ -230,7 +242,7 @@ defmodule Record do
|
||||
|
||||
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>.
|
||||
cannot escape #Function<12.90072148/2 in :erl_eval.expr/5>.
|
||||
|
||||
To work around this error, redefine the field with your own &M.f/a function,
|
||||
like so:
|
||||
@@ -247,11 +259,11 @@ defmodule Record do
|
||||
tag = tag || name
|
||||
fields = Record.__fields__(:defrecord, kv)
|
||||
|
||||
defmacro unquote(name)(args \\ []) do
|
||||
defmacro(unquote(name)(args \\ [])) do
|
||||
Record.__access__(unquote(tag), unquote(fields), args, __CALLER__)
|
||||
end
|
||||
|
||||
defmacro unquote(name)(record, args) do
|
||||
defmacro(unquote(name)(record, args)) do
|
||||
Record.__access__(unquote(tag), unquote(fields), record, args, __CALLER__)
|
||||
end
|
||||
end
|
||||
@@ -265,11 +277,11 @@ defmodule Record do
|
||||
tag = tag || name
|
||||
fields = Record.__fields__(:defrecordp, kv)
|
||||
|
||||
defmacrop unquote(name)(args \\ []) do
|
||||
defmacrop(unquote(name)(args \\ [])) do
|
||||
Record.__access__(unquote(tag), unquote(fields), args, __CALLER__)
|
||||
end
|
||||
|
||||
defmacrop unquote(name)(record, args) do
|
||||
defmacrop(unquote(name)(record, args)) do
|
||||
Record.__access__(unquote(tag), unquote(fields), record, args, __CALLER__)
|
||||
end
|
||||
end
|
||||
@@ -278,88 +290,74 @@ defmodule Record do
|
||||
# Normalizes of record fields to have default values.
|
||||
@doc false
|
||||
def __fields__(type, fields) do
|
||||
normalizer_fun = fn
|
||||
{key, value} when is_atom(key) ->
|
||||
:lists.map(fn
|
||||
{key, val} when is_atom(key) ->
|
||||
try do
|
||||
Macro.escape(value)
|
||||
Macro.escape(val)
|
||||
rescue
|
||||
e in [ArgumentError] ->
|
||||
raise ArgumentError, "invalid value for record field #{key}, " <> Exception.message(e)
|
||||
else
|
||||
value -> {key, value}
|
||||
val -> {key, val}
|
||||
end
|
||||
|
||||
key when is_atom(key) ->
|
||||
{key, nil}
|
||||
|
||||
other ->
|
||||
raise ArgumentError, "#{type} fields must be atoms, got: #{inspect(other)}"
|
||||
end
|
||||
|
||||
:lists.map(normalizer_fun, fields)
|
||||
raise ArgumentError, "#{type} fields must be atoms, got: #{inspect other}"
|
||||
end, fields)
|
||||
end
|
||||
|
||||
# Callback invoked from record/0 and record/1 macros.
|
||||
@doc false
|
||||
def __access__(tag, fields, args, caller) do
|
||||
def __access__(atom, fields, args, caller) do
|
||||
cond do
|
||||
is_atom(args) ->
|
||||
index(tag, fields, args)
|
||||
|
||||
index(atom, fields, args)
|
||||
Keyword.keyword?(args) ->
|
||||
create(tag, fields, args, caller)
|
||||
|
||||
create(atom, fields, args, caller)
|
||||
true ->
|
||||
fields = Macro.escape(fields)
|
||||
|
||||
case Macro.expand(args, caller) do
|
||||
{:{}, _, [^tag | list]} when length(list) == length(fields) ->
|
||||
record = List.to_tuple([tag | list])
|
||||
Record.__keyword__(tag, fields, record)
|
||||
|
||||
{^tag, arg} when length(fields) == 1 ->
|
||||
Record.__keyword__(tag, fields, {tag, arg})
|
||||
|
||||
{:{}, _, [^atom | list]} when length(list) == length(fields) ->
|
||||
record = List.to_tuple([atom | list])
|
||||
Record.__keyword__(atom, fields, record)
|
||||
{^atom, arg} when length(fields) == 1 ->
|
||||
Record.__keyword__(atom, fields, {atom, arg})
|
||||
_ ->
|
||||
quote(do: Record.__keyword__(unquote(tag), unquote(fields), unquote(args)))
|
||||
quote do: Record.__keyword__(unquote(atom), unquote(fields), unquote(args))
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
# Callback invoked from the record/2 macro.
|
||||
@doc false
|
||||
def __access__(tag, fields, record, args, caller) do
|
||||
def __access__(atom, fields, record, args, caller) do
|
||||
cond do
|
||||
is_atom(args) ->
|
||||
get(tag, fields, record, args)
|
||||
|
||||
get(atom, fields, record, args)
|
||||
Keyword.keyword?(args) ->
|
||||
update(tag, fields, record, args, caller)
|
||||
|
||||
update(atom, fields, record, args, caller)
|
||||
true ->
|
||||
raise ArgumentError,
|
||||
"expected arguments to be a compile time atom or a keyword list, got: " <>
|
||||
Macro.to_string(args)
|
||||
msg = "expected arguments to be a compile time atom or keywords, got: #{Macro.to_string args}"
|
||||
raise ArgumentError, msg
|
||||
end
|
||||
end
|
||||
|
||||
# Gets the index of field.
|
||||
defp index(tag, fields, field) do
|
||||
defp index(atom, fields, field) do
|
||||
if index = find_index(fields, field, 0) do
|
||||
# Convert to Elixir index
|
||||
index - 1
|
||||
index - 1 # Convert to Elixir index
|
||||
else
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(field)}"
|
||||
raise ArgumentError, "record #{inspect atom} 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
|
||||
defp create(atom, fields, keyword, caller) do
|
||||
in_match = Macro.Env.in_match?(caller)
|
||||
keyword = apply_underscore(fields, keyword)
|
||||
|
||||
{match, remaining} =
|
||||
Enum.map_reduce(fields, keyword, fn {field, default}, each_keyword ->
|
||||
Enum.map_reduce(fields, keyword, fn({field, default}, each_keyword) ->
|
||||
new_fields =
|
||||
case Keyword.fetch(each_keyword, field) do
|
||||
{:ok, value} -> value
|
||||
@@ -372,45 +370,42 @@ defmodule Record do
|
||||
|
||||
case remaining do
|
||||
[] ->
|
||||
{:{}, [], [tag | match]}
|
||||
|
||||
_ ->
|
||||
{:{}, [], [atom | match]}
|
||||
_ ->
|
||||
keys = for {key, _} <- remaining, do: key
|
||||
raise ArgumentError, "record #{inspect(tag)} does not have the key: #{inspect(hd(keys))}"
|
||||
raise ArgumentError, "record #{inspect atom} does not have the key: #{inspect hd(keys)}"
|
||||
end
|
||||
end
|
||||
|
||||
# Updates a record given by var with the given keyword.
|
||||
defp update(tag, fields, var, keyword, caller) do
|
||||
defp update(atom, fields, var, keyword, caller) do
|
||||
if Macro.Env.in_match?(caller) do
|
||||
raise ArgumentError, "cannot invoke update style macro inside match"
|
||||
end
|
||||
|
||||
keyword = apply_underscore(fields, keyword)
|
||||
|
||||
Enum.reduce(keyword, var, fn {key, value}, acc ->
|
||||
Enum.reduce keyword, var, fn({key, value}, acc) ->
|
||||
index = find_index(fields, key, 0)
|
||||
|
||||
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)}"
|
||||
raise ArgumentError, "record #{inspect atom} does not have the key: #{inspect key}"
|
||||
end
|
||||
end)
|
||||
end
|
||||
end
|
||||
|
||||
# Gets a record key from the given var.
|
||||
defp get(tag, fields, var, key) do
|
||||
defp get(atom, fields, var, key) do
|
||||
index = find_index(fields, key, 0)
|
||||
|
||||
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)}"
|
||||
raise ArgumentError, "record #{inspect atom} does not have the key: #{inspect key}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -420,32 +415,29 @@ defmodule Record do
|
||||
|
||||
# Returns a keyword list of the record
|
||||
@doc false
|
||||
def __keyword__(tag, fields, record) do
|
||||
if is_record(record, tag) do
|
||||
def __keyword__(atom, fields, record) do
|
||||
if is_record(record, atom) do
|
||||
[_tag | values] = Tuple.to_list(record)
|
||||
|
||||
case join_keyword(fields, values, []) do
|
||||
kv when is_list(kv) ->
|
||||
kv
|
||||
|
||||
expected_fields ->
|
||||
raise ArgumentError,
|
||||
"expected argument to be a #{inspect(tag)} record with " <>
|
||||
"#{expected_fields} fields, got: " <> inspect(record)
|
||||
msg = "expected argument to be a #{inspect atom} record with #{expected_fields} fields, got: #{inspect record}"
|
||||
raise ArgumentError, msg
|
||||
end
|
||||
else
|
||||
raise ArgumentError,
|
||||
"expected argument to be a literal atom, literal keyword or " <>
|
||||
"a #{inspect(tag)} record, got runtime: " <> inspect(record)
|
||||
msg = "expected argument to be a literal atom, literal keyword or a #{inspect atom} record, got runtime: #{inspect record}"
|
||||
raise ArgumentError, msg
|
||||
end
|
||||
end
|
||||
|
||||
# Returns a keyword list, or expected number of fields on size mismatch
|
||||
defp join_keyword([{field, _default} | fields], [value | values], acc),
|
||||
do: join_keyword(fields, values, [{field, value} | acc])
|
||||
|
||||
defp join_keyword([], [], acc), do: :lists.reverse(acc)
|
||||
defp join_keyword(rest_fields, _rest_values, acc), do: length(acc) + length(rest_fields)
|
||||
defp join_keyword([], [], acc),
|
||||
do: :lists.reverse(acc)
|
||||
defp join_keyword(rest_fields, _rest_values, acc),
|
||||
do: length(acc) + length(rest_fields) # expected fields
|
||||
|
||||
defp apply_underscore(fields, keyword) do
|
||||
case Keyword.fetch(keyword, :_) do
|
||||
@@ -454,7 +446,6 @@ defmodule Record do
|
||||
|> Enum.map(fn {k, _} -> {k, default} end)
|
||||
|> Keyword.merge(keyword)
|
||||
|> Keyword.delete(:_)
|
||||
|
||||
:error ->
|
||||
keyword
|
||||
end
|
||||
|
||||
@@ -1,31 +1,33 @@
|
||||
defmodule Record.Extractor do
|
||||
@moduledoc false
|
||||
|
||||
def extract(name, opts) do
|
||||
extract_record(name, from_or_from_lib_file(opts))
|
||||
# Retrieve a record definition from an Erlang file using
|
||||
# the same lookup as the *include* attribute from Erlang modules.
|
||||
def extract(name, from: file) when is_binary(file) do
|
||||
extract_record(name, from_file(file))
|
||||
end
|
||||
|
||||
def extract_all(opts) do
|
||||
extract_all_records(from_or_from_lib_file(opts))
|
||||
# Retrieve a record definition from an Erlang file using
|
||||
# the same lookup as the *include_lib* attribute from Erlang modules.
|
||||
def extract(name, from_lib: file) when is_binary(file) do
|
||||
extract_record(name, from_lib_file(file))
|
||||
end
|
||||
|
||||
defp from_or_from_lib_file(opts) do
|
||||
cond do
|
||||
file = opts[:from] ->
|
||||
{from_file(file), Keyword.delete(opts, :from)}
|
||||
# Retrieve all records definitions from an Erlang file using
|
||||
# the same lookup as the *include* attribute from Erlang modules.
|
||||
def extract_all(from: file) when is_binary(file) do
|
||||
extract_all_records(from_file(file))
|
||||
end
|
||||
|
||||
file = opts[:from_lib] ->
|
||||
{from_lib_file(file), Keyword.delete(opts, :from_lib)}
|
||||
|
||||
true ->
|
||||
raise ArgumentError, "expected :from or :from_lib to be given as option"
|
||||
end
|
||||
# Retrieve all records definitions from an Erlang file using
|
||||
# the same lookup as the *include_lib* attribute from Erlang modules.
|
||||
def extract_all(from_lib: file) when is_binary(file) do
|
||||
extract_all_records(from_lib_file(file))
|
||||
end
|
||||
|
||||
# Find file using the same lookup as the *include* attribute from Erlang modules.
|
||||
defp from_file(file) do
|
||||
file = String.to_charlist(file)
|
||||
|
||||
case :code.where_is_file(file) do
|
||||
:non_existing -> file
|
||||
realfile -> realfile
|
||||
@@ -35,33 +37,28 @@ defmodule Record.Extractor do
|
||||
# Find file using the same lookup as the *include_lib* attribute from Erlang modules.
|
||||
defp from_lib_file(file) do
|
||||
[app | path] = :filename.split(String.to_charlist(file))
|
||||
|
||||
case :code.lib_dir(List.to_atom(app)) do
|
||||
{:error, _} ->
|
||||
raise ArgumentError, "lib file #{file} could not be found"
|
||||
|
||||
libpath ->
|
||||
:filename.join([libpath | path])
|
||||
end
|
||||
end
|
||||
|
||||
# Retrieve the record with the given name from the given file
|
||||
defp extract_record(name, {file, opts}) do
|
||||
form = read_file(file, opts)
|
||||
defp extract_record(name, file) do
|
||||
form = read_file(file)
|
||||
records = extract_records(form)
|
||||
|
||||
if record = List.keyfind(records, name, 0) do
|
||||
parse_record(record, form)
|
||||
else
|
||||
raise ArgumentError,
|
||||
"no record #{name} found at #{file}. Or the record does not exist or " <>
|
||||
"its entry is malformed or depends on other include files"
|
||||
raise ArgumentError, "no record #{name} found at #{file}"
|
||||
end
|
||||
end
|
||||
|
||||
# Retrieve all records from the given file
|
||||
defp extract_all_records({file, opts}) do
|
||||
form = read_file(file, opts)
|
||||
defp extract_all_records(file) do
|
||||
form = read_file(file)
|
||||
records = extract_records(form)
|
||||
for rec = {name, _fields} <- records, do: {name, parse_record(rec, form)}
|
||||
end
|
||||
@@ -75,11 +72,10 @@ defmodule Record.Extractor do
|
||||
# includes record but with macros and other attributes expanded,
|
||||
# such as "-include(...)" and "-include_lib(...)". This is done
|
||||
# by using Erlang's epp.
|
||||
defp read_file(file, opts) do
|
||||
case :epp.parse_file(file, opts) do
|
||||
defp read_file(file) do
|
||||
case :epp.parse_file(file, []) do
|
||||
{:ok, form} ->
|
||||
form
|
||||
|
||||
other ->
|
||||
raise "error parsing file #{file}, got: #{inspect(other)}"
|
||||
end
|
||||
@@ -89,7 +85,9 @@ defmodule Record.Extractor do
|
||||
# list of tuples where the first element is the field
|
||||
# and the second is its default value.
|
||||
defp parse_record({_name, fields}, form) do
|
||||
cons = List.foldr(fields, {nil, 0}, fn f, acc -> {:cons, 0, parse_field(f), acc} end)
|
||||
cons = List.foldr fields, {nil, 0}, fn f, acc ->
|
||||
{:cons, 0, parse_field(f), acc}
|
||||
end
|
||||
eval_record(cons, form)
|
||||
end
|
||||
|
||||
@@ -106,10 +104,12 @@ defmodule Record.Extractor do
|
||||
end
|
||||
|
||||
defp eval_record(cons, form) do
|
||||
form = form ++ [{:function, 0, :hello, 0, [{:clause, 0, [], [], [cons]}]}]
|
||||
form = form ++
|
||||
[{:function, 0, :hello, 0, [
|
||||
{:clause, 0, [], [], [cons]}]}]
|
||||
|
||||
{:function, 0, :hello, 0, [{:clause, 0, [], [], [record_ast]}]} =
|
||||
:erl_expand_records.module(form, []) |> List.last()
|
||||
{:function, 0, :hello, 0, [
|
||||
{:clause, 0, [], [], [record_ast]}]} = :erl_expand_records.module(form, []) |> List.last
|
||||
|
||||
{:value, record, _} = :erl_eval.expr(record_ast, [])
|
||||
record
|
||||
|
||||
+66
-174
@@ -1,13 +1,14 @@
|
||||
defmodule Regex do
|
||||
@moduledoc ~S"""
|
||||
Provides regular expressions for Elixir.
|
||||
Provides regular expressions for Elixir. Built on top of Erlang's `:re`
|
||||
module.
|
||||
|
||||
Regex is based on PCRE (Perl Compatible Regular Expressions) and
|
||||
built on top of Erlang's `:re` module. More information can be found
|
||||
in the [`:re` module documentation](http://www.erlang.org/doc/man/re.html).
|
||||
As the `:re` module, Regex is based on PCRE
|
||||
(Perl Compatible Regular Expressions). More information can be
|
||||
found in the [`:re` module documentation](http://www.erlang.org/doc/man/re.html).
|
||||
|
||||
Regular expressions in Elixir can be created using the sigils
|
||||
[`~r`](Kernel.html#sigil_r/2) or [`~R`](Kernel.html#sigil_R/2):
|
||||
Regular expressions in Elixir can be created using `Regex.compile!/2`
|
||||
or using the special form with [`~r`](Kernel.html#sigil_r/2) or [`~R`](Kernel.html#sigil_R/2):
|
||||
|
||||
# A simple regular expressions that matches foo anywhere in the string
|
||||
~r/foo/
|
||||
@@ -15,36 +16,8 @@ defmodule Regex do
|
||||
# A regular expression with case insensitive and Unicode options
|
||||
~r/foo/iu
|
||||
|
||||
Regular expressions created via sigils are pre-compiled and stored
|
||||
in the `.beam` file. Notice this may be a problem if you are precompiling
|
||||
Elixir, see the "Precompilation" section for more information.
|
||||
|
||||
A Regex is represented internally as the `Regex` struct. Therefore,
|
||||
`%Regex{}` can be used whenever there is a need to match on them.
|
||||
Keep in mind it is not guaranteed two regular expressions from the
|
||||
same source are equal, for example:
|
||||
|
||||
~r/(?<foo>.)(?<bar>.)/ == ~r/(?<foo>.)(?<bar>.)/
|
||||
|
||||
may return `true` or `false` depending on your machine, endianness,
|
||||
available optimizations and others. You can, however, retrieve the source
|
||||
of a compiled regular expression by accessing the `source` field, and then
|
||||
compare those directly:
|
||||
|
||||
~r/(?<foo>.)(?<bar>.)/.source == ~r/(?<foo>.)(?<bar>.)/.source
|
||||
|
||||
## Precompilation
|
||||
|
||||
Regular expressions built with sigil are precompiled and stored in `.beam`
|
||||
files. This may be a problem if you are precompiling Elixir to run in
|
||||
different OTP releases, as OTP releases may update the underlying regular
|
||||
expression engine at any time.
|
||||
|
||||
For such reasons, we always recommend precompiling Elixir projects using
|
||||
the OTP version meant to run in production. In case cross-compilation is
|
||||
really necessary, you can manually invoke `Regex.recompile/1` or
|
||||
`Regex.recompile!/1` to perform a runtime version check and recompile the
|
||||
regex if necessary.
|
||||
|
||||
## Modifiers
|
||||
|
||||
@@ -105,7 +78,7 @@ defmodule Regex do
|
||||
|
||||
"""
|
||||
|
||||
defstruct re_pattern: nil, source: "", opts: "", re_version: ""
|
||||
defstruct re_pattern: nil, source: "", opts: ""
|
||||
|
||||
@type t :: %__MODULE__{re_pattern: term, source: binary, opts: binary}
|
||||
|
||||
@@ -118,7 +91,7 @@ defmodule Regex do
|
||||
|
||||
The given options can either be a binary with the characters
|
||||
representing the same regex options given to the `~r` sigil,
|
||||
or a list of options, as expected by the Erlang's `:re` module.
|
||||
or a list of options, as expected by the Erlang's [`:re` module](http://www.erlang.org/doc/man/re.html).
|
||||
|
||||
It returns `{:ok, regex}` in case of success,
|
||||
`{:error, reason}` otherwise.
|
||||
@@ -133,86 +106,40 @@ defmodule Regex do
|
||||
|
||||
"""
|
||||
@spec compile(binary, binary | [term]) :: {:ok, t} | {:error, any}
|
||||
def compile(source, options \\ "") do
|
||||
compile(source, options, version())
|
||||
end
|
||||
def compile(source, options \\ "")
|
||||
|
||||
defp compile(source, options, version) when is_binary(options) do
|
||||
def compile(source, options) when is_binary(options) do
|
||||
case translate_options(options, []) do
|
||||
{:error, rest} ->
|
||||
{:error, {:invalid_option, rest}}
|
||||
|
||||
translated_options ->
|
||||
compile(source, translated_options, options, version)
|
||||
compile(source, translated_options, options)
|
||||
end
|
||||
end
|
||||
|
||||
defp compile(source, options, version) when is_list(options) do
|
||||
compile(source, options, "", version)
|
||||
def compile(source, options) when is_list(options) do
|
||||
compile(source, options, "")
|
||||
end
|
||||
|
||||
defp compile(source, opts, doc_opts, version) when is_binary(source) do
|
||||
defp compile(source, opts, doc_opts) 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}}
|
||||
|
||||
{:ok, %Regex{re_pattern: re_pattern, source: source, opts: doc_opts}}
|
||||
error ->
|
||||
error
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Compiles the regular expression and raises `Regex.CompileError` in case of errors.
|
||||
Compiles the regular expression according to the given options.
|
||||
Fails with `Regex.CompileError` if the regex cannot be compiled.
|
||||
"""
|
||||
@spec compile!(binary, binary | [term]) :: t
|
||||
def compile!(source, options \\ "") do
|
||||
case compile(source, options) do
|
||||
{:ok, regex} -> regex
|
||||
{:error, {reason, at}} -> raise Regex.CompileError, "#{reason} at position #{at}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Recompiles the existing regular expression if necessary.
|
||||
|
||||
This checks the version stored in the regular expression
|
||||
and recompiles the regex in case of version mismatch.
|
||||
"""
|
||||
@spec recompile(t) :: t
|
||||
def recompile(%Regex{} = regex) do
|
||||
version = version()
|
||||
|
||||
# We use Map.get/3 by choice to support old regexes versions.
|
||||
case Map.get(regex, :re_version, :error) do
|
||||
^version ->
|
||||
{:ok, regex}
|
||||
|
||||
_ ->
|
||||
%{source: source, opts: opts} = regex
|
||||
compile(source, opts, version)
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Recompiles the existing regular expression and raises `Regex.CompileError` in case of errors.
|
||||
"""
|
||||
@spec recompile!(t) :: t
|
||||
def recompile!(regex) do
|
||||
case recompile(regex) do
|
||||
{:ok, regex} -> regex
|
||||
{:error, {reason, at}} -> raise Regex.CompileError, "#{reason} at position #{at}"
|
||||
end
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns the version of the underlying Regex engine.
|
||||
"""
|
||||
# TODO: No longer check for function_exported? on OTP 20+.
|
||||
def version do
|
||||
if function_exported?(:re, :version, 0) do
|
||||
:re.version()
|
||||
else
|
||||
"8.33 2013-05-29"
|
||||
{:error, {reason, at}} -> raise Regex.CompileError, message: "#{reason} at position #{at}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -228,7 +155,7 @@ defmodule Regex do
|
||||
false
|
||||
|
||||
"""
|
||||
@spec match?(t, String.t()) :: boolean
|
||||
@spec match?(t, String.t) :: boolean
|
||||
def match?(%Regex{re_pattern: compiled}, string) when is_binary(string) do
|
||||
:re.run(string, compiled, [{:capture, :none}]) == :match
|
||||
end
|
||||
@@ -277,12 +204,12 @@ defmodule Regex do
|
||||
def run(regex, string, options \\ [])
|
||||
|
||||
def run(%Regex{re_pattern: compiled}, string, options) when is_binary(string) do
|
||||
return = Keyword.get(options, :return, :binary)
|
||||
return = Keyword.get(options, :return, :binary)
|
||||
captures = Keyword.get(options, :capture, :all)
|
||||
|
||||
case :re.run(string, compiled, [{:capture, captures, return}]) do
|
||||
:nomatch -> nil
|
||||
:match -> []
|
||||
:match -> []
|
||||
{:match, results} -> results
|
||||
end
|
||||
end
|
||||
@@ -304,7 +231,7 @@ defmodule Regex do
|
||||
nil
|
||||
|
||||
"""
|
||||
@spec named_captures(t, String.t(), [term]) :: map | nil
|
||||
@spec named_captures(t, String.t, [term]) :: map | nil
|
||||
def named_captures(regex, string, options \\ []) when is_binary(string) do
|
||||
names = names(regex)
|
||||
options = Keyword.put(options, :capture, names)
|
||||
@@ -329,7 +256,7 @@ defmodule Regex do
|
||||
"foo"
|
||||
|
||||
"""
|
||||
@spec source(t) :: String.t()
|
||||
@spec source(t) :: String.t
|
||||
def source(%Regex{source: source}) do
|
||||
source
|
||||
end
|
||||
@@ -343,7 +270,7 @@ defmodule Regex do
|
||||
"m"
|
||||
|
||||
"""
|
||||
@spec opts(t) :: String.t()
|
||||
@spec opts(t) :: String.t
|
||||
def opts(%Regex{opts: opts}) do
|
||||
opts
|
||||
end
|
||||
@@ -357,7 +284,7 @@ defmodule Regex do
|
||||
["foo"]
|
||||
|
||||
"""
|
||||
@spec names(t) :: [String.t()]
|
||||
@spec names(t) :: [String.t]
|
||||
def names(%Regex{re_pattern: re_pattern}) do
|
||||
{:namelist, names} = :re.inspect(re_pattern, :namelist)
|
||||
names
|
||||
@@ -391,13 +318,13 @@ defmodule Regex do
|
||||
[["$"], ["£"], ["€"]]
|
||||
|
||||
"""
|
||||
@spec scan(t, String.t(), [term]) :: [[String.t()]]
|
||||
@spec scan(t, String.t, [term]) :: [[String.t]]
|
||||
def scan(regex, string, options \\ [])
|
||||
|
||||
def scan(%Regex{re_pattern: compiled}, string, options) when is_binary(string) do
|
||||
return = Keyword.get(options, :return, :binary)
|
||||
return = Keyword.get(options, :return, :binary)
|
||||
captures = Keyword.get(options, :capture, :all)
|
||||
options = [{:capture, captures, return}, :global]
|
||||
options = [{:capture, captures, return}, :global]
|
||||
|
||||
case :re.run(string, compiled, options) do
|
||||
:match -> []
|
||||
@@ -418,7 +345,6 @@ defmodule Regex do
|
||||
given pattern.
|
||||
|
||||
* `:trim` - when `true`, removes empty strings (`""`) from the result.
|
||||
Defaults to `false`.
|
||||
|
||||
* `:on` - specifies which captures to split the string on, and in what
|
||||
order. Defaults to `:first` which means captures inside the regex do not
|
||||
@@ -439,7 +365,7 @@ defmodule Regex do
|
||||
["abc"]
|
||||
|
||||
iex> Regex.split(~r{}, "abc")
|
||||
["", "a", "b", "c", ""]
|
||||
["a", "b", "c", ""]
|
||||
|
||||
iex> Regex.split(~r{a(?<second>b)c}, "abc")
|
||||
["", ""]
|
||||
@@ -454,7 +380,7 @@ defmodule Regex do
|
||||
["a", "b", "c"]
|
||||
|
||||
"""
|
||||
@spec split(t, String.t(), [term]) :: [String.t()]
|
||||
@spec split(t, String.t, [term]) :: [String.t]
|
||||
def split(regex, string, options \\ [])
|
||||
|
||||
def split(%Regex{}, "", opts) do
|
||||
@@ -465,32 +391,26 @@ defmodule Regex do
|
||||
end
|
||||
end
|
||||
|
||||
def split(%Regex{re_pattern: compiled}, string, opts)
|
||||
when is_binary(string) and is_list(opts) do
|
||||
def split(%Regex{re_pattern: compiled}, string, opts) when is_binary(string) and is_list(opts) do
|
||||
on = Keyword.get(opts, :on, :first)
|
||||
|
||||
case :re.run(string, compiled, [:global, capture: on]) do
|
||||
{:match, matches} ->
|
||||
index = parts_to_index(Keyword.get(opts, :parts, :infinity))
|
||||
trim = Keyword.get(opts, :trim, false)
|
||||
include_captures = Keyword.get(opts, :include_captures, false)
|
||||
do_split(matches, string, 0, index, trim, include_captures)
|
||||
|
||||
do_split(matches, string, 0,
|
||||
parts_to_index(Keyword.get(opts, :parts, :infinity)),
|
||||
Keyword.get(opts, :trim, false),
|
||||
Keyword.get(opts, :include_captures, false))
|
||||
:match ->
|
||||
[string]
|
||||
|
||||
:nomatch ->
|
||||
[string]
|
||||
end
|
||||
end
|
||||
|
||||
defp parts_to_index(:infinity), do: 0
|
||||
defp parts_to_index(:infinity), do: 0
|
||||
defp parts_to_index(n) when is_integer(n) and n > 0, do: n
|
||||
|
||||
defp do_split(_, string, offset, _counter, true, _with_captures)
|
||||
when byte_size(string) <= offset do
|
||||
[]
|
||||
end
|
||||
defp do_split(_, string, offset, _counter, true, _with_captures) when byte_size(string) <= offset,
|
||||
do: []
|
||||
|
||||
defp do_split(_, string, offset, 1, _trim, _with_captures),
|
||||
do: [binary_part(string, offset, byte_size(string) - offset)]
|
||||
@@ -498,10 +418,8 @@ defmodule Regex do
|
||||
defp do_split([], string, offset, _counter, _trim, _with_captures),
|
||||
do: [binary_part(string, offset, byte_size(string) - offset)]
|
||||
|
||||
defp do_split([[{pos, _} | h] | t], string, offset, counter, trim, with_captures)
|
||||
when pos - offset < 0 do
|
||||
do_split([h | t], string, offset, counter, trim, with_captures)
|
||||
end
|
||||
defp do_split([[{pos, _} | h] | t], string, offset, counter, trim, with_captures) when pos - offset < 0,
|
||||
do: do_split([h | t], string, offset, counter, trim, with_captures)
|
||||
|
||||
defp do_split([[] | t], string, offset, counter, trim, with_captures),
|
||||
do: do_split(t, string, offset, counter, trim, with_captures)
|
||||
@@ -510,13 +428,16 @@ defmodule Regex do
|
||||
new_offset = pos + length
|
||||
keep = pos - offset
|
||||
|
||||
<<_::binary-size(offset), part::binary-size(keep), match::binary-size(length), _::binary>> =
|
||||
string
|
||||
|
||||
if keep == 0 and trim do
|
||||
[match | do_split([h | t], string, new_offset, counter - 1, trim, true)]
|
||||
if keep == 0 and length == 0 do
|
||||
do_split([h | t], string, new_offset, counter, trim, true)
|
||||
else
|
||||
[part, match | do_split([h | t], string, new_offset, counter - 1, trim, true)]
|
||||
<<_::binary-size(offset), part::binary-size(keep), match::binary-size(length), _::binary>> = string
|
||||
|
||||
if keep == 0 and (length == 0 or trim) do
|
||||
[match | do_split([h | t], string, new_offset, counter - 1, trim, true)]
|
||||
else
|
||||
[part, match | do_split([h | t], string, new_offset, counter - 1, trim, true)]
|
||||
end
|
||||
end
|
||||
end
|
||||
|
||||
@@ -524,7 +445,7 @@ defmodule Regex do
|
||||
new_offset = pos + length
|
||||
keep = pos - offset
|
||||
|
||||
if keep == 0 and trim do
|
||||
if keep == 0 and (length == 0 or trim) do
|
||||
do_split([h | t], string, new_offset, counter, trim, false)
|
||||
else
|
||||
<<_::binary-size(offset), part::binary-size(keep), _::binary>> = string
|
||||
@@ -577,7 +498,7 @@ defmodule Regex do
|
||||
"Abcadc"
|
||||
|
||||
"""
|
||||
@spec replace(t, String.t(), String.t() | (... -> String.t()), [term]) :: String.t()
|
||||
@spec replace(t, String.t, String.t | (... -> String.t), [term]) :: String.t
|
||||
def replace(regex, string, replacement, options \\ [])
|
||||
|
||||
def replace(regex, string, replacement, options)
|
||||
@@ -586,7 +507,7 @@ defmodule Regex do
|
||||
end
|
||||
|
||||
def replace(regex, string, replacement, options)
|
||||
when is_binary(string) and is_function(replacement) and is_list(options) do
|
||||
when is_binary(string) and is_function(replacement) and is_list(options) do
|
||||
{:arity, arity} = :erlang.fun_info(replacement, :arity)
|
||||
do_replace(regex, string, {replacement, arity}, options)
|
||||
end
|
||||
@@ -598,16 +519,15 @@ defmodule Regex do
|
||||
case :re.run(string, compiled, opts) do
|
||||
:nomatch ->
|
||||
string
|
||||
|
||||
{:match, [mlist | t]} when is_list(mlist) ->
|
||||
apply_list(string, replacement, [mlist | t]) |> IO.iodata_to_binary()
|
||||
|
||||
apply_list(string, replacement, [mlist | t]) |> IO.iodata_to_binary
|
||||
{:match, slist} ->
|
||||
apply_list(string, replacement, [slist]) |> IO.iodata_to_binary()
|
||||
apply_list(string, replacement, [slist]) |> IO.iodata_to_binary
|
||||
end
|
||||
end
|
||||
|
||||
defp precompile_replacement(""), do: []
|
||||
defp precompile_replacement(""),
|
||||
do: []
|
||||
|
||||
defp precompile_replacement(<<?\\, ?g, ?{, rest::binary>>) when byte_size(rest) > 0 do
|
||||
{ns, <<?}, rest::binary>>} = pick_int(rest)
|
||||
@@ -627,7 +547,6 @@ defmodule Regex do
|
||||
case precompile_replacement(rest) do
|
||||
[head | t] when is_binary(head) ->
|
||||
[<<x, head::binary>> | t]
|
||||
|
||||
other ->
|
||||
[<<x>> | other]
|
||||
end
|
||||
@@ -654,8 +573,7 @@ defmodule Regex do
|
||||
string
|
||||
end
|
||||
|
||||
defp apply_list(whole, string, pos, replacement, [[{mpos, _} | _] | _] = list)
|
||||
when mpos > pos do
|
||||
defp apply_list(whole, string, pos, replacement, [[{mpos, _} | _] | _] = list) when mpos > pos do
|
||||
length = mpos - pos
|
||||
<<untouched::binary-size(length), rest::binary>> = string
|
||||
[untouched | apply_list(whole, rest, mpos, replacement, list)]
|
||||
@@ -682,10 +600,8 @@ defmodule Regex do
|
||||
cond do
|
||||
is_binary(part) ->
|
||||
part
|
||||
|
||||
part >= tuple_size(indexes) ->
|
||||
""
|
||||
|
||||
true ->
|
||||
get_index(string, elem(indexes, part))
|
||||
end
|
||||
@@ -713,6 +629,9 @@ defmodule Regex do
|
||||
[get_index(string, h) | get_indexes(string, t, arity - 1)]
|
||||
end
|
||||
|
||||
{:ok, pattern} = :re.compile(~S"[.^$*+?()\[\]{}\\\|\s#-]", [:unicode])
|
||||
@escape_pattern pattern
|
||||
|
||||
@doc ~S"""
|
||||
Escapes a string to be literally matched in a regex.
|
||||
|
||||
@@ -725,33 +644,9 @@ defmodule Regex do
|
||||
"\\\\what\\ if"
|
||||
|
||||
"""
|
||||
@spec escape(String.t()) :: String.t()
|
||||
@spec escape(String.t) :: String.t
|
||||
def escape(string) when is_binary(string) do
|
||||
string
|
||||
|> escape(_length = 0, string)
|
||||
|> IO.iodata_to_binary()
|
||||
end
|
||||
|
||||
@escapable '.^$*+?()[]{}|#-\\\t\n\v\f\r\s'
|
||||
|
||||
defp escape(<<char, rest::binary>>, length, original) when char in @escapable do
|
||||
escape_char(rest, length, original, char)
|
||||
end
|
||||
|
||||
defp escape(<<_, rest::binary>>, length, original) do
|
||||
escape(rest, length + 1, original)
|
||||
end
|
||||
|
||||
defp escape(<<>>, _length, original) do
|
||||
original
|
||||
end
|
||||
|
||||
defp escape_char(<<rest::binary>>, 0, _original, char) do
|
||||
[?\\, char | escape(rest, 0, rest)]
|
||||
end
|
||||
|
||||
defp escape_char(<<rest::binary>>, length, original, char) do
|
||||
[binary_part(original, 0, length), ?\\, char | escape(rest, 0, rest)]
|
||||
:re.replace(string, @escape_pattern, "\\\\&", [:global, {:return, :binary}])
|
||||
end
|
||||
|
||||
# Helpers
|
||||
@@ -764,7 +659,7 @@ defmodule Regex do
|
||||
def unescape_map(?t), do: ?\t
|
||||
def unescape_map(?v), do: ?\v
|
||||
def unescape_map(?a), do: ?\a
|
||||
def unescape_map(_), do: false
|
||||
def unescape_map(_), do: false
|
||||
|
||||
# Private Helpers
|
||||
|
||||
@@ -773,15 +668,12 @@ defmodule Regex do
|
||||
defp translate_options(<<?x, t::binary>>, acc), do: translate_options(t, [:extended | acc])
|
||||
defp translate_options(<<?f, t::binary>>, acc), do: translate_options(t, [:firstline | acc])
|
||||
defp translate_options(<<?U, t::binary>>, acc), do: translate_options(t, [:ungreedy | acc])
|
||||
|
||||
defp translate_options(<<?s, t::binary>>, acc),
|
||||
do: translate_options(t, [:dotall, {:newline, :anycrlf} | acc])
|
||||
|
||||
defp translate_options(<<?s, t::binary>>, acc), do: translate_options(t, [:dotall, {:newline, :anycrlf} | acc])
|
||||
defp translate_options(<<?m, t::binary>>, acc), do: translate_options(t, [:multiline | acc])
|
||||
|
||||
# TODO: Remove on 2.0
|
||||
defp translate_options(<<?r, t::binary>>, acc) do
|
||||
IO.warn("the /r modifier in regular expressions is deprecated, please use /U instead")
|
||||
IO.warn "the /r modifier in regular expressions is deprecated, please use /U instead"
|
||||
translate_options(t, [:ungreedy | acc])
|
||||
end
|
||||
|
||||
|
||||
+67
-327
@@ -23,11 +23,11 @@ defmodule Registry do
|
||||
|
||||
## Using in `:via`
|
||||
|
||||
Once the registry is started with a given name using
|
||||
`Registry.start_link/1`, it can be used to register and access named
|
||||
Once the registry is started with a given name (using
|
||||
`Registry.start_link/2`), it can be used to register and access named
|
||||
processes using the `{:via, Registry, {registry, key}}` tuple:
|
||||
|
||||
{:ok, _} = Registry.start_link(keys: :unique, name: Registry.ViaTest)
|
||||
{:ok, _} = Registry.start_link(:unique, Registry.ViaTest)
|
||||
name = {:via, Registry, {Registry.ViaTest, "agent"}}
|
||||
{:ok, _} = Agent.start_link(fn -> 0 end, name: name)
|
||||
Agent.get(name, & &1)
|
||||
@@ -38,7 +38,7 @@ defmodule Registry do
|
||||
|
||||
Typically the registry is started as part of a supervision tree though:
|
||||
|
||||
{Registry, keys: :unique, name: Registry.ViaTest}
|
||||
supervisor(Registry, [:unique, Registry.ViaTest])
|
||||
|
||||
Only registries with unique keys can be used in `:via`. If the name is
|
||||
already taken, the case-specific `start_link` function (`Agent.start_link/2`
|
||||
@@ -50,7 +50,7 @@ defmodule Registry do
|
||||
dispatch logic triggered from the caller. For example, let's say we have a
|
||||
duplicate registry started as so:
|
||||
|
||||
{:ok, _} = Registry.start_link(keys: :duplicate, name: Registry.DispatcherTest)
|
||||
{:ok, _} = Registry.start_link(:duplicate, Registry.DispatcherTest)
|
||||
|
||||
By calling `register/3`, different processes can register under a given key
|
||||
and associate any value under that key. In this case, let's register the
|
||||
@@ -109,9 +109,10 @@ defmodule Registry do
|
||||
|
||||
In this example, we will also set the number of partitions to the number of
|
||||
schedulers online, which will make the registry more performant on highly
|
||||
concurrent environments:
|
||||
concurrent environments as each partition will spawn a new process, allowing
|
||||
dispatching to happen in parallel:
|
||||
|
||||
{:ok, _} = Registry.start_link(keys: :duplicate, name: Registry.PubSubTest,
|
||||
{:ok, _} = Registry.start_link(:duplicate, Registry.PubSubTest,
|
||||
partitions: System.schedulers_online)
|
||||
{:ok, _} = Registry.register(Registry.PubSubTest, "hello", [])
|
||||
Registry.dispatch(Registry.PubSubTest, "hello", fn entries ->
|
||||
@@ -149,7 +150,9 @@ defmodule Registry do
|
||||
Note that the registry uses one ETS table plus two ETS tables per partition.
|
||||
"""
|
||||
|
||||
@keys [:unique, :duplicate]
|
||||
# TODO: Decide if it should be started as part of Elixir's supervision tree.
|
||||
|
||||
@kind [:unique, :duplicate]
|
||||
@all_info -1
|
||||
@key_info -2
|
||||
|
||||
@@ -157,7 +160,7 @@ defmodule Registry do
|
||||
@type registry :: atom
|
||||
|
||||
@typedoc "The type of the registry"
|
||||
@type keys :: :unique | :duplicate
|
||||
@type kind :: :unique | :duplicate
|
||||
|
||||
@typedoc "The type of keys allowed on registration"
|
||||
@type key :: term
|
||||
@@ -178,15 +181,12 @@ defmodule Registry do
|
||||
case key_info!(registry) do
|
||||
{:unique, partitions, key_ets} ->
|
||||
key_ets = key_ets || key_ets!(registry, key, partitions)
|
||||
|
||||
case safe_lookup_second(key_ets, key) do
|
||||
{pid, _} ->
|
||||
if Process.alive?(pid), do: pid, else: :undefined
|
||||
|
||||
_ ->
|
||||
:undefined
|
||||
end
|
||||
|
||||
{kind, _, _} ->
|
||||
raise ArgumentError, ":via is not supported for #{kind} registries"
|
||||
end
|
||||
@@ -220,36 +220,25 @@ defmodule Registry do
|
||||
|
||||
Manually it can be started as:
|
||||
|
||||
Registry.start_link(keys: :unique, name: MyApp.Registry)
|
||||
Registry.start_link(:unique, MyApp.Registry)
|
||||
|
||||
In your supervisor tree, you would write:
|
||||
|
||||
Supervisor.start_link([
|
||||
{Registry, keys: :unique, name: MyApp.Registry}
|
||||
])
|
||||
supervisor(Registry, [:unique, MyApp.Registry])
|
||||
|
||||
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(:unique, MyApp.Registry, partitions: System.schedulers_online())
|
||||
|
||||
or:
|
||||
|
||||
Supervisor.start_link([
|
||||
{Registry, keys: :unique, name: MyApp.Registry,
|
||||
partitions: System.schedulers_online()}
|
||||
])
|
||||
supervisor(Registry, [:unique, MyApp.Registry, [partitions: System.schedulers_online()]])
|
||||
|
||||
## Options
|
||||
|
||||
The registry requires the following keys:
|
||||
|
||||
* `:keys` - choose if keys are `:unique` or `:duplicate`
|
||||
* `:name` - the name of the registry and its tables
|
||||
|
||||
The following keys are optional:
|
||||
The registry supports the following options:
|
||||
|
||||
* `:partitions` - the number of partitions in the registry. Defaults to `1`.
|
||||
* `:listeners` - a list of named processes which are notified of `:register`
|
||||
@@ -259,80 +248,28 @@ defmodule Registry do
|
||||
* `:meta` - a keyword list of metadata to be attached to the registry.
|
||||
|
||||
"""
|
||||
@spec start_link(
|
||||
keys: keys,
|
||||
name: registry,
|
||||
partitions: pos_integer,
|
||||
listeners: [atom],
|
||||
meta: meta
|
||||
) :: {:ok, pid} | {:error, term}
|
||||
when meta: [{meta_key, meta_value}]
|
||||
def start_link(options) do
|
||||
keys = Keyword.get(options, :keys)
|
||||
|
||||
unless keys in @keys do
|
||||
raise ArgumentError,
|
||||
"expected :keys to be given and be one of :unique or :duplicate, got: #{inspect(keys)}"
|
||||
end
|
||||
|
||||
name = Keyword.get(options, :name)
|
||||
|
||||
unless is_atom(name) do
|
||||
raise ArgumentError, "expected :name to be given and to be an atom, got: #{inspect(name)}"
|
||||
end
|
||||
|
||||
@spec start_link(kind, registry, options) :: {:ok, pid} | {:error, term}
|
||||
when options: [partitions: pos_integer, listeners: [atom], meta: [{meta_key, meta_value}]]
|
||||
def start_link(kind, registry, options \\ []) when kind in @kind and is_atom(registry) do
|
||||
meta = Keyword.get(options, :meta, [])
|
||||
|
||||
unless Keyword.keyword?(meta) do
|
||||
raise ArgumentError, "expected :meta to be a keyword list, got: #{inspect(meta)}"
|
||||
raise ArgumentError, "expected :meta to be a keyword list, got: #{inspect meta}"
|
||||
end
|
||||
|
||||
partitions = Keyword.get(options, :partitions, 1)
|
||||
|
||||
unless is_integer(partitions) and partitions >= 1 do
|
||||
raise ArgumentError,
|
||||
"expected :partitions to be a positive integer, got: #{inspect(partitions)}"
|
||||
raise ArgumentError, "expected :partitions to be a positive integer, got: #{inspect partitions}"
|
||||
end
|
||||
|
||||
listeners = Keyword.get(options, :listeners, [])
|
||||
|
||||
unless is_list(listeners) and Enum.all?(listeners, &is_atom/1) do
|
||||
raise ArgumentError,
|
||||
"expected :listeners to be a list of named processes, got: #{inspect(listeners)}"
|
||||
raise ArgumentError, "expected :listeners to be a list of named processes, got: #{inspect listeners}"
|
||||
end
|
||||
|
||||
# The @info format must be kept in sync with Registry.Partition optimization.
|
||||
entries = [
|
||||
{@all_info, {keys, partitions, nil, nil, listeners}},
|
||||
{@key_info, {keys, partitions, nil}} | meta
|
||||
]
|
||||
|
||||
Registry.Supervisor.start_link(keys, name, partitions, listeners, entries)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Starts the registry as a supervisor process.
|
||||
|
||||
Similar to `start_link/1` except the required options,
|
||||
`keys` and `name` are given as arguments.
|
||||
"""
|
||||
@spec start_link(keys, registry, keyword) :: {:ok, pid} | {:error, term}
|
||||
def start_link(keys, name, options \\ []) when keys in @keys and is_atom(name) do
|
||||
start_link([keys: keys, name: name] ++ options)
|
||||
end
|
||||
|
||||
@doc """
|
||||
Returns a specification to start a registry under a supervisor.
|
||||
|
||||
See `Supervisor`.
|
||||
"""
|
||||
@since "1.5.0"
|
||||
def child_spec(opts) do
|
||||
%{
|
||||
id: Keyword.get(opts, :name, Registry),
|
||||
start: {Registry, :start_link, [opts]},
|
||||
type: :supervisor
|
||||
}
|
||||
entries = [{@all_info, {kind, partitions, nil, nil, listeners}},
|
||||
{@key_info, {kind, partitions, nil}} | meta]
|
||||
Registry.Supervisor.start_link(kind, registry, partitions, listeners, entries)
|
||||
end
|
||||
|
||||
@doc """
|
||||
@@ -355,13 +292,11 @@ defmodule Registry do
|
||||
[{self(), 2}]
|
||||
|
||||
"""
|
||||
@spec update_value(registry, key, (value -> value)) ::
|
||||
{new_value :: term, old_value :: term} | :error
|
||||
@spec update_value(registry, key, (value -> value)) :: {new_value :: term, old_value :: term} | :error
|
||||
def update_value(registry, key, callback) when is_atom(registry) and is_function(callback, 1) do
|
||||
case key_info!(registry) do
|
||||
{:unique, partitions, key_ets} ->
|
||||
key_ets = key_ets || key_ets!(registry, key, partitions)
|
||||
|
||||
try do
|
||||
:ets.lookup_element(key_ets, key, 2)
|
||||
catch
|
||||
@@ -371,11 +306,9 @@ defmodule Registry do
|
||||
new_value = callback.(old_value)
|
||||
:ets.insert(key_ets, {key, {pid, new_value}})
|
||||
{new_value, old_value}
|
||||
|
||||
{_, _} ->
|
||||
:error
|
||||
end
|
||||
|
||||
{kind, _, _} ->
|
||||
raise ArgumentError, "Registry.update_value/3 is not supported for #{kind} registries"
|
||||
end
|
||||
@@ -390,16 +323,17 @@ defmodule Registry do
|
||||
associated to the pid. If there are no entries for the given key,
|
||||
the callback is never invoked.
|
||||
|
||||
If the registry is partitioned, the callback is invoked multiple times
|
||||
per partition. If the registry is partitioned and `parallel: true` is
|
||||
given as an option, the dispatching happens in parallel. In both cases,
|
||||
the callback is only invoked if there are entries for that partition.
|
||||
If the registry is not partitioned, the callback is invoked in the process
|
||||
that calls `dispatch/3`. If the registry is partitioned, the callback is
|
||||
invoked concurrently per partition by starting a task linked to the
|
||||
caller. The callback, however, is only invoked if there are entries for that
|
||||
partition.
|
||||
|
||||
See the module documentation for examples of using the `dispatch/3`
|
||||
function for building custom dispatching or a pubsub system.
|
||||
"""
|
||||
@spec dispatch(registry, key, (entries :: [{pid, value}] -> term), keyword) :: :ok
|
||||
def dispatch(registry, key, mfa_or_fun, opts \\ [])
|
||||
@spec dispatch(registry, key, (entries :: [{pid, value}] -> term)) :: :ok
|
||||
def dispatch(registry, key, mfa_or_fun)
|
||||
when is_atom(registry) and is_function(mfa_or_fun, 1)
|
||||
when is_atom(registry) and tuple_size(mfa_or_fun) == 3 do
|
||||
case key_info!(registry) do
|
||||
@@ -408,70 +342,39 @@ defmodule Registry do
|
||||
|> safe_lookup_second(key)
|
||||
|> List.wrap()
|
||||
|> apply_non_empty_to_mfa_or_fun(mfa_or_fun)
|
||||
|
||||
{:duplicate, 1, key_ets} ->
|
||||
key_ets
|
||||
|> safe_lookup_second(key)
|
||||
|> apply_non_empty_to_mfa_or_fun(mfa_or_fun)
|
||||
|
||||
{:duplicate, partitions, _} ->
|
||||
if Keyword.get(opts, :parallel, false) do
|
||||
registry
|
||||
|> dispatch_parallel(key, mfa_or_fun, partitions)
|
||||
|> Enum.each(&Task.await(&1, :infinity))
|
||||
else
|
||||
dispatch_serial(registry, key, mfa_or_fun, partitions)
|
||||
end
|
||||
registry
|
||||
|> dispatch_task(key, mfa_or_fun, partitions)
|
||||
|> Enum.each(&Task.await(&1, :infinity))
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
defp dispatch_serial(_registry, _key, _mfa_or_fun, 0) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp dispatch_serial(registry, key, mfa_or_fun, partition) do
|
||||
partition = partition - 1
|
||||
|
||||
registry
|
||||
|> key_ets!(partition)
|
||||
|> safe_lookup_second(key)
|
||||
|> apply_non_empty_to_mfa_or_fun(mfa_or_fun)
|
||||
|
||||
dispatch_serial(registry, key, mfa_or_fun, partition)
|
||||
end
|
||||
|
||||
defp dispatch_parallel(_registry, _key, _mfa_or_fun, 0) do
|
||||
defp dispatch_task(_registry, _key, _mfa_or_fun, 0) do
|
||||
[]
|
||||
end
|
||||
|
||||
defp dispatch_parallel(registry, key, mfa_or_fun, partition) do
|
||||
defp dispatch_task(registry, key, mfa_or_fun, partition) do
|
||||
partition = partition - 1
|
||||
parent = self()
|
||||
|
||||
task =
|
||||
Task.async(fn ->
|
||||
registry
|
||||
|> key_ets!(partition)
|
||||
|> safe_lookup_second(key)
|
||||
|> apply_non_empty_to_mfa_or_fun(mfa_or_fun)
|
||||
|
||||
Process.unlink(parent)
|
||||
:ok
|
||||
end)
|
||||
|
||||
[task | dispatch_parallel(registry, key, mfa_or_fun, partition)]
|
||||
task = Task.async(fn ->
|
||||
registry
|
||||
|> key_ets!(partition)
|
||||
|> safe_lookup_second(key)
|
||||
|> apply_non_empty_to_mfa_or_fun(mfa_or_fun)
|
||||
:ok
|
||||
end)
|
||||
[task | dispatch_task(registry, key, mfa_or_fun, partition)]
|
||||
end
|
||||
|
||||
defp apply_non_empty_to_mfa_or_fun([], _mfa_or_fun) do
|
||||
:ok
|
||||
end
|
||||
|
||||
defp apply_non_empty_to_mfa_or_fun(entries, {module, function, args}) do
|
||||
apply(module, function, [entries | args])
|
||||
end
|
||||
|
||||
defp apply_non_empty_to_mfa_or_fun(entries, fun) do
|
||||
fun.(entries)
|
||||
end
|
||||
@@ -516,11 +419,9 @@ defmodule Registry do
|
||||
case key_info!(registry) do
|
||||
{:unique, partitions, key_ets} ->
|
||||
key_ets = key_ets || key_ets!(registry, key, partitions)
|
||||
|
||||
case safe_lookup_second(key_ets, key) do
|
||||
{_, _} = pair ->
|
||||
[pair]
|
||||
|
||||
_ ->
|
||||
[]
|
||||
end
|
||||
@@ -543,12 +444,6 @@ defmodule Registry do
|
||||
value or tuple element, while :"$1" can be used to temporarily assign part
|
||||
of pattern to a variable for a subsequent comparison.
|
||||
|
||||
It is possible to pass list of guard conditions for more precise matching.
|
||||
Each guard is a tuple, which describes check that should be passed by assigned part of pattern.
|
||||
For example :"$1" > 1 guard condition would be expressed as {:>, :"$1", 1} tuple.
|
||||
Please note that guard conditions will work only for assigned variables like :"$1", :"$2", etc.
|
||||
Avoid usage of special match variables :"$_" and :"$$", because it might not work as expected.
|
||||
|
||||
An empty list will be returned if there is no match.
|
||||
|
||||
For unique registries, a single partition lookup is necessary. For
|
||||
@@ -570,16 +465,11 @@ 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> Registry.match(Registry.MatchTest, "hello", {:_, :_, :"$1"}, [{:>, :"$1", 1}])
|
||||
[{self(), {2, :atom, 2}}]
|
||||
iex> Registry.match(Registry.MatchTest, "hello", {:_, :"$1", :_}, [{:is_atom, :"$1"}]) |> Enum.sort()
|
||||
[{self(), {1, :atom, 1}}, {self(), {2, :atom, 2}}]
|
||||
|
||||
"""
|
||||
@spec match(registry, key, match_pattern :: term, guards :: list()) :: [{pid, term}]
|
||||
def match(registry, key, pattern, guards \\ []) when is_atom(registry) and is_list(guards) do
|
||||
guards = [{:"=:=", {:element, 1, :"$_"}, {:const, key}} | guards]
|
||||
spec = [{{:_, {:_, pattern}}, guards, [{:element, 2, :"$_"}]}]
|
||||
@spec match(registry, key, match_pattern :: atom() | tuple()) :: [{pid, term}]
|
||||
def match(registry, key, pattern) when is_atom(registry) do
|
||||
spec = [{{key, {:_, pattern}}, [], [{:element, 2, :"$_"}]}]
|
||||
|
||||
case key_info!(registry) do
|
||||
{:unique, partitions, key_ets} ->
|
||||
@@ -632,17 +522,7 @@ defmodule Registry do
|
||||
def keys(registry, pid) when is_atom(registry) and is_pid(pid) do
|
||||
{kind, partitions, _, pid_ets, _} = info!(registry)
|
||||
{_, pid_ets} = pid_ets || pid_ets!(registry, pid, partitions)
|
||||
|
||||
keys =
|
||||
try do
|
||||
spec = [{{pid, :"$1", :"$2"}, [], [{{:"$1", :"$2"}}]}]
|
||||
:ets.select(pid_ets, spec)
|
||||
catch
|
||||
:error, :badarg -> []
|
||||
end
|
||||
|
||||
# Handle the possibility of fake keys
|
||||
keys = gather_keys(keys, [], false)
|
||||
keys = safe_lookup_second(pid_ets, pid)
|
||||
|
||||
cond do
|
||||
kind == :unique -> Enum.uniq(keys)
|
||||
@@ -650,22 +530,6 @@ defmodule Registry do
|
||||
end
|
||||
end
|
||||
|
||||
defp gather_keys([{key, {_, remaining}} | rest], acc, _fake) do
|
||||
gather_keys(rest, [key | acc], {key, remaining})
|
||||
end
|
||||
|
||||
defp gather_keys([{key, _} | rest], acc, fake) do
|
||||
gather_keys(rest, [key | acc], fake)
|
||||
end
|
||||
|
||||
defp gather_keys([], acc, {key, remaining}) do
|
||||
List.duplicate(key, remaining) ++ Enum.reject(acc, &(&1 === key))
|
||||
end
|
||||
|
||||
defp gather_keys([], acc, false) do
|
||||
acc
|
||||
end
|
||||
|
||||
@doc """
|
||||
Unregisters all entries for the given `key` associated to the current
|
||||
process in `registry`.
|
||||
@@ -676,7 +540,7 @@ defmodule Registry do
|
||||
|
||||
## Examples
|
||||
|
||||
For unique registries:
|
||||
It unregister all entries for `key` for unique registries:
|
||||
|
||||
iex> Registry.start_link(:unique, Registry.UniqueUnregisterTest)
|
||||
iex> Registry.register(Registry.UniqueUnregisterTest, "hello", :world)
|
||||
@@ -687,7 +551,7 @@ defmodule Registry do
|
||||
iex> Registry.keys(Registry.UniqueUnregisterTest, self())
|
||||
[]
|
||||
|
||||
For duplicate registries:
|
||||
As well as duplicate registries:
|
||||
|
||||
iex> Registry.start_link(:duplicate, Registry.DuplicateUnregisterTest)
|
||||
iex> Registry.register(Registry.DuplicateUnregisterTest, "hello", :world)
|
||||
@@ -723,96 +587,6 @@ defmodule Registry do
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc """
|
||||
Unregister entries for a given key matching a pattern.
|
||||
|
||||
## Examples
|
||||
|
||||
For unique registries it can be used to conditionally unregister a key on
|
||||
the basis of whether or not it matches a particular value.
|
||||
|
||||
iex> Registry.start_link(:unique, Registry.UniqueUnregisterMatchTest)
|
||||
iex> Registry.register(Registry.UniqueUnregisterMatchTest, "hello", :world)
|
||||
iex> Registry.keys(Registry.UniqueUnregisterMatchTest, self())
|
||||
["hello"]
|
||||
iex> Registry.unregister_match(Registry.UniqueUnregisterMatchTest, "hello", :foo)
|
||||
:ok
|
||||
iex> Registry.keys(Registry.UniqueUnregisterMatchTest, self())
|
||||
["hello"]
|
||||
iex> Registry.unregister_match(Registry.UniqueUnregisterMatchTest, "hello", :world)
|
||||
:ok
|
||||
iex> Registry.keys(Registry.UniqueUnregisterMatchTest, self())
|
||||
[]
|
||||
|
||||
For duplicate registries:
|
||||
|
||||
iex> Registry.start_link(:duplicate, Registry.DuplicateUnregisterMatchTest)
|
||||
iex> Registry.register(Registry.DuplicateUnregisterMatchTest, "hello", :world_a)
|
||||
iex> Registry.register(Registry.DuplicateUnregisterMatchTest, "hello", :world_b)
|
||||
iex> Registry.register(Registry.DuplicateUnregisterMatchTest, "hello", :world_c)
|
||||
iex> Registry.keys(Registry.DuplicateUnregisterMatchTest, self())
|
||||
["hello", "hello", "hello"]
|
||||
iex> Registry.unregister_match(Registry.DuplicateUnregisterMatchTest, "hello", :world_a)
|
||||
:ok
|
||||
iex> Registry.keys(Registry.DuplicateUnregisterMatchTest, self())
|
||||
["hello", "hello"]
|
||||
iex> Registry.lookup(Registry.DuplicateUnregisterMatchTest, "hello")
|
||||
[{self(), :world_b}, {self(), :world_c}]
|
||||
"""
|
||||
def unregister_match(registry, key, pattern, guards \\ []) when is_list(guards) do
|
||||
self = self()
|
||||
|
||||
{kind, partitions, key_ets, pid_ets, listeners} = info!(registry)
|
||||
{key_partition, pid_partition} = partitions(kind, key, self, partitions)
|
||||
key_ets = key_ets || key_ets!(registry, key_partition)
|
||||
{pid_server, pid_ets} = pid_ets || pid_ets!(registry, pid_partition)
|
||||
|
||||
# Remove first from the key_ets because in case of crashes
|
||||
# the pid_ets will still be able to clean up. The last step is
|
||||
# to clean if we have no more entries.
|
||||
|
||||
# Here we want to count all entries for this pid under this key, regardless
|
||||
# of pattern.
|
||||
underscore_guard = {:"=:=", {:element, 1, :"$_"}, {:const, key}}
|
||||
total_spec = [{{:_, {self, :_}}, [underscore_guard], [true]}]
|
||||
total = :ets.select_count(key_ets, total_spec)
|
||||
|
||||
# We only want to delete things that match the pattern
|
||||
delete_spec = [{{:_, {self, pattern}}, [underscore_guard | guards], [true]}]
|
||||
|
||||
case :ets.select_delete(key_ets, delete_spec) do
|
||||
# We deleted everything, we can just delete the object
|
||||
^total ->
|
||||
true = :ets.delete_object(pid_ets, {self, key, key_ets})
|
||||
|
||||
unlink_if_unregistered(pid_server, pid_ets, self)
|
||||
|
||||
for listener <- listeners do
|
||||
Kernel.send(listener, {:unregister, registry, key, self})
|
||||
end
|
||||
|
||||
0 ->
|
||||
:ok
|
||||
|
||||
deleted ->
|
||||
# There are still entries remaining for this pid. delete_object/2 with
|
||||
# duplicate_bag tables will remove every entry, but we only want to
|
||||
# remove those we have deleted. The solution is to introduce a temp_entry
|
||||
# that indicates how many keys WILL be remaining after the delete operation.
|
||||
remaining = total - deleted
|
||||
temp_entry = {self, key, {key_ets, remaining}}
|
||||
true = :ets.insert(pid_ets, temp_entry)
|
||||
true = :ets.delete_object(pid_ets, {self, key, key_ets})
|
||||
real_keys = List.duplicate({self, key, key_ets}, remaining)
|
||||
true = :ets.insert(pid_ets, real_keys)
|
||||
# We've recreated the real remaining key entries, so we can now delete
|
||||
# our temporary entry.
|
||||
true = :ets.delete_object(pid_ets, temp_entry)
|
||||
end
|
||||
|
||||
:ok
|
||||
end
|
||||
|
||||
@doc """
|
||||
Registers the current process under the given `key` in `registry`.
|
||||
|
||||
@@ -821,7 +595,7 @@ defmodule Registry do
|
||||
lookup.
|
||||
|
||||
This function returns `{:ok, owner}` or `{:error, reason}`.
|
||||
The `owner` is the pid in the registry partition responsible for
|
||||
The `owner` is the pid is the registry partition responsible for
|
||||
the pid. The owner is automatically linked to the caller.
|
||||
|
||||
If the registry has unique keys, it will return `{:ok, owner}` unless
|
||||
@@ -860,22 +634,18 @@ defmodule Registry do
|
||||
{pid_server, pid_ets} = pid_ets || pid_ets!(registry, pid_partition)
|
||||
|
||||
# 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
|
||||
# always be able to do the clean up. If we register first to the
|
||||
# key one and the process crashes, the key will stay there forever.
|
||||
Process.link(pid_server)
|
||||
true = :ets.insert(pid_ets, {self, key, key_ets})
|
||||
|
||||
case register_key(kind, pid_server, key_ets, key, {key, {self, value}}) do
|
||||
{:ok, _} = ok ->
|
||||
for listener <- listeners do
|
||||
Kernel.send(listener, {:register, registry, key, self, value})
|
||||
end
|
||||
|
||||
ok
|
||||
|
||||
{:error, {:already_registered, ^self}} = error ->
|
||||
error
|
||||
|
||||
{:error, _} = error ->
|
||||
true = :ets.delete_object(pid_ets, {self, key, key_ets})
|
||||
unlink_if_unregistered(pid_server, pid_ets, self)
|
||||
@@ -887,7 +657,6 @@ defmodule Registry do
|
||||
true = :ets.insert(key_ets, entry)
|
||||
{:ok, pid_server}
|
||||
end
|
||||
|
||||
defp register_key(:unique, pid_server, key_ets, key, entry) do
|
||||
if :ets.insert_new(key_ets, entry) do
|
||||
{:ok, pid_server}
|
||||
@@ -902,7 +671,6 @@ defmodule Registry do
|
||||
:ets.delete_object(key_ets, current)
|
||||
register_key(:unique, pid_server, key_ets, key, entry)
|
||||
end
|
||||
|
||||
[] ->
|
||||
register_key(:unique, pid_server, key_ets, key, entry)
|
||||
end
|
||||
@@ -929,7 +697,7 @@ defmodule Registry do
|
||||
:ets.lookup(registry, key)
|
||||
catch
|
||||
:error, :badarg ->
|
||||
raise ArgumentError, "unknown registry: #{inspect(registry)}"
|
||||
raise ArgumentError, "unknown registry: #{inspect registry}"
|
||||
else
|
||||
[{^key, value}] -> {:ok, value}
|
||||
_ -> :error
|
||||
@@ -961,7 +729,7 @@ defmodule Registry do
|
||||
:ok
|
||||
catch
|
||||
:error, :badarg ->
|
||||
raise ArgumentError, "unknown registry: #{inspect(registry)}"
|
||||
raise ArgumentError, "unknown registry: #{inspect registry}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -978,7 +746,7 @@ defmodule Registry do
|
||||
:ets.lookup_element(registry, @all_info, 2)
|
||||
catch
|
||||
:error, :badarg ->
|
||||
raise ArgumentError, "unknown registry: #{inspect(registry)}"
|
||||
raise ArgumentError, "unknown registry: #{inspect registry}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -987,7 +755,7 @@ defmodule Registry do
|
||||
:ets.lookup_element(registry, @key_info, 2)
|
||||
catch
|
||||
:error, :badarg ->
|
||||
raise ArgumentError, "unknown registry: #{inspect(registry)}"
|
||||
raise ArgumentError, "unknown registry: #{inspect registry}"
|
||||
end
|
||||
end
|
||||
|
||||
@@ -1018,7 +786,6 @@ defmodule Registry do
|
||||
defp partitions(:unique, key, pid, partitions) do
|
||||
{hash(key, partitions), hash(pid, partitions)}
|
||||
end
|
||||
|
||||
defp partitions(:duplicate, _key, pid, partitions) do
|
||||
partition = hash(pid, partitions)
|
||||
{partition, partition}
|
||||
@@ -1036,8 +803,7 @@ defmodule Registry.Supervisor do
|
||||
use Supervisor
|
||||
|
||||
def start_link(kind, registry, partitions, listeners, entries) do
|
||||
arg = {kind, registry, partitions, listeners, entries}
|
||||
Supervisor.start_link(__MODULE__, arg, name: registry)
|
||||
Supervisor.start_link(__MODULE__, {kind, registry, partitions, listeners, entries}, name: registry)
|
||||
end
|
||||
|
||||
def init({kind, registry, partitions, listeners, entries}) do
|
||||
@@ -1045,7 +811,7 @@ defmodule Registry.Supervisor do
|
||||
true = :ets.insert(registry, entries)
|
||||
|
||||
children =
|
||||
for i <- 0..(partitions - 1) do
|
||||
for i <- 0..partitions-1 do
|
||||
key_partition = Registry.Partition.key_name(registry, i)
|
||||
pid_partition = Registry.Partition.pid_name(registry, i)
|
||||
arg = {kind, registry, i, partitions, key_partition, pid_partition, listeners}
|
||||
@@ -1071,7 +837,7 @@ defmodule Registry.Partition do
|
||||
|
||||
# This process owns the equivalent key and pid ets tables
|
||||
# and is responsible for monitoring processes that map to
|
||||
# its own pid table.
|
||||
# the its own pid table.
|
||||
use GenServer
|
||||
@all_info -1
|
||||
@key_info -2
|
||||
@@ -1112,11 +878,9 @@ defmodule Registry.Partition do
|
||||
# If we have only one partition, we do an optimization which
|
||||
# is to write the table information alongside the registry info.
|
||||
if partitions == 1 do
|
||||
entries = [
|
||||
{@key_info, {kind, partitions, key_ets}},
|
||||
{@all_info, {kind, partitions, key_ets, {self(), pid_ets}, listeners}}
|
||||
]
|
||||
|
||||
entries =
|
||||
[{@key_info, {kind, partitions, key_ets}},
|
||||
{@all_info, {kind, partitions, key_ets, {self(), pid_ets}, listeners}}]
|
||||
true = :ets.insert(registry, entries)
|
||||
else
|
||||
true = :ets.insert(registry, {i, key_ets, {self(), pid_ets}})
|
||||
@@ -1130,25 +894,14 @@ defmodule Registry.Partition do
|
||||
defp init_key_ets(:unique, key_partition) do
|
||||
:ets.new(key_partition, [:set, :public, read_concurrency: true, write_concurrency: true])
|
||||
end
|
||||
|
||||
defp init_key_ets(:duplicate, key_partition) do
|
||||
:ets.new(key_partition, [
|
||||
:duplicate_bag,
|
||||
:public,
|
||||
read_concurrency: true,
|
||||
write_concurrency: true
|
||||
])
|
||||
:ets.new(key_partition, [:duplicate_bag, :public, read_concurrency: true, write_concurrency: true])
|
||||
end
|
||||
|
||||
# A process can always have multiple keys, so the
|
||||
# pid partition is always a duplicate bag.
|
||||
defp init_pid_ets(_, pid_partition) do
|
||||
:ets.new(pid_partition, [
|
||||
:duplicate_bag,
|
||||
:public,
|
||||
read_concurrency: true,
|
||||
write_concurrency: true
|
||||
])
|
||||
:ets.new(pid_partition, [:duplicate_bag, :public, read_concurrency: true, write_concurrency: true])
|
||||
end
|
||||
|
||||
def handle_call(:sync, _, state) do
|
||||
@@ -1157,28 +910,15 @@ defmodule Registry.Partition do
|
||||
|
||||
def handle_info({:EXIT, pid, _reason}, ets) do
|
||||
entries = :ets.take(ets, pid)
|
||||
|
||||
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.
|
||||
{key_ets, _} ->
|
||||
key_ets
|
||||
|
||||
_ ->
|
||||
key_ets
|
||||
end
|
||||
|
||||
try do
|
||||
:ets.match_delete(key_ets, {key, {pid, :_}})
|
||||
catch
|
||||
:error, :badarg -> :badarg
|
||||
end
|
||||
end
|
||||
|
||||
{:noreply, ets}
|
||||
end
|
||||
|
||||
def handle_info(msg, state) do
|
||||
super(msg, state)
|
||||
end
|
||||
|
||||
+16
-16
@@ -6,7 +6,7 @@ defmodule Set do
|
||||
"""
|
||||
|
||||
@type value :: any
|
||||
@type values :: [value]
|
||||
@type values :: [ value ]
|
||||
@type t :: map
|
||||
|
||||
# TODO: Remove by 2.0
|
||||
@@ -15,8 +15,10 @@ defmodule Set do
|
||||
defmacrop target(set) do
|
||||
quote do
|
||||
case unquote(set) do
|
||||
%module{} -> module
|
||||
set -> unsupported_set(set)
|
||||
%{__struct__: x} when is_atom(x) ->
|
||||
x
|
||||
x ->
|
||||
unsupported_set(x)
|
||||
end
|
||||
end
|
||||
end
|
||||
@@ -34,8 +36,7 @@ defmodule Set do
|
||||
else
|
||||
Enumerable.reduce(set2, {:cont, set1}, fn v, acc ->
|
||||
{:cont, target1.delete(acc, v)}
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -49,10 +50,9 @@ defmodule Set do
|
||||
Enumerable.reduce(set2, {:cont, true}, fn member, acc ->
|
||||
case target1.member?(set1, member) do
|
||||
false -> {:cont, acc}
|
||||
_ -> {:halt, false}
|
||||
_ -> {:halt, false}
|
||||
end
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -77,6 +77,7 @@ defmodule Set do
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def intersection(set1, set2) do
|
||||
target1 = target(set1)
|
||||
target2 = target(set2)
|
||||
@@ -86,15 +87,16 @@ defmodule Set do
|
||||
else
|
||||
Enumerable.reduce(set1, {:cont, target1.new}, fn v, acc ->
|
||||
{:cont, if(target2.member?(set2, v), do: target1.put(acc, v), else: acc)}
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
def member?(set, value) do
|
||||
target(set).member?(set, value)
|
||||
end
|
||||
|
||||
|
||||
def put(set, value) do
|
||||
target(set).put(set, value)
|
||||
end
|
||||
@@ -127,8 +129,7 @@ defmodule Set do
|
||||
else
|
||||
Enumerable.reduce(set2, {:cont, set1}, fn v, acc ->
|
||||
{:cont, target1.put(acc, v)}
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
end
|
||||
|
||||
@@ -136,13 +137,12 @@ defmodule Set do
|
||||
Enumerable.reduce(set1, {:cont, true}, fn member, acc ->
|
||||
case target2.member?(set2, member) do
|
||||
true -> {:cont, acc}
|
||||
_ -> {:halt, false}
|
||||
_ -> {:halt, false}
|
||||
end
|
||||
end)
|
||||
|> elem(1)
|
||||
end) |> elem(1)
|
||||
end
|
||||
|
||||
defp unsupported_set(set) do
|
||||
raise ArgumentError, "unsupported set: #{inspect(set)}"
|
||||
raise ArgumentError, "unsupported set: #{inspect set}"
|
||||
end
|
||||
end
|
||||
|
||||
+245
-380
File diff suppressed because it is too large
Load Diff
@@ -1,65 +1,50 @@
|
||||
defmodule Stream.Reducers do
|
||||
# Collection of reducers and utilities shared by Enum and Stream.
|
||||
# Collection of reducers shared by Enum and Stream.
|
||||
@moduledoc false
|
||||
|
||||
def chunk_every(chunk_by, enumerable, count, step, leftover) do
|
||||
limit = :erlang.max(count, step)
|
||||
defmacro chunk(amount, step, limit, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc(head, {buffer, count}, tail) ->
|
||||
buffer = [entry | buffer]
|
||||
count = count + 1
|
||||
|
||||
chunk_fun = fn entry, {acc_buffer, acc_count} ->
|
||||
acc_buffer = [entry | acc_buffer]
|
||||
acc_count = acc_count + 1
|
||||
new_state =
|
||||
if count >= unquote(limit) do
|
||||
left = count - unquote(step)
|
||||
{Enum.take(buffer, left), left}
|
||||
else
|
||||
{buffer, count}
|
||||
end
|
||||
|
||||
new_state =
|
||||
if acc_count >= limit do
|
||||
remaining = acc_count - step
|
||||
{Enum.take(acc_buffer, remaining), remaining}
|
||||
if count == unquote(amount) do
|
||||
next_with_acc(unquote(fun), :lists.reverse(buffer), head, new_state, tail)
|
||||
else
|
||||
{acc_buffer, acc_count}
|
||||
skip(acc(head, new_state, tail))
|
||||
end
|
||||
|
||||
if acc_count == count do
|
||||
{:cont, :lists.reverse(acc_buffer), new_state}
|
||||
else
|
||||
{:cont, new_state}
|
||||
end
|
||||
end
|
||||
|
||||
after_fun = fn {acc_buffer, acc_count} ->
|
||||
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)), []}
|
||||
end
|
||||
end
|
||||
|
||||
chunk_by.(enumerable, {[], 0}, chunk_fun, after_fun)
|
||||
end
|
||||
|
||||
def chunk_by(chunk_by, enumerable, fun) do
|
||||
chunk_fun = fn
|
||||
entry, nil ->
|
||||
{:cont, {[entry], fun.(entry)}}
|
||||
|
||||
entry, {acc, value} ->
|
||||
case fun.(entry) do
|
||||
^value -> {:cont, {[entry | acc], value}}
|
||||
new_value -> {:cont, :lists.reverse(acc), {[entry], new_value}}
|
||||
end
|
||||
defmacro chunk_by(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn
|
||||
entry, acc(head, {buffer, value}, tail) ->
|
||||
new_value = unquote(callback).(entry)
|
||||
if new_value == value do
|
||||
skip(acc(head, {[entry | buffer], value}, tail))
|
||||
else
|
||||
next_with_acc(unquote(fun), :lists.reverse(buffer), head, {[entry], new_value}, tail)
|
||||
end
|
||||
entry, acc(head, nil, tail) ->
|
||||
skip(acc(head, {[entry], unquote(callback).(entry)}, tail))
|
||||
end
|
||||
end
|
||||
|
||||
after_fun = fn
|
||||
nil -> {:cont, :done}
|
||||
{acc, _value} -> {:cont, :lists.reverse(acc), :done}
|
||||
end
|
||||
|
||||
chunk_by.(enumerable, nil, chunk_fun, after_fun)
|
||||
end
|
||||
|
||||
defmacro dedup(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc(head, prev, tail) = acc ->
|
||||
fn(entry, acc(head, prev, tail) = acc) ->
|
||||
value = unquote(callback).(entry)
|
||||
|
||||
case prev do
|
||||
{:value, ^value} -> skip(acc)
|
||||
_ -> next_with_acc(unquote(fun), entry, head, {:value, value}, tail)
|
||||
@@ -73,7 +58,6 @@ defmodule Stream.Reducers do
|
||||
fn
|
||||
_entry, acc(head, amount, tail) when amount > 0 ->
|
||||
skip(acc(head, amount - 1, tail))
|
||||
|
||||
entry, acc(head, amount, tail) ->
|
||||
next_with_acc(unquote(fun), entry, head, amount, tail)
|
||||
end
|
||||
@@ -85,7 +69,6 @@ defmodule Stream.Reducers do
|
||||
fn
|
||||
entry, acc(head, curr, tail) when curr in [unquote(nth), :first] ->
|
||||
skip(acc(head, 1, tail))
|
||||
|
||||
entry, acc(head, curr, tail) ->
|
||||
next_with_acc(unquote(fun), entry, head, curr + 1, tail)
|
||||
end
|
||||
@@ -106,7 +89,7 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro filter(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc ->
|
||||
fn(entry, acc) ->
|
||||
if unquote(callback).(entry) do
|
||||
next(unquote(fun), entry, acc)
|
||||
else
|
||||
@@ -118,7 +101,7 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro filter_map(filter, mapper, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc ->
|
||||
fn(entry, acc) ->
|
||||
if unquote(filter).(entry) do
|
||||
next(unquote(fun), unquote(mapper).(entry), acc)
|
||||
else
|
||||
@@ -130,7 +113,7 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro map(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc ->
|
||||
fn(entry, acc) ->
|
||||
next(unquote(fun), unquote(callback).(entry), acc)
|
||||
end
|
||||
end
|
||||
@@ -141,7 +124,6 @@ defmodule Stream.Reducers do
|
||||
fn
|
||||
entry, acc(head, curr, tail) when curr in [unquote(nth), :first] ->
|
||||
next_with_acc(unquote(fun), unquote(mapper).(entry), head, 1, tail)
|
||||
|
||||
entry, acc(head, curr, tail) ->
|
||||
next_with_acc(unquote(fun), entry, head, curr + 1, tail)
|
||||
end
|
||||
@@ -150,7 +132,7 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro reject(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc ->
|
||||
fn(entry, acc) ->
|
||||
unless unquote(callback).(entry) do
|
||||
next(unquote(fun), entry, acc)
|
||||
else
|
||||
@@ -165,7 +147,6 @@ defmodule Stream.Reducers do
|
||||
fn
|
||||
entry, acc(head, :first, tail) ->
|
||||
next_with_acc(unquote(fun), entry, head, {:ok, entry}, tail)
|
||||
|
||||
entry, acc(head, {:ok, acc}, tail) ->
|
||||
value = unquote(callback).(entry, acc)
|
||||
next_with_acc(unquote(fun), value, head, {:ok, value}, tail)
|
||||
@@ -175,7 +156,7 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro scan3(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc(head, acc, tail) ->
|
||||
fn(entry, acc(head, acc, tail)) ->
|
||||
value = unquote(callback).(entry, acc)
|
||||
next_with_acc(unquote(fun), value, head, value, tail)
|
||||
end
|
||||
@@ -184,15 +165,13 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro take(fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc(head, curr, tail) = original ->
|
||||
fn(entry, acc(head, curr, tail) = original) ->
|
||||
case curr do
|
||||
0 ->
|
||||
{:halt, original}
|
||||
|
||||
1 ->
|
||||
{_, acc} = next_with_acc(unquote(fun), entry, head, 0, tail)
|
||||
{:halt, acc}
|
||||
|
||||
_ ->
|
||||
next_with_acc(unquote(fun), entry, head, curr - 1, tail)
|
||||
end
|
||||
@@ -205,7 +184,6 @@ defmodule Stream.Reducers do
|
||||
fn
|
||||
entry, acc(head, curr, tail) when curr in [unquote(nth), :first] ->
|
||||
next_with_acc(unquote(fun), entry, head, 1, tail)
|
||||
|
||||
entry, acc(head, curr, tail) ->
|
||||
skip(acc(head, curr + 1, tail))
|
||||
end
|
||||
@@ -214,7 +192,7 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro take_while(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc ->
|
||||
fn(entry, acc) ->
|
||||
if unquote(callback).(entry) do
|
||||
next(unquote(fun), entry, acc)
|
||||
else
|
||||
@@ -226,9 +204,8 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro uniq_by(callback, fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc(head, prev, tail) = original ->
|
||||
fn(entry, acc(head, prev, tail) = original) ->
|
||||
value = unquote(callback).(entry)
|
||||
|
||||
if Map.has_key?(prev, value) do
|
||||
skip(original)
|
||||
else
|
||||
@@ -240,7 +217,7 @@ defmodule Stream.Reducers do
|
||||
|
||||
defmacro with_index(fun \\ nil) do
|
||||
quote do
|
||||
fn entry, acc(head, counter, tail) ->
|
||||
fn(entry, acc(head, counter, tail)) ->
|
||||
next_with_acc(unquote(fun), {entry, counter}, head, counter + 1, tail)
|
||||
end
|
||||
end
|
||||
|
||||
+164
-417
File diff suppressed because it is too large
Load Diff
@@ -4,21 +4,16 @@ defprotocol String.Chars do
|
||||
@moduledoc ~S"""
|
||||
The `String.Chars` protocol is responsible for
|
||||
converting a structure to a binary (only if applicable).
|
||||
|
||||
The only function required to be implemented is
|
||||
`to_string/1`, which does the conversion.
|
||||
`to_string` which does the conversion.
|
||||
|
||||
The `to_string/1` function automatically imported
|
||||
by `Kernel` invokes this protocol. String
|
||||
interpolation also invokes `to_string/1` in its
|
||||
interpolation also invokes `to_string` in its
|
||||
arguments. For example, `"foo#{bar}"` is the same
|
||||
as `"foo" <> to_string(bar)`.
|
||||
"""
|
||||
|
||||
@doc """
|
||||
Converts `term` to a string.
|
||||
"""
|
||||
@spec to_string(t) :: String.t()
|
||||
def to_string(term)
|
||||
end
|
||||
|
||||
@@ -39,9 +34,9 @@ defimpl String.Chars, for: BitString do
|
||||
|
||||
def to_string(term) do
|
||||
raise Protocol.UndefinedError,
|
||||
protocol: @protocol,
|
||||
value: term,
|
||||
description: "cannot convert a bitstring to a string"
|
||||
protocol: @protocol,
|
||||
value: term,
|
||||
description: "cannot convert a bitstring to a string"
|
||||
end
|
||||
end
|
||||
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user